Hibernate 5 Exception: Found shared references to a collection

Question: I realize that this question has been asked many times on StackOverflow, and I've read through many of these questions which were asked from 13 years ago to 3 months ago, and none of these have answered my question.  I am working on a non-Spring application, and we are going from Hibernate 3.x to Hibernate 5.6.0.Final at this time.  I can tell you since we are not using Spring to control our persistence and session management, this is code that was written by us.  So, let me start with our stack trace which is quite long:
Message: org.hibernate.HibernateException: Found shared references to a collection: com.myproject.server.model.user.User.roles
javax.persistence.PersistenceException: org.hibernate.HibernateException: Found shared references to a collection: com.myproject.server.model.user.User.roles
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1406)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1389)
at com.myproject.server.services.db.Transaction.commit(Transaction.java:51)
at com.myproject.server.services.db.service.PersistenceManager.commitTransactionIfOpen(PersistenceManager.java:156)
at com.myproject.server.services.db.service.DataService.save(DataService.java:300)
at com.myproject.server.services.db.service.DataService.save(DataService.java:241)
at com.myproject.server.rest.user.LoginResourceImpl.acceptEula(LoginResourceImpl.java:113)
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.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at com.myproject.server.log.AddLogRequestIdFilter.doFilter(AddLogRequestIdFilter.java:38)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at com.myproject.server.log.AddLogContextFilter.doFilter(AddLogContextFilter.java:61)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at com.myproject.server.services.user.SessionSetupFilter.doFilter(SessionSetupFilter.java:54)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at com.myproject.server.services.db.DataLayerThreadFilter.doFilter(DataLayerThreadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at com.myproject.server.services.security.CrossOriginFilter.doFilter(CrossOriginFilter.java:68)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:394)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:522)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: org.hibernate.HibernateException: Found shared references to a collection: com.myproject.server.model.user.User.roles
at org.hibernate.engine.internal.Collections.processReachableCollection(Collections.java:188)
at org.hibernate.event.internal.FlushVisitor.processCollection(FlushVisitor.java:53)
at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:104)
at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:65)
at org.hibernate.event.internal.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:59)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:183)
at com.myproject.server.services.db.eventlisteners.debug.DebugFlushEntityEventListener.onFlushEntity(DebugFlushEntityEventListener.java:25)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:229)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:93)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1402)
... 78 more

The User.hbm.xml file looks like this:
<hibernate-mapping package="com.ekotrope.server.model.user">
   <class name="User" table="user">
        <id name="id" column="id">
            <generator class="increment" />
        </id>
    <bag name="roles" table="roles" cascade = "all,delete-orphan" lazy="false">
       <key column="userId" not-null="false" />
       <element type="com.ekotrope.server.model.user.RoleUserType"/>
   </bag>
    <set name="permissions" table="user_permission" cascade="all" lazy="false">
       <key column="userId" not-null="true"/>
       <element column="permission" not-null="true" type="java.lang.String" />
   </set>
      <property name="password" not-null="true"/>
      <property name="name" not-null="true"/>
      <property name="username" not-null="true" unique="true"/>
      <property name="email" not-null="true"/>
      <property name="lastUpdateAt" type="timestamp" not-null="true"/>
  </class>
</hibernate-mapping>

I know we're using Hibernate 5, but we're not quite ready to jump to completely annotated classes yet, but that is what we want to do in a near future sprint.
We definitely have some servlet filters in our chain that open to the database user and we can get that successfully.  We are definitely tracking the count of instances within the JVM and the session and we think we only have ONE User.   We are using Eclipse and when we right-click on a Variable in debug mode we can see the instance count, we can see all the instances, and we can see the references.
The collection of roles is EAGER loaded from the database and we can see we have 2 roles, and we aren't touching the roles at all.  But when we save to the database, or even just do a session flush, then we come to this error.
So, we've tried to eliminate a lot of issues by checking painfully what is in the session, and making sure we only have the one instance, and we still get this error.  We are in the Hibernate code to see what is causing this error.   We know we have triggered the isReached part and that is throwing the exception.  So, if we can figure out why our session has more than once instance, then we can fix that in our code.  If any one has any tips for us or suggestions we can try, that would be helpful.
Answer: I figured this one out, but it took quite a bit of time.  As I added more logging into a variety of methods in our company code (not the hibernate code), I found that somehow we were jumping into the hibernate code twice.
In the company I was working at, we had some Hibernate Listeners, and this code was rather old.  I actually posted more of this on the Hibernate support boards.   With the help of the Hibernate Developers, I found a much better way to have code for the Listeners, the approved way, and when I did that, it solved our issue.
We were able to write code to the database, but with the listeners making sure we only jumped into the Hibernate code ONCE, not TWICE.  This made the issue go away.   I will come back and update this story when I have more details.


How to display the button based on the alphabet in front of the file name?

Question: I am created the button to display buttons based on the alphabet in front of the file. Anyone can guide me how to display buttons based on the first alphabet in front of the file. For my files, my files name first alphabet is m. I want just show the Edit Meeting File button if file name first alphablet is m, if alphabet not is m , just don't show the Edit Meeting File button. Below is my code:
<?php
$i = 1;
$files = scandir("upload_dms_file/uploads_filing_file");
$date = $files[$a];
for ($a = 2; $a < count($files); $a++) {

    ?>

         <?php echo $i++; ?>
         <a href="upload_dms_file/uploads_filing_file/<?php echo $files[$a]; ?>" target="_blank"> <?php echo $files[$a]; ?>

            <button class="btn btn-sm btn-primary"><a href="upload_dms_file/uploads_filing_file/<?php echo $files[$a]; ?>"
                                                      download="<?php echo $files[$a]; ?>" style="color: white;">
                    Download</button>
            &nbsp &nbsp
            <button class="btn btn-sm btn-primary"><a
                        href="upload_dms_file/delete_filing_storage.php?name=uploads_filing_file/<?php echo $files[$a]; ?>" style="color: white;">
                    Delete
                </button>

                <button class="btn btn-sm btn-primary"><a
                        href="upload_dms_file/edit_filing_storage.php?name=uploads_filing_file/<?php echo $files[$a]; ?>" style="color: white;">
                    Edit Meeting File
                </button>

    <?php
} ?>

This is my output page, this output is show all the  Edit Meeting File button:

Hope anyone can guide me how to solve it. Thanks.
Answer: Just wrap the code that outputs that button in an if block that checks whether the first letter of the filename is m:
<?php
if ($files[$a][0] == 'm') {
?>
<button class="btn btn-sm btn-primary"><a
        href="upload_dms_file/delete_filing_storage.php?name=uploads_filing_file/<?php echo $files[$a]; ?>" style="color: white;">
    Edit Meeting File
</button>
<?php
}
?>

Answer: You need to add an if clause to the button part:
            <button class="btn btn-sm btn-primary"><a
                    href="upload_dms_file/delete_filing_storage.php?name=uploads_filing_file/<?php echo $files[$a]; ?>" style="color: white;">
                Edit Meeting File
            </button>

should be
            <?php if(strlen($files[$a]) > 1 and substr($files[$a], 0, 2) = "m-"){ ?>
            <button class="btn btn-sm btn-primary"><a
                    href="upload_dms_file/delete_filing_storage.php?name=uploads_filing_file/<?php echo $files[$a]; ?>" style="color: white;">
                Edit Meeting File
            </button>
            <?php } ?>


Elastic Search Results to POJO

Question: I am using spring-data-elasticsearch (version 4.0). Now I need to convert search results from rest high level client to POJO objects.
I would use ObjectMapper from Jackson library. I am sure there are better ways to do it.
Spring-data-elasticsearch now (from 4.0) uses MappingElasticsearchConverter. Unfortunately, I don't have an idea how to accomplish this - I don't see any relevant documentation.
Entity
@Document(indexName="addresses")
public class Address {

    @Id
    private String uam;

    @Field
    private String street;

    ....
}

I just need to convert SearchHits to Address entity
@SpringBootTest
@RunWith(SpringRunner.class)
@ActiveProfiles(profiles = "dev")
public class TestElasticSearch {

    @Autowired
    private RestHighLevelClient highLevelClient;

