text:
Q: cross domain websocket connections fail in chrome, works in firefox i recently started to face this problem on chrome,where i am not able to connect to a websocket which is hosted under a different domain.
Example use case:
consider a domain that is front-ended by load balancer -> lb.com with two datacenters -> lb-dc1 and lb-dc2.The application page is hosted from lb.com but the code in this page, will create a web socket connection to lb-dc1 or lb-dc2.
This works fine on firefox/safari, but this connection is failing on chrome.
You can also see this behavior one
https://www.websocket.org/echo.html
Where the test socket connection will fail on chrome (i am using latest 91.0 version) whereas it will work on firefox.
I have an nginx proxy to pass the WSS request.. it looks something like this
    location /socket {
      proxy_pass http://<my-service>:8080/socket;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "Upgrade";
      proxy_buffering off;
      proxy_ignore_client_abort off;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header Host $host;
      proxy_read_timeout 86400;
      break;
    }

A: Maybe it's late but it may help others. After spending the whole day, clearing cookies helped me. It was a nightmare


text:
Q: SharePoint Access Services App Not working (greyed out) I am trying to setup Access Services on SharePoint 2016. Server is hosted on Azure Platform.
When I look at the ULS logs. What am I looking for?
How would I know there is something that is irregular with my setup or an error throwing that I could resolve? I have filter all "Access Services".

Maybe this is an error that will cause:
Any ideas to resolve?

ApplicationDatabase.AlterDatabaseProperties: ServerName='KRITHSHAREPOINT'; DatabaseName='db_bbcf9886_b86a_4b98_b09c_7c7352675d1c'; DatabaseType='Access'. Failed with exception: System.Data.SqlClient.SqlException (0x80131904): The sp_configure value 'contained database authentication' must be set to 1 in order to alter a contained database.  You may need to use RECONFIGURE to set the value_in_use.  ALTER DATABASE statement failed.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource 1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
  at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
  at Microsoft.Office.Server.Data.SqlSession.ExecuteNonQuery(SqlCommand command, SqlInfoMessageEventHandler handler)
  at Microsoft.Office.Server.Data.SqlSession.ExecuteNonQuery(SqlCommand command)
  at Microsoft.Office.Access.Services.Database.RetryableSqlCommand.ExecuteNonQuery()
   at Microsoft.Office.Access.Services.Database.SqlClientExtensions.ExecuteNonQueryLogged(SecureSqlCommand command, SqlCommandScope scope)
   at Microsoft.Office.Access.Services.Database.SqlScriptBatcher.ExecuteBatch(SecureSqlCommand command, SqlString batch, SqlCommandScope scope, Boolean logBatch)
   at Microsoft.Office.Access.Services.Database.SqlScriptBatcher.ExecuteDynamicScript(SqlString script, SqlTransaction transaction, Boolean logScript)
   at Microsoft.Office.Access.Services.Database.AccessDatabase.AlterDatabasePropertiesInternal()
   at Microsoft.Office.Access.Services.Database.ApplicationDatabase.ExecuteOperation(Action operation, String operationType)  ClientConnectionId:6be5a95c-25fd-488f-a94f-492d241f8faf  Error Number:12824,State:1,Class:16

A: You need to run this on your SQL Server.
sp_configure 'contained database authentication', 1;
GO
RECONFIGURE;
GO

Note that Access Services has been retired from SharePoint Online. You may want to give alternatives a thought before perusing this technology on-premises, as well.

A: Maybe the issue is related to the MinRole Server Roles,
Where the Access Service is only available at the below Minroles:

*

*Front-end

*Single-server farm

*Front-end with Distributed Cache.

The Access Service is not available at the below Minroles.

*

*Application

*Distributed cache.

*Search

*Custom

*Application with Search

For more details check MinRole and associated services in SharePoint Server 2016

So you will not be able to configure access service! , if the server Minrole is not one of the following

*

*Front-end

*Single-server farm

*Front-end with Distributed Cache.

Fortunately, you can to convert your server roles in a SharePoint farm deployment as mentioned at Role conversion using MinRole in SharePoint Server 2016

redpajama_set_name: RedPajamaStackExchange


text:
Q: display text file and update when the file contents change I want to have a window open that is just the content of the file file.txt. I do not care which command I use to open it, nano, cat, vi or whatever. I want it to update every time it changes, so if I open it in another window, edit it and save it, the file in the original window will update, kind of like screen. Any suggestions?
I have already tried just having it open a new cat file.txt command every few seconds, but it is very unreliable.

A: The low-tech solution in case watch is not available:
 while sleep 1; do tput clear; cat file.txt; done

(lets you easily adapt the checking interval).

A: On Linux, you can use the inotifywait command like so:
#!/bin/sh
while inotifywait --event modify file.txt; do
    tput clear
    cat file.txt
done

which is a modified version of Example 2 in the man page. This has the great advantage of doing absolutely nothing until file.txt is modified. The answers suggesting polling have the problems that polling always does: it will waste time when nothing has changed, and it will fail to catch changes until the polling interval has ended.

A: If you are on macOS you probably don't have watch installed per standard. You could go for the low-tech solution - which is elegant anyway, but you can also revert to home-brew.
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

You might have to give it (once!) your (administration) password. After the installation finishes, you should always check the system:
brew doctor
There should be a message along the lines:

Your system is ready to brew.

Now you are ready to install watch:
brew install watch
Once that is finished, you are ready for the solution by @dave-mackintosh:
watch cat file.txt

A: Use
watch cat file.txt

That should update when any changes occur, also try
man watch

To see what options it has so you can update the frequency of the updates.


text:
Q: Overriding global operator new to track huge memory allocations? I am trying to produce a special build of a large monolithic application. The problem I am trying to solve is tracking hard-to-reproduce huge memory allocations (30-80 gigabytes, judging by what OS reports).
I believe the problem is an std::vector resized to a negative 32-bit integer value. The only platform exhibiting this behavior is Solaris (maybe it's the only platform that manages to successfully allocate such chunks of contiguous memory).
Can I globally replace std::vector with my class, delegating all calls to the real vector, watching for suspicious allocations (size > 0x7FFFFFFFu)? Maybe selectively replace the constructor that takes size_t and the resize() methods? Maybe even hijacking the global operator new?

A: Why not to do something like this?
void *operator new(size_t size)
{
    // if (size > MAX_SIZE) ...
    return malloc(size);
}

void *operator new [](size_t size)
{
    // if (size > MAX_SIZE) ...
    return malloc(size);
}

Setting a breakpoint in the if would find the problem right away.

A: You can provide a custom allocator on your vector at the time it's constructed.
You could just delegate to std::allocator, and firewall the requested memory size, in the first instance.

A: Take a look at the implementation of the std::vector class on the problem platform.  Each implementation handles memory management differently (e.g. some double the currently allocated space when you add an object outside the vector's currently allocation size).  If your objects are sufficiently large and/or you have a large number of entries being added to the vector, would be possible to attempt to allocate beyond the available (contiguous) memory on the computer.  If that is the case, you'll want to look into a custom allocator for that vector.
If you're storing that many large items in a vector, you may want to look into another collection (e.g. std::list) or try storing pointers instead of actual objects.

A: You can supply your own allocator type to std::vector to track allocation.
But I doubt that's the reason. First, looking at the sizes (30-80GB) I conclude it's a 64-bit code. How could 32-bit negative integer value make it to vector size, which is 64-bit, it would have been promoted to 64-bit first to preserve value? Second, if this problem only occurs on Solaris then it can indicate a different problem. As far as I remember, Solaris is the only OS that commits memory on allocation, the other operating systems only mark the address space allocated until those memory pages are actually used. So I would search for unused allocations.


text:
Q: RotateTransform Webview in Windows 8 Metro apps I'm facing issues in rotating the Webview control in Windows 8 metro Apps using RotateTransform on click of a button.
RotateTransform rt = new RotateTransform();
        rt.CenterX = webView.Width / 2;
        rt.CenterY = webView.Height / 2;
        rt.Angle = 90;
        webView.RenderTransform = rt;

As you can check, I'm rotating Webview to 90 degrees, but Webview is not rotating.
please refer:
http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/d25bb7bd-d7ac-4e15-a4ee-882bf21464da
Any help/solution/reason will be helpful for me?

A: WebViews are special and cannot be rotated in a XAML application. It's due to the fact that a WebView is an instance of Internet Explorer, which is an ActiveX component (likely still hosted that way) that cannot be rotated in the same way as XAML content. WebViews always are aligned to the rotation of the device. For what it's worth, WPF has a similar design limitation.
Depending on what you're trying to accomplish, an HTML based Win8 application might be a better choice as you can rotate HTML content using CSS3 transforms. Or, you might be able to rotate content inside of the browser in a XAML application as long as you didn't need anything but right angles (0, 90, 180, 270).

A: Since Windows 8.1 the WebView should be able to rotate.
<WebView x:Name="WebView1" RenderTransformOrigin="0.5,0.5">
<WebView.RenderTransform>
    <CompositeTransform Rotation="30" ScaleX="1" ScaleY="1" SkewX="15" SkewY="0" />
</WebView.RenderTransform>

See: What's new in WebView in Windows 8.1


text:
Q: Graph theory results about the spread of a boolean value over a graph (e.g. epidemic contamination)? Let's say we have an undirected graph of 50 millions of nodes (let's say a first approximation of a country with closed borders).
Let's say there is a link/edge between node $a$ and node $b$ if person $a$ and $b$ have met with distance < 1 meter today.
On each node, you have a boolean value True/False (or "contaminated+recovered+dead" / "not contaminated").
Which part of graph theory and which theorems give us asymptotic information for a question like:
We put value True for 1000 random nodes on the graph, and False everywhere else. Let's say that after 1 iteration, there is a probability $p=0.5$ that if $a$ has a link with $b$ who has True, then $a$ becomes True too (contamination).
Question: after $n$ days, how many people have True?
Of course this will depend on the topology of the graph. Are there ways to answer to this question, given a few constants that describe the graph's topology, like:
$$\alpha = \text{average number of edges for nodes}$$
?
What are the relevant keywords in graph theory to search about this? (sadly, graph theory wasn't taught where I studied maths at university).

Numerical simulation: I more or less know how to simulate such a process with code (e.g. Python), and how to observe such things, but I was interested in the part of graph theory that can give answers.


text:
Q: How to get the device settings of time format (24/12 hour) on iOS/Xamarin I need to access the device settings of an iOS device from code and get the settings that specifies if the time is displayed as 12hour or 24hour format. I could use the "NSLocale.CurrentLocale" property but that just has the default time format of given locale, not the device settings, doesn't it?
I haven't found and related info online, so I'm asking for help here.

A: Try this code for iOS:
private bool CheckIsTwelveTimeFormat()
{
    var dateFormatter = new NSDateFormatter();
    dateFormatter.DateStyle = NSDateFormatterStyle.None;
    dateFormatter.TimeStyle = NSDateFormatterStyle.Short;

    var dateString = dateFormatter.ToString(NSDate.Now);
    var isTwelveHourFormat =
    dateString.Contains(dateFormatter.AMSymbol) ||
    dateString.Contains(dateFormatter.PMSymbol);
    return isTwelveHourFormat;
}

And this for android:
private bool CheckIsTwelveTimeFormat()
{
    return Android.Text.Format.DateFormat.Is24HourFormat(Android.App.Application.Context);
}


text:
Q: install pyspark in EC2 instance (amazon linux) Hi I tried to install pyspark in a EC2 instance (standard Amazon linux image). I installed anaconda python 3.6 and used "pip install pyspark" to install spark. It worked just fine. But when I try to enter pyspark with command "pyspark", I got the following error message. What could have gone wrong? Thanks!
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 18:10:19)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
18/03/03 05:47:13 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
18/03/03 05:47:13 WARN SparkContext: Another SparkContext is being constructed (or threw an exception in its constructor).  This may indicate an error, since only one SparkContext may be running in this JVM (see SPARK-2243). The other SparkContext was created at:
org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.lang.reflect.Constructor.newInstance(Constructor.java:423)
py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
py4j.Gateway.invoke(Gateway.java:236)
py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
py4j.GatewayConnection.run(GatewayConnection.java:214)
java.lang.Thread.run(Thread.java:748)
Traceback (most recent call last):
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/python/pyspark/shell.py", line 45, in <module>
    spark = SparkSession.builder\
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/sql/session.py", line 169, in getOrCreate
    sc = SparkContext.getOrCreate(sparkConf)
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/context.py", line 334, in getOrCreate
    SparkContext(conf=conf or SparkConf())
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/context.py", line 118, in __init__
    conf, jsc, profiler_cls)
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/context.py", line 180, in _do_init
    self._jsc = jsc or self._initialize_context(self._conf._jconf)
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/context.py", line 273, in _initialize_context
    return self._jvm.JavaSparkContext(jconf)
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1401, in __call__
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext.
: java.lang.ExceptionInInitializerError
        at org.apache.spark.SparkConf.validateSettings(SparkConf.scala:546)
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:373)
        at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:236)
        at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
        at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.UnknownHostException: 10-236-108-194: 10-236-108-194: Temporary failure in name resolution
        at java.net.InetAddress.getLocalHost(InetAddress.java:1505)
        at org.apache.spark.util.Utils$.findLocalInetAddress(Utils.scala:891)
        at org.apache.spark.util.Utils$.org$apache$spark$util$Utils$$localIpAddress$lzycompute(Utils.scala:884)
        at org.apache.spark.util.Utils$.org$apache$spark$util$Utils$$localIpAddress(Utils.scala:884)
        at org.apache.spark.util.Utils$$anonfun$localHostName$1.apply(Utils.scala:941)
        at org.apache.spark.util.Utils$$anonfun$localHostName$1.apply(Utils.scala:941)
        at scala.Option.getOrElse(Option.scala:121)
        at org.apache.spark.util.Utils$.localHostName(Utils.scala:941)
        at org.apache.spark.internal.config.package$.<init>(package.scala:204)
        at org.apache.spark.internal.config.package$.<clinit>(package.scala)
        ... 14 more
