text:
Q: Why AspectJ weaving on package scoped methods not working? I am trying to print logs for private and package scoped methods (from package scoped classes) in my application which is based on Spring. Since Spring's proxy based aspects don't work on private and package scoped methods(?), I tried to use AspectJ load time weaving as per the documentation. Below are the details:
LoggingAspect
@Component(Constants.LOGGING_ASPECT_BEAN)
@Aspect
public class LoggingAspect {
  @Around("@annotation(my.pkg.Loggable)")
  public Object doLogging(final ProceedingJoinPoint joinPoint) throws Throwable {
    // ... logging code.
  }
}

Spring Configuration
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Import(AnotherBaseConfig.class)
@ComponentScan("my.pkg")
@EnableWebMvc
@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.AUTODETECT)
public class AppConfiguration extends WebMvcConfigurerAdapter {
  // ... bean configs
}

src/main/webapp/META-INF/aop.xml
<aspectj>
  <weaver>
    <include within="my.pkg.*">
  </weaver>
  <aspects>
    <aspect name="my.logger.LoggingAspect"/>
  </aspects>
</aspectj>

JVM Config
-javaagent:"/path/to/spring-instrument-4.0.6.jar" -javaagent:"/path/to/aspectjweaver-1.8.1.jar"

With above configurations, I have my package scoped classes as:
@Component("someClass")
class SomeClass {
  @Loggable
  void doSomething(@Loggable final String s, @Loggable final Integer i) {
    // ... do something here.
  }
}

The weaving is not working for such package scoped classes. Am I doing anything wrong?

A: You are mixing up two AOP styles here:

*

*Spring AOP ist a proxy-based "AOP lite" approach which is activated via @EnableAspectJAutoProxy. It only works for public, non-static methods of Spring components.

*AspectJ, a full-blown AOP framework which also works on package-local or private methods, no matter if they are Spring components or not, is enabled from within Spring via @EnableLoadTimeWeaving and the weaving agent via -javaagent:"/path/to/aspectjweaver-1.8.1.jar". In this case your aspect does not need to be a Spring component either. P.S.: I recommend to use the latest AspectJ version 1.8.5, not 1.8.1.

As you want to work with package-locals, you need AspectJ LTW. Please configure Spring clearly in preference of one AOP type. More information can be found in the Spring Manual, chapter 9. Specific information about AspectJ LTW configuration is in chapter 9.8.


text:
Q: implement a coverflow UI in an Android web application I am trying to build a coverflow UI on an Android web application using HTML,CSS, JavaScript and some images.
CSS 3D transforms, which are supported in Safari sine 2009 and on the iPhone since version 2.0, is not supported well on the Android. worse then that, the implementation is buggy on Android 2.1 and Android 2.2, and in each version in a different way.
Any idea how can I build a coverflow UI on an Android web application using HTML,CSS, JavaScript and some images without CSS 3D transforms?

A: If you're looking for textured 3D transformations without the use of CSS 3D or plugins, look no further than Canvas, the HTML element present on most cutting-edge browsers. There are already 3D libraries that take advantage of this, like K3D.
On the flip side, you can use dynamic HTML and pre-rendered images at different angles. For a 3D effect without rotations, simply implement a basic 3D rendering formula, such as this one:
Point's X position on the screen = position X in pixels / distance away + half of the screen width
Point's Y position on the screen = position Y in pixels / distance away + half of the screen height

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java pattern for [j-*] Please help me with the pattern matching. I want to build a pattern which will match the word starting with j- or c- in the following in a string (Say for example)
[j-test] is a [c-test]'s name with [foo] and [bar]

The pattern needs to find [j-test] and [c-test] (brackets inclusive).
What I have tried so far?
String template = "[j-test] is a [c-test]'s name with [foo] and [bar]";
Pattern patt = Pattern.compile("\\[[*[j|c]\\-\\w\\-\\+\\d]+\\]");
Matcher m = patt.matcher(template);
while (m.find()) {
    System.out.println(m.group());
}

And its giving output like
[j-test]
[c-test]
[foo]
[bar]

which is wrong. Please help me, thanks for your time on this thread.

A: Inside a character class, you don't need to use alternation to match j or c. Character class itself means, match any single character from the ones inside it. So, [jc] itself will match either j or c.
Also, you don't need to match the pattern that is after j- or c-, as you are not bothered about them, as far as they start with j- or c-.
Simply use this pattern:
Pattern patt = Pattern.compile("\\[[jc]-[^\\]]*\\]");

To explain:
Pattern patt = Pattern.compile("(?x)      "   // Embedded flag for Pattern.COMMENT
                             + "\\[       "   // Match starting `[`
                             + "    [jc]  "     // Match j or c
                             + "    -     "     // then a hyphen
                             + "    [^    "     // A negated character class
                             + "       \\]"        // Match any character except ]
                             + "    ]*    "     // 0 or more times
                             + "\\]       "); // till the closing ]

Using (?x) flag in the regex, ignores the whitespaces. It is often helpful, to write readable regexes.


text:
Q: Convergence of Linear First-Order Differential Equations Suppose $u$ is a twice continuously differentiable function with linear growth, $$\lim_{x\rightarrow \infty} u'(x)-\frac{1}{g(x)} u(x) = 0 $$
and $g$ is a Lipschitz continuous function with Lipschitz constant $L<1$.
Consider the first order linear homogenous differential equation
$$y'(x)- \frac{1}{g(x)} y(x) = 0 .$$
The general solution is
$$y(x)=c \exp\left(\int \frac{1} {g(x)} dx\right)$$
for constant $c \in \mathbb R$. In any solution with linear growth, $\lim_{x\rightarrow \infty} y(x)=0$.
Is it possible to conclude that
$\lim_{x\rightarrow \infty}u(x)=0$?

A: If we only consider the limit
$$
\lim_{x\rightarrow \infty} u'(x)-\frac{1}{g(x)}\, u(x) = 0
$$
and impose conditions $\,u \in \mathcal{C}^2(\mathbb R),\,$ $\,u(x) = O(x),\,$ and $g$ – Lipschitz continuous with $\,L<1$, then the answer is no, we cannot conclude that
$$
\lim_{x\rightarrow \infty}u(x)=0.
$$
Counterexample:
set $u(x) = 2x$, and $g(x) = x$.
Then all conditions are satisfied,
$$
\lim_{x\rightarrow \infty} u'(x)-\frac{1}{g(x)} u(x)
= \lim_{x\rightarrow \infty} \left(2-\frac{1}{x} 2x\right)
= 0,
$$
and yet
$$
\lim_{x\rightarrow \infty} u(x) = \infty.
$$


text:
Q: Suprimir componentes repetidos java Estoy intentando añadir a una lista nueva los componentes que no se repiten a partir de la lista original. He realizado este código pero no funciona. Si alguien me puede ayudar....
public static <E> IndexedList<E> deleteRepeated(IndexedList<E> l)
{
  IndexedList<E> list = new ArrayIndexedList<E>();
     for(int i=0;i<=l.size();i++)
     {
        for(int j=0;j<list.size();j++)
        {
            if(list.get(i).equals(l.get(j)))
            {
                list.removeElementAt(i);
                j=0;
            }
        }
      }
         return list;
}

A: Lo que quieres hacer se resuelve con un java.util.Set. El Set no admite repetidos, con lo cual no tendrias por que remover nada.
Por otro lado si queres seguir usando la lista, podes hacer algo asi:
private List<String> removeReated(List<String> originalValues) {
    List<String> newValues = new ArrayList<>();
    for (int i = 0; i < originalValues.size(); i++) {
        int repeated = 0;
        if (originalValues.contains(originalValues.get(i))) {
            repeated++;
            if (repeated < 1) {
                newValues.add(originalValues.get(i));
            }
        }
    }
    return newValues;
}

EDIT: La solucion correcta es usar un set:
Set mySet = new HashSet();

A: Usa un set y asegúrate de sobrescribir el método equals en los objetos que pasas al método.
En los dos casos tu. Equals no va a funcionar si no sobrescribes el método equals porque aunque los valores sean los mismos tus objetos son diferentes.

A: Lo más fácil es a través de streams:
private List<String> removeReated(List<String> originalValues) {
    return originalValues
        .stream()
        .distinct()
        .collect(Collectors.toList());
}


text:
Q: WCF returning Endpoint not found on live I have hosted a WCF service on shared environment which contains two different methods. One is returning the desired output, while the other gives endpoint not found exception, which is my main method to authenticate users.
The scenario is depicted here:
My Iservice.cs is as below
[OperationContract]
[WebInvoke(Method="GET", UriTemplate = "Data?Id={id}", ResponseFormat=WebMessageFormat.Json)]
string GetData(string id);

[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "Login?InstId={inst}&UserId={user}&pwd={pwd}", ResponseFormat = WebMessageFormat.Json)]
string Authenticate(string inst, string user, string pwd);

which then authenticates user details through DAL, which is working fine. My web config is as below:
  <system.serviceModel>
    <!--<serviceHostingEnvironment multipleSiteBindingsEnabled="True" aspNetCompatibilityEnabled="True">
    </serviceHostingEnvironment>-->
    <serviceHostingEnvironment multipleSiteBindingsEnabled="True">
    </serviceHostingEnvironment>
    <services>
      <service name="WCFDemo.Service1">
        <endpoint address="http://www.ekotri.com/Service1.svc" behaviorConfiguration="restfulBehavior"
                  binding="webHttpBinding" listenUri="/" bindingConfiguration="" contract="WCFDemo.IService1">
        </endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://www.ekotri.com" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="restfulBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="restfulBehavior">
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

GetData is working fine, but Authenticate gives endpoint not found error. It works fine on local IIS though.

A: Try this configuration:
<system.serviceModel>
<!--<serviceHostingEnvironment multipleSiteBindingsEnabled="True" aspNetCompatibilityEnabled="True">
</serviceHostingEnvironment>-->
<serviceHostingEnvironment multipleSiteBindingsEnabled="True">
</serviceHostingEnvironment>
<services>
  <service name="WCFDemo.Service1">
    <endpoint address="rest" behaviorConfiguration="restfulBehavior"
              binding="webHttpBinding" contract="WCFDemo.IService1">
    </endpoint>
    <host>
      <baseAddresses>
        <add baseAddress="http://www.ekotri.com/Service1.svc" />
      </baseAddresses>
    </host>
  </service>
</services>
<behaviors>
  <endpointBehaviors>
    <behavior name="restfulBehavior">
      <webHttp />
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior name="restfulBehavior">
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
</behaviors>

I have tested it on default WCF application project from visual studio and did not have any problems.

A: Try changing your interface like this
[OperationContract]
 [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "Login/{inst}/{user}/{pwd}",
    BodyStyle = WebMessageBodyStyle.Bare)]
string Authenticate(string inst, string user, string pwd);