    @Test
    void convertToPojo() throws Exception {
        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHit[] hits = searchResponse.getHits().getHits();

        Arrays.stream(hits).map(hit -> hit.toString()).forEach(System.out::println);
    }

Comment: why do you use the `@RestHighLevelClient`directly? You should use `ElasticsearchOperations` or repositories. That's what Spring Data Elasticsearch is for.
Comment: I like repositories, but I have some more difficult use cases (suggestions etc.). For now, I am more comfortable with RestHighLevelClient (a lot of documentation).
So this what I am trying to do is according to you generally bad practice?
Answer: The SearchHits class extends Streamable class, so if you use ElasticsearchOperations like leiblix said, you don't even need to call stream() on it
    public <T> List<T> search(Query query, Class<T> clazz) {
        return elasticsearchOperations.search(query, clazz).map(SearchHit::getContent).toList();
    }

Answer: As P.J.Meisch mentioned, is much better to use ElasticsearchOperations
void convertToPojo() {
    SearchHits<Address> hits = operations.search(Query.findAll(), Address.class);
    List<Address> addresses = hits.stream().map(hit -> hit.getContent()).collect(Collectors.toList());
}

Comment: Is it necessary to map it to SearchHits first and stream to POJO, cant we directly map the elastic result to List. ??
Answer: I have another solution to this that is working well for me, and can work when you need a complex query that you can only get hits from, you can use
template.getElasticsearchConverter().read(YourPOJOClass.class, DocumentAdapters.from(hit));

where template is a org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate you can get this injected into your class.

Elastic Search Results to POJO


Summoning Written Books and others

Question: Using the /summon command, is it possible to summon written books? I have the /give command for the book that I wrote (can supply said command if needed), but when I tried changing it to be in the /summon format, it summoned a piece of stone. Another quick question I had along the same lines is summoning enchanted items. Any suggestions?
This is another book with the same number of pages and the same characteristics as my first book (click event, colored text)
<code>/give @p written_book 1 0 {pages:["{\"text\":\"Welcome\",\"color\":\"dark_red\"}","{\"text\":\"Introduction\",\"color\":\"dark_red\"}","{\"text\":\"DRAMA!\",\"color\":\"dark_red\"}","[\"\",{\"text\":\"C\",\"color\":\"dark_red\",\"clickEvent\":{\"action\":\"run_command\",\"value\":\"/say Test Success\"}},{\"text\":\"lIcK MURdEr!\",\"color\":\"dark_red\"}]","{\"text\":\"Dramatic ending!\",\"color\":\"dark_red\"}"],title:"How to Kill a Minecrafter",author:SMILIECHICKEN,generation:3}
</code>
Comment: Is there a reason you need to summon them and not just use the /give command?
Comment: Can you provide the commands you tried using?
Comment: @Jason_ Not really, but I have had this question for a while, and it looks good.
Comment: @Skylinerw The book I wrote is pretty long, so I'll put up another book with the same number of pages and the same characteristics (click event, colored text.) I'll put in the answer section, since it's too long to fill here. It's in /give form now, but I need in it summon -- if that's possible.
Answer: It is possible. You can use the datatag like this:
<code>/summon Item ~ ~ ~ {Item:{id:"minecraft:written_book",count:1,Damage:0,tag:{pages:[I don't want to copy-paste]}}}
</code>

Summoning Written Books and others


Can I track how many trees I have planted?

Question: I know if I plant 100+ trees on Arrrbor Day, I get better rewards the next Arrrbor Day for whatever tree type I planted.
Is there any way to track this, short of just keeping a count in my head?
Answer: Not specifically, though it's one adventure per tree so you can watch you adventure count or use the <code>/timer</code> command.


How to update JavaScript Error class

Question: I want when any one of
EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError is thrown through my code I want to these error should thrown after an ajex request so that I can get to know analyse the client error logs.
When I went deep, I found that sevral interface are created for these error by extending Error class e.g.
interface TypeError extends Error {
}
interface TypeErrorConstructor {
    new (message?: string): TypeError;
    (message?: string): TypeError;
    prototype: TypeError;
}

declare var TypeError: TypeErrorConstructor;

interface Error {
    name: string;
    message: string;
}

interface ErrorConstructor {
    new (message?: string): Error;
    (message?: string): Error;
    prototype: Error;
}

declare var Error: ErrorConstructor;

So is there any way to redefine/update these interface defination so before throwing these error it should make an ajex request to the server.
Note: I dont want to use windows.onerror since some other library(rollbar) has own onerror implimentation.
Is it possible to redefine these interface. e.g.
I can redefine console.log as follows:
console.log=function(){
   return arguments;
}

Comment: Possible duplicate of [Logging Clientside JavaScript Errors on Server](http://stackoverflow.com/questions/119432/logging-clientside-javascript-errors-on-server)
Comment: that's not javascript, so, not sure how it's relevant to your needs
Comment: I dont want to use windows.onerror. Is there any way to update these defination?
Answer: I faced same issue , solved it by redefining error class
As follows:
var Error = {
       name: this.name,
       message: this.message,
       toString: function () {
            window.Rollbar.error("Something went wrong", this.message );
             ......
            return this.message;
       }
   };

How to update JavaScript Error class


No search results in Kibana when searching for a specific keyword

Question: I installed ELK stack on my windows 10 machine. I used log4net to push logs to logstash -> elasticsearch. The logs data is displayed in Kibana and everything is fine. My logstach config is:
input {
udp {
port => 5960
codec => multiline {
        charset => "UTF-8"
        pattern => "^(DEBUG|WARN|ERROR|INFO|FATAL)"
        negate => true
        what => previous
    }
type => "log4net"
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "myindex"
}
}

When I try to search for a keyword that exists in the message text (using the search input and the date is set to 3 months ago) I get:
"No results match your search criteria"

Note: If I use: stdin {} instead of udp{} in logstash config I can search for any keyword.
I reinstalled the stack in another machine and the same issue happened.
Any suggestions?
Answer: I found the solution:
The problem was with the encoding data coming from log4net. So you need to set the log4net config file as following for udp appender:
<appender name="UdpAppender" type="log4net.Appender.UdpAppender">
<remoteAddress value="127.0.0.1" />
<remotePort value="5960" />
<encoding value="UTF-8" />
<layout type="log4net.Layout.PatternLayout, log4net">
  <conversionPattern value="%-5level %date [%-5.5thread] %-40.40logger - %message%newline" />
</layout>


How to serialize a httplib SSL connection object in python?

Question: I am trying to send a httplib connection object over a zmq socket, but I am getting the following error TypeError: can't pickle _ssl._SSLSocket objects.
Now I thought this would have been the case as I am just experimenting at the moment, but does anyone know of a method to wrap or serialize the SSL object so that I can send it to other threads, over sockets?
An example use case:
#Script 1
import zmq
ctx = zmq.Context()
GLOBAL_SOCKET=ctx.socket(zmq.PUB)
GLOBAL_SOCKET.bind('tcp://127.0.0.1:2000')

conn = httplib.HTTPSConnection('site...')
GLOBAL_SOCKET.send_pyobj(conn)

#script 2
import zmq
ctx = zmq.Context()
GLOBAL_SOCKET=ctx.socket(zmq.SUB)
GLOBAL_SOCKET.connect('tcp://127.0.0.1:2000')
GLOBAL_SOCKET.setsockopt(zmq.SUBSCRIBE, '')

#recv SSL object in response hopefully
conn_ = GLOBAL_SOCKET.recv_pyobj()

#work with the connection object in another thread
conn_.request('GET', ....)
conn_.request.getresponse()

Any help welcome.
Comment: Why can't you just open a new connection from the second process?
Comment: @Blender I knew this would come up: I had a longer question with more code explaining that I was trying to persist a single connection throughout the program, as I don't want to be making any new TCP handshakes. If you want I can elaborate in the question, but only if you think there might be a chance of a solultion?
Comment: @georgexsh what do you mean by "but one's child" ?
Comment: @ajsp you could send socket to another process with `sendmsg(2)` syscall, but IMO ZMQ works on top of socket API, so this is not possible.
Comment: @georgexsh could you shouw me a quick example of passing a httplib connection object over a socket georgexsh? That would actually answer the question. I have carved out a solution with ZMQ but there is a lot of work in it...hecne if I could just send the connection that would be better.
Comment: @ajsp socket cannot send over *socket* connection but with `sendmsg(2)` syscall within the same machine, you do want that?
Comment: @georgexsh That would answer the question, yes, 100%. Can you provide a working example below?
Answer: a working example using multiprocessing.Queue:
import httplib
import ssl
import copy_reg
from multiprocessing.reduction import rebuild_socket, reduce_socket
from multiprocessing import Queue
import os

def save_sslcontext(obj):
    return obj.__class__, (obj.protocol,)

copy_reg.pickle(ssl.SSLSocket, reduce_socket, rebuild_socket)
copy_reg.pickle(ssl.SSLContext, save_sslcontext)

def parent():
    conn = httplib.HTTPSConnection('www.baidu.com')
    conn.connect()
    queue.put(conn)
    os.wait()

def child():
    conn = queue.get()
    conn.request('GET', '/')
    r = conn.getresponse()
    print r.status

queue = Queue()
if 0 == os.fork():
    child()
else:
    parent()

Comment: Excellent, I see you have saved the actual protocol of the connection object, that's interesting, I will change the question tittle to reflect this. Thanks for your time.
Comment: @ajsp that is for pickle `SSLContext` object, [see this ref](https://stackoverflow.com/questions/33994158/how-to-pickle-a-ssl-sslcontext-object).


Range of re-parameterized function

Question: I am little confused here.
Let us define a function $f:[0,1]\rightarrow \mathbb{R}$, where
$\begin{equation*}
\mathop{f}(t)= \left\{
 \begin{array}{ll}
 2\sqrt t & \mbox{if}\; 0\leq t < \frac{1}{2},\\
 5\sqrt t & \mbox{if}\; \frac{1}{2}\leq t \leq 1.
 \end{array} \right.
 \end{equation*}
$
Then the re-parameterized function with $t\mapsto t^2$, will be
$\begin{equation*}
\mathop{f}(t^2)= \left\{
 \begin{array}{ll}
 2t & \mbox{if}\; 0\leq t < \sqrt \frac{1}{2},\\
 5t & \mbox{if}\;\sqrt \frac{1}{2}\leq t \leq 1.
 \end{array} \right.
 \end{equation*}
$
Could anyone please tell me is it right or not. I have doubt about the range of the re-parameterized function.
Thanks in advance.
Answer: This looks good to me.
$f(t)$ maps $[0,1/2)$ to $[0,\sqrt{2})$ and $[1/2,1]$ to $[5/\sqrt{2},5]$.
$f(t^2)$ maps $[0,\sqrt{1/2})$ to $[0,\sqrt{2})$ and $[\sqrt{1/2},1]$ to $[5/\sqrt{2},5].$
So, the range is the same.
Comment: Thanks for the answer. Also, range are same but the partition of the domain changes. Though it is consistent with the transformation.

Range of re-parameterized function


Changing the font of a ul in Bootstrap and CSS

Question: I'm using Bootstrap and I tried to change the font of my ul with CSS but it doesn't work. I tried the code below.
ul {
   font-family: Arial;
}

 My Account

Comment: Bootstrap specifies a font set in its css. To use the Bootstrap class names but have your own font over-ride it i'd put "!important at the end of your font declartion. Like so....."font-family:Arial !important;" or if you feel comfortable editing the source Bootstrap go in there and change the font for the classes you are using
Comment: Doesn't work :/ I'll try editing the source code.
Comment: You're placing the text inside your `glyphicon` tag (which isn't closed), place it after your closed `span` tag and it will work. And use `navbar-right `instead of `pull-right` [Docs](https://getbootstrap.com/components/#navbar-component-alignment)
Answer: I believe this is caused by your  tag not being closed. The following works for me:

 My Account

Comment: Since `````` was not closed, the ```glyphicon glyphicon-user``` styles were likely being applied to everything passed that point, which includes the 'My Account' text.
Comment: Oh. Thanks for explaining!
Comment: It worked. But could you explain to me why that was the problem? I'm trying to learn Bootstrap and not just memorize stuff :P


Is there a way to see units' health-bars?

Question: Seeing health-bars would be incredibly useful for determining, for instance, how powerful each tower actually is.  Is there a way to show health-bars?
Answer: It turns out that you can do this by hitting f2 (there is no way of doing it from the UI).
As a side-note, you can see how powerful each of the towers/units are on the towerwars wiki.


How many ghosts are there, and what do they say?

Question: In the graveyard levels I encountered multiple ghosts.

 You can see them when the lightning flashes.  Pressing "B" will cause them to say something.

How many are there, and what is the transcript of what they say?  Is there any known relationship between what they say and a puzzle or easter egg?
Answer: There are four ghosts and they're unconnected to the puzzles and Easter eggs.

In the skull room: "Afterlife / Outerspace / Afterspace / Outerlife."
In the "dots to dots" room that leads to the mausoleum: "Don't believe the hypercube."
In the room atop the prior one: "Because you can't see something, doesn't mean it's not there."
In the golden cube return warp (farthest away): "Owls creep me out... / But I forget why..."
Comment: Way to come back and edit with additional info even after the check.


How do I properly finish basement without framing?

Question: Here is the issue: we have an unfinished laundry room and an unfinished closet. I would like to finish both of them. We are in a wet/moisture climate (Wisconsin). I am trying to do this without framing - hoping I can do some sort of waterproofing+furrough stripping+drywall. The walls in our laundry room were completely painted with some sort of moisture barrier/sealer prior to purchase purchase.
So I've done some research. I think I know what I need to do, but looking for pointers and any further input or recommendations. From what I am seeing, the process is as follows:
Boarded insulation directly to the block wall
Moisture/vapor barrier
Furring strips 24" apart with masonry or tapcon screws
Affix drywall to furring strips
The basement areas to be done are not currently framed or have footings. Not sure if this NEEDS to be done or if I can just start with the above listed steps without framing.
I have done some home drywall before but was not attached to cinder block. If I decided to add insulation, how would I ago about this? Do they make a moisture/vapor barrier that is like a 'board' similar to insulation board that would just be applied first? Would love any info from people who have done this before - and preferably people who are in the trades. Thanks!
Comment: Do you plan to [install]|[accommodate any existing] electrical services?
Comment: "The basement areas to be done are not currently framed or have footings." What does this mean, in particular the "or have footings" part? Also, please [edit] to focus on one thing in this question. Feel free to post several questions, just not all in one - it's how we work here. Take the [tour] and read through [how to ask a good question](https://diy.stackexchange.com/help/how-to-ask) for more info.
Comment: *Boarded insulation* - what is that? Foam boards? Not a good idea from a fire-safety standpoint - fiberglass or many other things would be safer.
Comment: Paint on the interior existing wall does not guarantee future performance. A polyethylene barrier applied to the face of the inside wall at grade and below and tied into a vapor barrier on the interior face should be considered. Joints should be sealed with acoustic sealant.
Answer: As I sit here in the unfinished half of my basement...
If you want to put up drywall, you really need proper framing. Since this framing doesn't need to support much, it could be a bit thinner than a standard 2x4 wall (nominal 1.5" x 3.5"). However, the usual 2x4 wall structure has some significant benefits over thinner structures:

3-1/2" available for insulation
The bottom plate is attached to the floor. The top plate is attached above. The studs are attached to the bottom and top plates but do not need to be attached to the existing walls.
Electrical and plumbing can be run inside the walls in standard ways. Furring strips will probably be OK for electrical, almost certainly not deep enough for plumbing.
Standard electrical boxes can be used for switches, receptacles, etc.
Studs can be used to mount shelving or other things.


How to shift the values of a list to the left as much as possible?

Question: Let's consider these two lists :
list1 = ['N/A', 'a', 'b', 'c']
list2 = [None, None, 'd', None, 'e']

1-) I need to shift their items to the left as long as there is a target value at the beginning but 2-) we should ignore the eventual targets that can be in the middle and finally 3-) we fill the replacements with a value from the end.
In a parallel universe, the function I need would be a method of the python's list: list.lstrip(target_value, fill_value)
I tried to make it real with the code below but it doesn't give the expected output for list2 :
def lstrip(a_list, target_value=None, fill_value='Invalid'):
    if a_list[0] != target_value:
        return a_list
    else:
        result = []
        for element in a_list:
            if element != target_value:
                result.append(element)
        return result + [fill_value]*(len(a_list) - len(result))

The current outputs are :
print(lstrip(list1, 'N/A'))
['a', 'b', 'c', 'Invalid']

print(lstrip(list2))
['d', 'e', 'Invalid', 'Invalid', 'Invalid']

The second output should be ['d', None, 'e', 'Invalid', 'Invalid'].
Do you guys have an idea how to fix my code ?
Comment: I don't think that the purpose of the program is to `strip`, it looks more a rearrangement
Answer: It seems like you could just find the index of the first non_target value and return the slice from that point on plus an array of fill values of the same length as the index:
list1 = ['N/A', 'a', 'b', 'c']
list2 = [None, None, 'd', None, 'e']

def lstrip(a_list, target_value=None, fill_value='Invalid'):
    i = next((i for i, v in enumerate(a_list) if v != target_value), len(a_list))
    return a_list[i:] + [fill_value] * i

print(lstrip(list1, 'N/A'))
# ['a', 'b', 'c', 'Invalid']

print(lstrip(list2))
# ['d', None, 'e', 'Invalid', 'Invalid']

Giving the length of the list as a default to next() covers the case where a list is all target values:
lstrip([None, None])
# ['Invalid', 'Invalid']

Answer: The issue with your implementation is that the condition if element != target_value: continues to filter out target_values even after an element that does not match the target value has been seen. You can fix this by adding a simple boolean flag for when a mismatch is found:
def lstrip(a_list, target_value=None, fill_value="Invalid"):
    if a_list[0] != target_value:
        return a_list
    else:
        seen_mismatch = False
        result = []
        for element in a_list:
            if element != target_value:
                seen_mismatch = True
            if seen_mismatch:
                result.append(element)
        return result + [fill_value] * (len(a_list) - len(result))

Here's an alternative implementation that makes use of partially consuming an iterator over the list. This also generalizes the function to work on empty lists and over other arbitrary iterables.
from collections.abc import Iterable, Iterator
from typing import TypeVar, Literal

_T = TypeVar("_T")

def lstrip(
    it: Iterable[_T],
    target_value: _T | None = None,
    fill_value: _T | Literal["Invalid"] = "Invalid",
) -> Iterator[_T]:
    it = iter(it)
    backfill = 0
    for elem in it:
        if elem == target_value:
            backfill += 1
        else:
            yield elem
            break

    yield from it
    yield from [fill_value] * backfill

>>> print(list(lstrip(list1, "N/A")))
['a', 'b', 'c', 'Invalid']

>>> print(list(lstrip(list2)))
['d', None, 'e', 'Invalid', 'Invalid']

Comment: Curious about the expected result of `lstrip([None, None])`


Appending a value to return value of function range()

Question: I'm learning python and am studying from the book Dive into the Python. It says :

The built−in range function returns a list of integers. In its
  simplest form, it takes an   upper limit and returns a zero−based list
  counting up to but not including the upper limit.

According to what it says, it returns a list. I thought that I could append a value to it with append function, but I couldn't.
>>> l = range(7)
>>> l
[0, 1, 2, 3, 4, 5, 6]
>>> l.append(13)
>>> l
[0, 1, 2, 3, 4, 5, 6, 13]
>>> l = range(7).append(13)
>>> l

It doesn't print anything, what's the reason?
Comment: Side note: `range` only returns a list in Python 2.x. In Python 3, you'll get an `AttributeError: 'range' object has no attribute 'append'`
Answer: The reason is that list.append operates in-place and therefore always returns None.
In other words, this line:
l = range(7).append(13)

is equivalent to this:
l = None

Note too that the example you posted proves that appending values to the list returned by range works as expected if you call list.append on its own line:
>>> l = range(7)
>>> l.append(13)  # Call list.append on its own line
>>> l  # And it works as expected
[0, 1, 2, 3, 4, 5, 6, 13]
>>>


How to gradually increase teleport amount

Question: I'm trying to make an armor stand accelerate towards the ground, but the method I am using to move it is teleporting it forward, so it won't go down in the process. I can't find any way to use a scoreboard to increase the amount so I'm wondering if there is any other way.
Answer: You could use a scoreboard which constantly is added to the armor stand. As the score gets higher, you can use more and more command blocks.
Run once:
<code>/scoreboard objectives add speed dummy
</code>
Run on a clock:
<code>/scoreboard players add @e[type=minecraft:armor_stand] speed 1
/execute as @e[type=armor_stand,scores={speed=1..}] at @s run tp @s ~ ~-0.1 ~
/execute as @e[type=armor_stand,scores={speed=50..}] at @s run tp @s ~ ~-1 ~
/execute as @e[type=armor_stand,scores={speed=100..}] at @s run tp @s ~ ~-2 ~
</code>


Can I access my companion's inventory when they're not in my active party?

Question: I have recently acquired a new party member, but given that the party maximum is 4, she tells me she'll wait for me in my camp. So I go to camp, tell Wyll to take a load off, and recruit my new companion!
...only to realize that Wyll was wielding the magic dagger I wanted to give her, and, well, I can't seem to reach his equipment, anymore.
Is there a way to access your inactive companion's inventories short of doing the party shuffle? (Heavens forbid you forget whomst is holding what!)
Answer: To do this I am using the Camp Chest.
If you right click an item in your inventory you can select 'Send to Camp'. On PC, you can also use Shift or Ctrl + LMB to multi-select.
This will place it inside the chest in your camp.
Then when you visit camp you can retrieve it from the chest and pass it to whomever you need. So I tend to dump everything my party are not actively using into the chest, and then my new party can go select what items they might need for the next adventure.
I do not know of a way to see a companions inventory without having them in the party.
Comment: Yep, it seems like better inventory management with party members is one of the main quality-of-life feature requests for the game right now.


How the user instance of systemd is started?

Question: So, I've read the porting guide (https://wiki.tizen.org/wiki/Porting_Guide). There is a section named "Tizen Bootup Overview".
How the user instance of systemd is started in Tizen? I know when it is started, but who does it?
Answer: The user session in Tizen is started through firstname.lastname@example.com service file in /usr/lib/systemd/system/graphical.target.wants/ directory.


Inheritance constructor error

Question: so i have my child class Line that inherits form my parent class Point and i don't use my base class's constructor in my child class but i get this error :

'Shape.Point' does not contain a constructor that takes 0 arguments

this is my parent class:
public class Point
{

   public Point(int x, int y)
   {
       X = x;
       Y = y;
   }
   public int X { get; set; }
   public int Y { get; set; }
}

this is my child class:
public class Line : Point
{
   public Point Start { get; set; }
   public Point End { get; set; }
   public double Lenght { get; set; }

    public Line(Point start , Point end)
    {
        Start = start;
        End = end; ;
    }

    public double Calculate_Lenght()
    {
        Lenght = System.Math.Sqrt((End.X - Start.X) ^ 2 + (End.Y - End.X) ^ 2);
        return Lenght;
    }
}

Answer: You extend with Point which has a ctor of
public Point(int x, int y)
{
   X = x;
   Y = y;
}

In Line you'll have to call this constructor or implement it, too
Either
public Line(int x, int y)
{
}

Or
public Line(Point start, Point end)
   : base (...)
{
}

While this seems to make no sense, I guess you really don't want to extend Line with Point maybe.
Or, if Point has some common functionality you want to inherit, you can give Point a parameter-less constructor.
Comment: @Ela: but my line class hast 2 point objects , start and end , and both of them have y and x how can i pass them to start and end in Line ctor with :base(...)
Comment: @rNuǝɹɐ that's what I meant with it doesn't make sense, because usually a Line does not have X and Y, if you really want to have the properties from Point inherited, I cannot tell you what logic should be behind it
Comment: @Ela: the line dont have X and Y it has two Points Start Point and End Point and Every point has X and Y in diagram so i wrote point class so i can use it in line class
Comment: @rNuǝɹɐ ok if Line should not have X and Y, why do you inherit from Point? Inherit means Line will get the properties of Point...
`class Line : Point` is the inheritance...
Comment: @Ela well that was logical answer , you'r right there is no need for inheritance , thanks

Inheritance constructor error


How to see restored value from savepoints?

Question: I have tried to log info about states that recovered when I start a Flink app using savepoints.
I see that the app was started using a savepoint correctly. But I can't log state values that were recovered.
The app calculates how many products were bought.
Can I use CheckpointedFunction in such way?
I see that context.isRestored() return true, but the checkpointedState is always empty. Where do I misunderstand something?
public class ProductStatisticFunction extends RichFlatMapFunction<User, ProductStatistic> implements CheckpointedFunction {

    private transient ValueState<ProductStatistic> statisticsValueState;
    private transient ListState<ProductStatistic> checkpointedState;

    @Override
    public void flatMap(User user, Collector<ProductStatistic> out) throws Exception {

        ProductStatistic currentValue = statisticsValueState.value();

        if (currentValue.getAge() == 0) {
            currentValue.setAge(user.getAge());
        }

        currentValue.setAmount(currentValue.getAmount() + 1);
        statisticsValueState.update(currentValue);

        out.collect(new ProductStatistic(currentValue.getId, currentValue.getAge(), currentValue.getAmount()));
    }

    @Override
    public void open(Configuration config) {
        ValueStateDescriptor<ProductStatistic> descriptor =
                new ValueStateDescriptor<>("age-statistic", TypeInformation.of(new TypeHint<>() {
                }),
                        new ProductStatistic());
        statisticsValueState = getRuntimeContext().getState(descriptor);
    }

    @Override
    public void initializeState(FunctionInitializationContext context) throws Exception {

        this.checkpointedState = context.getKeyedStateStore().getListState(new ListStateDescriptor<>("restored", ProductStatistic.class));
        if (context.isRestored()) {
            for (ProductStatistic entry : this.checkpointedState.get()) {
                log.warn("...."));
            }
        }
    }
}

Answer: I'm afraid that's not how this works, and there's no straightforward way to see the key/value pairs that are being restored to the age-statistic ValueState.
You could, however, use the State Processor API to examine the state stored in the savepoint. Or you could change ProductStatisticFunction into a KeyedBroadcastProcessFunction and use applyToKeyedState to examine the live state values whenever you want to while the job is running.


use of UIpageControl

Question: Can any one explain what is the specific usage of UIPagecontrol in iPhone please.
I am using it for pagination in scroll view. Is there any other specific purpose for it???
Answer: Reading documentation for UIPageControl help you to understand uses of pagination.
Pagination, which automatically separates the content in your form into smaller groups of rendered content. When you use pagination, these groups of content are automatically formatted to fit the target device. The form also renders user interface (UI) elements that you can use to browse to other pages.
Here is the more simple explanation
http://www.smashingmagazine.com/2007/11/16/pagination-gallery-examples-and-good-practices/
Answer: You can know how many pages are there and also tapping on it ll navigate to next page.

use of UIpageControl


kivy: python for android + C++

Question: I've used python-for_android to create a kivy based application running on android.
Some parts of my application have been optimized in c++ using cython.
I manage to compile all my code using python for android and a custom recipes.
My code also works perfectly with kivy under linux.
But on my android device, it failed to load some c++ function. For instance, I get the message :
ImportError: Cannot load library: reloc_library[1307]:  1839 cannot locate '_ZNSt9basic_iosIcSt11char_traitsIcEE4initEPSt15basic_streambufIcS1_E'...

Any idea ?
Thanks
Answer: I've finally managed to make my code work using C++ under android.
There were two difficulties :
1 - Access to c++ header from the arm environment created by push_arm. I had to add the correct includes in my recipe, and modify the default CXX var :
    #dirty hack
    export C_INCLUDE="-I$ANDROIDNDK/sources/cxx-stl/gnu-libstdc++/$TOOLCHAIN_VERSION/include/ -I$ANDROIDNDK/sources/cxx-stl/gnu-libstdc++/$TOOLCHAIN_VERSION/libs/armeabi/include/"
    export OLD_BOUBOU=$CC
    export CC="$CXX $C_INCLUDE"

    try $BUILD_PATH/python-install/bin/python.host setup.py install -O2
    #try cp libgnustl_shared.so $LIBS_PATH/
    try cp $ANDROIDNDK/sources/cxx-stl/gnu-libstdc++/4.4.3/libs/armeabi/libgnustl_shared.so $LIBS_PATH/

    export CC=$OLD_BOUBOU

2 - Find the shared library containing the libstl functions, and load it. This was the harder part :
After some research, I discover that stl functions are stored in libgnustl_shared.so, and not listdc++.so. So you have to embed this library in your apk.
This is the purpose of the line try cp $ANDROIDNDK/sources/cxx-stl/gnu-libstdc++/4.4.3/libs/armeabi/libgnustl_shared.so $LIBS_PATH/
Then, you have to load it. I've modified :
src/src/org/renpy/android/PythonActivity.java
src/src/org/renpy/android/PythonService.java
by adding this line after the others System.loadLibrary() :
System.loadLibrary("gnustl_shared");

Answer: I am currently trying to build pybox2d (with swig) via python-for-android.
The build seems to be fine unit i try to import Box2D ( from the app on the actual android device) i get  a
"cannot locate symbol __cxa_end_cleanup".
Unfortunately the above fix doies not help.
Any other ideas?
Update:
I could fix all issues.
I had to link against stlport_shared.
All my work is in my fork of https://github.com/DerThorsten/python-for-android/ . It works with newer ndks then the orginal python-for-android.
And it has Box2D.

kivy: python for android + C++


Use listener event to call function within the same cog using discord.py

Question: I'm trying to use a listener event to activate a function I have in a cog using discord.py. This same code functions properly in the main bot.py file (removing self and using @client.event instead of a listener) but when used in the cog, it tells me that the repeater() function is an undefined variable when being used in the listener event
import discord
from discord.ext import commands, tasks

class Repeater(commands.Cog):

    def __init__(self, client):
        self.client = client

    @tasks.loop(seconds = 10)
    async def repeater(self):
        channel = self.client.get_channel(834554679265329172)
        await channel.send('test')

    @commands.Cog.listener()
    async def on_ready(self):
        repeater.start()

def setup(client):
    client.add_cog(Repeater(client))

EDIT:
So I changed the code match this after a comment recommended it, and the console throws this error
@commands.Cog.listener()
async def on_ready(self):
    self.repeater()

> discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.repeater'
> raised an error: TypeError: Cog.listener expected str but received
> 'function' instead.

EDIT 2:
Changed the code to match this, and it will run the loop exactly one time, but doesn't actually loop
@commands.Cog.listener()
async def on_ready(self):
    await self.repeater()

Comment: `self.repeater` ?
Answer: In class you have to use self. to access its method self.repeater and self.repeater.start()
I tested it on this code and it works for me.
import discord
from discord.ext import commands, tasks
import os
import datetime

TOKEN = os.getenv('DISCORD_TOKEN')
CHANNEL = 834554679265329172

class Repeater(commands.Cog):

    def __init__(self, client):
        self.client = client

    @tasks.loop(seconds=10)
    async def repeater(self):
        #channel = self.client.get_channel(CHANNEL)
        await self.channel.send(datetime.datetime.now().strftime("It's %H:%M.%S"))

    @commands.Cog.listener()
    async def on_ready(self):
        self.channel = self.client.get_channel(CHANNEL)

        print('starting repeater')
        self.repeater.start()

def setup(client):
    client.add_cog(Repeater(client))

# --- main ---

client = commands.Bot(command_prefix='!')
setup(client)

print('starting bot')
client.run(TOKEN)

Answer: repeater is a function of the class. So you can call it with self.repeater. And to start a discord task use start attribute. self.repeater.start() is the answer.
Comment: when using `self.repeater.start()` I get the error "Method 'repeater' has no 'start' member"


On python I'm running a command where i want it to say the day and then the date for example Wednesday the 7th

Question: This is what I've come up with so far:
import time
datestr2 = time.strftime("%d")
import dateutil.parser
start_time_local = "2010-08-07T00:00:00+10:00"
weekday = dateutil.parser.parse(start_time_local).strftime('%A')
print (weekday + " The " + datestr2),
if datestr2 =="01"or datestr2 =="02" or datestr2 =="03"or datestr2 =="04"or datestr2 =="05"or datestr2 =="06"or datestr2 =="07":
    print "th"
else:
    print

But when I run this it comes up with: Saturday The 07 th I would like it to say Saturday The 7th instead how would I do this?
Answer: datestr = time.strftime("%-d")

should give you the result you want. This page is a great resource, I highly recommend bookmarking it.
Also, your if statement is way too repetitive. Try this (correcting for the fact that we now have correct format):
if datestr[-1] in ['4', '5', '6', '7', '8', '9', '0']:
    print 'th'

This checks the last character of datestr and compares it to a list. Much easier than what you were doing.


How can you paint tile?

Question: Our bathroom is out of the 70's and the wife doesn't care for the colors. Remodeling is out of the question for now. Is there something I can use to paint over that ceramic tile so we can at least get a color she likes better?
I should clarify, the tile is on the wall no shower.
Comment: Painted tile will likely be worse than whatever is there now, cover it with floor mats as best you can until you can retile.
Comment: ^ agree if we're talking the floor, but I assume these are shower or wall tiles.
Comment: Painted tile will be ugly on both floors and walls, its still painted tile.
Comment: Agreed. But you can't put floor mats on the wall very easily. ;)
Comment: If it is the shower walls, a decorative shower curtain will hide it most of the time (except when showering).  The main point is, hide it until you can fix it.
Comment: It was just a thought... nothing too serious at this point.
Comment: Your next question will likely be "how can I strip paint from tiles".  Be strong!  Take her to the local home improvement store and show her the price of tile, then tell her to use her natural girl instincts to decorate and cover it up.
Comment: If you go paint route, you'll be out the cost of paint and time putting it on. I say give it a shot (and would suggest the epoxy-based paint route). If it's ugly now, you really have nothing to lose.
Answer: They make paint specifically for tile. It's typically an epoxy based paint.
Comment: A link to an example paint might help.
Comment: I've never used a particular brand to recommend one over another, but there's plenty of examples on google: http://www.google.com/search?q=tile%20paint
Answer: You can prime the tiles with a sealer/primer designed to stick to tiles, and then paint with the paint of your choice. Here's an example of a primer that claims to adhere to tile.
Good luck! Now you just have to find a paint color you can agree on. :)
Comment: You mean I have a choice? I believe the correct words are "yes dear".

How can you paint tile?


$PA = LU$ descomposition. Prove that $\max_{1\leq i,j\leq n}|u_{i,j}| \leq 2\max_{1\leq i,j\leq n}|a_{i,j}|$

Question: I am stuck on this problem:

Let $A = (a_{ij}) \in \mathbb{C}^{n\times n}$ be nonsingular matrix.
$a_{i,j} = 0$ for $|i −j| ≥ 2$ so matrix looks like this
  \begin{bmatrix}  a_{11} & a_{12} & 0      & \cdots & \cdots & 0 \\
 a_{21} & a_{22} & a_{23} & 0 & \ddots & \vdots \\   0     & a_{32} &
 a_{33} & \ddots & \ddots & \vdots \\  \vdots & 0 & \ddots & \ddots &
 \ddots & 0 \\  \vdots & \ddots & \ddots & \ddots & a_{n-1,n-1} &
 a_{n-1,n} \\  0      & \cdots & \cdots & 0      & a_{n,n-1} & a_{nn}
 \end{bmatrix} We apply the Gaussian elmination with pivoting to the
  matrix $A$. So we have $PA = LU$ where $P$ is permutation matrix. $L$
  is lower triangular matrix and $l_{i,j}\leq1$, $l_{i,i}=1$. $U$ is
  upper triangular matrix. Prove that  $$\max_{1\leq i,j\leq n}|u_{i,j}|
 \leq 2\max_{1\leq i,j\leq n}|a_{i,j}|$$

$P$ matrix do not change $\max$ so $\max(PA) = \max(A)$
Rows of $A$ can be rearranged but we know that they have at most 3 nonzero values (same for columns).
Let choose one column (any) of $U$, $U_k =  \left(\begin{array}{c}
      u_{1,k} \\
      u_{2,k} \\
\vdots  \\
     u_{n,k}
    \end{array}\right)$.
$LU_k$ is column of $PA$ so there are at most 3 nonzero elements.
Then there is system of equations:
\begin{cases}
u_{1,k} = PA_{1,k}\\
u_{2,k} = PA_{2,k} - u_{1,k}\cdot l_{2,1}\\
\vdots  \\
u_{n,k} = PA_{n,k} - (u_{1,k}\cdot l_{n,1}+ u_{2,k}\cdot l_{n,2} + \dots + u_{n-1,k}\cdot l_{n,n-1} )
\end{cases}
and most of them are zeros.
Please give me a hint or a clue what to do next. Thanks in advance.
Answer: As you say, $P$ does not change the magnitude of any elements. Let us for convenience call the elements of the matrices involved
$$
PA = \begin{pmatrix}
a_1 & b_1 & & \\
c_1 & a_2 & b_2 & \\
& c_2 & a_3 & \ddots \\
& & \ddots & \ddots
\end{pmatrix}
=
\begin{pmatrix}
1 & & & \\
l_1 & 1 & & \\
& l_2 & 1 & \\
& & \ddots & \ddots
\end{pmatrix}
\begin{pmatrix}
u_1 & b_1 & & \\
& u_2 & b_2 & \\
& & u_3 & \ddots \\
& & & \ddots
\end{pmatrix}
= LU.
$$
Then, the recursion you have mentioned in your question becomes
\begin{align}
u_1 &= a_1 \\
l_j &= c_j / u_j \\
u_{j+1} &= a_{j+1} - l_j b_j.
\end{align}
Note first that if $\max_{i,j}|u_{i,j}| = |b_k|$, for any $k$, then the statement holds, since $b_k$ is an element of $PA$ (hence of $A$) as well as of $U$. So assume instead that $\max_{i,j}|u_{i,j}| = |u_k|$ for some $k$. Note further that, since pivoting is being used, we have $|l_j| \leq 1$ for all $j$.
Now, if $\max_{i,j}|u_{i,j}| = |u_1|$, then by the recursion above, the statement holds, since $u_1 = a_1$ is an element of $PA$. So assume not. That means $\max_{i,j}|u_{i,j}| = |u_k|$ for some $k \neq 1$. However, for any $j$ we have
$$
|u_{j+1}| = |a_{j+1} - l_j b_j| \leq |a_{j+1}| + |l_j b_j| \leq |a_{j+1}| + |b_j| \leq 2 \max_{i,j} |a_{i,j}|
$$
since both $a_{j+1}$ and $b_j$ are elements of $PA$, hence of $A$.
Update: As was pointed out in a comment, $PA$ must not necessarily be tridiagonal, and so the above argument might be invalid. However, note the following two things:
i) Let the elements of $PA$ be denoted $pa_{i,j}$. Above the main diagonal, the only non-zero elements of $PA$ are of the form $pa_{j-1,j}$ and $pa_{j-2,j}$
ii) $PA$ has at most one non-zero sub-diagonal element in each column. Therefore, $L$ has at most one non-zero sub-diagonal element in each column.
Let the elements of $U$ and $L$ be $u_{i,j}$ and $l_{i,j}$ respectively. The recursion written in the question takes the form
$$
(1) \qquad u_{i,j} = pa_{i,j} - \sum_{k=1}^{i-1} l_{i,k} u_{k,j}.
$$
Now, note that $U$ only has non-zero elements of the form $u_{j,j}$, $u_{j-1,j}$ and $u_{j-2,j}$. Using (1), this, together with $|l_{i,j}| \leq 1$, gives
\begin{align}
u_{j-2,j} &= pa_{j-2,j} \leq 2 \max_{i,j} |pa_{i,j}| \\
u_{j-1,j} &= pa_{j-1,j} - l_{j,j-2} u_{j-2,j} \\
&= pa_{j-1,j} - l_{j,j-2} pa_{j-2,j} \\
& \leq 2 \max_{i,j} |pa_{i,j}|
\end{align}
and finally
\begin{align}
u_{j,j} &= pa_{j,j} - l_{j,j-1} u_{j-1,j} - l_{j,j-2} u_{j-2,j} \\
&= pa_{j,j} - l_{j,j-1} pa_{j-1,j} - l_{j,j-2} pa_{j-2,j} (1 - l_{j,j-1}).
\end{align}
Note:
(i) If $pa_{j-2,j} = 0$ we are done.
(ii) If $l_{j,j-2}=0$ we are done.
(iii) If $l_{j,j-1}=0$ we are done (or $l_{j,j-1}=1$).
Left to consider is therefore $u_{j,j}$ when $pa_{j-2,j} \neq 0$, $l_{j,j-1} \neq 0$ and $l_{j,j-2} \neq 0$. I will leave the details for you to fill in, but you can proceed as follows:
(i) Show that $pa_{j,j} = 0$ in this case. Hint: consider the permutations necessary for this to happen.
(ii) Show that $u_{j-2,j} = pa_{j-2,j}$. Hint: This follows from (1).
(iii) Show that $u_{j-1,j} = pa_{j-1,j}$. Hint: Consider (1) for $u_{j-1,j}$ and use the fact that $L$ only has one non-zero sub-diagonal element.
All in all this should reduce the formula for $u_{j,j}$ to
$$
u_{j,j} = -l_{j,j-1} pa_{j-1,j} - l_{j,j-2} pa_{j-2,j} \leq 2 \max_{i,j} |pa_{i,j}|,
$$
and we are done.
Comment: I realise this became more than just a hint. Nonetheless, there are details to fill in regarding the elements $b_j$ appearing in $U$, and why $|l_j| \leq 1$. Anyway, hope it will help.
Comment: One question - $A$ is band matrix but $PA$ may look different.
If we have fragment like this:
\begin{pmatrix}
1 & 1 & & \\
1 & 2 & 1 & \\
& 1 & 1 & \ddots \\
& & \ddots & \ddots
\end{pmatrix}
then it will be rearranged to
\begin{pmatrix}
1 & 2 & 1 & \\
1 & 1 & & \\
& 1 & 1 & \ddots \\
& & \ddots & \ddots
\end{pmatrix}
which is no longer band matrix.
So why $L$,$U$ still look like in your answer?
Comment: Pardon me, that was a misunderstanding on my part. I'll update my answer shortly.
Comment: Ok, I am too stupid to understand it. Let's take example (numbers from Octave):
$$\begin{pmatrix}  & 1 &  & \\ 1 &  & & \\ &  &  & 1 \\ & & 1 & \end{pmatrix} \cdot \begin{pmatrix} 1 & 9 & 0 & 0\\ 7 & 4 & 3& 0\\ 0 & 6 & 5 & 9 \\ 0 & 0 & 7 & 3 \end{pmatrix} = \begin{pmatrix} 1 &  &  & \\  0.14286 & 1 & & \\ 0 & 0 & 1 &  \\0 & 0.71186 &  0.75787 & 1 \end{pmatrix} \cdot \begin{pmatrix} 7 & 4 & 3 & 0\\  & 8.42857  & \mathbf{-0.42857} & 0\\ &  & 7 & 3\\ & &  & 6.72639 \end{pmatrix}$$
How can we assure that -0.42.. not become something larger in different example?PA super-d is 4 0 3, sub-d is 1 0 5
Comment: It's not you being stupid; it's me being unclear (and mistaken on a few points). I'll change my answer and leave a few pieces for you to fill in.


Do I always have to await on an Async method of a disposable object instead of returning its Task?

Question: Seems I fell into a massive gotcha and after hours of debugging I saw that process goes out of "using" scope in RunGame1() and the Task never completes when awaited upon.
async void Execute(object o)  // ICommand.Execute
{
    // fire and forget
    try
    {
        await RunGame2();  // RunGame1() fails to complete
    }
    finally
    { ... }
}

// This fails due to process going out of "using" scope and never completes
Task RunGame1()
{
    var info = new ProcessStartInfo("game.exe") { CreateNoWindow = true };
    using var process = new Process() { StartInfo = info };
    process.Start();
    return process.WaitForExitAsync();
}

// Have to await the Task inside the method
async Task RunGame2()
{
    var info = new ProcessStartInfo("game.exe") { CreateNoWindow = true };
    using var process = new Process() { StartInfo = info };
    process.Start();
    await process.WaitForExitAsync();
}

Is there a pattern to get around this so I can return the Task to save the compiler making an extra state machine or is it just something to be aware of?
Comment: @GSerg I would strongly advise against that; there's no reason the caller needs to know any of those implementation details, and you're forcing extra ceremony onto the call-site for no good reason; adding the `await` would be preferable
Comment: That's a good reading, if you haven't already read it: [Eliding Async and Await](https://blog.stephencleary.com/2016/12/eliding-async-await.html)
Comment: You could return `Task`, at which point you would get rid of the `using` inside your method and let the caller dispose it.
Answer: This is a common gotcha indeed - I've seen several bugs due to similar.
In short:

no, you're not always required to await a task, and sometimes it can be actively advantageous to avoid the overhead of the async machinery - especially in tight code like file/network IO loop, but (and it is a big but)
if that means you're escaping a try/finally region (which also includes using and lock, although there are other bigger problems with lock in async code), then you need to take that into consideration, which usually means "yes, you need to await"

It would be nice if there was an analyzer that spotted the return of a Task[<T>]/ValueTask[<T>] in a non-async method, inside such a region, as it is almost always a bug, and for the few times that it isn't (where the finally has nothing to do with the thing being returned) it could be suppressed.


How can i read this kind of text

Question: First of all i dont understand all this coding thing, im just doing this out of curiousity and boredom.
So what i want to ask is...
Is there a way to read this in English
or you know in any languange people speak
(Like any languange, since i can use google translate)
\x79\x5D\xEF\xBF\xBD\x0F\xE6\x99\xB8\xEF\xBF\xBD\x5D\x2C\xEF\xBF\xBD\x10\x33\x2D\x23\xEF\xBF\xBD

If yes, then how to do it ?
If no, thanks for reading and trying to help.
Thanks
Answer: Most people would easily be able to do this with a bit of practice.
As it's a language not designed for humans, it will take a while
The above test is in ASCII.
Broken down: \xST is how ASCII is written
\x tells the machine to convert to hexadecimal
ST are just any one of 0-9 and a-f
So you just have to find the translator tool and start learning
Comment: Not a-z, but A-F

How can i read this kind of text


Javascript: Stop until RETURN key is press

Question: I'm newbie with javascript and I'm not able to figure out how to stop and wait until return key has been pressed.
Any help is appreciated.
Thanks in advance.
Answer: You could either do it with a callback function, or using async await to wait a specific key is pressed:

const keyIsPressed = target => new Promise(resolve => {
  document.body.addEventListener('keyup', ({ key }) => {
    if(key.toUpperCase() === target.toUpperCase()) {
      resolve();
    }
  }, { once: true });
});

async function start() {
  console.log('Waiting for user to press enter...');

  // pause here until enter is pressed
  await keyIsPressed('enter');

  console.log('Enter is pressed.');
}

start();
Comment: You might need to add `{once: true}` options or manually unsubscribe to avoid memory leak.
Comment: @YuryTarabanko You're absolutely right. Thanks for the correction.


Forcing to center footer doesn't make it

Question: I have a footer I want to center and having this code with CSS:
.footer {
    background: linear-gradient(180deg, rgba(42,53,65,1) 0%, rgba(0,67,121,1) 150%);
    padding:20px;
    z-index: 70;
    font-size:9px;

    margin: 0 auto !important;
    left: 0 !important;
    right: 0 !important;
    text-align: center !important;

    border: 0.1em dotted red;
}
.fullWidthFooter, .fullWidthFooter#nav {
    width: 100% !important;
    margin: 0 auto !important;
    left: 0 !important;
    right: 0 !important;
    text-align: center !important;

    border: 0.1em dotted brown;
}
#menu-footer-menu, #menu-footer-menu-footer-links-english {
    margin: 0 auto !important;
    left: 0 !important;
    right: 0 !important;
    text-align: center !important;
    width: 900px important;

    border: 0.1em dotted yellow;
}
#menu-footer-menu ul {
    display: inline-block;

