text:
Q: .net 2.0 setup project with custom action and InstallState file In my application I have one windows form application and two windows services. Currently I am using .net setup project to install application and windows services. I have added custom action which opens windows form and accepts SQL server detail to creates SQL database for the application.

I am raising InstallException if user closes or clicks Cancel button on the form to cancel setup wizard.

The problem I am facing is after cancelling setup wizard using InstallException, it gives error "Error 1001. Could not find file 'C:\Program Files (x86)\MyApp\MyService1.InstallState'." for both of my windows service one by one.

For temporary solution I kept both InstallState file and added manually in my setup project which adds both InstallState file to installation directory.

It worked for few months. But after some change in application it started giving me some other error "Error 1001. Object type not found for element ArrayOfKeyValueOfanyTypeanyType System.Collections.Hashtable"

I found that it need to add again new InstallState file for the changes.

I think this is not the proper way to adding InstallState file manually.
Has anybody other idea to implement in my setup project to overcome this problem?
I need to rollback SQL database changes(creating database) if user cancels installation wizard at the time of installation and if user cancels un-install wizard it should not delete database.
Thanks in advance.

A: I solved the problem my self. The custom action sequence  was
1)Custom action dll
2)Windows Service 1
3)Windows Service 2

I changed sequence to
1)Windows Service 1
2)Windows Service 2
3)Custom action dll
I think it was trying to rollback windows service state and windows service was not installed in 1st case


text:
Q: How to figure out where the session was closed? I'm getting an exception when trying to return a ResponseEntity with an object in a Spring Boot controller. The exception is "could not initialize proxy - the owning Session was closed". I checked the session around one particular line in the filter that is throwing the exception and and the session exists there, but not inside a method that it calls, so I want to know if there's some way to figure out where and why the session is getting closed. I just want that, to know how to figure out, but if you want to check my code here it is.
@PostMapping("/revitions/{entityId}")
@Transactional
public ResponseEntity<?> getRevision(@PathVariable Long personId, Pageable pageable){
        Page<Revision<Long, Person>> personRevisions = personRepository.findRevisions(personId, pageable);
        personRevisions.forEach(revision -> System.out.println(revision.getEntity().getPersonType())); // here it can access
        return ResponseEntity.ok(personRevisionsDTO); // here it fails
}

The filter CustomJsonFilter:

    @Override
    @Transactional // I added this and also made it a @Component, didn't have any effect
    public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer)
            throws Exception {

        boolean serialize = true;

        if (include(writer)) {
            if (serialize) {
                Session session = entityManager.unwrap(Session.class); //added for testing
                System.out.println(session.isOpen()); //always returns true
                System.out.println(session.isConnected()); //always returns true
                System.out.println(session.isJoinedToTransaction()); //always returns true
                writer.serializeAsField(pojo, jgen, provider); //this ends up in the exception, and debugging I see that the session doesn't exist in it

            }
        } else if (!jgen.canOmitFields()) {
            writer.serializeAsOmittedField(pojo, jgen, provider);
        }
    }

The Exception Stack Trace, when not including the call commented before, is :
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not initialize proxy [com.api.model.PersonType#665] - the owning Session was closed; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy [com.api.model.PersonType#665] - the owning Session was closed (through reference chain: org.springframework.data.domain.PageImpl["content"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.data.history.Revision["entity"]->com.api.model.Person["personType"]->com.api.model.PersonType$HibernateProxy$youawsnK["createdDate"])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:465)
    at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:290)
    at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:219)
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78)
    at org.springframework.hateoas.server.mvc.RepresentationModelProcessorHandlerMethodReturnValueHandler.handleReturnValue(RepresentationModelProcessorHandlerMethodReturnValueHandler.java:108)
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:135)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:111)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:111)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:109)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at com.api.util.security.ImpersonationProtectionFilter.doFilterInternal(ImpersonationProtectionFilter.java:92)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at com.api.util.security.AuthTokenFilter.doFilterInternal(AuthTokenFilter.java:74)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at com.api.util.security.RequestRejectedExceptionFilter.doFilter(RequestRejectedExceptionFilter.java:31)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1743)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy [com.api.model.PersonType#665] - the owning Session was closed (through reference chain: org.springframework.data.domain.PageImpl["content"]->java.util.Collections$UnmodifiableRandomAccessList[0]->org.springframework.data.history.Revision["entity"]->com.api.model.Person["personType"]->com.api.model.PersonType$HibernateProxy$youawsnK["createdDate"])
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:392)
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:351)
    at com.fasterxml.jackson.databind.ser.std.StdSerializer.wrapAndThrow(StdSerializer.java:316)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:782)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
    at com.api.util.serialize.CustomJsonFilter.serializeAsField(CustomJsonFilter.java:82)
    at com.api.util.serialize.CustomJsonFilter$$FastClassBySpringCGLIB$$5a9f2d1.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:783)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:698)
    at com.api.util.serialize.CustomJsonFilter$$EnhancerBySpringCGLIB$$a12bc417.serializeAsField(<generated>)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFieldsFiltered(BeanSerializerBase.java:825)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:176)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
    at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:119)
    at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:79)
    at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serialize(IndexedListSerializer.java:18)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
    at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1518)
    at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:1007)
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:456)
    ... 96 more
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy [com.api.model.PersonType#665] - the owning Session was closed
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:179)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:322)
    at org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor.intercept(ByteBuddyInterceptor.java:45)
    at org.hibernate.proxy.ProxyConfiguration$InterceptorDispatcher.intercept(ProxyConfiguration.java:95)
    at com.api.model.PersonType$HibernateProxy$youawsnK.getCreatedDate(Unknown Source)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:689)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:774)
    ... 127 more

I tried making everything a Bean and adding @Transactional everywhere with no success. I just want some way to detect where it's closing the session, so that I can continue researching from there.

A: **
In a Spring Boot application that uses Hibernate, a common reason for a session to be closed unexpectedly is when an exception is thrown during database access. When this happens, Hibernate may close the session to prevent further use of a potentially corrupted session.
**
To determine where the session was closed, you can enable Hibernate SQL logging and examine the log output for any errors or exceptions that may have occurred during the session. To do this, you can add the following lines to your application.properties file:
# Enable Hibernate SQL logging
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

With these settings, Hibernate will log all SQL statements it executes, as well as any parameter bindings, to the console. This can help you identify any errors that may have occurred during database access.
You can also use Spring Boot's transaction management capabilities to ensure that sessions are properly managed and closed after each transaction. By default, Spring Boot will automatically create and manage transactions for you if you use the @Transactional annotation on your service or repository methods. If you are not using this annotation, you may want to consider adding it to your code to ensure that sessions are properly managed and closed after each transaction.

redpajama_set_name: RedPajamaStackExchange


text:
Q: format-table outputting blank? What I'm trying to do is look at some processes and get a list of the user of these processes. ANd the following code worked fine for me.
get-wmiobject win32_process |
where{$_.name -like "*notepad*"}|sort {$_.CommandLine}|
select @{n="User";e={$_.getowner().user}},@{n="ProcessID";e={$_.ProcessID}},{$_.CommandLine} |ft -AutoSize |Out-String -Width 300 >> C:\ListUsers.txt