Caused by: java.net.UnknownHostException: 10-236-108-194: Temporary failure in name resolution
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
        at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928)
        at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323)
        at java.net.InetAddress.getLocalHost(InetAddress.java:1500)
        ... 23 more

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/python/pyspark/shell.py", line 54, in <module>
    spark = SparkSession.builder.getOrCreate()
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/sql/session.py", line 169, in getOrCreate
    sc = SparkContext.getOrCreate(sparkConf)
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/context.py", line 334, in getOrCreate
    SparkContext(conf=conf or SparkConf())
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/context.py", line 118, in __init__
    conf, jsc, profiler_cls)
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/context.py", line 180, in _do_init
    self._jsc = jsc or self._initialize_context(self._conf._jconf)
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/context.py", line 273, in _initialize_context
    return self._jvm.JavaSparkContext(jconf)
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1401, in __call__
  File "/home/ec2-user/anaconda3/lib/python3.6/site-packages/pyspark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling None.org.apache.spark.api.java.JavaSparkContext.
: java.lang.NoClassDefFoundError: Could not initialize class org.apache.spark.internal.config.package$
        at org.apache.spark.SparkConf.validateSettings(SparkConf.scala:546)
        at org.apache.spark.SparkContext.<init>(SparkContext.scala:373)
        at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:247)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:236)
        at py4j.commands.ConstructorCommand.invokeConstructor(ConstructorCommand.java:80)
        at py4j.commands.ConstructorCommand.execute(ConstructorCommand.java:69)
        at py4j.GatewayConnection.run(GatewayConnection.java:214)
        at java.lang.Thread.run(Thread.java:748)

A: Just use a Docker container: https://github.com/jupyter/docker-stacks/tree/master/pyspark-notebook why go thru the hassle of configuring it?


text:
Q: http-kit websocket resolve symbol Problem:  I get a null pointer exception when I call the caller function in the below code if I pass it data via json from a javascript socket client.  I don't get the error when I run this same code from the repl and I pass it the same data i.e.
In repl:
(def data (json/write-str {:controller "hql" :function "something"}))
(caller data)

This works fine
From javascript: this gives me s null pointer exception when calling the function caller from the handler.
<script>
var msg = {'controller': 'hql','function':'something'};
socket = new WebSocket('ws://192.168.0.7:9090');
socket.onopen = function() {
  socket.send(JSON.stringify(msg));
}
socket.onmessage = function(s) {
 console.log(s);
 socket.close();
}
socket.onclose = function() {
  console.log('Connection Closed');
}
</script>

(ns hqlserver.core
 (:use [org.httpkit.dbcp :only [use-database! close-database! insert-record update-values query delete-rows]]
       [org.httpkit.server])
 (:require [clojure.data.json :as json]))

(defn hql [data]
 (use-database! "jdbc:mysql://localhost/xxxx" "user" "xxxxx")
 (let [rows (query ("select username,firstname,lastname from users order by lastname,firstname")]
 (close-database!)
 (json/write-str rows)))

(defn get-controller [data]
 (if data
   (let [data (json/read-str data :key-fn keyword)]
     (data :controller))))

(defn caller [data]
  ((ns-resolve *ns* (symbol (get-controller data))) data))

(defn handler [request]
 (with-channel request channel
   (on-close channel (fn [status] (println "channel closed: " status)))
   (on-receive channel (fn [data] (send! channel (caller data))))))

 (defn -main [& args]
   (run-server handler {:port 9090}))

A: Don't know if it's the best way but this is the solution:
Thanks to noisesmith for helping and tips....
(ns hqlserver.core
(:use [org.httpkit.dbcp :only [use-database! close-database! insert-   record update-values query delete-rows]]
    [org.httpkit.server]
    [hqlserver.s300.login :only [login]])
(:require [clojure.data.json :as json]
        [hqlserver.s300.site :refer [site-index site-update]]
        [clojure.string :as str]))

(defn get-site [data]
 (if data
   (let [data (json/read-str data :key-fn keyword)]
     (-> data :site))))

(defn get-controller [data]
  (if data
    (let [data (json/read-str data :key-fn keyword)]
      (-> data :controller))))

(defn get-function [data]
  (if data
    (let [data (json/read-str data :key-fn keyword)]
      (-> data :function))))

(defn caller [data]
 (let [site (get-site data)]
   (let [controller (get-controller data)]
     (let [function (get-function data)]
       (cond
         (and (= site "s300")(= controller "login")(= function "login")) (login data)
         (and (= site "s300")(= controller "site")(= function "site-index")) (site-index data)
         (and (= site "s300")(= controller "site")(= function "site-update")) (site-update data)
         :else (json/write-str {:error "No records found!"}))))))

(defn async-handler [ring-request]
  (with-channel ring-request channel
    (if (websocket? channel)
      (on-receive channel (fn [data]
                        (send! channel (caller data))))
      (send! channel {:status 200
                  :headers {"Content-Type" "text/plain"}
                  :body    "Long polling?"}))))

(defn -main [& args]
 (run-server async-handler {:port 9090}));


text:
Q: creating IAM policy for Amazon S3 I am trying to implement an IAM policy where A user can only have access to the folder he is entitled too. I got this code from Amazon docs
Allow a user to list only the objects in his or her home directory in the corporate bucket
This example builds on the previous example that gives Bob a home directory. To give Bob the ability to list the objects in his home directory, he needs access to ListBucket. However, we want the results to include only objects in his home directory, and not everything in the bucket. To restrict his access that way, we use the policy condition key called s3:prefix with the value set to home/bob/. This means that only objects with a prefix home/bob/ will be returned in the ListBucket response.
{
  "Statement":[{
    "Effect":"Allow",
    "Action":"s3:ListBucket",
    "Resource":"arn:aws:s3:::my_corporate_bucket",
    "Condition":{
      "StringLike":{
      "s3:prefix":"home/bob/*"
    }
  }]
}

This is not working for me. When I run my code I am able to see all the folders and sub folders. My modified code looks something like this:
{
  "Statement":[{
    "Effect":"Allow",
    "Action":"s3:ListBucket",
    "Resource":"arn:aws:s3:::Test-test",
    "Condition":{
      "StringLike":{
      "s3:prefix":"Test/*"
    }
  }]
}

When I run my code in c# using the credentials of the user that is attached to the above policy I get all the folders and not just the one under "Test"...
Would really appreciate some help!

A: I finally got it working. Although I think there is a bug in AWS management console or atleast it seems like one. The problem is my policy was right all along the way but it behaved differently when I accessed it through AWS management console then softwares like CloudBErry. One thing I had to modify was ACL settings for objects and buckets.That too would have been done earlier had the AWS console worked properly. Anyways here is my policy:
{
  "Statement": [

    {
      "Effect": "Allow",
      "Action": "s3:ListAllMyBuckets",
      "Resource": "arn:aws:s3:::*",
      "Condition": {}
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:ListBucket",
        "s3:ListBucketVersions"
      ],
      "Resource": "arn:aws:s3:::pa-test",
      "Condition": {
        "StringLike": {
          "s3:prefix": "test/*"
        }
      }
    },
    {
      "Effect": "Allow",
      "Action": "s3:*",
      "Resource": "arn:aws:s3:::pa-test/test/*",
      "Condition": {}
    }
  ]
}

1) The problem is when I access management console for this IAM user through AWS console I get access denied when I click on my bucket although when I log in through Cloudberry I can see my folders.
2) I had to modify the ACL settings for my bucket and objects(folders)
for my bucket:
Owner : Full Control
Authenticated Users : Readonly
For my folders:
Owner : Full Control
Now the issue is that you cannot set ACl settings for folders(object) in AWS console. You can set them for files(object). For example if you right click on a folder(object) inside a bucket and then click properties it won't show you a permission tabs. But if you right click on a bucket or a file(Say test.html) and click properties it will show you a permissions tab.
I am not sure if someone else has noticed this issue. Anyways that is my script and it's working now.