    margin: 0 auto !important;
    left: 0 !important;
    right: 0 !important;
    text-align: center !important;
}

        ::before

....

....

....

....

as you can see in CSS I try to force to show it centered but it doesn't and it remains at left, as you can see in the screenshot:

maybe forcing with 0 value is not the right way?...
I thought it was the right way after following what it's said here in the comment: Center footer on wordpress theme
A direction would be appreciated, thanks! Cheers!
Comment: What's definitively not the right way to _ask_, is to show only snippets that appear to not be able to reproduce what your screenshots shows in the first place (https://jsfiddle.net/2h5etms3/) - _proper_ [mre], please, when you ask this kind of question here.
Answer: As far as I could understand your question, you need to center the div with yellow border.
1) For this, you need to remove the width property applied at #menu-footer-menu, #menu-footer-menu-footer-links-english and hopefully, it'd work for you.
2) Second approach you can use is to apply these properties to the above selector.
    display: flex;
   justify-content: center;

The code formatter isn't working, don't know why. But I guess you've got my point.
Comment: thank you for your direction!!!.... applying a different display was the trick... didn't thought about that because it's an horizontal menu and I thought it could broke horizontal placement of the `` list but indeed it worked! Thanks again!
Comment: I'm glad it worked for you...


Determining an expression problem