Put this configuration,
<system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="customBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
        <message clientCredentialType="UserName" algorithmSuite="Default"/>
      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<services>
  <service behaviorConfiguration="asmx" name="WCFDemo.Service1">
    <endpoint address="basic" binding="basicHttpBinding" name="httpEndPoint" contract="WCFDemo.IService1"/>
    <endpoint address="json" binding="webHttpBinding" behaviorConfiguration="webBehavior" name="webEndPoint" contract="WebApplication1.IService"/>
    <endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
  </service>
</services>
<behaviors>
    <endpointBehaviors>
        <behavior name="webBehavior">
            <webHttp />
        </behavior>
    </endpointBehaviors>
    <serviceBehaviors>
    <behavior name="asmx">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>

A: What url are you using when you attempt to hit your login method?
According to your service file, the url template you are using is
Login?InstId={inst}&UserId={user}&pwd={pwd}

Further in your config file you are binding it to a specific domain/url path
<endpoint address="http://www.ekotri.com/Service1.svc" behaviorConfiguration="restfulBehavior"
                  binding="webHttpBinding" listenUri="/" bindingConfiguration="" contract="WCFDemo.IService1">

Based on these two pieces of information, the expected access path would be
http://www.ekotri.com/Service1.svc/Login?InstId={inst}&UserId={user}&pwd={pwd}

If I take that template url and plug in some fake values..
Service Action URL
This url returns "False" which is expected.


text:
Q: how can i add an expiration date function on a model? i am trying to make a key verification app that when accepted it would create the same app on the user's profile, so i have done everything but i have struggled making the expiration date part, i want the expired boolean become true when the date is expired, but i have no idea on how to implement it
#models.py
    class ProductKey(models.Model):
        product = models.ForeignKey(Product, on_delete=models.CASCADE,
        unique=False)
        key = models.CharField(max_length=14)
        valid_from = models.DateTimeField(default=timezone.now)
        valid_to = models.DateTimeField()
        expired = models.BooleanField(default=False)

A: Please do not add a database field for this. You will introduce data duplication: if you later set the valid_to, you will have to update expred as well, so the logic would introduce extra challenges.
You can annotate your ProductKey model, such that objects that arise from this have an attribute expired:
from django.db.models import BooleanField, ExpressionWrapper, Q
from django.db.models.functions import Now

ProductKey.objects.annotate(
    expired=ExpressionWrapper(Q(valid_to__lt=Now()), output_field=BooleanField())
)
You can then filter on that property. For example you can retrieve the ProductKeys that are expired with:
ProductKey.objects.annotate(
    expired=ExpressionWrapper(Q(valid_to__lt=Now()), output_field=BooleanField())
).filter(expired=True)
If you need this often, you can annotate this in the manager, like:
class ExpiredManager(models.Manager):

    def get_queryset(self):
        return super().get_queryset().annotate(
            expired=ExpressionWrapper(Q(valid_to__lt=Now()), output_field=BooleanField())
        )

class ProductKey(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE,
    unique=False)
    key = models.CharField(max_length=14)
    valid_from = models.DateTimeField(default=timezone.now)
    valid_to = models.DateTimeField()

    objects = ExpiredManager()

A: You could use a property for this use case and calculate that on the fly.
@property
def expired(self):
   # calculate here if its still valid


text:
Q: Hosting WCF service as Windows Service? I have manage to move my complexed WCF service into a Windows Service. The binding looks like this :
<service behaviorConfiguration="MyAppClientService.CustomValidator_Behavior" name="MyApp.ServiceImplementation.MyAppClientService">
        <endpoint binding="netTcpBinding" bindingConfiguration="netTcpRegular" address="Regular" bindingNamespace="http://MyApp.ServiceContracts/2007/11" contract="MyApp.ServiceContracts.IMyAppClientService"/>
        <endpoint binding="netTcpBinding" bindingConfiguration="netTcpWindowMessageSecurity" address="Windows" bindingNamespace="http://MyApp.ServiceContracts/2007/11" contract="MyApp.ServiceContracts.IMyAppClientService"/>
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8001/MyAppService/Client"/>
            <add baseAddress="http://localhost:8002/MyAppService/Client"/>
          </baseAddresses>
        </host>
      </service>

When the service is started I browse : http://localhost:8002/MyAppService/Client This works fine and I can also see the WSDL.
But when I try to connect to the service with my Winform client It cant find the service, this is how the address looks like in the client :
<client>
<endpoint address="net.tcp://localhost:8001/MyAppService/Client/MyAppClientService.svc/Regular" behaviorConfiguration="BasicBehavior" binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IMyAppClientServiceRegular" contract="MyApp.ServiceContracts.IMyAppClientService" name="MyTest_RegularLogin"/>
</client>

When browsing http://localhost:8001/MyAppService/Client I will get a missing page, I suppose that this is right because it is hosted on tcp and not http?
When the service was hosted in the IIS7(WAS) this was working just fine but then I used a endpoint at the client that looked like this :
<endpoint address="net.tcp://localhost/MyAppDev/MyAppClientService.svc/Regular" behaviorConfiguration="BasicBehavior" binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IMyAppClientServiceRegular" contract="MyApp.ServiceContracts.IMyAppClientService" name="MyApp_RegularLogin"/>

Note : Regular stats that this is a regular login where the client provides username and password(no Windows login)
Edit :
I have followed this article : http://msdn.microsoft.com/en-us/library/ms733069.aspx
And this is how windows service class looks like
public class MyAppWindowsService : ServiceBase
    {
        public ServiceHost _serviceHost = null;
        public MyAppWindowsService()
        {
            // Name the Windows Service
            ServiceName = "MyAppWindowsService";
        }

        public static void Main()
        {
            ServiceBase.Run(new MyAppWindowsService());
        }

        // Start the Windows service.
        protected override void OnStart(string[] args)
        {
            if (_serviceHost != null)
            {
                _serviceHost.Close();
            }

            // Create a ServiceHost for the CalculatorService type and
            // provide the base address.
            _serviceHost = new ServiceHost(typeof(MyApp.ServiceImplementation.MyAppClientService));

            // Open the ServiceHostBase to create listeners and start
            // listening for messages.
            _serviceHost.Open();
        }

        protected override void OnStop()
        {
            if (_serviceHost != null)
            {
                _serviceHost.Close();
                _serviceHost = null;
            }
        }

    }

A: The problem was that I tried to connect to localhost/MyAppDev/MyAppClientService.svc/Regular but it whould be localhost/MyAppDev/Regular


text:
Q: Architecture of c++ projects I am from JAVA so please please guide me if i am wrong.
In Java we mostly use a singleton class and create all the class objects thought the singleton class.
What about in c++?
I know we can use singleton but mostly while going through most of the stack overflow questions. Most of them says it's not good to use singleton in c++
Can you recommend some book or some project which will be easy to understand?

A: Whether you're writing in C++ or Java singletons have many,  bad implications.
They make it very difficult to test as their static nature preculdes late binding to, say, sway a real database with a stub that's quicker and has fewer depencies.
They also provide a fig leaf for global variables, trying to make them masquerade as a good design decision. Take a look at the alternatives, it'll pay off in a better design. You may want to look into dependency injection for ways to design a more testable system without singletons.


text:
Q: Как исправить ошибку в sqlite3? Вообщем-то при моей попытки объединить две таблицы, выскакивает ошибка:
sqlite3.OperationalError: no such column: Kode.gorod
Хотя нужная колонка присутствует, читал в других источниках, пишут, что обычно где-то не хватает кавычек, но у меня вроде всё проставлено. Конкретно ошибка в этой функции:
def Request_Toy_Res(self):
        self.db.c.execute(
            '''SELECT Tovar.tovar, Tovar.vid_tovara, Tovar.Kod, Kode.Izgotovitel, Kode.gorod FROM Tovar INNER JOIN Kode ON Tovar.Kod=Kode.Kod ''')
        for i in self.tab3.get_children():
            self.tab3.delete(i)
        for row in self.db.c.fetchall():
            self.tab3.insert('', 'end', values=row)

Ругается только на колонку Kode.gorod, когда её удаляю всё работает.


text:
Q: systemd service fle: Restart=on-failure not allowed for Type=oneshot services I created a systemd service file to run two rsync commands sequentially and I need to retry until successful. Sometimes the rsync server is down. Systemd tells me Restart=on-failure is not allowed for Type=oneshot services. What other Type of service can I use?
[Unit]
Description=Sync

[Service]
Type=oneshot
Restart=on-failure
ExecStart=/usr/bin/rsync -atvzq --no-owner --no-group --delete rsync://(some address) /srv/www/
ExecStart=/usr/bin/rsync -atvzq --no-owner --no-group --delete rsync://(some address) /srv/www1/

A: I assume you're only using Type=oneshot so you can have several ExecStart= commands.   Other than that, there is no reason to use Type=oneshot since you don't seem to have services that are triggered on successful activation and you aren't using RemainAfterExit=true
Instead, use Type=simple and use ExecStartPre=
[Service]
Type=simple
Restart=on-failure
ExecStartPre=/usr/bin/rsync -atvzq --no-owner --no-group --delete rsync://(some address) /srv/www/
ExecStart=/usr/bin/rsync -atvzq --no-owner --no-group --delete rsync://(some address) /srv/www1/

Here is what will happen:

*

*ExecStartPre= will run before the ExecStart= command.

*During ExecStartPre= execution, the unit will be "activating"

*If ExecStartPre= fails, ExecStart= will not run, the unit will be considered "failed" and will restart.

*During ExecStart= execution, the unit will be "activated"

*After ExecStart= finishes, the unit will be "inactive (dead)" if everything was successful or "failed" if either command was unsuccessful.

If you want to ignore the failure of ExecStartPre= and force ExecStart= to run, prefix the ExecStartPre= command with a - to ignore the non-zero exit code.

A: You could, for example, try to use two services A and B, where B depends on A and A is a oneshot service.
With the set-up shown in the example below, service B is pulled in when the multi-user target is reached (or any other target you specify in the [Install] section). Service B won't start before service A because it has a dependency on service A and is set to start after service A. Also, service B will wait for service A to terminate due to service A being type oneshot.
Because service A is requisite to service B, service B will fail to start if service A fails. Should service B fail, it will restart. Note that default settings put a limit on how many unsuccessful restart attempts (in a given time interval) are allowed before systemd will stop any further attempts to restart.
B.service
[Unit]
Description=Sync Task B Service
Requisite=A.service
After=A.service

[Service]
Type=simple
Restart=on-failure
ExecStart=/usr/bin/rsync -atvzq --no-owner --no-group --delete rsync://(some address) /srv/www/

[Install]
WantedBy=multi-user.target

A.service
[Unit]
Description=Sync Task A Service

[Service]
Type=oneshot
ExecStart=/usr/bin/rsync -atvzq --no-owner --no-group --delete rsync://(some address) /srv/www/