A: The result you are expecting from the listBucket, is not happen like that.
Because the policy only let you to access allow and deny on the objects according to the bucket policy.
ListBucket will list all the objects but you will have access only on the prefix folder and it's content.
If you want to list only folder then you have to code for that like read IAM policy and then get prefix string and then list with that prefix then you will get only the desired folder. because till now no such option provided by amazon s3.


text:
Q: iPhone 6s storage problem I have a 16 GB iPhone 6s. Just 7 days ago I restored as new because my phone keeps taking up all my storage. When I restored, I had 4 GB available, 5 days went passed and I was forced to restore again because I had no space. I didn't even download a single thing.
3 days ago I restored as new, again. I had 3.9 GB available. Yesterday and this morning I had 1.32 GB available, now I have 600 MB available. This has been a problem since my iPhone 5c on iOS 7.
I've done numerous restoring from backups and as new. I haven't downloaded any apps and in storage usage settings, it doesn't add up to what is being used. I've called Apple and all they say is do a restore even though I've done it many times.
If I delete an app, my phone will take up the space within a day. It got so bad I couldn't send texts because my phone would "forget" them. iTunes says I have more storage than I actually do. I've used 3rd party cleaning software such as PhoneClean. It freed up some but not all.
Here is a picture of the Storage section on Preferences after a recent restore:

It looks ok now but available space will slowly go down after a couple of days.


text:
Q: Five-year Annual Average vs five-year Weighted average maintenance costs for two car types If we are comparing maintenance costs (M$) per mile (M$/m = Mtype) of two car models over a 5 year period, where the number of cars that are type (a) is much less than type (b), and the number of type (b) cars keeps increasing at a faster rate than type (a) so the mix keeps getting heavier for type (b), which would be a more reliable comparison of the average cost of maintenance for type (a) and (b) cars, and why: (1) the average annual costs for a and b types , where Avg. M$a =(Ma1+Ma2+Ma3+Ma4+Ma5)/5 and Avg. M$b = (Mb1+Mb2+Mb3+Mb4+Mb5)/5  or (2) Weighted 5-year averages where, WAvg. M$a = Sum Ma1-5/Sum ma1-5  and WAvg. M$b = Sum Mb1-5/Sum mb1-5. If the weighted average is considered more reliable, why does it matter that there are more type )b) cars and their number is increasing faster than type (a) cars as long as the number of both types does not present small sample problems?

A: It all depends on what you are trying to do. If you care about estimating the reputation of each car type, as determined by maintenance costs, then this doesn't really depend on how many of the car you have as long as it's not too small (say like around 50-100 or more). So you would consider each average equally, without any weights. However, if you want to evaluate something like average maintenance cost over all cars where both types of cars are being included, say to measure overall satisfaction with all the cars, then you'll probably want a weighted average. As for when it's increasing or decreasing over time, if the only thing you care about is future 5 year averages, then you can simply use a time series forecasting method to predict future years, and then include those future year predictions in your calculations. The simplest forecasting method is to assume that the difference between last year and year before will continue to be the difference between years in future years. Or you can fit a quadratic polynomial to your annual data, if you suspect that costs may be increasing/decreasing at an increasing or decreasing rate. If you don't have a lot of years of data though, you probably don't want to go beyond a quadratic or cubic fit to make future predictions.


text:
Q: \( \) don't work with TOC? If I write this line of code
\subsection{Ranger \( n \) boules distinguables dans \( M \) boîtes}

I obtain an error over the second \)
(./Probabilité.toc

./Probabilité.toc:8: LaTeX Error: Bad math environment delimiter.

while if I write
\subsection{Ranger $ n $ boules distinguables dans $ M $ boîtes}

everything is ok.
Why? \(\) has problems with TOC?

A: \( and \) are not robust, you need to \protect them.
Or load package fixltx2e that makes them robust.
(Update:) Package fixltx2e defines the command \MakeRobust that redefines a macro in the same way, as the macro would has been defined by using \DeclareRobustCommand in the first place.
"Robust" means, that the macro can be used inside moving arguments (entries for the table of contents, header lines, …) without breaking and the need to add \protect in front of them.

A: A short 'aftermath': Since fixltx2e content has entered the LaTeX Kernel as of 2015/01/01 the fixltx2e amendments are available without loading the package.
This means: \(...\) is robust now without much further ado!
Heiko Oberdiek's answer is valid anyway for older distributions of course!
\documentclass{article}

\usepackage[utf8]{inputenc}
\begin{document}
\tableofcontents
\section{Ranger \( n \) boules distinguables dans \( M \) boîtes}
\end{document}


text:
Q: Take image of the disk if Windows are already activated I am planning to make a Windows installation in some laptops. I ve planned to make installations, new settings etc in one laptop, take an imageof the disk and mount the image to the other machines. The questions is, what can I do if Windows are already activated? It's a bit illegal I think. Any ideas?

A: If you are not using a Volume Licence Key to be legal you will need to enter in a new key for each machine after you load the image. (at the bottom of the 2nd link there is a command line version so you could script it to make the action of loading the image faster.)

A: Before you capture your image, run sysprep. I prefer the OOBE, Generalize, and Shutdown options. These will prepare your image to handle some operations on firstboot.
OOBE: Will ask for computer name, reset SSIDs, initial admin user creation, and a new license key for activation.
Generalize: Will make changes to the HAL to accommodate any driver/hardware differences between the machines.
Shutdown: Boot to your imaging software CD after shutdown and capture the image.
If the computers are all a single brand and came with Windows 7 installed already, you will most likely not have to enter a license key because it will be pulled in from the BIOS/SLIC. This is the case atleast with imaging Dell machines that had OEM Windows 7 installed at the factory.
Sysprep can be found at c:\windows\system32\sysprep\sysprep.exe and you can either choose these options from the GUI or specify them on the command line.
c:\windows\system32\sysprep\sysprep.exe /oobe /generalize /shutdown


text:
Q: Javascript returns valid date of invalid date-string When I try to parse a string - to check if it is a valid date, javascript parses it as a date, and returns a valid date.

console.log(new Date("Agent 007"));  // returns Sun Jul 01 2001 00:00:00 GMT+0200
console.log(Date.parse("Agent 007")); // returns 993938400000
console.log(moment.utc("Agent 007").valueOf()); // returns 993945600000
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

How to prevent it ?
For you @Andreas:
Chrome Debugger console window:


text:
Q: How closely does the analogy of a 2-sphere hold in cosmology? Two dimensional creatures living on the surface of an inflating 2-sphere are often used to explain general relativity, curved space, and big bang cosmology.  For years, though, I have wanted to ask: The 2-sphere is closed.  What about the actual universe?  Is it closed in the same sense?  When cosmologists talk about a "closed" or "open" universe, it is not clear to me that they are answering the question that I want to ask.
So I think I have figured out how to ask my question:  Let's say we take a space-like hypersurface defined by the points where the proper time since the big bang singularity is, say, 13 billion years.  What are some of the global properties of this hypersurface?  Does it close back in on itself, like the 2-sphere, or does it extend to inifinity?  Does it have a volume, or is it infinite in volume?  Does it have a finite number of, say, galaxies in it, or are they infinite in number?

A: This is (almost) exactly what cosmologist mean when the talk about the Universe being open or closed.
Observational evidence points to the universe being almost perfectly flat.* This means that the spatial slices of the universe are not 3-spheres. Or, at least if they are, the radius of curvature of this 3-sphere would have to be much larger than the observable universe.
Being flat, however, does not necessarily imply that the spatial slices are infinite. For example, they could also be 3-tori, in which case the volume and total number of stars would be finite. Thus far we have found no real evidence that the universe is period in some way. This suggests that any periodicity length scale cannot be much smaller than the size of the observable universe.
*Recently is has been suggested (see 2003.04935) that allowing a small positive spatial curvature may help resolve the tension between different measurements of the Hubble rate. This would suggest that the spatial slices are in fact (very big) 3-spheres. However, this is not widely accepted.


text:
Q: IWebElement becomes null after being sent to a function I want to check if my IWebElement is displayed or not. When I try to reach and check the IWebElement within the class it's all OK but when I send it to my KontrolElement() function I get a NullReferenceException. KontrolElemet() is required because this process takes place several times.
KontrolElement():
//This is inside a class called 'Helpers'
public void KontrolElement(IWebDriver WebDriver, IWebElement WebElement, string msg)
{
    try
    {
        //"WebElement" is null
        Assert.IsTrue(WebElement.Displayed);
    }
    catch (AssertionException)
    {
        Console.WriteLine("Kontrol: " + msg);

        //Sends an E-mail with the screenshot of the page attached to it
        new ScreenShot().Crush(WebDriver, msg, "");
    }
}

How I use it ('el' is generally an object inside an IReadOnlyCollection which is iterared with a foreach loop):
//This takes place in the PageObject class which extends 'Helpers'
IWebElement el = WebDriver.FindElement(By.ClassName("listTop"));

//Console.WriteLine(el.Displayed) outputs True

KontrolElement(WebDriver, el, "el is not displayed");

Has anyone faced a problem like this? What can be the alternative solutions?

A: I'm not a big fan of wrapping Asserts or wrapping anything so simple into a function. What do you gain? Don't make things more complicated than they need to be.
Remove the function and just use the below code in your scripts
IWebElement el = WebDriver.FindElement(By.ClassName("listTop"));
Assert.IsTrue(el.Displayed, "Verify element is displayed");

I would change "element" in the assert comment to something more specific, e.g. "Verify login button is displayed".
If you insist on using the function, why are you passing in IWebDriver when you aren't using it?
Another thing... catching a generic Exception is not a good practice. Catch only what you plan to handle.

A: A conflict between the System.Debug and Nlog library was causing the problem, the compiler would see the Assert reference in the System.Debug library which in return would throw a NullReferenceException.

A: In my case, it had to do with the namespace. I was using OpenQA.Selenium.Support.PageObjects. This caused the element to be null always. Fixed the issue by using the SeleniumExtras.PageObjects namespace instead.


text:
Q: DateTime new Date(params) in javascript is faster by 1 month It is very weird but it seems that new Date(params), when passed in the correct format of year, month, day, hours, minutes, seconds, milliseconds, it is ahead by 1 month.
Take a look at the following implementation:
  // The format below needs to be changed according to req.param('dateTime')
  // dateTime format is as follows: "dd/MM/yyyy HH:mm:ss"
  var dateTime = report['dateTime'];
  console.log('dateTime: '+dateTime);
  var dateTimeSplit = dateTime.split(' ');
  var dateSplit = dateTimeSplit[0].split('/');
  var timeSplit = dateTimeSplit[1].split(':');
  var day = parseInt(dateSplit[0]);
  var month = parseInt(dateSplit[1]);
  var year = parseInt(dateSplit[2]);
  var hour = parseInt(timeSplit[0]);
  var minute = parseInt(timeSplit[1]);
  var second = parseInt(timeSplit[2]);
  var createdAt = new Date(year, month, day, hour, minute, second, 0);
  console.log('createdAt: '+createdAt);

And the results from the logs are:
Feb 09 04:13:46 sails-wusrs app/web.1:  createdAt: Mon Mar 09 2015 12:02:24 GMT+0000 (UTC)
Feb 09 04:13:46 sails-wusrs app/web.1:  dateTime: 09/02/2015 12:02:24

This server is running on heroku and it's weird that the log of createdAt is in front of dateTime. Everything else is alright, except for the month. 02 is Feb right? I'm so confused. Thanks for any help!

A: Month in javascript datetime starts from 0.
http://javascript.info/tutorial/datetime-functions


text:
Q: Check / Improve a Proof - Convex functional on convex domain is continuous throughout its interior I am working through Luenberger's Vector Space Methods for Optimization book.  I am working on a corollary left to the reader, and I'm not quite sure that my proof is correct/the sharpest proof out there.  I'd love to get some feedback from people if you're interested.  Here it is:
$\bf{Claim}$: Let $X$ be a normed linear space.  Let $C \subset X$ be a finite-dimensional and convex subset, and let $\mathring{C}$ be its relative interior. If a functional $f: C \rightarrow \mathbb{R}$ is convex, then $f$ is continuous throughout $\mathring{C}$.
$\bf{Proof}$: I treat $C$ as a metric space in its own right so that I don't have to worry about relative interiors.  I make use of the following facts (These are facts that I can prove, and I won't regurgitate them, but they are all in Luenberger pp. 192-194).