Question:
Determine an expression, in simplified form, for the slope of the secant $PQ$ with $P(1,2)$ and $Q(1+h, f(1+h))$ where $f(x) = 2x^2$

I don't even know how to approach such a question. Any help would be much appreciated. Thanks.
I know the answer is either:
a. $4 + 2h$
b. $4 - 2h$
c. $8 - 4h$
d. $8 + 4h$
Comment: [Please see here](http://meta.math.stackexchange.com/q/5020/264) for help writing math with MathJax, and [see here](http://math.stackexchange.com/help/formatting) for help formatting posts with Markdown.
Comment: Hint: go, get the math book your teacher is using and read it. Honestly, there will be no use for you from this site, since obviously (given the nature of your all questions) you have no idea whats going on. It seems like you have no basic knowledge, or have no idea about the notions that your questions are about.
Comment: (Note: Tomas doesn't necessarily speak for anyone besides himself. If you are *that* lost, though, you should seek personal attention.)
Answer: As $f(x)=2x^2, f(1+h)=2(1+h)^2$
So, the slope will be $$\frac{f(1+h)-2}{1+h-1}$$
Comment: Is the answer 4 + 2h?
Comment: @mathgeek101, yes provided $h\ne0$ (why?)
Comment: @amWhy, I left the last calculation for the user which  he had re-confirmed. See his comment above
Answer:
I don't even know how to approach such a question.

That's no good! Hopefully we can get you on track...
Most of the time, the problem will tell you what it wants, often using an imperative verb.
In this case, it says "Determine...", but determine what?!?
A slope.
So if you don't know the standard formula for slope: $$m = \dfrac{y_2 -y_1}{x_2 -x_1}$$
... you're gonna have a bad time (as the saying goes).
We can rewrite the slope formula using whatever letters we like, so maybe the following will prove useful: $$m = \dfrac{P_2 - P_1}{Q_2 - Q_1}$$
... where $(P_1, P_2) = (1,2)$ and $(Q_1, Q_2) = (1 + h, 2(1+h)^2)$
From here, you should arrive at the same conclusion as in the other answer(s).
Comment: +1 (And my earlier "not so fitting" comment posted elsewhere now deleted.) ;-)

Determining an expression problem


Creating a USB media using UNetbootin isn't recognized as booting media

Question: I've installed Ubuntu by USB many times before. It's not working now and I'm not sure why.
I format the USB drive (a Kingston DataTraveler 100 G2, 16 GB) using GParted by wiping it and installing a FAT32 primary partition on it. I change the permissions of the drive filesystem from root to the main user (sudo chown user1: /media/user1/4B8C-3997). I download Ubuntu (wget http://mirror.switch.ch/ftp/mirror/ubuntu-cdimage/15.10/ubuntu-15.10-desktop-amd64.iso) and then write the ISO to USB using UNetbootin. Then, when I try to boot from the drive, it simply loops back to asking which drive to boot from.
Do you have any ideas about what might be causing this?
Answer: Unetbootin does not create the Ubuntu installation media properly.
Use the Disks tool (gnome-disk-utility) to create the USB media.
Open Disks, select Restore Disk Image from the menu on the top right.
Choose the ISO file and the USB drive to write it to and start restoring.
When you want to create the installation media from within Windows,
boot Windows, open command prompt as administrator and execute :
diskpart
list disk
select disk *
clean
create partition primary
active
format fs=fat32 quick
assign letter=**

Note : * = number of USB drive | ** = select a free drive letter
Now mount the ISO file and copy the content to the USB disk.
Comment: Can you at least explain why unetbootin doesn't work ? as it is actually supposed to..
Comment: @ArceusMaster0493 : You cannot use the Windows diskpart tool as a normal user, because you need to have elevated privileges to work on disks - so you will have to execute the commands as administrator. :)
Comment: Does opening as administrator make a difference?
Comment: Holy, wasted so much time trying to flash iso and it is that easy.
Answer: Use this git clone for a faster bootable usb creator.
git clone git://github.com/pbatard/rufus

Alternative Windows mirror: https://github.com/pbatard/rufus/archive/v2.8.zip
It can also format the partition to FAT32 easily
Answer: If you want to boot from USB and you are prepared to wipe all existing contents from the USB device, there is a much simpler way:
cat ubuntu-15.10-desktop-amd64.iso >/dev/sdx

Where /dev/sdx is the device name of the USB media. Be very careful because a small typo in this command could wipe your hard drive.
This works because the Ubuntu ISO images utilize the free space at the start of any ISO image to include a partition table and boot loader suitable for booting from USB.
It is also possible to partition the USB device manually, create a file system, copy the ISO file to that file system, install a boot loader, create a boot menu entry to boot from the ISO file. But performing all of these steps manually is more work, and it is easy to make mistakes meaning you have to try a few times before you get the system to boot.
Answer: I was having the same problem on Mac, and I believe it was because of how I'd formatted my USB stick. Originally I had just created a partition as FAT and was able to load many different ISOs onto the device. Then I made a mistake and had to re-format(?) the whole device, which included re-making the file/partition table. Originally I just chose the default "Scheme", "GUID Partition Map". From this point on I was having trouble. I had a hunch that it might require the "Master Boot Record" scheme, so I erased the whole USB stick again with that setting. Then when I ran unetbootin again it worked without issue.
what's more, if unetbootin is still not working with you, then change to another tools like SYSGeeker's WonderISO or rufus.
Answer: I think Etcher is worth a mention and works on all platforms.


JMS TextMessage itext PDF header signature not found

Question: I have a listener that receives a JMS TextMessage that has pdf content in there.
I am doing getBytes("Cp037") since it is coming from mainframe
when i run the line "PdfReader reader = new PdfReader(bais)";
it crashes with PDF header signature not found.
It should be a valid pdf since another app is able to get the pdf.
What could be the problem? Thanks
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

            TextMessage txtMessage = (TextMessage)message;
                ByteArrayInputStream bais = new ByteArrayInputStream(txtMessage.getText().getBytes("Cp037"));

                PdfReader reader = new PdfReader(bais);

Comment: You must NOT convert PDF to text.  There's a pile of binary information in there that Must Not Change.
Comment: @john Can you try `txtMessage.getText().getBytes(System.getProperty("file.encoding"))`?
Comment: no it did not work. I think this is more JMS related maybe...I am receiving a TextMessage instead of BytesMessage. I do see PDF-1.3 on the first line, but before that I see bunch of weird characters
Comment: ok. how is the other app, that you mentioned, processing it?
Comment: The weird characters might be a BOM sequence
Answer: I had the same error and I just changed my PdfReader from reading InputStreams to read Strings. So, it works perfectly with:
public static void doMerge(List<String> list, OutputStream outputStream)
        throws DocumentException, IOException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();
    PdfContentByte cb = writer.getDirectContent();

    for (String in : list) {
        PdfReader reader = new PdfReader(in);
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            document.newPage();
            // import the page from source pdf
            PdfImportedPage page = writer.getImportedPage(reader, i);
            // add the page to the destination pdf
            cb.addTemplate(page, 0, 0);
        }
    }

    outputStream.flush();
    document.close();
    outputStream.close();
}