text:
Q: Haskell list of tuples vs tuple comparrison I'm playing with my first non-trivial (in my eyes) attempt at something in Haskell. I'm probably going to ask questions about each part to compare my coming-from-long-term-relationship-with-c-like-languages attempt to what you-as-seasoned-functional-programmer might do. Luckily Haskell makes it hard to fall back on straight c-to-haskell code conversion. You have to learn how to do it right - and I want to.
For this part, I have a [2uple] and a 2uple. I want to know if any item in the 2uple is in any of the items in the [2uple].
hasmatch tlst tupm = foldr (\tup acc ->
                                let tmatch (a,b) (c,d) = a==c || b==c || a==d || b==d in
                                if tmatch tup tupm
                                then (Just True)    -- short out
                                else acc            -- do nothing, keep looping
                          ) Nothing tlst

-- hasmatch [(1,2), (3,4), (5,6)] (5,3) ==> Just True
-- hasmatch [(1,2), (9,4), (7,6)] (5,3) ==> Nothing

I'd prefer to return a plain Bool but no biggie there.
I'm sure there is another way that I would have to grok at for a while to understand. That is good. Looking for takers.
Thanks

A: Let's start from your code.
hasmatch tlst tupm =
   foldr (\tup acc ->
          let tmatch (a,b) (c,d) = a==c || b==c || a==d || b==d in
          if tmatch tup tupm
          then (Just True)    -- short out
          else acc            -- do nothing, keep looping
         ) Nothing tlst

Since you say you prefer a boolean result, we can switch to that. Indeed, a boolean would be better since in the above code we never return Just False.
hasmatch tlst tupm =
   foldr (\tup acc ->
          let tmatch (a,b) (c,d) = a==c || b==c || a==d || b==d in
          if tmatch tup tupm
          then True    -- short out
          else acc     -- do nothing, keep looping
         ) False tlst

Now, if x then True else y is simply x || y.
hasmatch tlst tupm =
   foldr (\tup acc ->
          let tmatch (a,b) (c,d) = a==c || b==c || a==d || b==d in
          tmatch tup tupm || acc
         ) False tlst

If you wonder, || will not evaluate acc when we find a match. This is the same lazy semantics as C short-circuiting. Compared to C, the main difference is that a boolean variable acc can represent the unevaluated boolean result, while in C it's always a fully evaluated boolean value.
Now, tmatch uses the same second argument, tupm, so we can inline that, and pattern-match early:
hasmatch tlst (c,d) =
   foldr (\tup acc ->
          let tmatch (a,b) = a==c || b==c || a==d || b==d in
          tmatch tup || acc
         ) False tlst

We can even move the let outside to improve readability.
hasmatch tlst (c,d) =
   let tmatch (a,b) = a==c || b==c || a==d || b==d
   in foldr (\tup acc -> tmatch tup || acc) False tlst

We can also use a where here:
hasmatch tlst (c,d) = foldr (\tup acc -> tmatch tup || acc) False tlst
   where tmatch (a,b) = a==c || b==c || a==d || b==d

Finally, we can exploit a library function: any. Calling any p list evaluates to True iff there is any element in list that satisfies property p. Our code becomes:
hasmatch tlst (c,d) = any tmatch tlst
   where tmatch (a,b) = a==c || b==c || a==d || b==d