*

*If $f$ is continuous at a single point, then it is continuous throughout $\mathring{C}$.

*If $x_0 \in C$ and there exists a neighborhood $N$ containing $x_0$ and an $\epsilon > 0$ such that $f(x) \leq \epsilon$ for all $x \in N$, then $f$ is continuous at $x_0$. ****I am pretty sure this is equivalent to there being an $r$ such that $(r,x_0)$ is in the relative interior of $[f,C]$, the epigraph of $f$, but I am not 100% sure, though I don't think that actually matters for the truth of the claim.
Without loss of generality, assume by translation that $0 \in C$ and $f(0) = 0$. Let $\{x_i\}$ be a basis of $C$,  and put $M = \max_i\{|f(x_i)|\}$.  Pick $x \in C$, which can be written as $\sum \alpha_ix_i$.  By convexity and translation,
$ f \big(x\big) = f \big(\sum \alpha_ix_i\big) = f \big(\sum \alpha_ix_i + (1-\sum \alpha_i)\cdot0\big) \leq \sum\alpha_if(x_i) \leq M\sum|\alpha_i|$.
Since $0 \in \mathring{C}$, there's a bounded open ball $N \subset C$ around $0$, and, since $N$ is bounded, there is a $\delta > 0$ so that for any $x = \sum\alpha_ix_i \in N$ it must be that $\max_i\{|\alpha_i|\} < \delta$. It follows that for any $x$ in $N$, $ f \big(x\big) \leq \dim\{C\} \cdot \delta \cdot M$.
QED.


text:
Q: Batch script to sort the largest file I am currently trying to make a script that will ask up to 9 variables, verify their sizes and then give me the largest one. It needs to work with less variables too. Also, it has to be done from a second script that is called from the first one.
I'm a student and I'm having trouble figuring out how to do this.

A: most of the job can be done with just dir (with proper switches). Add some code for getting input from user and a for to get the output of dir and you're done:
@echo off
setlocal
REM get filenames:
:loop
set "new="
set /p "new=Filename (or leave blank): "
if defined new (
  set files=%files% %new%
  goto :loop
)

REM list them sorted by size (for debugging/checking)
dir /a-d /os %files% |findstr /v /b /c:" "
echo/

REM get the last (biggest) of them:
for /f "delims=" %%a in ('dir /a-d /os /b %files%') do set biggest=%%a
echo biggest file is: %biggest%


text:
Q: Find the generators of $\mathbb{Z}^\times_{18}$ under multiplication. Find the generators of $\mathbb{Z}^\times_{18}$ under multiplication.
I know how to do it when it's a prime but I don't know how to do it when it's not a prime. Can someone help me please? Thanks.

A: $(\mathbf Z/18\mathbf Z)^\times=\{\pm 1,\pm 5 \pm 7\}$. It is a group of order $6$ and its generators are the elements with order $6$. It is enough to find which elements $x\ne \pm1$ are such that $x^3=-1$. One checks there's only one generator: $5$.