*Originally I took this code from
http://www.mindfiresolutions.com/Java-Merging-multiple-PDFs-into-a-single-PDF-using-iText-671.php
Answer: Why is it a TextMessage instead of a BytesMessage?
As Mark wrote, a PDF contains binary data. So it looks like the sender side of the JMS communication has to be changed too.


How to disassemble old Moen kitchen faucet

Question: I have an leaking older single-handle Moen faucet.  All the info I've found for such faucets shows a removable cap on top of the handle; removing that exposes a screw, which allows removal of the handle, etc.
This faucet doesn't have a clearly-removable cap; instead, it has a slightly inset surface on top of the faucet, which is covered with a 'Moen' sticker.  I tried gently prying on that, but it wasn't clear that it was meant to come off.
So, before pushing on and maybe defacing the surface, does anyone know how to disassemble this faucet?  Or, for that matter, what the model number would be.
Thanks
Edit: It turns out, the "Moen" thing is just a sticker.  Peel it back, and there's the screw.  No cap to pry off.
Comment: On the picture you posted that little center section where the Moen sticker is looks like it has a small recess where you can get a blade or a thin screwdriver under it or is that where you just tried to pry it before? That center cap judging by my previous experience should come out but I could be wrong. If it does that will certainly expose the screw that holds the handle on.
Comment: I had a faucet similar to this, the lever and cap that the screw holds down can be a real bear to pull still
Comment: do you know what model of this one? I have exact one and it is dripping. I can't find the model to find replacement part.
Comment: Model is on the back of the unit. If you turn the handle so its pointing away from you, you should be able to see the number.
Answer: So far, everything I find online shows that the screw is certainly under the cap but no direction how specifically to remove the cap. Here is an image that I found:

Hope it helps!
Comment: I had a faucet similar to this, the lever and cap that the screw holds down can be a real bear to pull still
Comment: Oooh, you even get to keep the sticker! Looked like a decal in the first pic.
Comment: do you know what model of this one? I have exact one and it is dripping. I can't find the model to find replacement part.
Answer: The entire piece that the moen label is on pulls off. It may take a little effort, but once you have it popped off you will find the single screw underneath.
Comment: Hello, and welcome to Home Improvement. Great answer; keep 'em coming!
Comment: do you know what model of this one? I have exact one and it is dripping. I can't find the model to find replacement part.
Answer: I drew a small black circle around the area of that tab where you can slip a utility knife point underneath of it and pop it out it should come out pretty easily.
Comment: I guess this is also a correct answer...
Comment: (as per my edit to the OP) The Moen thing is just a sticker covering the screw.  It peels off.
Comment: Where you able to get the handle off of there once you got to the screw or was it really really hard to get off?
Comment: > Where you able to get the handle off of there once you got to the screw ..
Comment: user41750: Try again: ran over the clock.  (and not getting this line break thing)  No problem.   After removing the screw, I pulled up on the handle and tipped it back, and it came right off. Pretty much like [YouTube](https://www.youtube.com/watch?v=F5M4feAc7Y8)
Comment: do you know what model of this one? I have exact one and it is dripping. I can't find the model to find replacement part.
Answer: It's possible the entire top half comes off, not just the label on top. It may pop off with a gentle prying, or with a small set screw that's exposed when the handle is raised. Shutoff the water and lift the handle to see if there are any small screws.
If you don't see any screws, feel the top label, press firmly, and see if there are any obvious indentations for a screw hole. Assuming there aren't any, give the entire top cap a gentle prying, and if it shows signs of loosening, keep working it from each side until it's free.
Answer: the cartridge for this and many other moen kitchen faucets is a #1225 cartridge..moen has a great warranty exchange for these cartridges most hardware stores and moen dealers have replacements, bring the old for a new.
Answer: This model is M7800 , replacement cartridge #1225 can be exchanged for free !
Thanks to Moen !
M7800 not sold anymore.


Wifi light switch needs neutral wire. Why? AND Can that wire be a skinny one?

Question: What does the neutral wire do on a light switch that responds to wifi?
My suspicion is that when the switch is in the off position, the electronics in the switch need to still be powered, so the neutral wire allows a tiny constant current through the switch so it can respond to a wifi instruction to actuate the switch.
If this is so, could the extra neutral wire going to the switch be a very light gauge wire?
Answer: Because unlike a normal switch, the wifi switch needs power, so it needs a neutral wire to complete a circuit at the switch between the unswitched hot wire and neutral for that power.
The neutral wire to the switch cannot be a light-gauge wire (at least if you are in an area subject to NEC codes; likely similar elsewhere in the world) because codes are based on what the circuit breaker protecting the circuit can supply when choosing wire size, so for 15A circuits the wire must be 14 Ga or larger, and for 20A circuits the wire must be 12Ga or larger. Smaller wires could overheat to the point of causing fires (without tripping the breaker) in the event of a fault condition, even if the normal current in them might be a matter of a few milliamperes.
I regard wifi switches (and thermostats) with the baleful gaze that only a network admin can view such things askance with, but I gather that there are units arranged in such a manner that the actual switch/relay can go in the ceiling where the light fixture that the switch loop originates from is, and the switch loop wires can (without adding any) be repurposed to operate the remote switch in the wall, no longer actually running the power for the lights through there. This type of unit will probably be much easier to install than to attempt to add a neutral wire to a switch box without one.
Comment: I gave up.  I'm just going to use another Ankuoo SW5101.  It is a wifi-controlled plug-in outlet.  I am already using two of them to control garage and workshop A/Cs.

I'll just plug the Ankuoo SW5101 into a nearby wall outlet, and plug the line going to the fan I want to control into the Ankuoo SW5101.

This bypasses the need for a fourth wire altogether.

https://www.amazon.com/Ankuoo-Smart-Plug-Wi-Fi-White/dp/B00NAX2GVU/ref=sr_1_fkmrnull_3?keywords=ankuoo+sw5101&qid=1558528360&s=gateway&sr=8-3-fkmrnull
Answer: That is correct.  In the mains power world, we have 3 wires.
EQUIPMENT SAFETY GROUND/EARTH which is not used for anything ever (except during a fault condition, of course)...
HOT which is what humans consider the "source" of power... and
NEUTRAL which is what humans consider the "power return".   Obviously, it's AC, which makes "source" vs "return" rather arbitrary. This can be said: the system has equipotential bonding that, in normal conditions, places neutral quite close to safety earth.  That's why it's called neutral.
When you want to power something 24x7, it must be connected between HOT and NEUTRAL.  If it is not, it won't have power. Since presumably you want the WiFi switch to respond to WiFi at all times, you need HOT and NEUTRAL to pull that off.
You may be thinking of early dimmers.  Those place themselves in series with the light bulb, so they connect between ALWAYS-HOT and SWITCHED-HOT.  When the bulb is on, they create a small voltage drop and power themselves that way. When the bulb is off, they leak a small amount of current through the bulb, which works great with incandescents, but badly with most LEDs. It's possible to build a smart switch this way, in which case it does not need neutral.  However it is difficult to design, and doesn't play well with most LEDs and CFLs.  This can be solved by using 1 incandescent, or by putting a capacitor in parallel with the light bulbs so some power can leak through 24x7.
A very small number of dimmers place themselves in series with the equipotential bonding that keeps neutral near ground. In short, they bootleg neutral off of ground, but do so in very controlled conditions that satisfy Underwriter's Laboratories that it won't be unsafe. Don't do this yourself, unless instructed to by this particular device's UL-approved labeling and instructions.

If you don't want to hunt down a compatible smart switch, you need to replace the entire cable between light switch and light, with a /3 cable (black red white +ground).  Then you make black always-hot, red switched-hot, and white neutral, hooking each as appropriate to the smart switch and up in the lamp.
If it is simpler to run power from the service panel, then run a /2 cable from the service panel to the switch, feed the lamp from the switch, and cap off the supply hot+neutral going into the lamp.  (or disconnect it from the lamp circuit in all respects).
If conduit is used with individual wires (THHN), and hot and switched-hot are already colored wires, then you can simply add a similar (THHN) white wire to the pipe.
Other than that, you cannot just run an individual wire.  I gather you're a DC electronics guy?  This is AC, and magnetic fields from AC have a serious kick. So currents must be equal in all cables or conduits so magnetic fields cancel each other out. Which means all related wires must be in the same cable.
You are allowed to run an individual safety ground (i.e. retrofit), because current does not flow over safety ground (except during a fault).

You can't run a tiny wire because we don't wire houses for ideal conditions, we wire them for fault conditions.  Fault conditions call for a shorting smart switch that is flowing 50A through that 15A-rated wire.  That 15A-rated wire will heat up at a predictable rate, and the breaker will thermal-trip before the wire heats up to a dangerous temperature.  Now if your neutral wire is smaller, it will heat up faster.
That's why you would need to size the entire circuit's breaker for that smallest wire.  They don't allow <15A circuits in houses because the incremental cost of copper for a larger wire becomes pretty marginal at that size.  That, and economies of scale make #14 effectively as cheap as smaller sizes.
Comment: @Gyrobob Harper will, I am sure, explain in full detail. But basically: 1 - You would likely find it shorter to run from the switch to the light fixture, as neutral is always present on the fixture (one side switched hot, one side neutral). 2 - You can't run a wire by itself - if you have individual wires in conduit, you can it **together with** the existing hot/switched hot wires; if you have **cable** then you need to **replace the cable** with a cable that has an extra wire for neutral.
Comment: @Gyrobob added.
Comment: @R.. because dimmers are not variacs, nor are they resistive.  They chop the AC waveform in some fashion. It takes some electronics to get from "(tiny)rheostat position" to "shape of chopped waveform", and also some power to get from "off" to "started up".
Comment: So I would guess the solution, then, is to run a 14 gauge wire from the wifi light switch all the way back to the circuit breaker box (about 50') and attach it to the neutral buss.
Comment: FYI, in Australia "hot" is called "active". Mentioning because we don't know where the OP lives.
Comment: Why would a conventional dimmer need to "power itself" at all?


Intermittent webservice error

Question: My webservice produces a "Service not available" error first, then when I restart the IIS service it works. When i checked the eventlog I found this error concerning
ASP.NET 2.0.50727.0
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 1/13/2010 5:31:02 PM
Event time (UTC): 1/13/2010 10:31:02 PM
Event ID: a3f163d4529d4e7389fd9828ef75a5f3
Event sequence: 2010
Event occurrence: 2
Event detail code: 0
Application information:
    Application domain: /LM/W3SVC/337954533/Root-1-129078638848593750
    Trust level: Full
    Application Virtual Path: /
    Application Path: C:\Inetpub\wwwroot##\
    Machine name: MU
Process information:
    Process ID: 6096
    Process name: w3wp.exe
    Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
    Exception type: TargetInvocationException
    Exception message: Exception has been thrown by the target of an invocation.
Request information:
    Request URL: https://www.##.com:443/AccountList.aspx?type=RklYRUQgREVQT1NJVA1/13/2010 5:31:02 PMd1/13/2010 5:31:02 PMd-ch1BLi4bsZQ1/13/2010 5:31:02 PMd
    Request path: /AccountList.aspx
    User host address: ##.##.##.##
    User:
    Is authenticated: False
    Authentication Type:
    Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
    Thread ID: 7
    Thread account name: NT AUTHORITY\NETWORK SERVICE
    Is impersonating: False
    Stack trace:    at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method, Boolean disposeInstance, Object& instance)
   at System.Web.UI.WebControls.ObjectDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments)
   at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback)
   at System.Web.UI.WebControls.DataBoundControl.PerformSelect()
   at System.Web.UI.WebControls.BaseDataBoundControl.DataBind()
   at System.Web.UI.WebControls.GridView.DataBind()
   at System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound()
   at System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls()
   at System.Web.UI.Control.EnsureChildControls()
   at System.Web.UI.Control.PreRenderRecursiveInternal()
   at System.Web.UI.Control.PreRenderRecursiveInternal()
   at System.Web.UI.Control.PreRenderRecursiveInternal()
   at System.Web.UI.Control.PreRenderRecursiveInternal()
   at System.Web.UI.Control.PreRenderRecursiveInternal()
   at System.Web.UI.Control.PreRenderRecursiveInternal()
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Answer: You might want to check the recycling/memory settings of your application pool. I've experienced similar errors that occur when memory objects grow too big and the app pool begins to choke. You may also want to download the IIS debug diagnostics tools:
http://support.microsoft.com/kb/919789
Comment: The thing is, none of the IIS services stopped as far as the system log is concerned.
Comment: The IIS service itself doesn't stop. What happens is an exception (somewhere) causes the w3wp.exe process to crash. This leaves the W3SVC intact but the application turns itself off. You can also try disabling "rapid fail protection" in the application pool properties to alleviate the symptom, but that will only mask the real problem.
Comment: I guess the best approach is to 1. configure recycling of the application pool once the worker process for my webservice gets large 2. Go through the code and make sure objects are being used and disposed properly.. any suggestions?
Comment: Too many to list here. A lot of things could be causing this. In my case it was a fairly large session object that had a memory leak (kept adding to itself with every page view). My immediate solution was to separate the session state from InProc to StateServer, but this only delayed the problem. The debug diagnostics was how I tracked down what was doing it. But be patient. It traps a LOT of info.