Somehow I wanted to split the $_.CommandLine string in the middle of way, and output some of the split arrary(see the following code for a better idea, although the code is wrong). But the updated code just output nothing into the text file. I think I must be using the select-object or fommat-object wrong, but i don't know how i can fix it.
get-wmiobject win32_process |
where{$_.name -like "*notepad*"}|sort {$_.CommandLine}|
%{
$split = $_.CommandLine.split("\")
select @{n="User";e={$_.getowner().user}},@{n="ProcessID";e={$_.ProcessID}},@{n="Ihub";e=$split[3]},@{n="version";e=$split[3]},@{n="version";e=$split[3]} |
ft -AutoSize |Out-String -Width 300 >> C:\ListUsers.txt
}

Can anyone advise? Thanks!!

A: You don't need to use select and then format-table. Format-table can create calculated properties too. Also, you forgot to wrap the $split[3] in a scriptblock. I removed the two "version" properties because they were identical to "Ihub".
Try this(untested):
get-wmiobject win32_process |
where{$_.name -like "*notepad*"}|sort {$_.CommandLine} |
Format-Table -Property @{n="User";e={$_.getowner().user}},@{n="ProcessID";e={$_.ProcessID}},@{n="Ihub";e={($_.CommandLine.split("\"))[3]}} -AutoSize |
Out-String -Width 300 >> ListUsers.txt


text:
Q: What effect in the current will have the change of the diameter of coil but same length of coil and same magnetic flux?
First image is one coil with the large diameter and a magnet rotating to create current in the coil. Second image is the same set but the diameter of coil is smaller.

A: The induced voltage according to Faradays Law is
$$V= - N\frac{\Delta \Phi}{\Delta t}$$
where $\Phi$ is the flux $\Phi = BA$, where $B$ is the magnetic field strength and $A$ is the area of the coil,  $A=\pi r^2$ where $r$ is the radius of the coil.
The induced current will be from $$V=IR$$
You can decide whether you require the magnetic field strength or magnetic flux to be constant.  Also whether the same length of wire means the same resistance, but more turns $N$.  When you put all these together you'll be to decide how the induced current in the coil changes.


text:
Q: Writing a testable Finagle Resolver I'd like to test a Finagle Resolver properly.
Let's get a sample code:
import com.twitter.finagle.{Addr, Address, Resolver}
import com.twitter.util._

class DummyResolver extends Resolver {

  override val scheme: String = "sample"

  override def bind(arg: String): Var[Addr] = {

    val delegate = SomeFactory.fromArgs(arg).build()

    Var.async(Addr.Pending: Addr)(u => addrOf(u)(delegate))
  }
}

The use of a static factory prevents me from unit-testing the resolver.
As far as I know, the only way to provide the resolver to Finagle is to declare it into the com.twitter.finagle.Resolver file in META-INF/services. Thus, I cannot provide an instance myself.
Given those constraints, how to design the resolver to either:

*

*be able to provide an instance of the delegate,

*or be able to properly test the behavior (and mock the delegate)?


text:
Q: Expanding JBOD with SAS extenders My project is expanding 24-HDD ZFS box by adding 45-drive box with option to add another 45-drive box later (all are JBODs).
Host box (24 HDDs) is Supermicro with single port expander backplane and LSI RAID card (I think, MegaRAID SAS 9240-8i). Currently backplane occupies one SAS port on card, leaving 1 port open.
My current understanding is that on first level, RAID card has to support number of drives I want to have via expanders. So I need to change RAID card to something supporting 128-drives.
After that I should be able to expand by daisy-chaining: Host backplane expander -> host RAID card <- extension 1, backplane 1 (24 HDDs) <- extension 1, backplane 2 (21 HDDs) <- extension 2, backplane 1 (24 HDDs) <- extension 2, backplane 2 (21 HDDs)
My RAID setup is volumes of 4 or 5 vdevs, RAIDZ2 (RAID6), 4TB SAS drives
Questions:
Will daisy-chaining of 2 or 4 backplanes preserve 6Gb/s speed? Is the only limitation is number of supported disks by RAID card?
Also, as I understand, use of dual-expander backplanes allows redundancy by connecting backplanes by daisy-chaining via additional paths. Is that true and is it worth extra 200$?
Should I throw away RAID card and use HBA instead since it will allow support for 128 drives cheaper and all I care is JBOD?
I used these sources to get understanding:

*

*SAS Expanders

*Supermicro SC847J SAS2 chassis manual

*Do SAS expanders work transparently with SAS controllers?

A: Many questions here!
Will daisy-chaining of 2 or 4 backplanes preserve 6Gb/s speed? Is the only limitation is number of supported disks by RAID card?
The Supermicro 45 slots SC847Exx JBOD has one or two expanders on the front backplane, and one or two on the back. Cascading the front and back backplane is OK, however I'd strongly advise against cascading JBODs.
In your situation I'd use the first port to drive the internal backplane, the second port to drive the first JBOD, and I'd add another controller to drive the second JBOD and to avoid driving too many disks from the same port, which would severely limit performance.
Also, as I understand, use of dual-expander backplanes allows redundancy by connecting backplanes by daisy-chaining via additional paths. Is that true and is it worth extra 200$?
No, dual expander backplanes allow multipathing with SAS drives only. If you're using SATA drives, dual expanders are useless (the second expander simply won't detect the drives at all).
Should I throw away RAID card and use HBA instead since it will allow support for 128 drives cheaper and all I care is JBOD?
A RAID controller provides a battery-backed cache which tremendously enhance performance, a HBA doesn't. Better use a RAID controller and set up the individual disks as distinct volumes, to get the additional cache performance.


text:
Q: Why the destructor of an object in an array isn't called when being replaced by another? Just see code
class SomeClass {
private:
    int i;
public:
    int getI() {
        return i;
    }

    SomeClass() {
        i = 0;
    }

    explicit SomeClass(int i) {
        this->i = i;
    }

    ~SomeClass(){
        cout << "SomeClass destructed with i=" << i << "." << endl;
    }
};

And the main function
int main() {
    auto* someClasses = new SomeClass[5];
    someClasses[2] = SomeClass(20);
    cout << "A new SomeClass Assigned." << endl;
    someClasses[2] = SomeClass(40);
    cout << "A new SomeClass Assigned." << endl;
    delete[] someClasses;
}

The array is initialized with all objects constructed with i=0, and we do some modification to someClasses[2].
When ending up an object, the destructor of the object should be called. However, the result shows that the destructor is not being invoked.
SomeClass destructed with i=20. // destructed after copy constructor is done.
A new SomeClass Assigned.
SomeClass destructed with i=40. // destructed after copy constructor is done.
A new SomeClass Assigned.
SomeClass destructed with i=0. // okay.
SomeClass destructed with i=0. // okay.
SomeClass destructed with i=40. // okay.
SomeClass destructed with i=0. // okay.
SomeClass destructed with i=0. // okay.

Process finished with exit code 0

If the destructor is designed not be called in this situation, how to assign a new object correctly to an existed array?
Using an object pointer array is an option but I'm just curious.

A: A destructor is called when the lifetime  of an object ends (goes out of scope, delete is called on the pointer  that was returned by new).  When you do
someClasses[2] = SomeClass(40);

the lifetime of someClasses[2] doesn't end, you just give it a new value.  It isn't until
delete[] someClasses;

when you delete the array that you end the lifetime of all the objects in the array, that the destructor is called.

A: It's not replaced with, it's assigned to. The object in the array continues live its lifetime happily, until the whole array is destroyed.

A: The assignments aren't calling a constructor or destructor, you're calling an assignment operator operator=. Since you didn't provide one for your SomeClass, the compiler generated one for you. This default operator= copies the member variable. For a simple class like yours this default is exactly what you need, which is why you see the result you expect in the array.


text:
Q: Creating A Custom Listbox - Tkinter I am messing around with tkinter and I am trying to create a custom listbox. The code I have so far works but I would like to set a different default width for for this widget but I can't figure out how to do it. What I have now returns this error:
AttributeError: 'ShelfListbox' object has no attribute 'tk'
The code:
from tkinter import *
from TestData import *
from Item import *
from Shelf import ShelfListbox

def create_item(lb):
    global item
    item = Item(sku_ent.get(), title_ent.get(), qty_ent.get())
    lb.insert(END, item.print_item())

root = Tk()
frame = Frame(root)

sku_lbl = Label(root, text="SKU: ").grid()
sku_ent = Entry(root)
sku_ent.grid(row=0, column=1)

title_lbl = Label(root, text="Title: ").grid(row=1, column=0)
title_ent = Entry(root)
title_ent.grid(row=1, column=1)

qty_lbl = Label(root, text="QTY: ").grid(row=2, column=0)
qty_ent = Entry(root)
qty_ent.grid(row=2, column=1)

item_list = ShelfListbox(root)
item_list.grid(row=0, rowspan=3, column=2)

for key in items:
    item_list.insert(END, items[key].print_item()) #ERROR COMES FROM THIS LINE

btn = Button(root, text="Confirm", command=lambda: create_item(item_list)).grid(row=3, columnspan=2)

root.mainloop()

The ShelfListbox code:
from tkinter import *

class ShelfListbox(Listbox):
    def __init__(self, master):
        Listbox.__init__(master, width=60)

A: You need to pass self as the first parameter to the Listbox.__init__ method:
Listbox.__init__(self, master, width=60)


text:
Q: What version of MS Exchange supports user picture associated to email messages? What version of MS Exchange or Windows Server add support for user picture associated to email messages?
Thanks.

A: I believe it's supported with at least Exchange 2010 and Outlook 2010.


text:
Q: How to easily retrieve nested firebase realtime database data for a chat app in java? I am writing a chat app in which I need to check if a two users u1 and u2 had a previous conversation or not. If they had, then retrieve the conversationId and send messages to that endpoint. Otherwise, create a new conversation.
My datastructure looks something like this.
userconversations:
    userId1:
        conversationID1:
            participants:
                user1: true
                user2: true
         conversationID2:
             participants:
                user1: true
                user7: true

In my app, I want to read all data from userconversations/userId1 and iterate over the list to figure out if user2 is part of a conversation or not.
My question is how do i design my class so that i quickly deserialize this data and avoid iterating over it using getChildren() calls?
If i normalize the data and keep the a different conversationId -> participants mapping, then for each conversationid, i will have to query that stream to get data. Given a user can have 100 conversations, this will be insanely slow and resource intensive.
Please feel free to suggest alternate schema designs which solve my purpose.

A: Since the keys user1, user2 and user7 are dynamic, they can't be automatically serialized into the properties of a POJO. The best you can do is get a Map<String, boolean> from participants with a GenericTypeIndicator or a cast: (Map<String, boolean>)snapshot.child("participants").getValue().


text:
Q: igb intel driver won't compile and igb.ko copied from another image kernel says format is incorrect? Ok so I have a rhel 6 machine running a rt 3.2 kernel- basically it looks like it needs a driver update as it is a clone, the image sees the expansion card nic an intel i350 and uses those as two eth ports. It does not however want to use the motherboards i210 ethernet ports. igb is the driver for both of these devices so my plan was to simply load a new driver in over the old one and hope it fixes the issue. I have taken 2 approaches to this standard build it and modprobe on system and also try to build the .ko on another system and cp it over and replace the existing .ko file
rmmod igb //to remove the previous driver
rpm -q igb // says there is no package igb so maybe it wasn't installed with rpm

tar -zxf igb-5-7.2.tar.gz
cd igb-5.7.2/src
make install
make[1]: Entering directory `/usr/src/kernels/3.2.23-rt37.56.el6rt.x86_64'
  CC [M]  /lib/modules/3.2.23-rt37.56.el6rt.x86_64/kernel/drivers/net/ethernet/intel/igb-5.7.2/src/igb_main.o
In file included from /lib/modules/3.2.23-rt37.56.el6rt.x86_64/kernel/drivers/net/ethernet/intel/igb-5.7.2/src/igb.h:32,
                 from /lib/modules/3.2.23-rt37.56.el6rt.x86_64/kernel/drivers/net/ethernet/intel/igb-5.7.2/src/igb_main.c:30:
/lib/modules/3.2.23-rt37.56.el6rt.x86_64/kernel/drivers/net/ethernet/intel/igb-5.7.2/src/kcompat.h:4183: error: conflicting types for 'netdev_features_t'
include/linux/netdev_features.h:15: note: previous declaration of 'netdev_features_t' was here
/lib/modules/3.2.23-rt37.56.el6rt.x86_64/kernel/drivers/net/ethernet/intel/igb-5.7.2/src/kcompat.h:4212: error: redefinition of 'ethtool_rxfh_indir_default'
include/linux/ethtool.h:769: note: previous definition of 'ethtool_rxfh_indir_default' was here
/lib/modules/3.2.23-rt37.56.el6rt.x86_64/kernel/drivers/net/ethernet/intel/igb-5.7.2/src/igb_main.c:2441: warning: initialization from incompatible pointer type
/lib/modules/3.2.23-rt37.56.el6rt.x86_64/kernel/drivers/net/ethernet/intel/igb-5.7.2/src/igb_main.c:2442: warning: initialization from incompatible pointer type
/lib/modules/3.2.23-rt37.56.el6rt.x86_64/kernel/drivers/net/ethernet/intel/igb-5.7.2/src/igb_main.c:2488: warning: initialization from incompatible pointer type
/lib/modules/3.2.23-rt37.56.el6rt.x86_64/kernel/drivers/net/ethernet/intel/igb-5.7.2/src/igb_main.c:2489: warning: initialization from incompatible pointer type
make[2]: *** [/lib/modules/3.2.23-rt37.56.el6rt.x86_64/kernel/drivers/net/ethernet/intel/igb-5.7.2/src/igb_main.o] Error 1
make[1]: *** [_module_/lib/modules/3.2.23-rt37.56.el6rt.x86_64/kernel/drivers/net/ethernet/intel/igb-5.7.2/src] Error 2
make[1]: Leaving directory `/usr/src/kernels/3.2.23-rt37.56.el6rt.x86_64'
make: *** [default] Error 2

if someone can maybe point out how to avoid the netdev_features_t and ethtool definition errors and just simply what I am doing wrong that would be great.
I also used the .ko file built on another system and copied over the exist .ko
modprobe igb //using .ko file from a newer system says headers are incompatible or incompatible format

so
A: am I doing something wrong with the build process ie didn't fully uninstall the old driver and its conflicting or another issue.
B: I used the latest driver should I use an older one since the kernel is so old
C: can you not use .ko files from other systems or do they have to be compiled against your specific kernel
thoughts and thanks in advance.

A: The driver you are trying to compile is too radically different in age from the kernel you are trying to use it with.  You need to change to a kernel in the correct version range this driver was designed for.
Also, RHEL6 is obsolete, you should upgrade to a supported version, which might also help.


text:
Q: Debugging unexpected results from DCount I have an Access database with two tables:
DaystoCount
|ID|Day      |Day      |
|1 |28-Feb-14|07-Mar-14|
|2 |01-May-14|02-May-14|

and
DaystoExclude
|Day        |
|27-Jan-2014|

I also have the following query, which is mean to find and count any 'DaystoExclude' within the 'DaystoCount':
SELECT  Nz([End],[Start]) AS NEndDate,
        DCount("Day","DaystoExclude","Day >= #" & [Start] & "# and Day <= #" & [NEndDate] & "#") AS ExcludedCount
FROM DaystoCount;

I keep getting the following results from the query:
|NEndDate |ExcludedCount|
|7/03/2014|0            |
|2/05/2014|1            |

As neither of the date ranges include 27-Jan-2014 I am expecting to the following results:
|NEndDate |ExcludedCount|
|7/03/2014|0            |
|2/05/2014|0            |

Can anyone point me in the right direction to where this code is going wrong?  Or suggestions on how to debug this?

A: Try to change your Dcount condition to:
"[Day] >= DateSerial(year(" & [start] & "), month(" & [start] & "), day(" & [start] & ")) or [Day] <= DateSerial(year(" & [nEndDate] & "), month(" & [nEndDate] & "), day(" & [nEndDate] & "))"

This will ensure that date format will not affect condition on [day] field.


text:
Q: PostgreSQL using json_populate_recordset without pre-defined type I am trying to use json_populate_recordset function in plpgsql. Everything works fine when the x is a custom type or table type. But is it possible to use it with something like cusom tyoe definer in execution time? Like we use in CTEs
WITH cte (a int, b int4)?


text:
Q: How to not hardcore my settings for my entity framework core database used by my generic host? While working with the generic host in .net core 2.2, I tried implementing a database project by creating a class that inherits from the DbContext class. So far so good. When I tried implementing the constructor for my Context like this:
public TestContext(DbContextOptions<TestContext> options) : base(options) { }

...and I try to create a migration by using
dotnet ef migrations add InitialCreate

to actually build the database, it shows me the following error:
Unable to create an object of type 'NavisionServicesContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

I also tried defining the startup project with the --startup-project parameter but it doesn't work since I don't have a startup class for my generic host.
The only thing that's working is overriding the OnConfiguring method of the DbContext class. My Problem is that then I have to hardcode my connection string into that method like this:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer("Server = (localdb)\\mssqllocaldb; Initial Catalog = TestDatabase; Trusted_Connection = True; MultipleActiveResultSets = true;");
}

And I haven't found a way to put that connection string into my settings file as I don't know how to use the IConfigurable inside my Context class.
How do I implement a correct database design pattern for my generic host in .netcore 2.2?

A: You need to use Microsoft.Extensions.Options.ConfigurationExtensions to hold config values. And best thing about dotnet core is every functionality is split in different library giving flexibility to add only what is required.
First build a connection setting class to hold values
public class ConnectionSettings
{
    public string DefaultConnectionString { get; set; }
}

And add configuration in config file as
{
  "connectionSettings": {
    "defaultConnectionString": "Here goes your connection setting"
  }
}

Now register this setting class in generic host builder as
IHostBuilder builder = new HostBuilder()
.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
{
    // Assuming config file is configsettings.json
    configurationBuilder.AddJsonFile("configsettings.json", optional: false, reloadOnChange: false);
    // Using Environment variables as well to override any settings provided
    configurationBuilder.AddEnvironmentVariables();
    // Command line args will be highest prioirty
    configurationBuilder.AddCommandLine(args);
})
.ConfigureServices((hostContext, services) =>
{
    IConfigurationSection config = hostContext.Configuration.GetSection("connectionSettings");
    // Adding class to be part of Options
    services.Configure<ConnectionSettings>(config);
});

Now coming to DbContext
public class MyDbContext : DbContext
{
    private IOptions<ConnectionSettings> connectionSettingsOptions;
    public MyDbContext(IOptions<ConnectionSettings> connectionSettingsOptions)
    {
        this.connectionSettingsOptions = connectionSettingsOptions;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(this.connectionSettingsOptions.Value.DefaultConnectionString);
    }
}

Now this connection string can be overridden as per below priority 1 being lowest and 3 being highest because i added them in this order only while configuring generic host builder

*

*Value from config file

*Value from environment variables

*Value from command line args passed as --connectionSettings:defaultConnectionString "myconnectionstring"

Nuget packages used

*

*Microsoft.EntityFrameworkCore (2.2.4)

*Microsoft.Extensions.Configuration.CommandLine (2.2.0)

*Microsoft.Extensions.Configuration.EnvironmentVariables (2.2.4)

*Microsoft.Extensions.Configuration.Json (2.2.0)

*Microsoft.Extensions.Hosting (2.2.0)

*Microsoft.Extensions.Options.ConfigurationExtensions (2.2.0)

Hope this helps!!


text:
Q: Chart.js: Don't stretch axes beyond chart I'm using chart.js 2.9.4 and the ng2-charts wrapper for Angular. I'm trying to display incoming live data, but have trouble configuring the chart so that the ticks/axis don't stretch beyond the data in the chart. In other words, I want the chart data points to fill the entire width of the chart grid.
StackBlitz showing my issue.
If you keep looking at the chart as data is added, you see that most of the time the ticks stretch beyond the last point in the chart:

The only solution I could come up with is overwriting the max value of the ticks on the x-axis each time new data is added to the chart: options.scales.xAxes[0].ticks.max = x;. Uncomment line 68 in the StackBlitz in order to apply this. This solves my problem but introduces another. Sometimes as data gets added, the last two ticks overlap:

I've tried experimenting with various parameters of the scales and ticks options (bounds,distribution,stepSize,source,autoSkip,autoSkipPadding) with no results. Is there any combination of configuration parameters to solve my issue ?

A: You may want to add delay at streaming plugin, the config will look something like:
scales: {
      x: {
        type: 'realtime',   // x axis will auto-scroll from right to left
        realtime: {         // per-axis options
          delay: 1000,      // delay of 1000 ms, so upcoming values are known before plotting a line
          pause: false,     // chart is not paused
          ttl: undefined,   // data will be automatically deleted as it disappears off the chart

        }
      },

I have tested this on your code, and it seems to work as expected, you may want to tune some parameters as needed.


text:
Q: AWS Athena map query The table has a column like this,
data  MAP<string, string>

and rows like,
id | data
1  | {"foo": 123}
2  | {"bar": 456}

Then, how can i search data["bar"] = 456?
I tried but it shows me the error "Column 'bar' cannot be resolved"

A: I found i was wrong.
" shouldn't be used in query. ' should be used!
so,
WHERE data['foo'] = 123

will be worked.

A: I had the same problem, had to resolve by adding the same attribute to all the map data.
You need to have foo and bar in every map data if you want to query on that.
If the property is not there, it does not know how to resolve to that column.
If you access the whole object as it is, then you don't need to have it.
Hope it help.


text:
Q: SQLite file with password protection I'm using sqlite to store some user work information in android mobile app. and weekly create a backup of this database file in different directory(which is accessible).
My main question is this:
Is it possible to set password to open this sqlite file.
like this:

If there are possible advice, please share with me.
Thanks in advance.


text:
Q: Button with same behavior in two distinct components I created a button that changes image depending on its state, start / pause and starts a time count.
I can run the button and run it on two different components, however, the button's image / status doesn't appear, it's just showing me the time :(
How can I solve this?
I successfully run the button on the services component as shown in the image
When I go to the over component, I want to get the exact same state of the button in the services component ... but the button doesn't change state :( This is my problem
HTML

        <button id="button-basic" dropdownToggle type="button" class="btn ">

    </button>

Start

Stop

            {{servicesService.fetchDisplay()}}

A: Modified your code, maintain the state in the service so it can be shared.
Stackblitz


text:
Q: Changing material UI button text based on a condition I am using the material UI button for my component and want to change the button text based on a condition that if order amount is 0, show button text as "cancel" else show "refund". Please help me how can I do the same.
      <Button
        className={classes.refundButton}
        onClick={() => setIsDialogOpen(true)}
      >
        Refund
      </Button>

A: You can use ternary operator for solution.
<Button
  className={classes.refundButton}
  onClick={() => setIsDialogOpen(true)}
  >
    {amount === 0 ? 'Cancel' : 'Refund'}
</Button>

A: You can just store the state and read from there conditionally...
import { useState } from "react"

const [amount, setAmount] = useState(0)

<Button
  className={classes.refundButton}
  onClick={() => setIsDialogOpen(true)}
>
  {amount === 0 ? 'Cancel' : 'Refund'}
</Button>


text:
Q: pf not stopping bruteforce attempts I am setting up an SFTP server for me and my friends and I am trying to stop brute force attempts.
I have read many articles on how to get pf to stop brute force attacks and am not having any luck.
I am running OpenBSD 6.4
Here is  my current /etc/pf.conf
#       $OpenBSD: pf.conf,v 1.55 2017/12/03 20:40:04 s then Exp $
#
# See pf.conf(5) and /etc/examples/pf.conf
set skip on lo
block return    # block stateless traffic
pass            # establish keep-state
# By default, do not permit remote connections to X11
block return in on ! lo0 proto tcp to port 6000:6010
# Port build user does not need network
block return out log proto {tcp udp} user _pbuild
ext_if="em0"
antispoof quick for ($ext_if) #No IP or GPS SPOOFING allowed here :)
table <bruteforce> persist
block quick from <bruteforce>
pass inet proto tcp to any:network port 22 \
        keep state (max-src-conn 10, max-src-conn-rate 5/5, \
         overload <bruteforce> flush global)
table <ssh_block> persist
block quick from <ssh_block> to any

When I checked the tables brute-force and ssh_block they didn't exist. So on ssh_block
I ran the command
pfctl -t ssh_block -T add 218.92.1.138
1 table created.
1/1 addresses added.
pfctl -t ssh_block -T show
218.92.1.138

However my /var/log/authlog is still filling up with attempts from that ip address.
What am I missing?

A: The issue was an error in the /etc/pf.conf file that prevented the firewall from loading its configuration at all (:network applies to a specific interface).
An example of using pf for blocking brute-force connections is given in the OpenBSD PF FAQ, and it boils down to the rules (modified from originally being a www example to something I am using for ssh):
table <bruteforce> persist
block in quick from <bruteforce>

pass in on egress proto tcp to any port ssh flags S/SA keep state \
        (max-src-conn 5, max-src-conn-rate 5/30, \
        overload <bruteforce> flush global)

This would put any host that connects more often than five times every 30 seconds into the <bruteforce> table, which would block it.  It also only allows five connections per source address.
Another option is to use SSHGuard.  There is a port of SSHGuard for OpenBSD, but it's very old (release 1.5 from 2011).  I've just (a few minutes ago) submitted an update to it which will hopefully be committed within a few days.


text:
Q: How can you show and hide the cookies icon in the Chrome address bar? In the picture of a Chrome address bar below, the cookies icon is missing. How is that possible/accomplished?

In this pick below, the address bar contains the cookie icon (which sometimes can have a red x to saw that cookies are disabled.

I am trying to actually figure out a login problem in Chrome for our website.  At certain random times, it appears that cookies don't get set. Other browsers are able to login. The problem then somehow corrects itself.
Trying to gather as much info on cookies in Chrom so any help is appreciated.

A: Icons appear in the address bar only to alert you about blocked or set cookies:

*

*The blocked cookies icon appears whenever a cookie has been blocked on the page you're viewing, even if you've allowed all local data by default, due to exceptions you've made for specific domains.

*The allowed cookies icon appears whenever cookies have been set on the page you're viewing, even though you've blocked all cookies by default, due to exceptions you've made for specific domains.

That means that when these conditions are not fulfilled, no icon will be displayed. See Manage your cookies and site data for more details.


text:
Q: How can import a wsdl file in Delphi offline? I have a web service and an outsource company will use my service. I don't want to open my service to the internet. I want to give only wsdl file to the outsource company. They use Delphi. Is this possible importing a wsdl file in Delphi offline?

A: Yes is possible, Delphi can import a WSDL file stored locally.
In Delphi Win32 Go to
File->New->Others->Delphi projects->WebServices->WSDL Importer

Then you get a dialog that prompts you for the location of the WSDL file.  From the WSDL, Delphi generates a unit with interfaces  for the classes and objects exposed by the webservice.  after that creates the file with the name of the service with the extension '.pas'.

In Delphi .Net Go to
Project->Add Web Reference
Select the file to import and press "Add reference"

Bye.

A: Sure!
Just provide them with the wsdl as a file. The WSDL Importer can import from a URL or from a file.


text:
Q: Filter and compare with UTC time i want to run a code that starts from 10:00:00 from Monday(UTC time) till 20:00:00 Friday(UTC time).
Firstly, i used utcnow() function to get hours and minutes
from datetime import datetime
UTC_time = datetime.utcnow()
current_UTC_time = (datetime.utcnow()).time()

Then tried to extract week name
UTC_week_name = (datetime.utcnow()).strftime('%A')

After that unable to devise any comparison?

A: Update
If you want to run every two hours starting from Monday 10 AM til Friday midnight then you can split this into two cron jobs.
One for Monday: 0 0 10/2 ? * MON *
Another one for Tues-Fri: 0 0 0/2 ? * TUE,WED,THU,FRI *
This website can help you create cron expressions if you need it.
I hope it helps.

The approach you are using is very inefficient as the python process to check the time will be getting executed at every moment.
There is a system-utility known as cron jobs. You can use it to schedule jobs. This link provides a detailed expression.
For your job, the following would be the cron-job expression.
0 0 10 ? * MON *


text:
Q: How to open JavaFX .jar file with JDK 11? I created a JavaFX project in IntelliJ.
I can run project in IntelliJ. I added below code in Configurations):
--module-path ${PATH_TO_FX} --add-modules=javafx.controls,javafx.fxml

But the output .jar file of project (made with Artifects) doesn't run. I tested these commands, but didn't get any chance:
java  --module-path %PATH_TO_FX% --add-modules javafx.controls,javafx.fxml -jar Timer.jar
java  --module-path %PATH_TO_FX% --add-modules javafx.controls  Timer.jar

Last error log of command line:
Error: Could not find or load main class Files\Java\javafx-sdk-11.0.1\lib
Caused by: java.lang.ClassNotFoundException: Files\Java\javafx-sdk-11.0.1\lib

p.s: I could run .jar file of this project when build on JDK-10
EDIT:
I downloaded JavaFX and added it's lib folder to System Environments.
for adding JavaFX to project I did this process:
Project Structure > Libraries > add > Java > JavaFxPath/lib
Then I created Artifect for output jar file in this process:
Project Structure > Artifects > Add > JAR > From Modules with dependencies > main Class : main.Main.

A: I had the similar issue exporting/generating an Jar using JavaFX and IntelliJ Non-modular with Gradle (https://openjfx.io/openjfx-docs/)
The jar I was generating using Gradle jar command does not run and throws error saying it can not find my Main Class. When I opened my jar I was able to locate my main class. So I realized the error has to do with Jar Packaging.

I fixed the problem by adding JavaFX SDK to my Java SDk in IntelliJ as shown below.

After this I use the regular Gradle build Jar command to generate my Jar file (as shown below) and it runs Normally.

A: Providing you have a simple (non-modular) JavaFX 11 project (without Maven/Gradle build tools), and you are using IntelliJ, like the HelloFX sample from here,
 this is how you can create a jar from IntelliJ that can be run from the console
A full tutorial on how to run the project can be found here, and instructions on how to create a jar are here (see section Non-modular project), but these doesn't cover Artifacts from IntelliJ.
Check that the HelloFX project runs from IntelliJ with these VM options:
--module-path ${PATH_TO_FX} --add-modules javafx.controls,javafx.fxml

where PATH_TO_FX has been set in File -> Settings -> Appearance & Behavior -> Path Variables, pointing to the JavaFX SDK lib.
Semi fat Jar
We can create a Jar that only contains the classes from the project, and third party dependencies, but not JavaFX ones.
Go to File -> Project Structure -> Artifacts -> Add -> JAR -> From modules with dependencies, add your main class, accept.
Then remove the JavaFX jars from the list, and accept.

Build the project, it will create a quite small jar (3 KB in this case).
Now you should be able to run it like:
java --module-path %PATH_TO_FX% --add-modules javafx.controls,javafx.fxml -jar out\artifacts\HelloFX_jar\HelloFX.jar

(make sure that %PATH_TO_FX% points to a valid folder and use quotes if it contains spaces.
You can distribute this jar, and run it in other platforms, providing those also have the JavaFX SDK.
Fat Jar
If you want a full fat jar that includes JavaFX dependencies, you can still use Artifacts.
Go to File -> Project Structure -> Artifacts -> Add -> JAR -> From modules with dependencies, add your main class, accept.
Then keep the JavaFX jars from the list, and accept. Build the project.
In theory, you should be able to run it like:
java -jar out\artifacts\HelloFX_jar\HelloFX.jar

But this won't work.
Reason 1: You need a launcher class, as explained here.
So create a launcher class:
public class Launcher {

    public static void main(String[] args) {
        Main.main(args);
    }
}

Reason 2: If you only add your SDK jars to the fat jar, you will be missing the native libraries, as explained here.
So edit the artifact, select the Launcher class as main class, and add the native libraries (Directory Content -> path-to/JavaFX SDK/bin on Windows):

Now build the project (now the jar is about 33 MB, and contains unnecessary native libraries) and run:
java -jar out\artifacts\HelloFX_jar\HelloFX.jar

You can distribute this jar, but only to Windows platforms.
You can create similar jars for other platforms, if you download their JavaFX SDKs, and you can also build cross-platform jars if you add them all together, as explained in the linked answers above.
Anyway, you should consider using jlink instead.
Note
About this error:

Caused by: java.lang.ClassNotFoundException: Files\Java\javafx-sdk-11.0.1\lib

it looks like the library path was set without quotes and it is missing the first part of the path C:\Program Files\.... Just make sure you use quotes:
set PATH_TO_FX="C:\Program Files\Java\javafx-sdk-11.0.1\lib"

A: The easiest way to do this is to use an OpenJDK build that include JavaFX.  Both Bellsoft and Azul produce such builds.
For Azul's Zulu builds of OpenJDK:
https://www.azul.com/downloads/zulu-community/?version=java-11-lts&package=jdk-fx
For Bellsoft Liberica JDK:
https://bell-sw.com/pages/downloads/#/java-11-lts
and choose "Full JDK"
These builds are basically OpenJDK with the OpenJFX JavaFX modules added.  Though be careful as some aspects of JavaFX may not be supported on LibericaFX.  See https://bell-sw.com/pages/liberica-release-notes-11.0.9.1/

A: The above answers apply to non-modular JavaFX projects. To get a modular JavaFX project (with modular dependencies) running I used jlink.
Take the JavaFX SDK from https://gluonhq.com/products/javafx/; unzip the files to a directory, and point a shell variable JFX_LIB to the unzipped lib/ directory.
Take the JavaFX jmods (not SDK) file from https://gluonhq.com/products/javafx/; unzip the jmods, they are in a folder similar to javafx-jmods-11.0.2/. Point a shell variable JMOD_PATH to the unzipped directory javafx-jmods-11.0.2/.
Compile, sending your compiled classes to the directory mods/:
javac -d mods  --module-source-path src --module-path $JFX_LIB/javafx.graphics.jar:$JFX_LIB/javafx.base.jar:$JFX_LIB/javafx.controls.jar --module com.mymodule

Create a custom JRE with jlink, referring to the module path containing the JavaFX mods and your own compiled mod:
jlink --module-path $JMOD_PATH:mods --add-modules com.mymodule --output customjre

Run:
customjre/bin/java --module com.mymodule/com.mymodule.Main

(I tried for a LONG TIME to get a java -jar running with --module-path and --add-modules. I always got the following error:)
Error: Could not find or load main class com.mymodule.Main
Caused by: java.lang.NoClassDefFoundError: javafx/application/Application


text:
Q: How to select both boolean values or one I have a ternary operator as below for a LINQ query as shown
 var sub = (SubordinationType == 1) ? (true&false) : false;

var query = from vw in dbContext.vw
                            where (vw.office == FieldOffice && vw.SubAgreement == sub)
                            select vw;

Here SubAgreement is a bit field in database I need to select both true and false(0,1) or false(0) based on the ternery how do i achieve this?
Any quick suggestions please.

A: I think I get your question.  Your logic is:

*

*If Subordination is 1, SubAgreement doesn't matter (true or false)

*If Subordination is not 1, SubAgreement should be false

hence add another condition:
//..
where (vw.office == FieldOffice && (Subordination == 1 || !vw.SubAgreement))

A: Try something like:
var query = from vw in dbContext.vw
            where vw.office == FieldOffice
            select vw;

if (SubordinationType != 1)
{
    query = query.Where(vw => vw.SubAgreement == false);
}

In LINQ it's very easy to add new where clauses that are in && with the other clauses (note that it's only easy to add if you want them to be in &&, the || case is much more complex! :-) )

A: You can make a condition that is true when SubordinationType is 1 or when SubAgreement is false:
var query = from vw in dbContext.vw
  where (vw.office == FieldOffice && (SubordinationType == 1 || vw.SubAgreement == false))
  select vw;


text:
Q: Looking for Geocoding / Mapping advice for iPad development Some friends of mine and I are developing an app for rural service providers in our state to take their lists of customers' addresses and plot them onto a pannable map to not only display the locations, but to interact with the database information stored on our servers as well (updates from service calls, deliveries, sales, etc.).
We are new to iPad development (two of us are familiar with Android development but the potential clients are invested in iOS technology), and we have run into a geocoding quandary. It seems that our plans for geocoding would either run afoul Google's geocoding / maps APIs, or require that hefty $10,000 business license.
As a workaround, we've been thinking about hosting an Open Street Map tile server for one  village as a demonstration piece for sales purposes, and dealing with any commercial licensing if and when the product is successful.
I guess my question is out of ignorance. Does anyone have experience creating native, for-profit iOS apps that utilize Google Maps APIs (maps, directions, geolocating)? If so, is Google the best suite of tools, or would another engine be a better fit (Bing, MapQuest, Yahoo!)? Is there another better, simpler, more elegant solution to getting these locations on the map?
Thanks for any insight you can provide.

A: I work at SmartyStreets where we maintain a geocoding (and verification) API called LiveAddress. I figure you're running into TOS and volume limits with Google/Bing/etc APIs. LiveAddress has a much more flexible TOS.
I'm aware of several very prominent iOS developers which use LiveAddress with their apps in the app store and have found it to be very worthwhile. Keep in mind that unlike regular geocoding APIs, LiveAddress will confirm the validity and completeness of the address instead of approximating it, while returning only valid suggestions if needed. This will help ensure that only high-quality data goes into your database and thus, into your customers' hands.
As Jesse mentioned, iOS 6 has some spiffy new maps built-in, so you may consider looking into using those. I'm not sure what the implications are as far as availability and licensing, maybe there aren't any since it's so proprietary to just iOS devices. Let me know what you find, I'd be interested to know!

A: MapQuest offers an iOS Maps API, which allows you to choose between 'regular' MapQuest tiles that are generated from licensed (commercial) data sources, or, the MapQuest-OSM tiles that are free and generated from OpenStreetMap data.  The iOS Maps API was in beta for the past few months, but the first production version of the API was just released.
As far as geocoding is concerned, a MapQuest Enterprise Solutions account manager could answer those questions and possibly quote you a price for an enterprise license if it is needed for what you would like to accomplish with your app.  Enterprise licenses provide an SLA, Technical Support, etc.  I believe the Community Edition license (free, but licensed data - not OpenStreetMap data) allows for 5,000 geocodes per day.
The forums on the MapQuest Developer Network are also a good resource for finding answers to questions about the iOS Maps API, so be sure to take a look!
Hope this information is helpful!

A: you should look into the new features of iOS 6 with your developer's access to Apple

A: I did some research into this a few weeks back and the only pricing info I found (without contacting the relevant companies) was that Bing is 'probably' cheaper than Google Maps. But on another note Apple are working on their own maps software because they're not happy with the price tag of Google Map's - so as Jesse says, look into that.
Edit:
Google maps for business starts at $11,000 USD


text:
Q: Weak assassins and essential morphisms Let $R$ be a commutative ring and let $M\rightarrow N$ be an essential morphism of $R$-modules. Then, $M$ and $N$ have the same associated primes.
Over non-noetherian rings the notion of associated primes does not behave very well, and it is sometimes appropriate to rather consider the so-called weakly associated primes of a module. (A prime ideal of $R$ is weakly associated with an $R$-module $L$ if it is a minimal prime of the annihilator of an element of $L$; see Bourbaki, AC.IV.1 Exer. 17, for basic facts about this notion.)
Unfortunately, if $M\rightarrow N$ is an essential morphism of $R$-modules then $M$ and $N$ need not have the same weakly associated primes. (This happens for example over every non-noetherian valuation ring with maximal ideal of finite type.)
This leads to the following question:

What are examples of (classes of) non-noetherian rings over which weakly associated primes do not change along essential morphisms?

EDIT: A sufficient condition is that weakly associated primes and associated primes coincide for every module. This happens e.g. for one-dimensional valuation rings. So, a sub-question of the above is the following:

What are examples of (classes of) non-noetherian rings over which weakly associated primes coincide with associated primes for every module?

EDIT 2: Neil pointed out, and rightly so, that in the previous edit I wrote some nonsense. Weakly associated primes and associated primes coincide for every module for example if $R$ is a local domain such that every non-zero ideal of $R$ contains a power of the maximal ideal. What I intended to say about one-dimensional valuation rings has in fact nothing to do with valuation rings, but should rather be the following: One-dimensional local domains are an example of a class of not necessarily noetherian rings that have the property asked for in the original question, i.e., weakly associated primes do not change along essential morphisms.


text:
Q: How is the ordering of the Geocoding results determined? I was wondering: When geocoding an address using Google's Geocoding API, based on which criteria are the results inside the result array ordered?
Is the first result also the most relevant or are they appear in random, or?
The documentation doesn't mention anything about this.

A: In my experience, the best score is first. I don't know if Google designed it that way, or if that was just how the results were returned in my case. Also, in most cases there is a single 100 score result.


text:
Q: Is there a Perfect/Model ASP.Net Website for Learning Purposes? I'm looking for a 'model' website/application written in ASP.Net that illustrates current best-practices of architecture, design, code etc. that could be used as a blueprint for development?
I'm working in ASP.Net webforms, but would like to get into MVC so examples from both would be very welcome.
Thanks.

A: You can have a web site that uses ASP.NET MVC and ASp.NET Webforms at the same time. Google it and you'll find dozens of samples. But if you weant to see an example of how to implement MVC Pattern* in ASp.NET Webforms projects, take a look at:  http://www.codeproject.com/KB/aspnet/mvcwebforms.aspx

A: It is very hard to find full blown best open source asp.net MVC sites. Here's the ones that go beyond beginner concepts.

*

*Code Camp Server

*Kona

*Orchard

*Kobe... where are you?

A: Nerd Dinner might be worth a look for MVC, it comes with a 185 page pdf walkthough of the code with screenshots. I think it was built as an example for the book ASP.NET MVC 1.0.
There's a bit more info on Scott Guthrie's blog


text:
Q: Solution to second order non constant differential equation without first derivative Cheers!
So I am studying the book 'Introduction to quantum mechanics' by David J. Griffiths for my introductory course of quantum mechanics. On page 51 at the bottom it introduces the differential expression:
\begin{equation}
\Phi'' = \xi^2 \Phi
\end{equation}
Without saying much further, it presents the general solution as:
\begin{equation}
\Phi = A e^{-\xi^2/2} + B e^{\xi^2/2}
\end{equation}
Indeed, when I check this solution with the differential equation, I can see that it can match it. However I am still completely missing on how one would arrive from the differential equation to the general solution.
I have already been trying several different methods, all unsuccessful, so I would indeed appreciate any help I could get.

A: For solving $y''-(\xi^2-K)y=0$ we have solution
$$y=Ae^{\sqrt{\xi^2-K}}+Be^{-\sqrt{\xi^2-K}}~~~~~,~~~~~\xi^2-K>0$$
with $\xi>>K$
$$\sqrt{\xi^2-K}=\sqrt{-K}\sqrt{1-\dfrac{\xi^2}{K}}=\sqrt{-K}\left(1-\dfrac{\xi^2}{K}\right)^\frac12\approx\sqrt{-K}\left(1-\frac12\dfrac{\xi^2}{K}\right)\approx\sqrt{-K}\left(-\frac12\dfrac{\xi^2}{K}\right)\approx\dfrac{\xi^2}{2i\sqrt{K}}\approx\dfrac{\xi^2}{2}$$


text:
Q: 2d data set as contour There is a set of data in the form of a table that I import into Mathematica:
https://dropmefiles.com/7BXAE
a = Import["To.mat"];

a = Partition[Flatten[a], 3];

Then I plot $x,y$ on the plane:
data = Transpose@{a[[All, 1]], a[[All, 2]]};

And I get the following picture:
ListPlot[data]

Desired result that I need:

That is, I need the place where the points are concentrated (where they are built) to be represented as a contour or surface. How to do it with Mathematica commands?

A: Using the free cloud account (since I don't have ConcaveHullMesh on v12.2.0-Win7-x64)
pts = RandomPoint[Annulus[{0, 0}, {50, 100}], 100];
{m1=ConcaveHullMesh[pts],m2= DelaunayMesh[pts]};
reg=BoundaryDiscretizeRegion[m1];
Show[reg,Graphics[{Red,MeshPrimitives[reg,1]}],Graphics[{Black,Point@pts}]]

A: *

*Using the data a  as @BobHanlon show in the comment.

*Using RegionDilation to inflate every point.

a = Import["To.mat",
     "IndeterminateValues" -> 999999] /. {999999. -> Nothing} /. {} ->
     Nothing;
reg = MeshRegion[a[[1]], Point /@ Range@Length@a[[1]]];
dilation = RegionDilation[reg, .3];
Show[Region[RegionBoundary[dilation], BaseStyle -> Red],
 Region[reg, BaseStyle -> Blue]]

A: Using fake data since we can't access your actual data:
data = Flatten[Table[{x, y}, {x, -1, 1, .1}, {y, -1, 1, .1}], 1];
data // Short
(* {{-1., -1.}, {-1., -0.9}, <<437>>, {1., 0.9}, {1., 1.}} *)

Now, let's add some z data so we can generate contours:
Raise[{x_, y_}] := If[RegionDistance[Circle[], {x, y}] < .2, {x, y, 1}, {x, y, 0}];
newData = Map[Raise, data, {-2}];
newData // Short
(* {{-1., -1., 0}, {-1., -0.9, 0}, <<437>>, {1., 0.9, 0}, {1., 1., 0}} *)

Now ListContourPlot can do the job:
ListContourPlot[newData, Contours -> 1]

All of this assumes that you can augment your data as needed. It looks like your data is on a grid/lattice, so I assume that this is feasible.

A: I just learned about ReconstructionMesh. So, taking a similar approach as Syed:
pts = RandomPoint[Annulus[{0, 0}, {50, 100}], 100];
reg = BoundaryDiscretizeRegion[ReconstructionMesh[pts]];
Show[reg, Graphics[{Red, MeshPrimitives[reg, 1]}], Graphics[{Black, Point@pts}]]

A: The following will essentially duplicate what you did by hand (although the dataset you provided isn't quite the same dataset shown in your question).
If you need to have the contours more "shrink-wrapped" to the outside border or something completely automatic, then you'll need something else as I tried a few different values for the kernel bandwidth and the contour value.
a = Import["c:\\users\\drjba\\Downloads\\To.mat",
     "IndeterminateValues" -> 999999] /. {999999. -> Nothing} /. {} -> Nothing;
skd = SmoothKernelDistribution[a[[1]], {0.25, 0.25}];
Show[ContourPlot[PDF[skd, {x, y}], {x, -6, 4}, {y, -5, 5},
  Contours -> {0.0023}, ContourShading -> None], ListPlot[a[[1]]]]

A completely automatic way is to allow the default bandwidth to be selected and then choose the contour that encompasses all points.
skd = SmoothKernelDistribution[a[[1]], "SheatherJones"];
pdf = PDF[skd, {#[[1]], #[[2]]}] & /@ a[[1]];
Show[ContourPlot[PDF[skd, {x, y}], {x, -6, 4}, {y, -5, 5},
  Contours -> {Min[pdf]}, ContourShading -> None,
  PlotPoints -> 100], ListPlot[a[[1]]]]


text:
Q: Is there a web service engine able to wrap queries in a (SOAP) web service? We have a very heterogeneus it environment, made of a main RDBMS (informix) and many aother RDBMSs (postgres, MS Sql, MySql...) due to several independent products acquired over time.
We need to read (just read) data from all these heterogeneus RDBMSs from within our main environment and we want to do it with web services (very likely SOAP ones) because of future rise of internal mobile applications.
I would like to set up (or write) a web services server that acts as a "wrapper" for all different databases, and it should more or less this way:
a) the tipical request should specify host, database and selection query and the typical response would be a recordset in xml form, like this for example:
<recordset>
    <row>
        <field1>content of field 1</field1>
        <field2>content of field 2</field2>
        ...
    </row>
</recordset>

b) It will run inside a "friendly" environment, queries wll be written just by IT dep. programmers, and will NEVER be accessibe from outside; this way security issues should be satisfied
My question is: before reinventing the wheel, is there something ready-made or similar in the open source community?
The product should allow general queries and should not force to write a web mehod for each query...
I was not able to find such a product; Oracle seem to have something similar as a feature but Oracle is one of the few RDBMSs we currently do not have and this feature seems to expose just Oracle RDBMS as a web service, not any in the local network
Thank you in advance


text:
Q: PL/SQL Trigger Issues I am trying to write a trigger to populate a table containing information on an employee's updated salary. I'm having a problem that I can't quite wrap my head around at the moment.
Here is the table to be populated:
 drop table SalUpdates cascade constraints;
 create table SalUpdates(
 SalSSN char(9),
 newSalary decimal(10,2),
 oldSalary decimal(10,2)

 );

This is my trigger:
 create or replace trigger t1
 after update of salary on employee
 for each row
 begin
 insert into SalUpdates values (:old.Ssn, :new.salary, :old.salary);
 end;

The trigger compiles with no issues, but when I try to run this update, Oracle tells me my trigger is invalid. What could be causing this?
update employee
set salary=4000
where ssn='123456789';

A: You've shown the code in chunks. but it seems you're running what you've shown together as a script, initially without the update:
drop table SalUpdates cascade constraints;
create table SalUpdates(
SalSSN char(9),
newSalary decimal(10,2),
oldSalary decimal(10,2)
);

create or replace trigger t1
after update of salary on employee
for each row
begin
insert into SalUpdates values (:old.Ssn, :new.salary, :old.salary);
end;

When run as a script in SQL Developer the script output window shows:
drop table SalUpdates cascade constraints
Error report -
ORA-00942: table or view does not exist
00942. 00000 -  "table or view does not exist"
*Cause:
*Action:

Table SALUPDATES created.

Trigger T1 compiled

If you then add the update statement to the script:
drop table SalUpdates cascade constraints;
create table SalUpdates(
SalSSN char(9),
newSalary decimal(10,2),
oldSalary decimal(10,2)
);

create or replace trigger t1
after update of salary on employee
for each row
begin
insert into SalUpdates values (:old.Ssn, :new.salary, :old.salary);
end;

update employee
set salary=4000
where ssn='123456789';

you get:
Table SALUPDATES dropped.

Table SALUPDATES created.

Trigger T1 compiled

Errors: check compiler log

If you then try to run the update on it's own (as a statement instead of a script; or by selecting that test and running as a script) you do indeed get:
SQL Error: ORA-04098: trigger 'MYSCHEMA.T1' is invalid and failed re-validation
04098. 00000 -  "trigger '%s.%s' is invalid and failed re-validation"
*Cause:    A trigger was attempted to be retrieved for execution and was
           found to be invalid.  This also means that compilation/authorization
           failed for the trigger.
*Action:   Options are to resolve the compilation/authorization errors,
           disable the trigger, or drop the trigger.

If you query the user_errors view, or run show errors, you'll see:
PLS-00103: Encountered the symbol "UPDATE"

The problem is that you aren't completing the create trigger statement properly. The update is being seen as part of the same PL/SQL block; an invalid part, but still included.
When you have a PL/SQL block you have to terminate it with a slash, as it explains in the SQL*Plus documentation (which mostly applies to SQL Developer too):

SQL*Plus treats PL/SQL subprograms in the same manner as SQL commands, except that a semicolon (;) or a blank line does not terminate and execute a block. Terminate PL/SQL subprograms by entering a period (.) by itself on a new line. You can also terminate and execute a PL/SQL subprogram by entering a slash (/) by itself on a new line.

SQL Developer doesn't complain if the last block in a script doesn't have a terminating slash though, so your original script (without the update) works; in SQL*Plus it would sit at a prompt. It kind of infers that it should be there - trying to be helpful. When you add the update statement it is no longer the end of the script so that doesn't apply.
If you add a slash to your script between the PL/SQL code and the following SQL statement it all works:
drop table SalUpdates cascade constraints;
create table SalUpdates(
SalSSN char(9),
newSalary decimal(10,2),
oldSalary decimal(10,2)
);

create or replace trigger t1
after update of salary on employee
for each row
begin
insert into SalUpdates values (:old.Ssn, :new.salary, :old.salary);
end;
/

update employee
set salary=4000
where ssn='123456789';

and you now see:
Table SALUPDATES dropped.

Table SALUPDATES created.

Trigger T1 compiled

1 row updated.


text:
Q: How can I bind ngModel through multiple directives with isolate scopes in AngularJs? I am trying to bind to a property via ngModel in a layer of directives 3 levels deep. This would be fine, except the middle level contains a ng-if which I believe creates a new scope. The binding is lost at this point.
I have created a jsfiddle to explain the situation:
http://jsfiddle.net/5fmck/2/
Note that it works if the ng-if directive is removed, but I am using ng-if instead of ng-show for performance reasons
Does anyone know how I can get the original ngModel to update from the 'inputDirective' template in the fiddle?

A: Simple :3
Just remember, that child scope is created = use reference to $parent :)

    In Wrapper
    <input-directive ng-model='$parent.ngModel'></input-directive>

http://jsfiddle.net/5fmck/3/
// upd
As I know you need to use reference to $parent only if ngModel is primitive, not object.

A: I suspect this is due to the nature of how scopes inherit from each other, and so you should use objects on the scope, and not primitives, and always pass the objects into directives via attributes if it's to be then to be used in another scope. So instead of:
$scope.test = "test";

and
<wrapper-directive ng-model="test" some-condition="true">

use:
$scope.userInput = {
  test: "Test"
}

and
<wrapper-directive user-input="userInput" some-condition="true">

Which can be seen at http://jsfiddle.net/4RBaN/1/ (I've also changed all-but-one of the ngModels to another custom attribute, as if you're not using ngModel specific things, like ngModelController, or integration with ngForm, then I think better to KISS).
The reason is that if you have 2 scopes in a parent/child relationship (via prototypical inheritance), such as the one created by ngIf, if you execute (or if Angular executes):
$parentScope.test = 'test';
$childScope.test = 'My new value';

Then $parentScope.test will still equal 'test'. However, if you use objects:
$parentScope.userInput = {test: 'test'}
$childScope.userInput.test = 'My new value';

Then $parentScope.userInput.test will then equal 'My new value'.
The standard quote from (whom I believe was) the original author of Angular, is "If you haven't got a dot in your model, you're doing it wrong". There are other questions on SO about this, such as If you are not using a .(dot) in your AngularJS models you are doing it wrong?
Edit: If you do want to use ng-model, and always pass a primitive to the directive, and not an object, then there is a way that allows this. You'll need to:

*

*Always ensure there is a dot in the model that is passed to ngModel, in every directive. Each directive therefore needs to create a new object on its scope in its controller (or linking function). So the template for your 'middle' directive will be:
<input-directive ng-model='userInput.test'>

And in its controller:
$scope.userInput = {
  test: $scope.ngModel
}

Where ngModel is bound to the value specified in the directive's attributes:
"scope" : {
  "ngModel" : "="
}

*Set up manual watchers in each directive, so that changes to the model from the inner directives get propagated back up the chain:
$scope.$watch('userInput.test', function(newTest) {
  $scope.ngModel = newTest;
});

This can be seen at: http://jsfiddle.net/zT9sD/ . I have to say, it feels a bit complicated, so I'm not quite sure I can recommend it. Still, (in my opinion) better than using $parent, as introducing a new scope can quite easily happen as things get more complicated, and then you'll have to use things like $parent.$parent.


text:
Q: How do I make my own recordedPath in GLPaint Sample Code I've recently downloaded the GLPaint sample code and looked at a very interesting part in it. There is a recordedPaths NSMutableArray that has points in it that are then read and drawn by GLPaint.
It's declared here:
NSMutableArray *recordedPaths;
recordedPaths = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Recording" ofType:@"data"]];
if([recordedPaths count])
     [self performSelector:@selector(playback:) withObject:recordedPaths afterDelay:0.2];

This is the code for playback:
 - (void) playback:(NSMutableArray*)recordedPaths {

     NSData*                    data = [recordedPaths objectAtIndex:0];

     CGPoint*               point = (CGPoint*)[data bytes];

     NSUInteger               count = [data length] / sizeof(CGPoint),

                              i;

     //Render the current path

     for(i = 0; i < count - 1; ++i, ++point)

          [self renderLineFromPoint:*point toPoint:*(point + 1)];

     //Render the next path after a short delay

     [recordedPaths removeObjectAtIndex:0];

     if([recordedPaths count])

          [self performSelector:@selector(playback:) withObject:recordedPaths afterDelay:0.01];

}

From this I understand that recordedPaths is a mutable array that his in it struct c arrays of CGPoint that are then read and rendered.
I'd like to put in my own array and i've been having trouble with that.
I tried changing the recordedPaths declaration to this:
      NSMutableArray *myArray = [[NSMutableArray alloc] init];

      CGPoint* points;

      CGPoint a = CGPointMake(50,50);

      int i;

      for (i=0; i<100; i++,points++) {

           a = CGPointMake(i,i);

           points = &a;

      }

      NSData *data = [NSData dataWithBytes:&points length:sizeof(*points)];

      [myArray addObject:data];

This didn't work though...
Any advice?

A: If you look at the Recording.data you will notice that each line is its own array.  To capture the ink and play it back you need to have an array of arrays.  For purposes of this demo - declare a mutable array - writRay
    @synthesize writRay;
//init in code
 writRay = [[NSMutableArray alloc]init];

Capture the ink
// Handles the continuation of a touch.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{

 CGRect    bounds = [self bounds];
 UITouch*   touch = [[event touchesForView:self] anyObject];

 // Convert touch point from UIView referential to OpenGL one (upside-down flip)
 if (firstTouch) {
  firstTouch = NO;
  previousLocation = [touch previousLocationInView:self];
  previousLocation.y = bounds.size.height - previousLocation.y;
  /******************* create a new array for this stroke's points **************/
  [writRay addObject:[[NSMutableArray alloc]init]];
  /***** add 1st point *********/
  [[writRay objectAtIndex:[writRay count] -1]addObject:[NSValue valueWithCGPoint:previousLocation]];
 } else {
  location = [touch locationInView:self];
     location.y = bounds.size.height - location.y;
  previousLocation = [touch previousLocationInView:self];
  previousLocation.y = bounds.size.height - previousLocation.y;
  /********* add additional points *********/
  [[writRay objectAtIndex:[writRay count] -1]addObject:[NSValue valueWithCGPoint:previousLocation]];
 }

 // Render the stroke
 [self renderLineFromPoint:previousLocation toPoint:location];

}

Playback the ink.
- (void)playRay{

 if(writRay != NULL){

  for(int l = 0; l < [writRay count]; l++){
    //replays my writRay -1 because of location point
   for(int p = 0; p < [[writRay objectAtIndex:l]count] -1; p ++){
    [self renderLineFromPoint:[[[writRay objectAtIndex:l]objectAtIndex:p]CGPointValue] toPoint:[[[writRay objectAtIndex:l]objectAtIndex:p + 1]CGPointValue]];
   }
  }
 }
}

For best effect shake the screen to clear and call playRay from changeBrushColor in the AppController.

A:   CGPoint* points;
  CGPoint a = CGPointMake(50,50);
  int i;
  for (i=0; i<100; i++,points++) {
       a = CGPointMake(i,i);
       points = &a;
  }
  NSData *data = [NSData dataWithBytes:&points length:sizeof(*points)];

Wrong code.
(1) You need an array of points. Simply declaring CGPoint* points; won't create an array of points, just an uninitialized pointer of CGPoint. You need to allocate space for the array either with
CGPoint points[100];

or
CGPoint* points = malloc(sizeof(CGPoint)*100);

Remember to free the points if you choose the malloc way.
(2) To copy value to the content of the pointer you need to use
*points = a;

But I suggest you keep the pointer points invariant in the loop, since you're going to reuse it later. Use the array syntax points[i].
(3)
sizeof(*points)

Since *points is just one CGPoint, so the sizeof is always 8 bytes. You need to multiply the result by 100 to get the correct length.
(4)
 [NSData dataWithBytes:&points ...

points already is a pointer to the actual data. You don't need to take the address of it again. Just pass points directly.

So the final code should look like
  CGPoint* points = malloc(sizeof(CGPoint)*100); // make a cast if the compiler warns.
  CGPoint a;
  int i;
  for (i=0; i<100; i++) {
       a = CGPointMake(i,i);
       points[i] = a;
  }
  NSData *data = [NSData dataWithBytes:points length:sizeof(*points)*100];
  free(points);

A: I was just reading over this post as I am trying to achive a similar thing. With modifications to the original project by Apple, I was able to create a new 'shape' by modifying the code accordingly.
Note that it only draws a diagonal line... several times. But the theory is there to create your own drawing.
I've taken the code from KennyTM's post and incorporated it into the 'payback' function, this could be adapted to create the array in the initWithCoder function and then send it through like the original code but for now - this will get you a result.
    CGPoint* points = malloc(sizeof(CGPoint)*100);
CGPoint a;
int iter;
for (iter=0; iter<200; iter++) {
    a = CGPointMake(iter,iter);
    points[iter] = a;
}
NSData *data = [NSData dataWithBytes:points length:sizeof(*points)*100];
free(points);

CGPoint*            point = (CGPoint*)[data bytes];
NSUInteger      count = [data length] / sizeof(CGPoint),
                    i;

for(i = 0; i < count - 1; ++i, ++point)
    [self renderLineFromPoint:*point toPoint:*(point + 1)];

[recordedPaths removeObjectAtIndex:0];
if([recordedPaths count])
    [self performSelector:@selector(playback:) withObject:recordedPaths afterDelay:0.01];

I am still in my first weeks on openGL coding, so forgive any glaring mistakes / bad methods and thanks for the help!
Hope this helps


text:
Q: Unable to install VirtualBox Guest Additions for Ubuntu 18.04 I have installed Ubuntu 18.04 in Oracle virtual box but I am not able to install Guest Additions to maximize the Ubuntu screen.
I have run the following command in the Ubuntu terminal but when I click "Devices => Insert Guest Addition CD Image" I get an error that unable to insert virtual optical disk. How to fix the issue ? I need to maximize the Ubuntu screen.
sudo apt install build-essential dkms linux-headers-$(uname -r)


text:
Q: function that organizes items by category I need to finish a function that starts:
function organizeItems(items) {

I need to finish that to organize a list of categories. my categories are fruit, dairy, and canned. My code looks like this:
[
  { category: 'fruit', itemName: 'oranges', onSale: false },
  { category: 'dairy', itemName: 'milk($)', onSale: true },
  { category: 'canned', itemName: 'peas', onSale: false },
  { category: 'canned', itemName: 'green beans($)', onSale: true },
  { category: 'fruit', itemName: 'grapes($)', onSale: true },
  { category: 'canned', itemName: 'carrots', onSale: false },
];

So how do I function this to return a list like:
{
  fruit:  ['apple', 'melon($)'],
  canned: ['beans', 'corn($)', 'soup'],
  frozen: ['pizza']
};

A: I would do this via the reduce function:

const items=[{category:'fruit',itemName:'oranges',onSale:false},{category:'dairy',itemName:'milk($)',onSale:true},{category:'canned',itemName:'peas',onSale:false},{category:'canned',itemName:'green beans($)',onSale:true},{category:'fruit',itemName:'grapes($)',onSale:true},{category:'canned',itemName:'carrots',onSale:false},];

const categorised = items.reduce((a, { category, itemName }) => {
  a[category] = a[category] || [];
  a[category].push(itemName);
  return a;
}, {});

console.log(categorised);
.as-console-wrapper {
  max-height: 100% !important;
  top: auto;
}

This works by getting the category name and item name of each item in the initial array, and then initialising each category name to be an empty array within the accumulator object. Then push the item name to the corresponding category array (either pre-existing or empty), and you're done!


text:
Q: Using Proxy IP for the users in LAN through Zentyal server Assume:**LAN USERS-->Zentyal Server as Gateway-->Internet.
**Current setup: All of my LAN users using their subscribed proxy credential in their browser LAN settings to get foreign IP to access my client's website. So the option is in their hand either to use the proxy or to access the site without proxy. My client wants us to access his site using IP from his county. Few times my LAN users accessed his site without proxy.
Requirement: I want all the LAN users to get proxy IP internet through zentyal server to access my client's website in his country. so that the proxy IP from zentyal will be distributed to my LAN users, so they cannot skip using Proxy details.
Please help me to setup the above requirement. Or is there a way to implement the above setup using any other way?


text:
Q: Hashing in Python dictionaries I have a very large matrix that I'm planning to store as a list of dictionaries in Python. The matrix is mostly 0's and I was wondering if the hashing function in the dictionary would store leading space for each row. So, for instance if I initialise a 100,000 x 100,000 matrix but only about 1,000 entries in each row store actual elements and for row 50,000 I have entries from 48,500 to 50,500 would Python create a dictionary of size 50,500 or 2,000? Further, if the former is true is there a way I could optimise within Python's current dictionary class or would I need to create my own?
As an example of my code, I have this:
class DictArray:

    def __init__(self, width, height):
        self.Width = width
        self.Height = height
        self.Data = [0 for _ in range(self.Height) ]

    def __getitem__(self, k):
        if (self.Data[ k[0] ] == 0):
            return 0
        elif (k[1] in self.Data[ k[0] ]):
            return self.Data[ k[0] ][ k[1] ]
        else:
            return 0

    def __setitem__(self, k, value):
        if (self.Data[ k[0] ] == 0):
            self.Data[ k[0] ] = { k[1] : value }
        else:
            self.Data[ k[0] ][ k[1] ] = value

A: The dictionary will be sized based on the number of keys you store in it.
If you have 2000 keys (each a (x, y) coordinate, perhaps?) then it'll be sized to hold 2000 keys (plus a little overhead to facilitate future growth without needing to resize).
However, if you are going to create keys for all 10^10 elements in your matrix (with all but 2000 referencing None, say), then you'll have a dictionary with 10 billion keys and it'll be sized accordingly.
Using a dictionary to build a sparse matrix can be as easy as:
class DictArray:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self._data = {}

    def _validate_coords(self, x, y):
        if not (0 <= x < self.width and 0 <= y < self.height):
            raise IndexError((x, y))

    def __getitem__(self, x_y):
        self._validate_coords(*x_y)
        return self._data.get(x_y, 0)

    def __setitem__(self, x_y, value):
        self._validate_coords(*x_y)
        if value == 0:
            try:
                del self._data[x_y]
            except KeyError:
                pass
        else:
            self._data[x_y] = value

Demo:
>>> da = DictArray(10, 10)
>>> da[0, 0] = 42
>>> da[0, 4] = 81
>>> len(da._data)
2
>>> da[0, 4] = 0
>>> len(da._data)
1
>>> da._data
{(0, 0): 42}
>>> da[0, 0]
42
>>> da[0, 4]
0

I'd urge you to look at SciPy or NumPy for such a large task, however. They have dedicated data structures for such tasks, such as those found in the scipy.sparse module.

A: If you have a sparse matrix, you might try to get away with the dictionary where the key is a (row,col) tuple (or some other way to quickly get row and column).
E.g.
# assume get_matrix(i,j) gives your (i,j)th element
m = {}
for i in xrange(0,100000):
    for j in xrange(0,100000):
        t = get_matrix(i,j)
        if t:
            m[(i,j)] = t

Regarding dictionary performance, assuming it has logarithmic search complexity, you might also look at how much memory it's going to take. Depending on what kind of machine you are using, something like 10K entries might work, but something like 1000K entries might not.
(but using numpy or scipy might be a better option)


text:
Q: Linker /delayload is not fully working with winhttp.dll I'm trying to prevent dll-hijacking vulnerability in my executable, which has only one explicit dynamic dependence - winhttp.dll.
My attempt is to use linker /delayload:winhttp.dll option and call SetDefaultDllDirectories in the very beginning of the program. Seems like it is working for some modules AND for winhttp itself, but not for it's dependencies - binary is still loading mpr.dll and a few other modules before main (and it is first trying to load it from my executable folder).
It is not helping to add mpr.dll to /delayload list - I'm getting LINK : warning LNK4199: /DELAYLOAD:mpr.dll ignored; no imports found from mpr.dll.
Dependency Walker is showing me this dependence chain: winhttp -> oleaut32 -> combase -> ole32 -> mpr.
Why is this module loading before any of winhttp functions usage?
P.S. I really want to avoid using LoadLibrary + GetProcAddress manually.
Win 8.1, MSVS 2013 Update 5
Procmon:

Dep. walker:

A: It is crazy, but the true reason for this behaviour appears to be my executable name. It does contain a word "launcher", which seems to be the one, triggering Windows AppCompat layer.
The same executable renamed to "test1.exe" works all well.


text:
Q: Make iframe expand/collapse I have several apps inside iframes in the page that consolidates the apps (it acts as an app container).
I want to add a button somewhere that can expand and collapse the iframes to full size of the page.
The app now has a menu, header, footer, etc. and the application in iframe. When the user clicks say "+" button I want to expand the iframe to the full page and make everything else invisible. When they click it again I want to return to original size.
Maybe there is already something written that can make this happen, I tried to do some js on iframes and it seems hard to write browser independent code.
I can't use HTML5 since we need to support IE7.

A: An example.
Basically, just give your expanded iframe these CSS attributes,
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
z-index: 10;

and it will fill its (relative) parent.

A:
Source: "Full screen" <iframe>

You can use either traditional JS or jQuery to achieve this. jQuery is a JS library that is meant to allow cross-browser DOM handling in a sane way.
If I were you, I might code it as (using jQuery):
$('iframe#myid').click(function() {
    $('iframe#' + current).removeClass('current');
    $('iframe#myid').addClass('current');
    var current = '#myid';
});

with the CSS code as:
body, iframe {
    margin: 0px; //to normalize the default stylesheet applied by the browser
}

iframe.current {
    position: absolute;

    top: 0;
    left: 0;

    height: 100%;
    width: 100%;

    z-index: 999;
}