A: We have $\mathbb{Z}_{18}^{\times}=\{\overline{1},\overline{5},\overline{7},\overline{11},\overline{13},\overline{17}\}$ and the generators are all the elements of order $6$, which is the order of $\mathbb{Z}_{18}^{\times}$. Since the order of every element divides the order of the group where it belongs (by Lagrange's theorem), the possible orders are 1(only for $\bar{1}$), $2,3$ and $6$. So:
$\overline{5}^2=\overline{25}=\overline{7},~ \overline{5}^3=\overline{35}=\overline{11}$, so the order of $\overline{5}$ is $6$ and $\overline{5}$ is a generator of $\mathbb{Z}_{18}^{\times}$.
You continue that way for the rest of the elements. This is one way (the hard one). Another option is to note that since $\mathbb{Z}_{18}^{\times}$ is cyclic, it's generators are the elements of the form $\overline{5}^k$ of order $6$. Since the order of $\overline{5}^k$ is $\frac{6}{gcd(6,k)}$, the only generators are $\overline{5},~\overline{5}^5=\overline{11}.$
Notice that generators always come in pairs, i.e. if $g$ is a generator then $g^{-1}$ is also a generator.

A: This group is small enough that you can just brute-force it. Consider each element, and check if it generates the full group.

A: As others have touched upon, $|(\Bbb Z_{18})^{\times}| = 6$. Since the multiplication (mod $18$) of $\Bbb Z_{18}$ is commutative, this is an abelian group of order $6$, and is thus cyclic. For any cyclic group of order $6$, say $G = \langle a\rangle$, we have just two generators, $a,a^{-1} = a^5$. Since the identity $[1]_{18}$ is clearly NOT a generator (it has order $1$), we've got a 40% chance of picking one of the two generators out of the remaining five, just by choosing at random.
Eliminating $[-1]_{18} = [17]_{18}$ straight off the bat is easy, it clearly has order $2 < 6$. Just to be perverse, let's look at $[7]_{18}$. We find that $[7]_{18}^2 = [13]_{18}$, and so $[7]^3 = [1]_{18}$. This shows both $[7]_{18},[13]_{18}$ have order $3$ (because in a cyclic group of order $3$, say $\langle x\rangle$, both $x$ and $x^2$ have order $3$).
The remaining elements, therefore, must have order $6$, so the generators are $[5]_{18},[11]_{18}$.


text:
Q: How to edit iPhone photos from Mac I want to develop a simple photo editor.
Basically application should just crop photos on iPhone.
I was looking for solution on iPhone, but found that Apple does not allow third party developers to edit photos in Photo Library.
Is there a possibility to do this from Mac?
Or I missed something and it can be managed from iPhone?

A: You can easily pull the photos from the Library and edit/save them freely if the user grants you the permissions to access the photos. You can only replace existing photos if your app created them in the first place.

A: You can create an app which functions as below:

*

*Access Photos Library using UIImagePickerController and get Image in your app. Check this

*Crop your image. Check this

*Save the cropped image to PhotoLibrary using following code:
UIImageWriteToSavedPhotosAlbum(croppedImage, nil, nil, NULL);
Hope this is what you are looking for.

A: As Kapil said you can use imagepicker to access the photos from library. If you need to develop a photo editor application you can have a look at this sample here.
From iOS8 or later its also good looking at the photo editing extension here.


text:
Q: How to set current datetime in gremlin console? How to set current DateTime in the gremlin console?
I need to add an audit field created_on with current_timestamp as default value
Eg:
g.addV('student').property('name', 'Thirumal').property('created_on', datetime())

In, the above query, I am getting an error on datetime(). What is the syntax to add default date time?

A: In the Gremlin Console, you can use new Date() if you do not have a version that supports datetime(). Note that datetime() was recently added to Gremlin so you may not have the version that contains it yet. I believe it was added in the 3.5.2 release. Also please see this discussion
Without datetime() you can still do
gremlin> g.addV('test').property('date', new Date())
==>v[61287]

gremlin> g.V(61287).valueMap()
==>[date:[Thu Feb 10 10:02:18 CST 2022]]

UPDATED based on comments:
If you are using Amazon Neptune, the database provides its own version of the datetime function that expects an ISO 8601 compliant date string. So you can do something like this:
g.addV('test').property('date', datetime('2022-02-10'))

If you are using Neptune's Jupyter notebooks, to set the current date, you can create a date in a cell above (using Python) of the form
my_date = # some date calculation that yields an ISO string.

or, more concretely:
import datetime
d=datetime.datetime.now()
my_date = d.strftime('%Y-%m-%d')

and inject that string like this:
g.addV('test').property('date', datetime('${my_date}'))


text:
Q: Confused with DateTime format I have String like 'Wed Jan 22 13:30:52 UTC 2020', need to convert this string To IST format using Sql Server.
I don't aware the about above format.

A: This doesn't seem to be any of the formats recognized internally by SQL Server:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
So, you will have to convert it yourself. Lets suppose that we have your sample date:
declare @date varchar(50) = 'Wed Jan 22 13:30:52 UTC 2020'

You can get the date parts using substring (supposing that every date uses exactly the same format):
select substring(@date, 1, 3) as day,
       substring(@date, 5, 3) as month,
       substring(@date, 9, 3) as year,
       substring(@date, 12, 2) as hour,
       substring(@date, 15, 2) as minute,
       substring(@date, 18, 2) as second,
       substring(@date, 25, 4) as utc

Now you only need to built a datetime value from those date parts :
select datetimefromparts(convert(int, substring(@date, 9, 3)) + 2000,
                         case substring(@date, 5, 3) when 'Jan' then 1
                                                     when 'Feb' then 2
                                                     ...
                         end,
                         case substring(@date, 1, 3) when 'Mon' then 1
                                                     when 'Tue' then 2
                                                     when 'Wed' then 3
                                                     ...
                         end,
                         convert(int, substring(@date, 12, 2)),
                         convert(int, substring(@date, 15, 2)),
                         convert(int, substring(@date, 18, 2)),
                         0)

Finally you can add AT TIME ZONE 'India Standard Time' to define your IST timezone.
select datetimefromparts(convert(int, substring(@date, 9, 3)) + 2000,
                         case substring(@date, 5, 3) when 'Jan' then 1
                                                     when 'Feb' then 2
                                                     ...
                         end,
                         case substring(@date, 1, 3) when 'Mon' then 1
                                                     when 'Tue' then 2
                                                     when 'Wed' then 3
                                                     ...
                         end,
                         convert(int, substring(@date, 12, 2)),
                         convert(int, substring(@date, 15, 2)),
                         convert(int, substring(@date, 18, 2)),
                         0)
       AT TIME ZONE 'India Standard Time'

A: The following might help:
declare @date varchar(50) = 'Wed Jan 22 13:30:52 UTC 2020'

select CAST(SUBSTRING(@date, 5, CHARINDEX('UTC',@date,1)-6) + SUBSTRING(@date,CHARINDEX('UTC',@date,1)+3,100) AS DATETIME) AT TIME ZONE 'India Standard Time'

AT TIME ZONE works on SQL Server 2016 and later.


text:
Q: comma in the middle of construction: than... and than Writing an essay on my trial region English test, I ran into a problem. I wanted to use doubled than, but I was not sure if it's right to do such a thing, and if I should put a comma before the "and than". So, if it wouldn't be a problem, could you please say which phrase (I'll write them both below) is right and, also, explain why?

Computers have way more occasions to spend time conveniently than people who're claiming this statement to be right are able to imagine, and than I've already mentioned earlier.

Computers have way more occasions to spend time conveniently than people who're claiming this statement to be right are able to imagine and than I've already mentioned earlier.

I guessed I knew English punctuation a bit, at least a bit. Anyway, we should put a comma before "and" if it connects two sentences in a case when they both have a subject + verb (sorry for a poor phrase, I didn't know how to say it in a proper way). This has seemed to be this case though I thought there's a chance of not putting a comma there due to such a construction as "than... and than".
I appreciate any help.


text:
Q: Returning multi SQL value as one row (despite its length) in HTML table This question might be seems basic but I don't know how to return multi SQL value as one row in HTML despite its length.
This is my current table looks like:

This is an example on how it looks like after filled by value.

With this code of mine:

              No
              Location 1
              Location 2
              Location 3
              Price

              {{$query.No}}
              {{$query.Location_1}}
              {{$query.Location_2}}
              {{$query.Location_3}}
              {{$query.Currency} {$query.Price}}

What I'm trying to do is to combine $query.Currency $query.Price $... and so on as one row, without any endline.
Desired Output:

A: So, I finally found out how to solve the breaking space for SQL return variables in my problem.
If you guys ever encountered such problem, you can fix it by separating variables. Here is how:
{{$query.Currency}} {{$query.Price}}


text:
Q: How to console.log the imagerySet of a layer? I found this simple openlayers example online , the map initialization looks like below:
var styles = [
  'Road',
  'Aerial',
  'AerialWithLabels',
  'collinsBart',
  'ordnanceSurvey'
];
var layers = [];
var i, ii;
for (i = 0, ii = styles.length; i < ii; ++i) {
  layers.push(new ol.layer.Tile({
    visible: false,
    preload: Infinity,
    source: new ol.source.BingMaps({
      key: 'Ak-dzM4wZjSqTlzveKz5u0d4IQ4bRzVI309GxmkgSVr1ewS6iPSrOvOKhA-CJlm3',
      imagerySet: styles[i]
      // use maxZoom 19 to see stretched tiles instead of the BingMaps
      // "no photos at this zoom level" tiles
      // maxZoom: 19
    })
  }));
}
var map = new ol.Map({
  layers: layers,
  // Improve user experience by loading tiles while dragging/zooming. Will make
  // zooming choppy on mobile or slow devices.
  loadTilesWhileInteracting: true,
  target: 'map',
  view: new ol.View({
    center: [-6655.5402445057125, 6709968.258934638],
    extent: [-16655.5402445057125, 6609968.258934638,0,6809968],
    maxZoom: 20,
    minZoom:13,
    zoom: 13
  })
});

var select = document.getElementById('layer-select');
function onChange() {
  var style = select.value;
  for (var i = 0, ii = layers.length; i < ii; ++i) {

    console.log( layers[i].getSource().item(1) +  " " + styles[i] );

    layers[i].setVisible(styles[i] === style);
  }
}

select.addEventListener('change', onChange);
onChange();

Now what i really was trying to do was , i wanted to console.log the imagerySet of every layer , inside the below peice of code:
function onChange() {
  var style = select.value;
  for (var i = 0, ii = layers.length; i < ii; ++i) {

    console.log( layers[i].getSource().item(1) +  " " + styles[i] );

    layers[i].setVisible(styles[i] === style);
  }
}

I tried the below few method:
layers[i].getSource().item(1);

and
layers[i].getSource().getImagerySet();

but it does't give me the desired result , can anybody corrent me and tell me whats the correct way to imagerySet inside the loop ?
FIDDLE HERE

A: imagerySet is a specific attribute for bing maps. It wont work in any other tile type. getImagerySet wont work as there is no such function documented on ol3. Also seems that ol3 have no function to retrieve the bing image type.
You can always pass a custom attribute during layer initilasation and the retrive it using the get method.
Check the following fiddle I use myattribute on layer and pass the styles[i] value. Then I can get this value using layers[i].get('myattribute')


text:
Q: Deploying a transaction event listener in a Neo4jDesktop installation I have created a project that contains an ExtensionFactory subclass annotated as @ServiceProvider that returns a LifecycleAdapter subclass which registers a transaction event listener in its start() method, as shown in this example.  The code is below:
@ServiceProvider
public class EventListenerExtensionFactory extends ExtensionFactory<EventListenerExtensionFactory.Dependencies> {

    private final List<TransactionEventListener<?>> listeners;

    public EventListenerExtensionFactory() {
        this(List.of(new MyListener()));
    }

    public EventListenerExtensionFactory(List<TransactionEventListener<?>> listeners) {
        super(ExtensionType.DATABASE, "EVENT_LISTENER_EXT_FACTORY");
        this.listeners = listeners;
    }

    @Override
    public Lifecycle newInstance(ExtensionContext context, Dependencies dependencies) {
        return new EventListenerLifecycleAdapter(dependencies, listeners);
    }

    @RequiredArgsConstructor
    private static class EventListenerLifecycleAdapter extends LifecycleAdapter {

        private final Dependencies dependencies;
        private final List<TransactionEventListener<?>> listeners;

        @Override
        public void start() {
            DatabaseManagementService managementService = dependencies.databaseManagementService();
            listeners.forEach(listener -> managementService.registerTransactionEventListener(
                    DEFAULT_DATABASE_NAME, listener));
            dependencies.log()
                    .getUserLog(EventListenerExtensionFactory.class)
                    .info("Registering transaction event listener for database " + DEFAULT_DATABASE_NAME);
        }
    }

    interface Dependencies {
        DatabaseManagementService databaseManagementService();
        LogService log();
    }
}

It works fine in an integration test:
public AbstractDatabaseTest(TransactionEventListener<?>... listeners) {
        URI uri = Neo4jBuilders.newInProcessBuilder()
                .withExtensionFactories(List.of(new EventListenerExtensionFactory(List.of(listeners))))
                .withDisabledServer()
                .build()
                .boltURI();
        driver = GraphDatabase.driver(uri);
        session = driver.session();
    }

Then I copy the jar file in the plugins directory of my desktop database:
$ cp build/libs/<myproject>.jar /mnt/c/Users/albert.gevorgyan/.Neo4jDesktop/relate-data/dbmss/dbms-7fe3cbdb-11b2-4ca2-81eb-474edbbb3dda/plugins/

I restart the database and even the whole desktop Neo4j program but it doesn't seem to identify the plugin or to initialize the factory: no log messages are found in neo4j.log after the start event, and the transaction events that should be captured by my listener are ignored. Interestingly, a custom function that I have defined in the same jar file actually works - I can call it in the browser. So something must be missing in the extension factory as it doesn't get instantiated.
Is it possible at all to deploy an ExtensionFactory in a Desktop installation and if yes, what am I doing wrong?

A: It works after I added a provider configuration file to META-INF/services, as explained in https://www.baeldung.com/java-spi. Neo4j finds it then.


text:
Q: why adding media change some properties of the element? I have started my first template with CSS and HTML. I was watching a tutorial for creating some of the mainline templates.
The code was very simple.
The HTML:

        Lorem ipsum dolor sit amet consectetur adipisicing elit.

The CSS:
.container {
  padding-left: 15px;
  padding-right: 15px;
  margin-left: auto;
  margin-right: auto;
  background-color: red;
  width: 600px;
}

When he decreased the size of the page from the browser, a horizontal scroll bar has appeared and the text did not wrap.
after adding this media the scroll bar has disappeared and the text wrapped.
@media (min-width: 768px) {
  .container {
    width: 750px;
  }
}
@media (min-width: 992px) {
  .container {
    width: 970px;
  }
}

Why the scroll bar disappeared after adding the media?

A: (The code you have provided won't exhibit that behaviour. See the end of this answer.)
If the element is too wide for the window, then a scrollbar will be added so you can scroll to see the whole element.
Media queries let you specify different CSS to be applied depending on properties of the media.
This allows you to say "If the window is wider (or narrower) than X set the width of the element to Y". This means you can change the width of the element so when the window is narrower, the element is also narrower, so it still fits in the window and a scrollbar isn't needed to view the whole thing. Since a scrollbar isn't needed, one isn't added.
However, in your code you won't see that effect because the .container element is at its smallest width if none of the media queries apply. I can only assume that the default width for .container was changed at the same time the media queries were added.


text:
Q: Why does assigning a capturing lambda to std::function result in more copies In the following code, assigning to an std function results in more copy constructor calls than assigning to an auto variable.
( actually initializing, not assigning ;) )
I get that a value captured local must be copied.
I get that each time i assign it to a new std::function an extra copy will be needed.
But why is there a difference between initializing an auto var and and a function var?
#include <iostream>
#include <functional>
using namespace std;
struct A { A()=default; A(const A&) {cout << "CC\n";} };
int main()
{
    A a1;
    //auto f = [a1] (){}; // just 1 CC
    //[a1] (){}; // just 1 CC
    function<void()> f=[a1] (){}; // 2 CC

    return 0;
}


text:
Q: Python API using 'Requests' is connecting to URL but producing error when retrieving data I am running the following Python script that is taken from a tutorial video.  This works on the video but when I copy the script it appears to connect to the API but then errors when returning the content.  This is the short script...
import requests
import json

baseurl = 'https://api.upcitemdb.com/prod/trial/lookup'
parameters = {'UPC': '0885909950805'}
response = requests.get(baseurl, params=parameters)
print(response.url)

content = response.content
info = json.loads(content)
print(type(info))
print(info)

The output is as below :
https://api.upcitemdb.com/prod/trial/lookup?UPC=0885909950805

<class 'dict'>

{'code': 'INVALID_QUERY', 'message': 'Missing upc or invalid JSON format.'}

Could someone please explain what is causing the error message.
Many thanks....

A: The parameter "upc" should be in lower case.
Using:
parameters = {'upc': '0885909950805'}

gives the following url: https://api.upcitemdb.com/prod/trial/lookup?upc=0885909950805
which gets a valid response.


text:
Q: RVM on ubuntu12.04 vps ~# curl -L get.rvm.io | bash -s stable
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   185  100   185    0     0     11      0  0:00:16  0:00:15  0:00:01  1057
100  9979  100  9979    0     0    317      0  0:00:31  0:00:31 --:--:-- 20235
Downloading RVM from wayneeseguin branch stable
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   125  100   125    0     0      8      0  0:00:15  0:00:15 --:--:--   384
100   125  100   125    0     0      1      0  0:02:05  0:01:33  0:00:32     0curl: (7) couldn't connect to host

Could not download 'https://github.com/wayneeseguin/rvm/tarball/stable'.
  curl returned status '7'.

A: I think your answer is here:
https://github.com/wayneeseguin/rvm/issues/804


text:
Q: Group stream(list) of objects to a map-> based on object type -> and then filter based on Map Keys using Predicates I have the following objects:
abstract class Fizz {

}

class Foo extends Fizz {

}

class Bar extends Fizz {

}

class Buzz extends Fizz {

}

Then i have a list of Fizz objects
List<Fizz> elements;

I want to group this elements in a
Map <Fizz, List<Fizz>> mapFizz;

And in the end be able to retrieve Map values as following:
List<Foo> fooList = mapFizz.get(Foo.class);
List<Bar> barList = mapFizz.get(Bar.class);
List<Buzz> buzzList = mapFizz.get(Buzz.class);

I want to be able to iterate over the Map keySet and check if an instance of the Buzz exist and then do something:

boolean buzzExists = mapFizz.keySet().stream()
           .anyMatch(theKey -> instanceof Buzz.class)

buzzExists = true

when i am able to do
List<Buzz> buzzList = mapFizz.get(Buzz.class)

and also be able to add new key that extends Fizz;
class Look extends Fizz{
}

mapFizz.keyValues().add(Look.class);

What i've tried is this, and it works partially:
List<Fizz> elements = a list with many Fizz elements;

Map<? extends Class<? extends Fizz>, List<Fizz>> mapedElements = elements.stream()
.collect(
          Collectors.groupingBy(
             Fizz::getClass
        )
     )

The above solution partially works. I can retrieve the elements of the map with:
List<Foo> fooList = mapedElements.get(Foo.class);

But all of the keys are instance of the Class.class and i can't do:
mapedElements.keySet().stream()
                      .anyMatch( aKey -> aKey instanceof Foo.class) //always false

even if I am able to do
List<Foo> fooElements = mapedElements.get(Foo.class)

The workaround that i've found would be:
Map<String, List<Fizz>> mapedElements = elements.stream()
.collect(
          Collectors.groupingBy(
             element -> element.getClass().getName()
        )
     )

and then the key would be the import path of each class that extends Fizz: com.package.folder.Foo
But i wanted to check if maybe there is a cleaner solution
Thanks

A: Your attempt is almost there:
Map<Class<? extends Fizz>, List<Fizz>> map = elements.stream().collect(
    Collectors.groupingBy(Fizz::getClass, HashMap::new, Collectors.toList())
);

You don't need ? extends Class<? extends Fizz>. Just Class<? extends Fizz> is fine. Also note that you should use the overload of groupingBy that allows you to specify a map supplier, since by default, the map returned by groupingBy is not guaranteed to be mutable, and you seem to want to add things to the map later on.
Just to clarify, this is how you could add a new key to the map:
map.put(AnotherFizzSubclass.class, new ArrayList<>());

There is no keyValues() method in Map :)
To check if a key is in the map, just use containsKey:
if (map.containsKey(Foo.class)) {
    doSomething();
}

This will doSomething() only if the map has exactly Foo.class. If you also want to doSomething in case the map has a subclass of Foo (similar to the behaviour of instanceof), then you can do:
if (map.keySet().stream().anyMatch(Foo.class::isAssignableFrom)) {
    doSomething();
}

A: You can always extend the Hashmap and override the Class to make it polymorphic.
import java.util.HashMap;
import java.util.Optional;

public class PolyHashMap<K extends Class<?>,V> extends HashMap<K,V> {
    @Override
    public boolean containsKey(Object key) {
        return findClass((K)key).isPresent();
    }

    @Override
    public V get(Object key) {
        var entry = findClass((K)key);
        return entry.map(Entry::getValue).orElse(null);
    }

    private Optional<Entry<K,V>> findClass(K key) {
        return entrySet().stream()
                .filter(e -> e.getKey().isAssignableFrom(key))
                .findFirst();
    }
}

Then you can use this map in your program as
public static void main(String[] args) {
    PolyHashMap<Class<?>, List<Fizz>> map = new PolyHashMap<>();
    map.put(Buzz.class, Arrays.asList(new Buzz(),new Buzz()));
    map.put(Foo.class, Arrays.asList(new Foo()));

    System.out.println(map.get(Buzz.class).size());
    System.out.println(map.get(Foo.class).size());

}


text:
Q: Divide circle into 3 parts with vertical text inside each sector I need to draw this shape using CSS (without JS or SVG):

with these conditions:

*

*Text should be in one position - absolutely vertically.

*It something like a circle divided into 3 parts without an outer border.

*Center should be empty (optional).

What I tried: fiddle. But it rotates text.
Also, I tried to use rotate with translateY property but it compresses the text:

A: Try doing the borders and rotations on :after pseudo-elements instead of the li's
you can translate to get the empty center.
and then just position the text
like this:

.circle {
  position: relative;
  padding: 0;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  list-style: none;
  overflow: hidden;
}

li:after {
  content:"";
  overflow: hidden;
  position: absolute;
  top: -20%;
  right: -20%;
  width: 70%;
  height: 70%;
  transform-origin: 0% 100%;
  border-bottom: solid black 1px;
}

.text {
  position: absolute;
  width: 10px;
  height: 10px;
  margin-left: -5px;
}

li:first-child:after {
  transform: rotate(0deg) skewY(30deg) translate(5px);
}

li:first-child .text {
  top: 25%;
  left: 75%;
}

li:nth-child(2):after {
  transform: rotate(120deg) skewY(30deg) translate(5px);
}

li:nth-child(2) .text {
  top: 70%;
  left: 50%;
}

li:nth-child(3):after {
  transform: rotate(240deg) skewY(30deg) translate(5px);
}

li:nth-child(3) .text {
  top: 25%;
  left: 25%;
}

1

2

3


text:
Q: What determines the encoding of then data you receive from an HTTP POST? There's one mechanism concerning characters encoding which I'm really not familiar with and I'd like to have detailed information as to what's going on and I'd like to know how I can control things in my webapp.
When a user pastes non-ASCII characters (like "ä æ é à") on my website, say in a form that shall then get POSTed, what does exactly happen and how is it determined?
For example, if I go to an HTML page using the charset iso-8859-1:
<HEAD>
 <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">

and I cut'n'paste "ä æ é à" to a window which is using Unicode chars, I see the correct "ä æ é à" characters.
It's not entirely clear to me what happened there: did the browser convert the characters to some encoding when reading the iso-latin-1 encoded page and then convert these characters again when I paste them into another window?
Can I programmatically "force" the encoding that shall be used when a form on a webpage shall be posted?
Will the browser be responsible for sending/encoding the characters correctly?
Can I force the encoding used in a form to be different than the one used in the webpage? (for example to allow POSTing in UTF-8 even though the page is in iso-latin-1... Note that I do not want to do that, it's just to understand what is it going on under the hood).
I guess my question may boil down to: "What should I do to not run into encoding issues?" but if someone could explain the above to me I'd have a much clearer picture as to what's going on.

A: The browser will use the same encoding as specified in the charset attribute of the HTTP Content-Type response header of the page which contains the form which is to be submitted. You can determine it for your own site with help of among others Firebug:

The one in the <meta> tag will only be used when the whole HTTP Content-Type response header is completely absent, which may happen when the server didn't set it (which is very unlikely), or when you saved the webpage to local disk file system and then viewed from it by file:// protocol.
So, if you have character encoding problems, apparently you (or your server) didn't set the charset attribute in the HTTP Content-Type response header. In that case the browser will decide it by itself what charset to use, which is often the platform default charset, but in some cases (e.g. Firefox) based on a "smart guess" based on the webpage's content. The one in the <meta> tag is a good fallback, but it won't be used when the page is served over HTTP.
In your question history I see that you're a Java developer, so you're possibly dealing with JSP/Servlet pages (or JSP/Servlet based frameworks), in that case you may find this article useful: Unicode - How to get the characters right?


text:
Q: Cast a list column into dummy columns in Python Polars? I have a very large data frame where there is a column that is a list of numbers representing category membership.
Here is a dummy version
import pandas as pd
import numpy as np

segments = [str(i) for i in range(1_000)]

# My real data is ~500m rows
nums = np.random.choice(segments, (100_000,10))

df = pd.DataFrame({'segments': [','.join(n) for n in nums]})

userId
segments

0
885,106,49,138,295,254,26,460,0,844

1
908,709,454,966,151,922,666,886,65,708

2
664,713,272,241,301,498,630,834,702,289

3
60,880,906,471,437,383,878,369,556,876

4
817,183,365,171,23,484,934,476,273,230

...
...

Note that there is a known list of segments (0-999 in the example)
I want to cast this into dummy columns indicating membership to each segment.
I found a few ways of doing this:
In pandas:
df_one_hot_encoded = (df['segments']
    .str.split(',')
    .explode()
    .reset_index()
    .assign(__one__=1)
    .pivot_table(index='index', columns='segments', values='__one__', fill_value=0)
)

(takes 8 seconds on a 100k row sample)
And polars
df2 = pl.from_pandas(df[['segments']])
df_ans = (df2
          .with_columns([
              pl.arange(0, len(df2)).alias('row_index'),
              pl.col('segments').str.split(','),
              pl.lit(1).alias('__one__')
          ])
          .explode('segments')
          .pivot(index='row_index', columns='segments', values='__one__')
          .fill_null(0)
     )
df_one_hot_encoded = df_ans.to_pandas()

(takes 1.5 seconds inclusive of the conversion to and from pandas,  .9s without)
However, I hear .pivot is not efficient, and that it does not work well with lazy frames.
I tried other solutions in polars, but they were much slower:
_ = df2.lazy().with_columns(**{segment: pl.col('segments').str.contains(segment) for segment in segments}).collect()

(2 seconds)
(df2
 .with_columns([
     pl.arange(0, len(df2)).alias('row_index'),
     pl.col('segments').str.split(',')
 ])
 .explode('segments')
 .to_dummies(columns=['segments'])
 .groupby('row_index')
 .sum()
)

(4 seconds)
Does anyone know a better solution than the .9s pivot?

A: This approach ends up being slower than the pivot but it's a got a different trick so I'll include it.
df2=pl.from_pandas(df)
df2_ans=(df2.with_row_count('userId').with_column(pl.col('segments').str.split(',')).explode('segments') \
    .with_columns([pl.when(pl.col('segments')==pl.lit(str(i))).then(pl.lit(1,pl.Int32)).otherwise(pl.lit(0,pl.Int32)).alias(str(i)) for i in range(1000)]) \
    .groupby('userId')).agg(pl.exclude('segments').sum())
df_one_hot_encoded = df2_ans.to_pandas()

A couple of other observations.  I'm not sure if you checked the output of your str.contains method but I would think that wouldn't work because, for example, 15 is contained within 154 when looking at strings.
The other thing, which I guess is just a preference, is the with_row_count syntax vs the pl.arrange.  I don't think the performance of either is better (at least not significantly so) but you don't have to reference the df name to get the len of it which is nice.
I tried a couple other things that were also worse including not doing the explode and just doing is_in but that was slower.  I tried using bools instead of 1s and 0s and then aggregating with any but that was slower.


text:
Q: Enable System clock synchronization 'timedatectl' is giving following output  -
                      Local time: Wed 2018-06-13 18:08:51 IST
                  Universal time: Wed 2018-06-13 12:38:51 UTC
                        RTC time: Wed 2018-06-13 12:38:51
                       Time zone: Asia/Kolkata (IST, +0530)
       System clock synchronized: no
systemd-timesyncd.service active: yes
                 RTC in local TZ: no

How to set System clock synchronized to yes?

A: For those using Ubuntu 18+ on AWS EC2 instances, I found this worked fantastically. It utilizes AWS' internal time sync service:
sudo apt install chrony
sudo nano /etc/chrony/chrony.conf

Add the following line before any other server entry:
server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4

and then
sudo /etc/init.d/chrony restart

The best part about this method for EC2 instances is that you don't have to modify your security group rules, even if your instance is not connected to the Internet :)
Source

A: A related case that isn't exactly this one but I want to add it somewhere:
It is possible, as was the case for me, for this timedatectl output to correspond to the NTP port being blocked by your firewall.
On Ubuntu, you can explicitly allow communications on the NTP port of 123 by running the following command:
sudo ufw allow out from any to any port 123

This will allow outbound traffic from a service running on your PC using any port/network-protocol combination to services running on a remote machine using port 123 with any network protocol. This includes services running on remote machines that implement the network time protocol, which is required for being able to ask for the time from a remote machine.

A: Gui Option:
Go to "Settings" --> "Details" --> "Date & Time" --> Turn on "Automatic Date and Time".
systemctl restart systemd-timesyncd might help

A: It can be done without deploying NTP like this:
sudo nano /etc/systemd/timesyncd.conf

Edit the NTP Server detail
[Time]
NTP=ur.ntp.srv
FallbackNTP=ur.fallbackntp.srv

Then
sudo systemctl daemon-reload
sudo timedatectl set-ntp off
sudo timedatectl set-ntp on

and you can check it with
timedatectl status

A: One way to do it is to use ntp which still works in Ubuntu 18.04.  Run the following command to install ntp.
sudo apt install ntp

After it is installed you can run ntpq -p to make sure that it is working.
~$ ntpq -p
     remote           refid      st t when poll reach   delay   offset  jitter
==============================================================================
 0.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 1.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 2.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 3.ubuntu.pool.n .POOL.          16 p    -   64    0    0.000    0.000   0.000
 ntp.ubuntu.com  .POOL.          16 p    -   64    0    0.000    0.000   0.000

Then in your /etc/crontab file add @reboot root /usr/sbin/ntpd -n so that the ntpd will automatically start when the system reboots.  Use your favorite editor like gedit or mousepad or whatever you like:
pkexec gedit /etc/crontab

It should kind of look like this when the line is added:
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user  command
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
@reboot     root    /usr/sbin/ntpd -n
#

Then reboot the computer for the settings to take effect.
~$ timedatectl status
                      Local time: Wed 2018-06-13 06:55:35 MDT
                  Universal time: Wed 2018-06-13 12:55:35 UTC
                        RTC time: Wed 2018-06-13 12:55:36
                       Time zone: America/Denver (MDT, -0600)
       System clock synchronized: yes
systemd-timesyncd.service active: yes
                 RTC in local TZ: no

If you want to change your servers to the Asia Pool servers add them into the # Use servers from the NTP Pool Project. part of the /etc/ntp.conf file like so:
# Use servers from the NTP Pool Project. Approved by Ubuntu Technical Board
# on 2011-02-08 (LP: #104525). See http://www.pool.ntp.org/join.html for
# more information.
server 0.asia.pool.ntp.org
server 1.asia.pool.ntp.org
server 2.asia.pool.ntp.org
server 3.asia.pool.ntp.org

Hope this helps!

A: I read somewhere that you have to have your system time maximum 1000 seconds off the sync-server time for the sync to work. If your current system time is more than 1000s off it will not work.
So try to change the time manually first:
timedatectl set-ntp false
timedatectl set-timezone 'Europe/Berlin'
timedatectl set-time 2022-01-13
timedatectl set-time 13:16
timedatectl set-ntp true

after doing so i got the "yes" in timedatectl
               Local time: Thu 2022-01-13 13:16:16 CET
           Universal time: Thu 2022-01-13 12:16:16 UTC
                 RTC time: n/a
                Time zone: Europe/Berlin (CET, +0100)
System clock synchronized: yes  # <----------- it's synced
              NTP service: active
          RTC in local TZ: no

For more information see the -g option here https://linux.die.net/man/8/ntpd

A: The following worked for me:
timedatectl set-ntp true

and then...
systemctl restart systemd-timesyncd

Example:

A: For those who followed max's answer, but failed.
Go to NTP, choose your specific pool zone, and add at least two pool zones to your /etc/systemd/timesyncd.conf. For instance, for Asia, add:
[Time]
NTP=0.asia.pool.ntp.org 1.asia.pool.ntp.org
FallbackNTP=0.pool.ntp.org 1.pool.ntp.org

Then run the rest of the commands in the recommended answer.


text:
Q: Adjust (column size of) all visible dataTables I'm trying to create a generic JS method that will adjust (fnAdjustColumnSizing()) all visible dataTables. Problem is that I just can't get the syntax quite right...
So far, i got this close:
$.fn.dataTable.fnTables(true); //this gets all visible dataTables...
$('#givenTable').dataTable().fnAdjustColumnSizing(); //this  adjusts a given dataTable

$.each($.fn.dataTable.fnTables(true), function(singleTable) {
    $(singleTable).dataTable().fnAdjustColumnSizing();
});  // And this just don't work! Don't know why...

Any ideas or suggestions on an alternative way to acomplish this?
EDIT: I marked the answer below as the correct answer but i did found what was wrong on my original approach (and will include it as it may be usefull to others): It is the syntax of the $.each's provided function, which should receive 2 parameters, being the first one the index and the second the element itself. So:
$.each($.fn.dataTable.fnTables(true), function(idx, singleTable) {
    $(singleTable).dataTable().fnAdjustColumnSizing();
});  // This works!

A: The DataTables API documentation contains an example that might help you:
var table = $.fn.dataTable.fnTables(true);
if ( table.length > 0 ) {
    $(table).dataTable().fnAdjustColumnSizing();
}


text:
Q: Hsqldb rename duplicates of item names with same parent I wrote a LibreOffice / OpenOffice extension that allows access to these Google Drive files.
To do so, I use a Hsqldb 2.4 database, script file is accessible at:
https://github.com/prrvchr/gDriveOOo/blob/master/gDriveOOo/hsqldb/vnd.google-apps.script
The LibreOffice / OpenOffice UNO API does not handle duplicate file names (such as under a file system), while Google Drive offers this possibility.
To work around this problem, I created four View ('ChildUri', 'IdentifierUri', 'ItemUri' and 'Uri') allowing me to build a new name of the form: CONCAT (name, ~, position) for the second and following doublon, position being their position in the GROUP BY clause...
CREATE VIEW PUBLIC."ChildUri" ("Id","Name","Parent") AS SELECT "I"."Id","I"."Name","C"."ItemId" FROM PUBLIC."Items" AS "I" JOIN PUBLIC."Children" AS "C" ON "I"."Id"="C"."ChildId"  WHERE "I"."Trashed"=FALSE

CREATE VIEW PUBLIC."IdentifierUri" ("Idx","Name","Parent") AS SELECT ARRAY_AGG("I"."Id" ORDER BY "I"."DateCreated","I"."Id"),"I"."Name","C"."Parent" FROM PUBLIC."Items" AS "I" JOIN PUBLIC."ChildUri" AS "C" ON "I"."Id"="C"."Id" GROUP BY "I"."Name","C"."Parent"

CREATE VIEW PUBLIC."ItemUri" ("Id","Name","Length","Position","Parent") AS SELECT "C"."Id","I"."Name",CARDINALITY("I"."Idx"),POSITION_ARRAY("C"."Id" IN "I"."Idx"),"I"."Parent" FROM PUBLIC."ChildUri" AS "C" JOIN PUBLIC."IdentifierUri" AS "I" ON "C"."Name"="I"."Name" AND "C"."Parent"="I"."Parent"

CREATE VIEW PUBLIC."Uri" ("Id","Name","Uri","Parent") AS SELECT "I"."Id","I"."Name",CASEWHEN("I"."Position"=1,"I"."Name",INSERT("I"."Name", LENGTH("I"."Name") - POSITION('.' IN REVERSE("I"."Name")) + 1,0,CONCAT('~',"I"."Position"))),"I"."Parent" FROM PUBLIC."ItemUri" AS "I"

It works well, but drastically lacks speed when calling the 'selectChild' procedure, it takes 10 seconds to execute, whereas before only some second.
CREATE PROCEDURE PUBLIC."selectChild"(IN USERID VARCHAR(100),IN ITEMID VARCHAR(100),IN URL VARCHAR(250),IN MODE SMALLINT,OUT ROWCOUNT SMALLINT) SPECIFIC "selectChild_1" LANGUAGE SQL NOT DETERMINISTIC READS SQL DATA NEW SAVEPOINT LEVEL DYNAMIC RESULT SETS 1 BEGIN ATOMIC DECLARE TMPCOUNT SMALLINT DEFAULT 0;DECLARE RESULT CURSOR WITH RETURN FOR SELECT "Title","Size","DateModified","DateCreated","IsFolder",CASEWHEN("IsFolder",CONCAT(URL,'/',"Id"),CONCAT(URL,'/',"Uri"))"TargetURL",FALSE "IsHidden",FALSE "IsVolume",FALSE "IsRemote",FALSE "IsRemoveable",FALSE "IsFloppy",FALSE "IsCompactDisc" FROM PUBLIC."Child" WHERE "UserId"=USERID AND "Parent"=ITEMID AND("IsFolder" OR "Loaded">=MODE)FOR READ ONLY;CALL "countChild"(USERID,ITEMID,MODE,TMPCOUNT);SET ROWCOUNT=TMPCOUNT;OPEN RESULT;END

I admit that it exceeds my skills, and turns to you for help.
Thanks in advance.

A: fredt, what a pleasure it's you who answers ... Can not find better ...
I admit that index management must be dismal.
So I modify the underlying tables (Users, Identifiers, Capabilities, Children) to add UNIQUE CONSTRAINT and FOREIGN KEY CONSTRAINT. I had confused UNIQUE INDEX and UNIQUE CONSTRAINT...
CREATE CACHED TABLE PUBLIC."Users"("Id" VARCHAR(100) NOT NULL PRIMARY KEY,"UserName" VARCHAR(100) NOT NULL,"DisplayName" VARCHAR(100),"RootId" VARCHAR(100) NOT NULL,"TimeStamp" TIMESTAMP DEFAULT CURRENT_TIMESTAMP(3) NOT NULL,CONSTRAINT "UniqueUserName" UNIQUE ("UserName"))
CREATE CACHED TABLE PUBLIC."Identifiers"("Id" VARCHAR(100) NOT NULL PRIMARY KEY,"UserId" VARCHAR(100) NOT NULL,"TimeStamp" TIMESTAMP DEFAULT CURRENT_TIMESTAMP(3) NOT NULL,CONSTRAINT "ForeignIdentifiersUsers" FOREIGN KEY ("UserId") REFERENCES "Users"("Id"))
CREATE CACHED TABLE PUBLIC."Children"("ChildId" VARCHAR(100) NOT NULL,"ItemId" VARCHAR(100) NOT NULL,"TimeStamp" TIMESTAMP DEFAULT CURRENT_TIMESTAMP(3) NOT NULL,CONSTRAINT "UniqueChildItem" UNIQUE ("ChildId", "ItemId"),CONSTRAINT "ForeignChildrenItems" FOREIGN KEY ("ItemId") REFERENCES "Items"("Id"))
CREATE CACHED TABLE PUBLIC."Capabilities"("UserId" VARCHAR(100) NOT NULL,"ItemId" VARCHAR(100) NOT NULL,"CanAddChild" BOOLEAN DEFAULT FALSE NOT NULL,"CanRename" BOOLEAN DEFAULT FALSE NOT NULL,"IsReadOnly" BOOLEAN DEFAULT FALSE NOT NULL,"IsVersionable" BOOLEAN DEFAULT FALSE NOT NULL,"Loaded" SMALLINT DEFAULT 0 NOT NULL,"SyncMode" SMALLINT DEFAULT 0 NOT NULL,"TimeStamp" TIMESTAMP DEFAULT CURRENT_TIMESTAMP(3) NOT NULL,CONSTRAINT "ForeignCapabilitiesUsers" FOREIGN KEY ("UserId") REFERENCES "Users"("Id"),CONSTRAINT "ForeignCapabilitiesItems" FOREIGN KEY ("ItemId") REFERENCES "Items"("Id"))

And I also added INDEX on the VIEW Item, Child and the VIEW allowing me to build the new name (ChildUri, IdentifierUri, ItemUri and Uri).
I did not know that we could put INDEX on VIEW...
CREATE INDEX "ItemIndex" ON "Item"("UserId", "Id")
CREATE INDEX "ChildUriIndex" ON "ChildUri"("Id","Parent")
CREATE INDEX "IdentifierUriIndex" ON "IdentifierUri"("Idx","Parent")
CREATE INDEX "ItemUriIndex" ON "ItemUri"("Id","Parent")
CREATE INDEX "UriIndex" ON "Uri"("Id","Parent")
CREATE INDEX "ChildIndex" ON "Child"("UserId", "Parent")

I kept the Indexes "TrashedIndex" and "MimeTypeIndex" on the Items table, these columns appearing in WHERE clauses
CREATE INDEX "TrashedIndex" ON PUBLIC."Items"("Trashed")
CREATE INDEX "MimeTypeIndex" ON PUBLIC."Items"("MimeType")

The "selectChild" request is now done in a few seconds, but I'm not sure of my indexes ... I think I have redundant or missing, or so I'm very lucky ...
Thanks again.
Edit:
After several performance tests, apparently only the CONSTRAINT UNIQUE and FOREIGN KEY at the level of the underlying tables improves the performance, the INDEX on the VIEW does not improve the query, or so imperceptibly without a performance test tool.

A: You need an index to improve SELECT query speed on a table. The SELECT in the procedure needs an index such as the following if it is not already a FOREIGN KEY
CREATE INDEX "ChildIndex" ON "Child"("Parent", "UserId")


text:
Q: Using Times New Roman in eps images with psfrag I'm using the chemstyle package to produce chemical reaction schemes.  It uses the psfrag package to replace placeholders in eps graphics with numbers for molecules.  I'm trying to use Times New Roman font in these eps files (not for the placeholders, but for other text), but LaTeX doesn't seem to like it:
### /usr/texbin/dvips -R -Poutline  -o /tmp/altpdflatex.31054-1317561093/Thesis.ps Thesis.dvi This is dvips(k) 5.97 Copyright 2008 Radical Eye Software (www.radicaleye.com) ' TeX output 2011.10.03:0011' -> /tmp/altpdflatex.31054-1317561093/Thesis.ps /usr/texbin/dvips: ! Couldn't find header file times.pfb. Note that an absolute path or a relative path with .. are denied in -R2 mode.
### FAILED to generate /tmp/altpdflatex.31054-1317561093/Thesis.ps ()
Is it possible to fix this, using LaTeX rather than pdfLaTeX?  Where might I find such a header file?
Edit:  The Times New Roman text was added in ChemDraw.  The eps in question is a chemical scheme, so I draw these in ChemDraw, sometimes with additional text.  I'd like that text to match the font I'm using for LaTeX (TNR).
Edit2: An example eps: http://www.2shared.com/file/upfvXkpS/Test.html

A: (More of an extended comment)
For me, this works fine using TeX Live 2011 on Windows 7.
\documentclass{article}
\usepackage{auto-pst-pdf,chemscheme}
\begin{document}
\begin{figure}
  \includegraphics{Test}
\end{figure}
\end{document}

My demo file builds as expected using pdlatex or latex -> dvips -> ps2pdf.  As egreg says, to say more we'll need an example of what you are doing.
(As an aside, I would urge against using a serif font in your schemes and figures. Sticking to sans serif looks much better for these: see any of the common journal templates.)


text:
Q: COM: Does the reference counter increase when I put a COM variable in a method? currently I have the misfortune to write C# code to read stuff from an Excel file. I'm using the Nuget Excel Interop to accomplish this.
I try to follow the advices given in this great blog post here: https://www.add-in-express.com/creating-addins-blog/2013/11/05/release-excel-com-objects/
But even when putting everything into a variable that gets released in the end, when I start accessing cells (type Range), the Excel process just wont die.
Hence my question: When I do this:
Application excel = new Application();
_toBeReleased.Add(excel);
DoStuff(excel);

...
void DoStuff(Application excel2)
{

...
Does excel2 also need to be released? Because the reference was given byval into the method?

A: I don't believe that passing a COM object to another method - excel2 in your example - would complicate any form of releasing objects you may need to perform. Passing a class to a method passes a reference to the object and as long as your method runs synchronously then it should return without any persisting reference to excel2.
It should be likely that if you wait long enough the garbage collector will run and clear up your running instance of Excel. As waiting for this is going to be a problem you can force it to run from your code:
GC.Collect();
GC.WaitForPendingFinalizers();

I have previously called Marshal.ReleaseComObject(excel) prior to calling the garbage collector, but I understand this isn't actually necessary.
Alternative Option (only supporting .xslx)
This isn't a direct answer to your question but if you can restrict your development to only support the newer (2007 / 2010) .xlsx format - rather than the older .xls format, then you wouldn't need to use Excel directly at all.
There is a great NuGet package called EPPlus which would allow you to create or edit a .xlsx file directly with no dependency on Excel the application.
I appreciate this is of no use if you must support the older .xls format.


text:
Q: Is a function discrete or continuous w.r.t. to the Lebesgue measure? I just read a paper where it said that

However, if the base measure $G_0$ is absolutely continuous with respect
  to Lebesgue measure, parameters will not be shared between groups.
  Only in the case where the base measure G0 is discrete will there be a
  strictly positive probability of the group specific distributions
  having overlapping support (i.e. sharing parameters between groups.)

What does the part in bold mean? I cannot seem to find a answer on Google that I understand, nor any useful papers.
My understanding is that the Lebesgue measure can tell us if a function is discrete or continuous? The wiki is not very helpful either...

A: There are two important characterizations of this notion. In both, I use $\lambda$ to refer to the Lebesgue measure and $\mu$ to refer to some other measure.

*

*$\mu$ is absolutely continuous with respect to Lebesgue measure if for all Lebesgue measurable sets $A$ with $\lambda(A)=0$, $\mu(A)=0$.

*$\mu$ is absolutely continuous with respect to Lebesgue measure $\lambda$ if there exists a Lebesgue measurable function $f$ such that $\mu(A) = \int_A f d \lambda$ for all Lebesgue measurable sets $A$.
It is not hard to see that 2 implies 1. The statement "1 implies 2" is an instance of the Radon-Nikodym theorem. Accordingly, in analysis the function $f$ in the second characterization is referred to as the Radon-Nikodym derivative of $\mu$ with respect to $\lambda$, and is sometimes denoted by $\frac{d \mu}{d \lambda}$.
A different place that you may have encountered this notion under a different name is in probability theory. The probability distribution of a (one-dimensional) continuous random variable is a probability measure on $\mathbb{R}$ which is absolutely continuous with respect to Lebesgue measure. In this context the function $f$ in my second characterization is called the density of the random variable.


text:
Q: handle vue-js dropdown plugin in selenium webdriver I am testing a web application which has v-select vuejs dropdown plugin for Country field. How Can I select values in dropdown using selenium webdriver.
It has no select/div.
Below is the HTML before selecting the country from the dropwdown

         <input type="search" autocomplete="false" placeholder="Country" aria-label="Search for option" class="form-control" style="width: 100%;"> <button type="button" title="Clear selection" class="clear">×</button>

Loading...

And this is the HTML after selecting the country as United States from the dropdown

            United States

         <input type="search" autocomplete="false" aria-label="Search for option" class="form-control" style="width: auto;"> <button type="button" title="Clear selection" class="clear">×</button>

Loading...

A: Please specify the language binding you are using and the things you've tried so far.
Algo in Java:

* click the 'dropdown' field: driver.findElement(By.name("country")).click()

* click the option: driver.findElement(By.name("country-1")).click()
These kinds of 'dropdown' fields are usually tied to another div / element.
E.g., when you click the 'dropdown' field (item 1), another dynamic div may appear containing the options in some form of tag.
Most common examples would be,
,
, . You'll then have to do another click() on the option you want. (item 2)
There are even cases where the dropdown div encloses an input tag to which you can do sendKeys() or setAttribute() as well as cases where you can do a javascript click directly into one of the options.
Suggest you provide more info so we can help you better.

* selenium language bindings

* html snippet of the dropdown - please avoid using screenshots for snippets

* html element of the options that appear when you click the dropdown