Intermittent webservice error


Django REST reject bad PATCH data

Question: So, I have a patch request that looks like the following to my /user/1 endpoint. Obviously, the "sdfsdf" is not a valid attribute on my User model. When I patch the following, I get a 200 response, but it should throw a 400 or 422 because "sdfsdf" is not a valid field. How do i reject bad patches?
{
    "sdfsdf": "sdfsdf"
    "username": "alex"
}

My User Serializer lookes like this:
class UserSerializer(serializers.ModelSerializer):
class Meta:
    model = User
    fields = ("first_name", "id", "username")

My User View looks like this:
class UserViewSet(viewsets.ViewSet):
serializer_class = UserSerializer

def list(self, request, pk=None):
    queryset = User.objects.filter()
    serializer = UserSerializer(queryset, many=True)
    return Response(serializer.data)

def retrieve(self, request, pk=None):
    queryset = User.objects.filter()
    user = get_object_or_404(queryset, pk=pk)
    serializer = UserSerializer(user)
    return Response(serializer.data)

def partial_update(self, request, pk=None):
    queryset = User.objects.filter()
    user = get_object_or_404(queryset, pk=pk)

    if not request.user.pk == user.pk:
        raise PermissionDenied

    serializer = UserSerializer(user, data=request.data, partial=True)

    serializer.is_valid(raise_exception=True)
    serializer.save()
    return Response(serializer.data)