That's it.
Note that there are alternatives to the above approach. One could be turning the list of tuples [(a,b), (c,d), ... into a list of all the components [a,b,c,d,..., and working with that.
hasmatch tlst (c,d) = any tmatch [ x | (a,b) <- tlst, x <- [a,b]]
   where tmatch x = x==c || x==d

A: Based on chi's answer you may be better off defining a datatype with this equality?
{-# Language DerivingStrategies       #-}
{-# Language InstanceSigs             #-}
{-# Language StandaloneKindSignatures #-}

import Data.Kind (Type)

type AnyTuple :: Type -> Type
data AnyTuple a = a :×: a
  deriving stock Show

instance Eq a => Eq (AnyTuple a) where
  (==) :: AnyTuple a -> AnyTuple a -> Bool
  a1:×:b1 == a2:×:b2 = or $ liftA2 (==) [a1, b1] [a2, b2]

Then the function you seek is a standard library function like elem or find
>> 5:×:3 `elem` [1:×:2, 3:×:4, 5:×:6]
True
>> 5:×:3 `elem` [1:×:2, 9:×:4, 7:×:6]
False

>> find (== 5:×:3) [1:×:2, 3:×:4, 5:×:6]
Just (3 :×: 4)
>> find (== 5:×:3) [1:×:2, 9:×:4, 7:×:6]
Nothing


text:
Q: .gitignore ignore folder with '@' symbol in path I'm trying to add an exception to my .gitignore file to include my team's custom npm packages in our repository, so we can work with vendors without giving them the password to our private account.
I'm trying this:
node_modules/
!node_modules/@our-team

But .gitignore does not pick it up and start including that folder. Any ideas?
I'm on Windows but need to support Mac as well.

A: You can use \ to escape the @ symbol
!node_modules/\@our-team

Find more info on gitignore files.

A: You can put it in quotes !"node_modules/@our-team"
Source: just tested with git check-ignore


text: Q: spacy Entity Linking at paragraph level Entity linking works well for sentence based one. How to use spacy entity linking for a paragraph level instead of sentence level text? Any guidance on it would be helpful.


text:
Q: Google Maps RouteBoxer API missing I've been using this API for several years now and it's worked as recently as March or April of this year.  Now, I'm getting a 404 error from:
http://google-maps-utility-library-v3.googlecode.com/svn/trunk/routeboxer/src/RouteBoxer.js
Has this API been deprecated?
Thanks!

A: That link stopped working. You can find the implementation here
https://github.com/denissellu/routeboxer/blob/master/src/RouteBoxer.js
or here
https://github.com/nmccready/google-maps-utility-library-v3-keydragzoom
Or you can use some other similar solutions, like Leaflet RouteBoxer which you can find here https://github.com/StephanGeorg/leaflet-routeboxer


text:
Q: Use Global Variables to dynamically change URL So this is going to be really hard to explain,
I have an A folder and I have a B folder. I am using a common database for both of them.
Both folder have following files, inside each of them => config.php, index.php, upload.php, control_admin.php, admin.php and view.php. There are some basic database, CSS and JS files which B shares with A(not of any problem).
Now A is for project A and B is for project B.
for each of the projects, I have URLs => a.example.com & b.example.com
At a.example.com/index.php I upload an image file which characteristics like project_name = Apple Version = 1.
At b.example.com/index.php I upload an image file which characteristics like project_name = Banana Version = 1.
These images are uploaded to image folders in A and B respectively.
Now to view these images, I could have gone to
a.example.com\view.php?$version=1 and could have seen the pic.
similarly for b.example.com
I have modified this in .htaccess to make a friendly URL which takes me to
a.example.com\1 and displays the image as required.
Now comes the problem. Each of the view.php file have the following image link
<img src = "<?php echo     "http://".$GLOBALS['url']."".$GLOBALS['img_folder']."/".$new ?>" style = 'margin: 0px auto; display:block; max-width: 100%;height: auto;'>

I take these global variables from config.php of each file.
For A:
<?php $GLOBALS['project_name'] = 'Apple';?>

<?php $GLOBALS['url'] = 'a.example.com/'?>

<?php $GLOBALS["folder"] = 'FolderA'; ?>

<?php $GLOBALS['img_folder'] = 'AppleImages'; ?>

For B:
<?php $GLOBALS['project_name'] = 'Banana';?>

<?php $GLOBALS['url'] = 'b.example.com/'?>

<?php $GLOBALS["folder"] = 'FolderB'; ?>

<?php $GLOBALS['img_folder'] = 'BananaImages'; ?>

Now the issue is, if I upload version 1 of A and then version 1 of B and then I go to the link which is friendly URL from a.example.com/1 or b.example.com/1... I cannot see the one at A after I upload a file at B. Because the URL is hard pointing at B as it is the recent upload in the same database.
What can I do to the URL to make sure, if I upload to a.example.com and then to b.example.com, files with same version... I can see both images at their respective URLs
a.example.com/2 and b.example.com/2
I hope I made sense. Thanks in advance.
https://drive.google.com/drive/folders/0B5nDbj-RhZJMa3drNFlfRzVaLXc?usp=sharing

A: I looked through the google drive link you provided.
view.php : line 64
$project_name_download_form = $_GET['project_name'];

Unless you are accessing view.php with a url like this:
a.example.com\view.php?version=1&project_name=apple

Your $project_name_download_form will have an empty string value and your SQL query becomes:
SELECT demo_id, demo_name, demo_version, demo_details, file
                      FROM demo
                      WHERE  demo_name = ''
                      AND  demo_version = '1'

So 2 actions, change line 64 to:
$project_name_download_form = $GLOBALS['project_name'];

And then check the database directly to make sure the demo_name column has values being set in it (and not just blank).


text:
Q: java - how to make generic function that sorts alphabetically a collection i would like to create a utility method that can take in a list and sort it by its to string value. but i cant seem to figure out how to write the generic a param . here is what i have so far:
public class StringUtils {

    public static <T> void sortAscending(List<T> list) {
        Collections.sort(list.getClass(),
                new Comparator<T>() {
            public int compare(T f1, T f2) {
                return f1.toString().compareTo(f2.toString());
            }
        });
    }
}

the line "Collection.sort" complains at compile time that im not passing in the right thing.  How can i achieve this ?

A: Source code of Collections.sort() method is as follows:
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> void sort(List<T> list, Comparator<? super T> c) {
    list.sort(c);
}

It is clear that the method is expecting a List object and not a Class object.
So, your code should pass the list instead of list.getClass() leaving the code to be as follows:
    Collections.sort(list,
        new Comparator<T>()
        {
            public int compare(T f1, T f2)
            {
                return f1.toString().compareTo(f2.toString());
            }
        });


text:
Q: I'm getting OutOfMemoryExceptions, but my trace file is much smaller than my available memory As the title says, I've got tons of free memory, but I keep getting OutOfMemoryExceptions when processing traces and calling properties on Data Sources. Why is this happening?

A: The ETL file format is designed to be very space-efficient, and also supports optional compression. Due to these factors taking the data from an .etl file and transforming it into our more useful structures can often require significantly more memory than the original size of the file. However there are two steps that can be taken to make OutOfMemoryExceptions less likely:

*

*Don't use data sources you don't need. Even if none of the properties on a data source are called by your code, simply turning it on by calling its Use method will result in the data source processing events and preparing data for consumption.

*Ensure your program is running as a 64-bit process. The default Visual Studio C# project settings are to compile your program targeting AnyCPU, but to prefer running it as a 32-bit process. Unchecking the "Prefer 32-bit" option in your project's Build properties or switching your project's build configuration to x64 will cause your program to run as a 64-bit process.


text:
Q: How to retrieve field attributes from dynamic fields in lightning component I am loading my fields dynamically trough a fieldset. Using  aura:id="requiredField" on the lightning:inputField I can get the fields using a map in the controller. I have made some fields required at fieldset level not at fieldlevel. How can I get these values in the controller to validate only on the required fields? Or how can I get the attributes for a specific field. Using required is returning empty.
Component
  <lightning:card title="{!v.title}" iconName="{!v.iconName}" class="slds-p-around--none">
        <lightning:recordEditForm aura:id="recordViewForm"
                                  recordId="{!v.recordId}"
                                  objectApiName="{!v.genericObject}"
                                  onsubmit="{!c.fireRefreshView}"
                                  onerror="{!c.handleError}"
                                  class="slds-p-around--small">
             <lightning:messages />

                        <aura:iteration items="{!v.fields}" var="field">
                <aura:if isTrue="{!v.inputModeBool == true? true: false}">
                    <lightning:inputField fieldName="{!field.fieldPath}"    aura:id="requiredField" />{!field.required}

Controller
next: function (component, event, helper) {
        var recUi = component.get('v.recordId');
        alert('recUi: '+recUi);
    var Fields = component.find('requiredField').map(function (i) {
        return i.get('v.fieldName') });
          alert('Fields: '+Fields);
       var FieldValue = component.find('requiredField').map(function (i) {
            return i.get('v.value');   });
        alert('FieldValue: '+FieldValue);
            var FieldRequired = component.find('requiredField').map(function (i) {
            return i.get('v.required');   });
        alert('FieldRequired: '+FieldRequired);

A:
Try as below (main point is having custom class and styling it). Also for validations, you need iterate over all fields and check which are required, and then check if that field has value
Aura comp:
<aura:component controller="poc" implements="lightning:isUrlAddressable" >

    <aura:attribute name="fields" type="List" default="[]" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

            <lightning:recordEditForm aura:id="form"
                                      recordId="00128000009j45qAAA"
                                      objectApiName="Account">

                <lightning:messages />

                <aura:iteration items="{!v.fields}" var="fld">
                    <lightning:inputField aura:id="field"
                                          fieldName="{!fld.fieldPath}"
                                          class="{!if(fld.required,'poc-required','')}"/>
                </aura:iteration>

                    <lightning:button variant="brand"
                                      name="save"
                                      label="Save"
                                      onclick="{!c.submit}"/>

            </lightning:recordEditForm>

</aura:component>

JS:
({
    doInit : function(component, event, helper) {
        let action = component.get("c.getFieldsFromFieldSet");
        action.setParams({
            objectName: "Account",
            fieldSetName: "POC"
        });
        action.setCallback(this, function(response){
            let state = response.getState();
            if(state==="SUCCESS"){
                let fieldsStr = response.getReturnValue();
                console.log("fields => ",fieldsStr);
                let fields = JSON.parse(fieldsStr);
                component.set("v.fields", fields);
            } else {
                alert("error");
            }
        });
        $A.enqueueAction(action);
    },
    submit : function(component, event, helper) {
        event.preventDefault();
        let fields = component.find("field");
        let isValid = !fields.find(fld => $A.util.hasClass(fld,"poc-required") && !fld.get("v.value"));
        if(isValid) {
            component.find("form").submit();
        } else {
            let invalidFields = fields.filter(fld => $A.util.hasClass(fld,"poc-required") && !fld.get("v.value"));
            console.error("invalidFields => ", JSON.stringify(invalidFields));
        }
    },
})

Styles:
.THIS .poc-required label::before{
    content: "* ";
    color: red;
}

Apex class method:
@AuraEnabled(Cacheable=true)
public static String getFieldsFromFieldSet(String objectName, String fieldSetName)
{
    Schema.DescribeSObjectResult sObjectDescribe =
        Schema.getGlobalDescribe().get(ObjectName).getDescribe();

    Schema.FieldSet fieldSet = sObjectDescribe.FieldSets.getMap().get(fieldSetName);

    System.debug('fields => '+fieldSet.getFields());
    return JSON.serialize(fieldSet.getFields());
}

A: How to validate required fields on JS

*

*Create new aura:attribute

<aura:attribute name="requiredFields" type="List" default="[]" access="private" />

*Init this attribute just after setting fields
component.set('v.requiredFields', fields.filter(el => el.required).map(el => el.fieldPath));

*You should use button of submit type in the body of
lightning:recordEditForm. Example:

<lightning:recordEditForm aura:id="recordViewForm"
    recordId="{!v.recordId}"
    objectApiName="{!v.genericObject}"
    onsubmit="{!c.handleSubmit}"
    onerror="{!c.handleError}"
    class="slds-p-around--small">

    <lightning:button type="submit" label="Save" />

</lightning:recordEditForm>

onsubmit="{!c.handleSubmit}"

*Override standard submit functionality

handleSubmit: function(component, event, helper) {
    event.preventDefault();
    let fields = event.getParam('fields');
    let isValid = true;
    let validationError = '';
    for(let requiredField of component.get('v.requiredFields')) {
        if($A.util.isEmpty(fields[requiredField])) {
            // Required field is empty
            isValid = false;
            validationError = requiredField + ' is blank!'
            break;
        }
    }
    if(isValid) {
        component.find('recordViewForm').submit(fields);
    } else {
        //Show validation error
    }
}


text:
Q: React function component renders Renders on focus I have problem with re-rendering. Every time user focuses on input it's re-rendering, even on input. Every time user types one word, function component re-renders, but I have big data and it makes everything very slow because of that.
import { useState } from "react";
import "./styles.css";

export default function App() {
  const [containerID, setContainerID] = useState();
  const [searchVal, setSearchVal] = useState();

  return (
    <div className="App">
      {console.log("its rendering again")}
      <input
        onInput={(e) => setSearchVal(e.currentTarget.value)}
        onFocus={(e) => setContainerID(e.currentTarget.id)}
        id={1}
      />
      <input
        onInput={(e) => setSearchVal(e.currentTarget.value)}
        onFocus={(e) => setContainerID(e.currentTarget.id)}
        id={2}
      />
      <input
        onInput={(e) => setSearchVal(e.currentTarget.value)}
        onFocus={(e) => setContainerID(e.currentTarget.id)}
        id={3}
      />
      <input
        onInput={(e) => setSearchVal(e.currentTarget.value)}
        onFocus={(e) => setContainerID(e.currentTarget.id)}
        id={4}
      />
    </div>
  );
}

Not a single function starts working just renders function return section on every focus and input. Any ideas how to stop these unwanted renders? Here is code snippet also:
https://codesandbox.io/s/funny-germain-t0h8n?file=/src/App.js:0-962

A: Changing state causes re-renders. You can use useRef to avoid this issue. You will get values in containerId.current and searchValue.current.
export default function App() {

    const containerId = useRef();
    const searchValue = useRef();

    return (
      <input
            onInput={(e) => searchValue.current = e.currentTarget.value}
            onFocus={(e) => containerId.current = e.currentTarget.id}
            id={1}
          />
    );

}


text:
Q: Stop git from silently clobbering ignorefiles (bug in git?)? I have found a way that git will not ask you to stash but instead silently delete your files that you believed to be safe in .gitignore.
This is true even if you had the same ignore file since your initial commit.
The problem occurs when you are in a commit that has a said file removed but listed in .gitignore and then you checkout another commit where it existed:
git init
mkdir ignored/
echo stuff > ignored/file
echo otherstuff > otherfile
git add -A
# Opps added my ignored folders files
# Forgeting to rm --cache
echo ignored/ > .gitignore ; git add .gitignore
git commit -m 'accidentally add ignored/file'
git status
touch dummyfile; git add dummyfile
# Remembered to rm --cache
git rm --cache -rf ignored/file #This file is now vulnerable to clobber
git commit -m 'add stuff'
echo somechange >> ignored/file

## Wait for it..
git checkout HEAD~
## somechange has been silently clobbered!!

# Please paste first paragraph, observe and then past the second.
# Note both commits have the correct ignore file and are not immune!

(cd to an empty folder before pasting above code into terminal)
Is there anyway to prevent this silent clobber?

A: It's not a bug (or at least, the git developers don't consider it to be one).
The contents of .gitignore are not "files that should be ignored" or "path names that should not be touched"; instead, they're "paths that don't get automatically added, and are suppressed from being shown as untracked" (which makes .gitignore a poor name).
Once you've committed a file, or even added it to the index, it's no longer ignored, regardless of whether it is listed in a .gitignore.
For some files, you can use git update-index --assume-unchanged or (better) git update-index --skip-worktree, but in general, if you've accidentally committed a file you should not have, and you want it ignored, you must "rewrite history" to take it entirely out of the repository to get good behavior.  That's not too difficult if you haven't pushed anything and have few commits that contain the unwanted file, but much harder if you have pushed, or have many such commits.
See also Git - Difference Between 'assume-unchanged' and 'skip-worktree'.
[Text below added December 2016]
Technical details
For Git, there is a short, simple, and sweet definition of a tracked file: A file is tracked if and only if there is an entry for it in the index.
The "assume unchanged" and "skip worktree" things are flags you can manually set or clear in the index.  They are separate flags and can be set individually, although it's not clear what it means to set both.  The intent of "assume unchanged" is merely to make Git faster, by allowing it to assume that the file is not changed and hence does not need to be updated by git add, while the intent of the "skip worktree" flag is to tell Git "hands off": don't just assume it's unchanged, try hard to keep it unchanged.  That's harder than it may look at first blush; for more about this, see the above linked post.
In order to set these flags, the file must have an index entry, so it must be tracked.
If a file is not tracked, it may or may not also be ignored.  There are numerous sources for these: not just the top-level .gitignore, which contains a list (one per line) of a variant of Git's pathspec that is limited to glob matching and negation, but also .gitignore files within each sub-directory within a repository, the file $GIT_DIR/info/exclude if it exists, and the file named by core.excludesFile if that configuration entry exists.  To find whether and why a file is ignored, use git check-ignore, available since Git version 1.8.2.  The -v option tells you which control file marked the file as ignored.
Unfortunately, as in the question to which this is an answer, "ignored" has two meanings.  While matching an ignore path keeps Git quiet about the file being untracked, it also makes Git feel free to clobber the file.


text:
Q: Identity scaffold pages not found at runtime I scaffold my identity pages so that their appeared in areas/account

/Account/Login
But now when I go to the Account/Login its not found should it not have created a Account controller for me as well ?
My Start-up is told to use identity so don't get it.
 public void ConfigureServices(IServiceCollection services) {
     services.AddDbContext<ApplicationDbContext>(options =>
     options.UseSqlServer(
         Configuration.GetConnectionString("DefaultConnection")));
         services.AddDefaultIdentity<IdentityUser>(options =>
         options.SignIn.RequireConfirmedAccount = true)
         .AddEntityFrameworkStores<ApplicationDbContext>();
        services.AddControllersWithViews().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
        services.AddRazorPages();
    }

A: Use area name in URL
/Identity/Account/Login

should it not have created a Account controller for me as well?

no, because it use Pages


text:
Q: Mount a NAS-Server on logon using Batch I have got 16 Laptops, 1 NAS-Server, and 3 Printers in an (isolated) Network
I want to run a Batch script (autostart.bat) when a user boots logs onto a Laptop which does the following:

*

*Run another Batch (autostart_server.bat) from the NAS which sets up the Printers on the
Laptop. I put this in a seperate Batch file which is ran from the NAS
because I dont want to run arround and change the local Batch on
every of the 16 Laptops if, e.g. a new Printer is added to the
Network.

*Adds a virtual Drive from the NAS where everyday-use files      are
located

Details about the NAS:

*

*It requires a user Name and Password when you connect to it. there is
no anonymous Login Feature or simmilar (At least I didnt find it (and
I searched)).

*Every Employee has an Account on the NAS which name is containing the first letter of his forename, "_", and the surname e.g. j_doe for John Doe
I figured it would be best to put the autostart_server.bat in a seperate virtual drive called 'Startup'

The Problem
I dont want to ask the User for his NAS credentials yet cause he might not need the files in this session
So I created a NAS Account with Name autostart_user and Password 123456 which I can use to log into the NAS to run the autostart_server.bat
Now I log into the NAS, run the autostart_server.bat, everything is fine for now.
But now I want to add the virtual drive with the files for everyday-use. when I mount it (using NET USE) it automatically adopts the autostart_user and its password. So now the User is logged into the NAS with the wrong Account
When the User now tries to access his files, he is getting promted to enter his credentials, because the autostart_user has no read/write rights on that virtual drive
Even if the User enters his credentials right, the NAS throws an error saying he doesnt have read rights
Possible Solutions I thought of:
I need to connect to the NAS, run autostart_server.bat and somehow disconnect again (NET USE A: /DELETE doesn't do the Job)
Next Thing is that I would like to add the virtual drive, without loggin in yet so the User gets prompted when he tries to Access the drive
My Code so far:
@echo off
TITLE Autostart Preload

SET NASIP=192.168.0.3

ping -n 1 %NASIP% | find "TTL=" >nul

if errorlevel 1 (
    echo NAS not available
    timeout /T 10
) else (
    NET USE A: /DELETE

    NET USE A: \\%NASIP%\userfiles "123456" /USER:startup_user /PERSISTENT:NO

    \\%NASIP%\Startup\autostart_server.bat

    echo Autostart executed

    pause
)


text:
Q: App not compatible with buildpack Когда делаю
git push heroku master

Вылазит это
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Writing objects: 100% (3/3), 238 bytes | 238.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz
remote:        More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !       Push rejected to botipz.
remote:
To https://git.heroku.com/****.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/****.git'

Что делать?

A: Добавьте requirements.txt и Procfile, а также проверьте, установили ли вы соответствующий buildpack


text:
Q: element.value method is returning undefined I have an ajax 'POST' method that sends the id input to a php file. For some reason whenever I write input.value method, it returns undefined:
input = document.getElementsByClassName("Input");
const id = input.value;
alert(id);

What am I doing wrong?
Edit: I tried making the element as a separate id instead of a class and the problem disappeared.

A: getElementsByClassName() returns an array-like collection of elements, not a single element.
You'll need to extract one of the elements from the collection, e.g.
input = document.getElementsByClassName("Input");
const id = input[0].value; //<--
alert(id);

Better would be to target the exact element in some way e.g.
document.querySelector('#theActualElement'); //<-- returns single element


text:
Q: java how to populate multiple JTextFields reading data from a .txt file I have to read some data from a .txt file. Each row contains a string.
Each string has to be displayed in a specific JTextField.
How can i solve the problem?
Thanks

A: Read the file line by line as described in the Java Tutorial | Reading, Writing, and Creating Files.
Call setText to set the text in a specific JTextField. e.g.
jTextField.setText(line);


text:
Q: Difference between 'get' and 'get set' in Swift I understand that 'get' is used to give instructions on value for the variable 'numberOfWheels' is acquired. However, I do not understand what 'get set' is supposed to achieve in the code below. Does it mean that value can be acquired from the class, enum, or struct AND can also be acquired by a parameter passed on?
protocol WheeledVehicle: Vehicle {
  var numberOfWheels: Int { get }
  var wheelSize: Double { get set }
}

A: This protocols requires conforming types (classes, structs or enums) to have two properties:

*

*numberOfWheels, which must provide at least a getter. This means it's either a let property, a var property, or a computed property with at least a getter (the setter is optional).

*wheelSize, which must provide a getter and a setter. This means it has to be either a var property, or a computer property with both a getter and a setter.


text:
Q: Multi - Step Approval Process I have a requirement which I am stating below:
1) when Amount < 100 - Automatically approve the record.
2) When Amount > 100 - Following is conditions:

*

*a) Notify to member called PD

*if PD approves notify to a member called CFO

*if CFO approves, notify a member called PT.

3)  When Amount > 100 & member PD denies it notify CFO - CFO member denies it again notify to PD again if PD approves notify CFO & now if CFO disapproves go back to PD.
Note : Whoever is notified of the approval or rejection is equivalent to becoming the Approver.
I have achieved 1 and 2 successfully but for 3 i am unable to achieve.
The entry criteria for the Approval Process is When Amount != null

A: 1 and 2 are straightforward, using the normal functionality in a single approval process.
Option 3 is very tricky, and is not possible with a single approval process.  Upon rejection, you could update a "status" field to indicate rejected, and then use process builder to auto submit to a different approval process to handle each part of the scenario.  I'm still not sure you could get it exactly as described but it may well be possible.
In approvals, on rejection you only have the option of going back one step, or doing a full rejection. And It's not possible to skip a step on the way "up" and hit it on a reject, I have tried that.  So basically you need to do a full reject and then auto submit to a new approval process to route it appropriately.


text:
Q: Which Points are not Contained in the Line The Circle $$x^2+y^2-4x=0$$ is cut by a line $AB$ at two points. If $A$,$B$ and two other points $C(1,0)$ and $D(0,1)$ are Concyclic, Then which of the Following points are not contained by the line.
$1.(1,1)$
$2.(-2,2)$
$3.(\frac{7}{4},\frac{3}{4})$
My Try: Equation of any Circle Passing through Circle and Line Intersections is
$$S+kL=0$$ i.e., $$x^2+y^2-4x+k(ax+by-1)=0$$ which passes through $C(1,0)$ and $D(0,1)$. we get two equations
$$a=1+\frac{3}{k}$$ and $$b=1-\frac{1}{k}$$
But how can we find $k$..Help needed

A: Circle($C_1$) is: $$(x-2)^2+y^2=4$$
Line($L_1$) could be taken as: $$y=mx+c$$
For the circle passing through intersection of $C_1$ and $L_1$ could be taken as:
$$C_1+\lambda L_1=0\implies (x-2)^2+y^2-4+\lambda(y-mx-c)=0$$
This passes through $(1,0)$ and $(0,1)$ both:
$$1+\lambda(1-c)=0\text{ and }-3+\lambda(-m-c)=0$$
So:
$$\require{cancel}\frac{\cancel{\lambda}(1-c)}{\cancel{\lambda}(-m-c)}=\frac{-1}{3}\implies 3-3c=m+c\implies c=\frac14(3-m)$$
So:
$$y=mx+\frac14(3-m)\implies 4y=4mx+3-m\implies \left(y-\frac34\right)=m\left(x-\frac14\right)$$
Clearly the line passes through $(1/4,3/4)$ and I have tested it on an app and all points seem to be lying on this line.

Graphs:
Legend:
$$\color{red}{(x-2)^2+y^2=4}\quad\color{blue}{y=mx+c}\quad\color{black}{(x-2)^2+y^2-4+k(y-mx-c)=0} \\\color{red}{(0,1)}\quad\color{green}{(1/4,3/4)}\quad\color{purple}{(1,1)}\quad\color{orange}{(-2,2)}\quad\color{black}{(7/4,3/4)}$$

$$\large m\approx0.33\text{ [actually it should be exactly }1/3]$$

$$\large m\approx0\text{ [actually it should be exactly }0]$$

$$\large m\approx-0.56\text{ [actually it should be exactly }-5/9]$$


text:
Q: mongod --datapath can't read collections from copied data folder from another pc My windows crashed so I copied the data folder of mongodb which I used to run mongod --datapath "C:/data" to another PC.
But when I run mongod --datapath "C:/data", I can't see my old collections.
How can I make it ?

A: Sorry everyone. I remember that my dbpath is /data/db and the log path is /data/log. Not a /data for all. Thanks


text:
Q: How to use oauth access token for twitter public stream I am brand new to twitter streaming api.I want to curl.
curl https://stream.twitter.com/1.1/statuses/filter.json?track=node
How can i use oAuth access token to get public stream.
My goal is to fetch public tweets about node and use node to display in a webpage.
I am using ubuntu terminal.

A: I know this question is old, but here's a solution to the curl / node portion of the question.  Hopefully this is helpful to others.
Twitter setup
First, register an app with twitter at https://apps.twitter.com.  This can be anything including testingAppForNode, etc.  Upon completion you should have a API KEY and API SECRET under apps > yourApp > Keys and Access Tokens
Next, on the same apps.twitter.com page your API KEY / SECRET is listed, generate the Access Token / Secret.  This section is just below the "Application Settings" section.  Any permissions will do for this use case.
Your twitter setup should be done, but stay on the same page to test with curl.
Test with CURL
In the "Keys and Access Tokens" section on your twitter app dashboard (apps.twitter.com), you should have a "Test OAuth" button at the top right.  Click that to the "OAuth Tool" (https://dev.twitter.com/oauth/tools/signature-generator/$APP_ID).
Replace the "Request URI" field with 'https://stream.twitter.com/1.1/statuses/filter.json?track=node' and click "Get OAuth Signature" button.  This should generate a customized curl command that you can cut and paste into your terminal.
Connect with Node
(I found the following example here: https://github.com/ciaranj/node-oauth/wiki/Interacting-with-Twitter.)
command line:

npm install oauth

twitter.js:
var OAuth = require("oauth").OAuth,
oa = new OAuth(
    "https://api.twitter.com/oauth/request_token",
    "https://api.twitter.com/oauth/access_token",
    "YOUR-CONSUMER-KEY",
    "YOUR-CONSUMER-SECRET",
    "1.0",
    "",
    "HMAC-SHA1"
);

var access_token = "YOUR-ACCESS-TOKEN";
var access_token_secret = "YOUR-ACCESS-TOKEN-SECRET";
var request = oa.get("https://stream.twitter.com/1.1/statuses/filter.json?track=node", access_token, access_token_secret);
request.addListener('response', function(response) {
    response.setEncoding('utf8');
    response.addListener('data', function(chunk) {
        console.log(chunk);
    });
    response.addListener('end', function() {
        console.log('-- END --');
    });
});
request.end();

Run "node twitter.js" from the command line and you should see streaming feed from twitter.


text:
Q: How to properly handle database queries without freezing the UI? FIRST! I know very similar questions have been asked before, however, the answers have been so case specific that I seriously don't understand how to apply them. Please don't roast me.
All I want is to build a rather generic application that has CRUD modules and reporting (c# and MySQL), nothing special. However, everytime my app runs a line where there is a call to a method that queries the server the UI freezes a few ms, the freeze-like-stuttering of the UI feels incredibly annoying.
As I understood, every DB call needs to be done in a different thread with a background worker or a task so the main thread doesn't get busy and makes the UI unresponsive BUT whenever I try to do this I have issues because I can't access the UI components.
Can you guys help me with this simple login form as an example, please?
I have a simple form, 2 textboxes, txtUser and txtPassword and a button with the following code:

    MySqlDataReader? user = MdlUsers.GetUserByUsername(txtUser.Text);
    if (user != null && user.Read())
    {
        string? pwd = user["clave"].ToString();
        if (pwd != null && pwd.Equals(txtPassword.Text))
        {
            MessageBox.Show("Acceso correcto.");
            logged = true;
        }
        else
        {
            MessageBox.Show("Acceso denegado.");
            logged = false;
        }
    }
    else
    {
        MessageBox.Show("No regresó nada.");
        logged = true;
    }

This is the code to the MdlUser class:
public class MdlUsers
    {
        public static MySqlDataReader? GetUserByUsername(string username)
        {
            MySqlDataReader? result = null;
            try
            {
                string qry = "SELECT * FROM usuarios WHERE login = @username";
                MySqlCommand cmd = new MySqlCommand(qry, MdlConnection.Connect());
                cmd.Parameters.AddWithValue("@username", username);

                result = cmd.ExecuteReader();
                return result;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }
    }

Whenever I click the button the UI stutters. So how can I handle this? Thank you very much.

A: The way to handle any situation of that sort is to perform your long blocking operation on a separate task, and when it finishes, post a call to the GUI thread.
You have not told us what kind of GUI you are using, (that's what tags are for on stackoverflow,) I suspect it is  WinForms, so the way to do this in WinForms is with Control.BeginInvoke().
When you specify an Action to be invoked with Control.BeginInvoke(), that Action will run in the GUI thread, so it will be able to safely "access the UI components."


text:
Q: Sorting HTML String in PHP I have a srting which is coming through loop

Alloys

cla

blloys

zloys

This is my actual HTML which is coming using PHP Logic. it is showing out at
Allows
Clas
Blloys
zloys

which is ok
But i want sorting like this
Allows
Blloys
Clas
zloys

Can anybody tell me how we achieve this result
Thanks

A: You can use sort(); function
$arr = array( 'Allows', 'Clas', 'Blloys', 'zloys');

sort($arr);

now loop, it will give you result in order
foreach($arr as $v) {
    echo '
'.$v.'
';
}

*

*Allows

*Blloys

*Clas

*zloys


text:
Q: ASP.NET Core Web App and windows form app give different results on service references I try to add service references on ASP.NET Core Web App. That results app reference.cs file is mostly missing,  classes are empty etc and only 100 lines.
But -even in same solution- if i try to add the same service reference in windows form app, all methods, interfaces and classes
are completely correct.
If i try to add web references in ASP.NET, theres no missing but i need to use WCF.
I try to copy other references file and paste it but it wont work.
What did i miss?
Note: I already check this answer and subject but it will not work first time and question isnt same. My reference.cs file isnt empty,and also theres no change even i try 100 time it will be the same output - this question pointed coincidence - so it is NOT duplicate question. Thanks.

A: After 5-6 hours thanks to this beautiful answer - actually i tried this before - and with my add ons, i figure it out.

*

*Delete the reference - right click and delete -

*Check file explorer, make sure no files in Connected Services.

*While your project is highlighted, right click on project and select clean

*After all of that, add your service reference and -just like the answer said- make sure reuse types in referenced assembles is not checked.


text:
Q: WCF Data Services 5.0 SDK Samples Downloaded and installed the WCF Data Services 5.0 from
WCF Data Services 5.0 for OData V3
According to the link below it is supposed to include some code samples.  But I cannot find the code samples.  Does anyone know if there really are code samples and if so where?  I am looking for code sample for Data Service Provider.
www.odata.org/developers
What may be the case is the code samples are in a prior version.  If someone knows the latest version with Data Service Provider code samples please let me know.
Thanks

A: The sample of the untyped custom provider is part of the OData Provider Toolkit: http://www.odata.org/ecosystem#samplecode


text:
Q: How do I automatically turn a URL I input into a cell into a hyperlinked text in Google Sheets? Please see image for reference. I want the cell to always read "Link" in columns B through E whenever any URL is posted in those cells. I was told this needs to be an Apps Script; however, I'm not exactly sure on how to go about doing this.
So as an example: I post a random URL, randomURL1.com, in cell B3 I want it to automatically change that to read "Link" and be a clickable text.
Thanks!
https://i.stack.imgur.com/ZYKbs.png

A: I believe your goal is as follows.

*

*When an URL is put to a cell, you want to convert the URL to a text which has a hyperlink of the URL.

In this case, how about the following sample script?
Sample script:
Please copy and paste the following script to the script editor of Google Spreadsheet and please set the sheet name. And, please save the script. When you use this script, please put an URL to a cell. By this, the URL is converted to a text of "Link" with the hyperlink.
function onEdit(e) {
  const sheetName = "Sheet1"; // Please set the sheet name.
  const { range } = e;
  const sheet = range.getSheet();
  const value = range.getValue();
  if (sheet.getSheetName() != sheetName || !value.match(/^https?:\/\/.+/)) return;
  const r = range.getRichTextValue().copy().setText("Link").setLinkUrl(value).build();
  range.setRichTextValue(r);
}

*

*For example, when an URL like https://sample.com is put to a cell, this script is run and a text of "Link" with the URL is put to the cell.

*In this script, RichText is used. If you want to use a formula of HYPERLINK, please modify as follows.

*

*From
  const r = range.getRichTextValue().copy().setText("Link").setLinkUrl(value).build();
  range.setRichTextValue(r);

*To
  range.setFormula(`=HYPERLINK("${value}","Link")`);

*In this script, in order to check the URL, http:// or https:// are checked. So, please put the URL including http:// or https://.
References:

*

*Simple Triggers

*Class RichTextValueBuilder

*setFormula(formula)


text:
Q: Conditionally format value in React-Final-Form based on data in form? I am displaying a currency value in a react-final-form. I am using a format function on the field.
const formatMoney = (value) => {
  if (!value) return value;
  const formatter = new Intl.NumberFormat('en-US', {
    style: 'currency',
    minimumFractionDigits: 2,
    currency: 'USD'
  });
  return formatter.format(value);
};

The problem is the currency is another option in the form. I do not see a clean way to access the rest of the values inside a format function.

A: After asking the question, I figured out this work around, pass the values into the render function of the form and pass down to the format function like this:
     <Field
      name="total"
      type="text"
      readOnly
      component={LabeledInput}
      placeholder="10"
      label="Total"
      help="Estimated total including tax"
      format={v => formatMoney(v, values.currency)}
    />


text:
Q: React js CSS same class name style is used on another page I used reactjs app, i am use coustom css file. i use css class name for a page , now I have added some styles in that class. now If face some problem, when I add sem  class name in another page , it automatically gets previous that style. I don't want to get any previous style in that class, how can I solve this problem?

A: recommend use styled-component or taiwwind etc easier to controll your css.


text:
Q: "x=x || 4" generates `ReferenceError: x is not defined` error Why does x = x || 4 or even x=(x||5) generate ReferenceError: x is not defined error, but var x=x || 4 work as expected?

A: This is because variable declarations are processed first (hoisting). The MDN page on var explains it well:

Because variable declarations (and declarations in general) are
  processed before any code is executed, declaring a variable anywhere
  in the code is equivalent to declaring it at the top. This also means
  that a variable can appear to be used before it's declared. This
  behaviour is called "hoisting", as it appears that the variable
  declaration is moved to the top of the function or global code.

So the following would also work:
x = x || 4;
var x;

A: You're attempting to use a variable that hasn't been declared before. This results in a Reference Error.
[edit]
so many wrong words.
[exit] @grc got it right.

A: x = x || 4 means assigning x or 4 in variable x.
if x is null 4 is assigned to variable x.
May be you have not declare x variable. that's why you are getting x is not defined
If you try below it work :
var x;
x=x||4;
alert(x);

This will also work :
x=x||4;
var x;
alert(x);


text:
Q: Rails 5: How to make a 'migration partial' in database migrations I have many tables using the same column names. I want to split them into partials so that I can just edit the partial to change the columns every time I re-create the database.
I've tried:
fruit migration file
class CreateFruit < ActiveRecord::Migration[5.0]
  def change
    create_table :fruits do |t|
      partial
    end
end

pet migration file
class CreatePet < ActiveRecord::Migration[5.0]
  def change
    create_table :pets do |t|
      partial
      t.string :personality
    end
end

partial file (application.rb?)
def partial
  t.string :name
  t.string :size
end

But, I'm always getting a syntax error when running migrations

A: Create a file named db/migrate/_partial_migration.rb:
class PartialMigration
  class << self
    def call(t)
      t.string :name
      t.string :size
    end
  end
end

In your migration db/migrate/20180209112447_create_pet.rb:
require_relative "./_partial_migration.rb"

class CreatePet < ActiveRecord::Migration[5.0]
  def change
    create_table :bar do |t|
      PartialMigration.call(t)
      t.string :personality
    end
  end
end


text: Q: Why does Vim cuts off UTF-8 characters? I am trying to get the utf-8 checkbox character in the text editor. I can see it fine in both Notepad and Notepad++. But vim cuts off the character (check out attached picture). Can you please help?


text:
Q: Is PhotoChooserTask still supported in Windows Phone 8.1 (Universal App)? Is PhotoChooserTask still supported?
When I try to add the Microsoft.Phone.dll, I get the following error at build time:
This is a rather difficult error to debug (at least for me), shouldn't it just prevent you from referencing the assembly if it is no longer supported in Universal Apps? If this is because it is a Silverlight assembly, how am I supposed to realize this?
PhotoChooserTask documentation on MSDN indicates that it is supported by Windows Phone 8.1

A: In Windows Phone App/Universal App, You can't use PhotoChooserTask any more.
You can use FileOpenPicker to access image from PictureLibrary.
Here is an example: Pick an image in windows phone 8.1


text:
Q: numbers not sorting in order Im trying to sort a column in order (1 to ...) within sql using asp.net and c#.  After doing some research it seems like I need to change my column type in SQL Server to int however this is not possible as the column is storing house numbers and I could end up with a house number of 10a (for example) so currently is set to varchar.  Because of this it doesnt correctly sort the column.  I have tried casting the relevant column as an int but then when running the application I get an error for its bind in gridview, I've also tried other this as the * 1 but still get errors on the bind part when running
SQL Statement
    SELECT DISTINCT tblcontact.ContactID, tblcontact.Forename, tblcontact.Surname,
    tbladdress.[House Number], tbladdress.AddressLine1, tbladdress.AddressLine2,
    tblcontact.[Business Name] FROM tblcontact INNER JOIN tbladdress ON tblcontact.AddressID = tbladdress.AddressID
    LEFT OUTER JOIN tblDonate
    ON tblcontact.ContactID = tblDonate.ContactID
    WHERE (tbladdress.CollectionArea = @CollectionArea) AND
(tbladdress.AddressLine1 = @drpCollectionStreet)
    ORDER BY tbladdress.[House Number] ASC

Gridview Markup
                                    <asp:TemplateField HeaderText="House Number">
                                        <EditItemTemplate>
                                            <asp:TextBox ID="txtHouseNum" runat="server" Text='<%# Bind("[House Number]") %>'></asp:TextBox>
                                        </EditItemTemplate>
                                        <ItemTemplate>
                                            <asp:Label ID="lblHouseNum" runat="server" Text='<%# Bind("[House Number]") %>'></asp:Label>
                                        </ItemTemplate>
                                    </asp:TemplateField>

Here's an example of how its sorting
21
22
27
28
5
6
8
9

This is how I cast as int which sorts fine within SQL but I get an error on the Bind (above)
SELECT DISTINCT tblcontact.ContactID, tblcontact.Forename, tblcontact.Surname, cast(tbladdress.[House Number] as int),
tbladdress.AddressLine1, tbladdress.AddressLine2, tblcontact.[Business Name]
FROM tblcontact INNER JOIN tbladdress ON tblcontact.AddressID = tbladdress.AddressID
LEFT OUTER JOIN tblDonate ON tblcontact.ContactID = tblDonate.ContactID
WHERE (tbladdress.CollectionArea = 'Queens Park') AND (tbladdress.AddressLine1 = 'Kings Road')
ORDER BY cast(tbladdress.[House Number] as int)

Error in runtime
this is the error when running (this is the most meaningful)
 "House Number is neither a DataColumn nor a DataRelation for table DefaultView."}

A: To sort the street number numerically you need to cast them as numbers. The trouble, of course, is that strings such as "10a" cannot be cast as an INT. The answer is to extract the numeric characters from your [House Number] column and then do the cast. The following does this for the ORDER BY clause:
...
ORDER BY CAST(SUBSTRING(tbladdress.[House Number], PATINDEX('%[0-9]%', tbladdress.[House Number]),
                 1 + PATINDEX('%[0-9][^0-9]%', tbladdress.[House Number] + ' ') -
                 PATINDEX('%[0-9]%',tbladdress.[House Number])) AS INT)

See http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/extracting-numbers-with-sql-server/ for an explanation of how the complicated looking formula works.

A: Remove the cast from select column list. Keep only in order by still it will order the result.
select A.ContactID,
                A.Forename,
                A.Surname,
                A.[House Number],
                A.AddressLine1,
                A.AddressLine2,
                A.[Business Name] from (
SELECT DISTINCT tblcontact.ContactID,
                tblcontact.Forename,
                tblcontact.Surname,
                tbladdress.[House Number],
                tbladdress.AddressLine1,
                tbladdress.AddressLine2,
                tblcontact.[Business Name]
FROM   tblcontact
       INNER JOIN tbladdress
               ON tblcontact.AddressID = tbladdress.AddressID
       LEFT OUTER JOIN tblDonate
                    ON tblcontact.ContactID = tblDonate.ContactID
WHERE  ( tbladdress.CollectionArea = 'Queens Park' )
       AND ( tbladdress.AddressLine1 = 'Kings Road' )) A
ORDER  BY Cast(tbladdress.[House Number] AS INT)

A: Correct Answer is a combination of JohnS and NoDisplayName answers thanks to you both
select A.ContactID,
                A.Forename,
                A.Surname,
                A.[House Number],
                A.AddressLine1,
                A.AddressLine2,
                A.[Business Name] from (
SELECT DISTINCT tblcontact.ContactID,
                tblcontact.Forename,
                tblcontact.Surname,
                tbladdress.[House Number],
                tbladdress.AddressLine1,
                tbladdress.AddressLine2,
                tblcontact.[Business Name]
FROM   tblcontact
       INNER JOIN tbladdress
               ON tblcontact.AddressID = tbladdress.AddressID
       LEFT OUTER JOIN tblDonate
                    ON tblcontact.ContactID = tblDonate.ContactID
WHERE  ( tbladdress.CollectionArea = 'Queens Park' )
       AND ( tbladdress.AddressLine1 = 'Kings Road' )) A
       ORDER BY CAST(SUBSTRING(A.[House Number], PATINDEX('%[0-9]%', A.[House Number]),
                 1 + PATINDEX('%[0-9][^0-9]%', A.[House Number] + ' ') -
                 PATINDEX('%[0-9]%',A.[House Number])) AS INT)


text:
Q: windows cookies index.dat parser Could someone explain how Internet Exploer cookies stored and how it retrived using the index.dat ,also could someone provide how this binray file is built and if there are a paserer/module/library for it written on perl /python ?

A: Have a look at HTTP::Cookies::Microsoft, part of libwww-perl.

A: Here is a series of blog posts I wrote about index.dat:

*

*Index.dat: Part I - What is index.dat?

*Index.dat: Part II - What are they used for?
Basically you'll need to be able to call the wininet UrlCacheEntry APIs from Perl.  I think there is a win32 module that let's you do this.


text:
Q: Universal, looping countdown timer for a web page I am looking for a timer to put on my website, and the timer would be set for an hour, and after it counts down to zero it resets back to one hour again. It also needs to be universal, so it displays the same for all users and does not reset back to 1hr if you refresh the page. I'm guessing this is relatively simple, however all I could find was timers which count to a certain time and stop, or timers which start back at zero after page refresh which is insufficient.
If someone could help, or knows of a link where something like that is available I would greately appreciate it!
Thanks in advance.

A: Here is a condition I know it will help.
ctsecs--;
if(ctsecs < 0) {
    if(ctmnts > 0) {
        ctsecs = 59;
        ctmnts--;
        if(cthrs > 0) {
            ctmnts = 59;
            cthrs--;
        } else {
            ctsecs = 0;
            ctmnts = 0;
            cthrs = 0;
        }
    }
}

A: You could have the timer just display the complement of the current minutes and seconds of UTC:
setInterval(function() {
    var d = new Date;
    var s = (60 - d.getUTCMinutes()) + ":" + (60 - d.getUTCSeconds());
    $("#time").text(s);
}, 250);

Here's a demo page where you can see it in action.

A: Why not just get the current time, and only display the minutes? Otherwise, it'd have to be done server side.

A: you can use ajax for this purpose. make a database entry on server about 60 minutes and update the time to client with ajax requests, this will be more secure than client side scripting.

A: If you want a timer that ticks every second, setInterval is a poor choice. It only runs at approximately the requested interval and will slowly drift. A clock using it will not be smooth unless you call it often, which is wasteful.
A better strategy is to use setTimeout to call itself sequentially, setting the lag based on the time to the next tick plus a small amount. e.g. a very simple clock:

If you are happy with using the system clock for your counter, and you want everyone to see the same numbers (more or less), you can use Date's UTC methods: getUTCHours, getUTCMinutes and getUTCSeconds.


text:
Q: Change in timezones for WRF data using numpy? I am extracting from a WRF simulation. The file is a .nc file.
The problem is WRF models in UTC+00. I need it in UTC+10.
Do I need to set the timezone first and then change the timezone?
Or would I change the timezone after I convert to a numpy dataset.
An example of what the timeseries looks like is:
2018-02-27T00:00:00.000000000
Many thanks.
f=Dataset("wrfout_d03_2018-02-27_00.nc", 'r', format='NETCDF4')
times = wrf.extract_times(f, timeidx=wrf.ALL_TIMES, squeeze=True)

tz_times = pd.Timestamp(times,tz='Australia/Melbourne')
convert_times = wrf.to_np(tz_times)
np_times = np.asarray(local_time, dtype='datetime64[s]')
np_times_ravel = np.ravel(np_times,order='C')

A: I'm not sure the order really matters.  You just need to remember (maybe with a comment) what you have at each step.  wrf.extract_times returns datetime.datetime objects in UTC.  pd.Timestamp shifts that to UTC+10, but still a datetime.datetime (essentially).  The numpy datetime64 object does not maintain a time zone, but because you've shifted it, the time should be in UTC+10.
If that's what you want, then I think you're golden.

A: You're totally right, I had to assign UTC to a pd.to_datetime, then I could move onto the local timezone
For all WRF users, adjust your timestamp by:
times = wrf.extract_times(f, timeidx=wrf.ALL_TIMES, squeeze=True)
times = pd.to_datetime(times)
times_index = times.tz_localize('UTC').tz_convert('Australia/Melbourne')

Thanks, Alyce


text:
Q: When using a functional component, why do parent state changes cause child to re-render even if context value doesn't change I'm switching a project from class components over to functional components and hit an issue when using a context.
I have a parent layout that contains a nav menu that opens and closes (via state change in parent). This layout component also contains a user property which I pass via context.
Everything worked great before switching to the functional components and hooks.
The problem I am seeing now is that when nav menu is opened from the layout component (parent), it is causing the child component to re-render. I would expect this behavior if the context changed, but it hasnt. This is also only happening when adding useContext into the child.
I'm exporting the children with memo and also tried to wrap a container with the children with memo but it did not help (actually it seemed to cause even more renders).
Here is an outline of the code:
AppContext.tsx
export interface IAppContext {
    user?: IUser;
}

export const AppContext = React.createContext<IAppContext>({});

routes.tsx
...
export const routes = <Layout>
    <Switch>
        <Route exact path='/' component={Home} />
        <Route exact path='/metrics' component={Metrics} />
        <Redirect to="/" />
    </Switch>
</Layout>;

Layout.tsx
...

const NavItems: any[] = [
    { route: "/metrics", name: "Metrics" }
];

export function Layout({ children }) {
    const aborter = new AbortController();
    const history = useHistory();
    const [user, setUser] = React.useState<IUser>(null);
    const [navOpen, setNavOpen] = React.useState<boolean>(false);
    const [locationPath, setLocationPath] = React.useState<string>(location.pathname);
    const contextValue = {
        user
    };

    const closeNav = () => {
        if (navOpen)
            setNavOpen(false);
    };

    const cycleNav = () => {
        setNavOpen(prev => !prev);
    };

    React.useEffect(() => {
        Fetch.get("/api/GetUser", "json", aborter.signal)
            .then((user) => !aborter.signal.aborted && !!user && setUser(user))
            .catch(err => err.name !== 'AbortError' && console.error('Error: ', err));

        return () => {
            aborter.abort();
        }
    }, []);

    React.useEffect(() => {
        return history.listen((location) => {
            if (location.pathname != locationPath)
                setLocationPath(location.pathname);
        })
    }, [history]);

    const navLinks = NavItems.map((nav, i) =>
<Link to={nav.route} onClick={closeNav}>{nav.name}</Link>
);

    return (

                                            <Icon iconName="GlobalNavButton" />

                    <Collapse className="mobile-nav" isOpen={navOpen}>

                            {navLinks}

                    </Collapse>

            <AppContext.Provider value={contextValue} >

                    {children}

            </AppContext.Provider>

    );
}

Metrics.tsx
...
function Metrics() {
   //Adding this causes re-renders, regardless if I use it
   const { user } = React.useContext(AppContext);
...
}

export default React.memo(Metrics);

Is there something I am missing? How can I get the metrics component to stop rendering when the navOpen state in the layout component changes?
Ive tried memo with the switch in the router and around the  block. I've also tried moving the contextprovider with no luck.

A: Every time your Layout component renders, it creates a new object for the contextValue:
const contextValue = {
    user
};

Since the Layout component re-renders when you change the navigation state, this causes the context value to change to the newly created object and triggers any components depending on that context to re-render.
To resolve this, you could memoize the contextValue based on the user changing via a useMemo hook and that should eliminate the rendering in Metrics when the nav state changes:
const contextValue = React.useMemo(() => ({
   user
}), [user]);

Alternatively, if you don't really need the object, you could simply pass the user as the context value directly:
<AppContext.Provider value={user}>

And then access it like:
const user = React.useContext(AppContext);

That should accomplish the same thing from an unnecessary re-rendering point of view without the need for useMemo.


text:
Q: Not getting currency symbol and locale code for few currency codes in java 7 Unable to get currency symbols and locale codes for few of the currency codes in Java 7. example: Currency codes.
AFN,
AMD,
ANG,
AOA,
AUD,
AWG,
AZN, etc..

and tried with DecimalFormat.getAvailableLocales() also instead of NumberFormat.getAvailableLocales() but no use.
following is the code to get currency symbols.
package com.test.testandbackups;

import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;

public class CurrencyUtils {

    public static void main(String args[]) throws Exception {
        String currencyCode = "INR";
        String ss = currencySymbol(currencyCode);

        System.out.println(ss);

    }

    public static String currencySymbol(String currencyCode) {
        String currencySymbol = null;
        currencySymbol = Currency.getInstance(currencyCode).getSymbol(
                getLocale(currencyCode));
        return currencySymbol;
    }

    private static Locale getLocale(String currencyCode) {
        for (Locale locale : NumberFormat.getAvailableLocales()) {
            String code = NumberFormat.getCurrencyInstance(locale)
                    .getCurrency().getCurrencyCode();
            if (currencyCode.equals(code)) {
                return locale;
            }
        }
        return null;
    }

}


text:
Q: json value '2' of type nsnumber cannot be converted to nsstring I am working on a imageSlider using Carousel imported from library: "react-native-banner-carousel"
I am trying to fetch the images which are stored locally inside a folder components. I am creating an array if images and then trying to render them through Carousel.
I am certainly getting an error like: "json value '2' of type nsnumber cannot be converted to nsstring"
ImageSlider code:
const BannerWidth = Dimensions.get('window').width;
const BannerHeight = 260;

const images = [
    require("./abc.jpg"),
    require("./xyz.jpg")
];

export default class ImageSlider extends React.Component {
    renderPage(image, index) {
        return (
            <View key={index}>
                <Image style={{ width: BannerWidth, height: BannerHeight }} source={{uri:image}} />
            </View>
        );
    }

render() {
    return (
        <View style={styles.container}>
            <Carousel
                autoplay
                autoplayTimeout={5000}
                loop
                index={0}
                pageSize={BannerWidth}
            >
                {images.map((image, index) => this.renderPage(image, index))}
            </Carousel>
        </View>
    );
}
}

    const styles = StyleSheet.create({
        container: {
            flex: 1,
            backgroundColor: '#fff',
            justifyContent: 'center'
        },
    });

As a result I should be able to render all the images displayed inside the images array. But I am getting this error.
Where am I getting wrong here?

A: Your issue is here:
const images = [
    require("./abc.jpg"),
    require("./xyz.jpg")
];

The require does not return the URL of the image but the internal index of the media. Which in your case I assume is 2, and the interface for the image is expecting a string.
Try this:
<Image style={{ width: BannerWidth, height: BannerHeight }} source={image} />

A: For anyone that is searching this error for whom the top answer didn't work: I received this error in React(Native) and wrote marginTop: '5'. With Parenthesis. It should be marginTop: 5
Wrong:
marginTop: '5'

Correct:
marginTop: 5


text:
Q: How to set value kendo multiselect? My scenario is I want to select some informations with checkbox in my grid and I can get that values like array ["3001","3004"] but when i click button kendo multiselect cannot set my values
here is onclick function:
function ongrdfleetinvoice() {

var multiselect = $("#fleetinvoice").data('kendoMultiSelect');
multiselect.value(["3001","3004"]);

}
// I also try like this same function
function ongrdfleetinvoice() {

$("#fleetinvoice").getKendoMultiSelect().value(["3001","3004"]);

}

//Here is my multiselect
@(Html.Kendo().MultiSelect().Name("fleetinvoice")
                  .DataTextField("CariNam")
                  .DataValueField("CariKod")
                  .Placeholder("All")
                  .Filter(FilterType.Contains)
                  .HtmlAttributes(new { style = "width: 300px;" })
                  .DataSource(source =>
                  {
                      source.Read(read =>
                      {
                          read.Action("FillFleet", "HeadOffice");
                      });
                  })
                )

   //C# Code
   var resultCariler = (from m in objEntities.Cariler
                                 where (m.CariTip == 13)
                                 orderby m.CariNam ascending
                                 select m).AsQueryable();
            foreach (var item in resultCariler)
            {
                Cariler objCariler = new Cariler();
                objCariler.CariKod = item.CariKod.Trim();
                objCariler.CariNam = item.CariNam + - + item.CariKod.Trim();
                listCari.Add(objCariler);
            }

but it's not working.
Do you have any idea?

A: I realise something when i fill my grid and my multiselect in C# side the field names are equal but values are not equeal when i change of that and put same values.. It worked...
var resultCariler = (from m in objEntities.Cariler
                             where (m.CariTip == 13)
                             orderby m.CariNam ascending
                             select m).AsQueryable();
        foreach (var item in resultCariler)
        {
            Cariler objCariler = new Cariler();
            objCariler.CariKod = item.CariKod.Trim();
            objCariler.CariNam = item.CariNam + - + item.CariKod.Trim(); //I changed this part with same in grid
            listCari.Add(objCariler);
        }

TO
var resultCariler = (from m in objEntities.Cariler
                             where (m.CariTip == 13)
                             orderby m.CariNam ascending
                             select m).AsQueryable();
        foreach (var item in resultCariler)
        {
            Cariler objCariler = new Cariler();
            objCariler.CariKod = item.CariKod.Trim();
            objCariler.CariNam = item.CariNam;
            listCari.Add(objCariler);
        }


text:
Q: Maximum number of allowed versions changes for SSM Parameter I have an SSM parameter created which will need a frequent update to it (almost 20 times a min). The SSM put_parameter API says it can return some error in case it exceeds the max limit versions.
ParameterMaxVersionLimitExceeded
The parameter exceeded the maximum number of allowed versions.
HTTP Status Code: 400
https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_PutParameter.html
So my question is what is the maximum allowed version changes we can make and is that limit configurable?
official documentation reference will be highly helpful

A: For your question, there is a limit for storing the 100 past values for the parameter.
For more information, you can go through the below link:
https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html#limits_ssm
According to AWS Support, 100 is the soft AND hard limit as of March 2022:

Our service team has got back to us and has informed us that unfortunately 100 is the hard limit for this specific service.
They've determined that a parameter can have max 100 versions at a given time. Parameter Store rotates the history of the parameter, when version 101 is created, the oldest version is deleted. This should happen automatically. If you're seeing ParameterMaxVersionLimitExceeded, you may have a label associated with the oldest version. You may need to move the label to another version, to be able to overwrite the parameter.


text:
Q: What is the meaning of this proposition by Robert Daublebsky von Sterneck? I found something wrong with this proposition, but I'm not sure.
Would you help me understand this proposition?  Thanks for all.
Can you give me an example?  It couldn't be better.
Cf. History of the Theory of Numbers, Volume II P152

English translation: He proved also that, if k is not a triangular number and if we represent k as a sum of integers so that the same part is not used oftener than 3 times in the same representation, then among the representations which contain ρ distinct parts less often than 3 times there are as many sums of even as of odd parts.

&

Original text: Ist k keine Trigonalzahl und stellt man k derart als Summe von ganzen Zahlen dar, dass eine und dieselbe Zahl bis zu dreimal, jedoch nicht öfter, in einer und derselben Darstellung verwendet werden darf, so gibt es unter den Darstellungen, welche ρ verschiedene Elemente weniger oft als dreimal enthalten, gleich viele gerade wie ungerade für jeden gegebenen Werth des ρ.

https://archive.org/details/HistoryOfTheTheoryOfNumbersVolII/page/n177
https://www.zobodat.at/pdf/SBAWW_106_2a_0115-0122.pdf


text:
Q: can't create 2 arrays in class else incomplete type is not allowerd c++ I'm learning to use OpenGL and refresh my knowledge of C++. I want to make simple way to render objects with one call, I've created Mesh class (that inherits from Component but that doesn't matter) and it should have 2 public variables (for now) which is float array for vertices and unsigned int array for indices, however when I try to create them in .h like this:
#pragma once

#include "../Component.h"

class Mesh : public Component {

public:
    float vertices[]; //error is on this line of code
    unsigned int indices[];

    Mesh(float vertices[], unsigned int indices[]);

};

it gives me a error which says "Incomplete type is not allowed", however this only happens if there are 2 arrays, if I remove the unsigned int array it works, then if unsigned int array would be declared one line higher like this:
public:
    unsigned int indices[]; //now the error is here
    float vertices[];

    Mesh(float vertices[], unsigned int indices[]);

and I remove the float array, then there is no error, I tried everything, and it can't be problem with that there is no size specified because if I remove the other array it magically works. Also sorry if this is like simple mistake I haven't worked with C++ in long time.
Cheers.


text:
Q: selenium.webdriver.chrome.webdriver' has no attribute 'ChromeOptions in Python Robotframework I am trying write function in python to avoid SSL certiicate error and chrome unpacked extension. But I am keep getting an issue in ChromeOptions.
Error :  module 'selenium.webdriver.chrome.webdriver' has no attribute 'ChromeOptions
Library imported
from selenium import webdriver
from selenium.webdriver.chrome import webdriver
from selenium.webdriver.chrome.options import Options

def open2browser():
    chromeOptions = webdriver.ChromeOptions()
    chromeOptions.add_experimental_option('useAutomationExtension', False)
    chromeOptions.add_argument('--ignore-certificate-errors')
    EXE_PATH = r'C:\ABC\chromedriver.exe'
    driver = webdriver.Chrome(executable_path=EXE_PATH, options=chromeOptions)
    driver.get('www.google.com')
    driver.maximize_window()

A: Root cause of this issue is the below import.
from selenium.webdriver.chrome import webdriver

your webdriver.Chrome is using the import from this and it's causing the issue.  Ideally you just need from selenium import webdriver import rest are not required in this case.