Comment: Maybe since you have specifically defined fields to deserialize [fields = ("first_name", "id", "username") ], others are ignored? Remove it and see if exception is thrown.
Comment: no dice, I removed that and it still returns a 200
Answer: You can override the UserSerializer.validate method to provide object level validation (read more in the docs).
For example:
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ("first_name", "id", "username")

    def validate(self, data):
        invalid_keys = set(self.initial_data.keys()) - set(self.fields.keys())
        if invalid_keys:
            raise serializers.ValidationError('invalid keys passed into serializer: {0}'.format(invalid_keys))
        return data

Django REST reject bad PATCH data


Whats is right sequence of using git?

Question: I have two branches: develop, production.

Firtsly, I pull latest changes from develop branch.
After I do changes with these files.
Then to make add/commit in current develop  branch
After switch on the brance production Then I do push to selected branch

Need I make pull when I change branches or I can just push changes from one branch to another?
Comment: You don't need to pull when you change branches, but not doing that risks that you might not have the latest changes which happened in that branch.  Also note that you never pushed your changes made to `develop`.  This may or may not be what you intended.  I would recommend reading a basic Git tutorial to get the feeling for how to use Git.
Comment: I recommend using `git fetch` often and `git pull` never (or almost never). See the "related questions" link, What is the difference between 'git pull' and 'git fetch'?, and learn that `git pull` starts by *running* `git fetch` (and then does a second step). Mentally—and then actually—splitting these up will give you a much better picture of what Git is doing.
Answer: You have three branches in total. I presume you have three, not considering master as Develop branch.
1. Master
2. Develop
3. Production

Step1:

you create a develop branch from master git checkout -b d/developing_f1

Step2:

You work on develop branch make commits and then create a review to the peer from Develop branch, when your done with review you merge your commit to master or just push the branch to origin.

git commands:
git add -A "feature"
git commit -m "Developed f1"
git push origin d/developing_f1

Step3:
If you want to create a branch from Develop to production is not advisable. You merge your branch to master and pull the latest and greatest of master. Then create production branch.
Because you don't want to miss the other feature developed by others.
Step4:

You can merge you branch or rebase your branch master is upto you.

Merge commands
git checkout master
git merge d/developing_f1
git push origin master

After merging your branch to master, now master has the f1 feature.
You need to do git pull origin master, it will have f2, f3 features developed by others and the create a production branch.
Now your production branch has all f1, f2, f3.

Whats is right sequence of using git?


Do toggle abilities proc on-hit passives like Spellblade?

Question: Some champions (like Ashe) have toggleable abilities (for example her Q - Frost Shot). When I activiate such an ability, how does it proc an On-Hit passive like the Spellblade passive from the item Trinity Force?
Does this behaviour apply to all champions with similar abilites, like Aatrox?
Answer: Toggle Abilities do not trigger an ability based effect
Now an Ability based effect is something like Sheen, Rageblade or The Maokai Passive which stacks up for every spell cast. This basically means that toggle abilities aren't considered spells.
You will however get stacks on Tear of Godess and the two items you can build out of it if you spend mana. Some good examples are Singed (Q costs mana every second activated) and Ashe (Costs mana every shot done with it).
Another thing that could be classified as a "Toggle" is the Ultimate of Nidalee. It won't give you stacks on a Tear like item but it will count as a spell cast (It doesn't cost any mana).
There are only two exceptions: The Toggle Abilities that do count as a full spell are Maokai Ultimate and Anivia Ultimate.
Here you can read the full Wiki article about toggle spells.
Comment: Well that kinda sucks but I suppose it would very overpowered to have a spellblade aa proc on Ashe if it were