text:
Q: How to connect to the server on с I have the code but it doesn't work and I don't understand why?
What do I need to do to connect to the server and how do I send messages to it in the future?
https://cdn.discordapp.com/attachments/503211497766256642/968519683030523964/unknown.png
Here is a photo of my mistakes. Most mistakes in the first part
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")

WSADATA wsaData;
int iResult;

iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

if (iResult != 0)
{
     printf("WSAStartup failed: %d\n", iResult);
     return 1;
}

struct addrinfo *result = NULL, *ptr = NULL;
struct addrinfo hints;

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
iResult = getaddrinfo("147.175.115.34", "777", &hints, &result);
if (iResult != 0)
{
     printf("getaddrinfo failed: %d\n", iResult);
     WSACleanup();
     return 1;
}
else
printf("getaddrinfo fail…\n");

SOCKET ConnectSocket = INVALID_SOCKET;
ptr = result;

ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,ptr->ai_protocol);

if (ConnectSocket == INVALID_SOCKET)
{
     printf("Error at socket(): %ld\n", WSAGetLastError());
     freeaddrinfo(result);
     WSACleanup();
     return 1;
}
else
printf("Error at socke occur…\n");

iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);

if (iResult == SOCKET_ERROR)
printf("Not connected to server…\n");
else
printf("Connected to server!\n");

if (iResult == SOCKET_ERROR)
{
    closesocket(ConnectSocket);
    ConnectSocket = INVALID_SOCKET;
    WSACleanup();
    return 1;
}

Sleep(250);

char sendbuf[4096];

iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR)
{
     printf("send failed: %d\n", WSAGetLastError());
     closesocket(ConnectSocket);
     WSACleanup();
     return 1;
}

printf("Bytes Sent: %ld\n", iResult);

#define DEFAULT_BUFLEN 4096

int recvbuflen = DEFAULT_BUFLEN;
char recvbuf[DEFAULT_BUFLEN];

iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();


text:
Q: NSDateComponents issue when want to get previous month I have code:
let components = NSDateComponents()
components.month -= 1
let dateInTheMiddleOfPeriod = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))!

But the dateInTheMiddleOfPeriod is 2015-11-18 06:00:12 +0000 , but I expect 2015-12-18 06:00:12 +0000 , because I need the date in the previous month. Why does this happen?

A: You can use Calendar component method to get the today's Date year and month components, pass day zero and get the month of the resulting date:

extension Calendar {
    static let iso8601 = Calendar(identifier: .iso8601)
}

extension Date {
    var year: Int {
        Calendar.iso8601.component(.year, from: self)
    }
    var month: Int {
        Calendar.iso8601.component(.month, from: self)
    }
    var lastDateOfPreviousMonth: Date? {
        DateComponents(calendar: .iso8601, year: year, month: month, day: 0).date
    }
    var previousMonth: Int {
        lastDateOfPreviousMonth?.month ?? 0
    }
}

Date().lastDateOfPreviousMonth  // "28 Feb 2022 00:00"
Date().previousMonth            // 2

A: For getting date for one month before you can follow the steps,

*

*Create components of current date,

*Then decrement one month,

*Finally convert the component to date again.

Example code :
let components = NSCalendar.currentCalendar().components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: NSDate())
components.month -= 1
let dateInTheMiddleOfPeriod = NSCalendar.currentCalendar().dateFromComponents(components)!
print(dateInTheMiddleOfPeriod)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Storyboard - insert a Searchbar and linked it to the containerview (tableviewcontroller) I had a tableviewcontroller with a SearchController I managed programmatically. For some reasons, I need to have a storyboard to display things a bit differently not anymore a tabéeview in full screen.
Everything is going fine with a container view inside my storyboard. The container view is linked to my custom tableviewcontroller which was managing my searchbar. When I instantiate an object, I can see my custom tableView (with a searchbar lying at the top) in the same way it was before.
I would like to remove the search bar embeded to my tableview (i.e in my tableviewcontroller) and add it directly in the storyboard (to have more at the top of my screen with free space between the search bar and the table view. I tried to insert a searchbar and displaycontroller but I am stuck in the sense I cannot link the searchBar to my tableViewController.
How can I do to link the searchbar in the UIViewController to the tableviewcontroller in the containerview? My tableviewcontroller conforms to the protocol necessary to have a searchbar working still there was no problem when they were not gathered inside a storyboard.
Here is an image if it can help.

If anyone could help me to link the searchbar and the tableviewcontroller...
Thanks!


text:
Q: Idle Citrix app remote connections are causing the Windows lock screen to appear I have an app published through Citrix. If I open the app and leave it idle for 15 minutes, the app temporarily disappears and is replaced by the Windows lock screen. It's of course the lock screen for the Windows session on the server and not my own PC. Inputting my credentials unlocks it and the app reappears.
I've timed it a few times and the timing seems fairly accurate. If I touch the app during that 15 minute period, the timeout resets. I've tried the following settings so far:

*

*Set time limit for disconnection sessions - Computer Configuration --> Administrative Templates --> Windows Components --> Remote Desktop Services --> Remote Desktop Session Host --> Session Time Limits

*

*Configure keep-alive connection interval - Computer Configuration --> Administrative Templates --> Windows Components --> Remote Desktop Services --> Remote Desktop Session Host --> Connections

*

*Interactive logon: Machine inactivity limit - Windows Settings --> Security Settings --> Local Policies --> Security Options

*

*Citrix idle timeout - Has been set to 24 hours.

Any ideas on what else it could be?

A: It may be the screen saver. Try to configure this policy setting:
User configuration -> Control panel -> Personalization -> Enable screen saver: "Disabled".


text:
Q: Need information about spring Controllers I am very confused about spring controllers,
pls help me.
i want to know that how spring controller initate and how its constructor get into action,
as when i call a controller  from one page, and then ask the same controller from another page it dosn't seems to create a new object of that controller rather than provide same reference of the controller object

A: Controllers are "application-scoped"; they are instantiated just once and then reused for all requests you associate them with. As such, it is important that they do not carry session-specific state.
You should refer to the documentation for more details on how controllers work and how to instantiate them.


text:
Q: IIS not passing URL which contain diacritic symbols I have a Django app installed on my IIS server. Everything works great on my local PC but links/URL on IIS app don't work if the contain diacritic symbols. If I use symbols like '%' it works fine.
Below is the code for links to attached files (both my local and server have the same code):

Attachment: {{post.file_close.name}}

If I upload file cars.png everything works fine in both versions. This works no matter the extension, pdf, excel, image, etc.
Problem is, if I upload file carsčč.png it fails only on server side, on my PC it works great.
I get the following error on my Django/debugg:
Page not found (404)
"C:\inetpub\files\PyWeb\media\PN_files\2022\03\06\cars" does not exist

Url of the error page is:
http://hidden_part/media/PN_files/2022/03/06/carsčč.png

But when I click copy and paste it's like this:
http://hidden_part/media/PN_files/2022/03/06/cars%C4%8D%C4%8D.png

Like the link is not complete, it stopped as soon as it runs into a special character.
But, shown link still containes all the letters, it's PN_files/2022/03/06/carsčč.png
Tried:
I looked at regional settings, it's the same on both PCs.
Also, when I manually search for the file, the name is not currupted, it's saved localy as carsčč.png. So I guess it's only the link, tring to get the file.
I figured out it's because of diacritic letters. On my 'base.html' I have meta charset="utf-8". Django setting LANGUAGE_CODE = 'hr-BA'.
I use Bootstrap 4.0 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
Server is hosted on Windows, IIS, .NET Globalization settings are set to utf-8. Do I need to add something to Request filtering?

A: I think you can try to set the configuration in Request Filtering,  IIS server will supports non-ASCII characters via this configuration,just refer to the screenshot:


text:
Q: Shell programming: nested expressions with command substitution I have trouble handling expressions within other expressions. For example, here's my code:
 #!/bin/sh
 number=0
 read number
 if [ `expr substr $number 1 2` = "0x" ];
 then
 echo "Yes that's hex: $number"
 number=`expr substr $number 3 `expr length $number``
 echo $number
 else
 echo "No that's not hex"
 fi

all I want is for echo to print the number without '0x'. Let's say if the input is 0x15 the output should be just 15. But it seems that finding the length of the string fails.
Now if I create another variable named length like this:
 #!/bin/sh
 number=0
 read number
 if [ `expr substr $number 1 2` = "0x" ];
 then
 echo "Yes that's hex: $number"
 length=`expr length $number`
 number=`expr substr $number 3 $length`
 echo $number
 else
 echo "No that's not hex"
 fi

it works.
So how to get the same result without creating another variable?

A: If your shell is POSIX (most are these days, except Solaris' /bin/sh), you can nest what is called command substitution with $(), eg.
number=$(expr substr $number 3 $(expr length $number))

Command substitution with nested backticks requires ugly layers of backslash escaping.

A: You can use
number=`expr substr $number 3 ${#number}`

${#number}

can be used to retrieve length of string


text:
Q: ¿Por qué este script no lee las variables que le paso con "read"? Estoy haciendo un instalador de SLURM y creé un pequeño script para modificar el archivo /etc/hosts y así añadir las IPs. En realidad creé 2, uno que añade solo una IP+Hostname (que si funciona) y este que utiliza un loop para añadir tantas como se necesiten:
#!/bin/bash

archivohosts=/etc/hosts
echo "¿Cuantas Ips y Hostnames quieres añadir?"
echo "Escribe el numero por ejemplo 3"
echo ""
read FINAL

for x in $(seq 1 $FINAL)
do
    echo "Inserte la IP$x:"
    read ip0$x
    echo "Inserte el hostname$x:"
    read hostname0$x
    echo "$ip0$x      $hostname0$x" >> $archivohosts
    sleep 2
done

cat $archivohosts

Y lo que añade al archivo hosts es:
1    1

2    2

3    3

En vez de la IP1   Hostname1, etc.

A: Trata de que quede así.
for x in $(seq 1 $FINAL)
do
    echo "Inserte la IP $x:"
    read ip0
    echo "Inserte el hostname $x:"
    read hostname0
    echo "$ip0      $hostname0" >> $archivohosts
done

Es decir, eliminando como sufijo la variable $x en cada variable como hostname0 e ip0.


text:
Q: SDN6 - Projection interfaces with Property Mapping I am using spring data neo4j 6.1.3 and following is my use case code snippets
Domain Entity
    @Data
    @Node("DATspace")
    public class DatSpace {

      @Id @GeneratedValue
      private Long neoId;

      @Property("SUPtitle")
      private String title;

      private String SUPid;
    }

Test class
@SpringBootTest
@EnableNeo4jRepositories(basePackages = "com.rahal.marvel")
public class ProjectionTest {

   @Autowired
   private Neo4jTemplate neo4jTemplate;

   interface DATspaceProjection {
      String getTitle();
      String getSUPid();
   }

   @Test
   public void test_projection(){
      DatSpace d = neo4jTemplate.findOne("MATCH (s:DATspace {SUPid: $id}) RETURN s", Collections.singletonMap("id", "SPC_ML7"), DatSpace.class).get();

      d.setTitle("title modified");
      d.setSUPid("SUPid modified");

      DATspaceProjection   p = neo4jTemplate.saveAs(d, DATspaceProjection.class);
   }
}

Ideally above saveAs function should modify both DATspace.SUPtitle and DATspace.SUPid. However it only modify SUPid but not SUPtitle. I presume it is due to property mapping (@Property) . Is this a bug or are there any workaround?

A: The provided @Property annotation does only have an impact on the annotated property (title) itself.
There is no knowledge right now that goes from the getTitle() method in the projection to the annotated title field in the domain class.
To be safe when modifying this use the explicit property name:
interface DATspaceProjection {
    String getSUPtitle();
    String getSUPid();
}

I created an issue for improvement https://github.com/spring-projects/spring-data-neo4j/issues/2371


text:
Q: VideoJS programmatic play only works with setTimeout Basically when I call player.play() alone the video does not play, but when I wrap it in setTimeout (even with 1ms) the video plays.
My app is built in React with NextJS.
Here is how the code looks:
const [currentVideoElement, setCurrentVideoElement] = useState(null);

useEffect(() => {
  if (!currentVideoElement) {
    return undefined;
  }

  const currentVideoPlayer = videojs(currentVideoElement, {
    autoplay: true,
    controls: false,
    loop: true,
    preload: 'auto',
  });

  currentVideoPlayer.ready(() => {
    // Should be just: currentVideoPlayer.play();
    setTimeout(() => currentVideoPlayer.play(), 1);

    currentVideoPlayer.muted(
      isCurrentVideoMuted || !isCurrentVideoFullScreen
    );
  });

  return () => {
    currentVideoPlayer.pause();
    currentVideoPlayer.currentTime(0);
  };
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentVideoElement]);

And the video element is as follows:
<video
  className="video-js vjs-custom h-full object-cover"
  playsInline
  muted
  ref={setCurrentVideoElement}
>
  <source src={url} type="video/mp4" />
</video>

For now this works, but would love to understand why this is happening!


text:
Q: Do I have to specify a 'to' recipient? When I'm sending email via mailgun, must I specify a 'to' recipient?
In some cases, I'd prefer to specify only 'Bcc' recipients.

EDIT: I've already tried to do this on my own and I receive a
'Bad Request - 'to' parameter is missing' error.

I just wanted to know if there's another way around this, because typically you can send an email without a 'To' recipient, so long as you specify a CC or Bcc recipient.

A: You may not send mail only using bcc.  There is a trick I use in which I make the from and to the same address (something like info@mydomain.com) and then fill up the bcc slot with whatever I need.
You may send mail using mailing lists that does not require you to expose other email addresses.
https://documentation.mailgun.com/en/latest/api-mailinglists.html

A: Eventually, the SMTP call is being translated to a call to the SMTP provided which is usually not forced to have a 'to' recipient, but the best way is to perform a test where you send an email with only 'bcc' recipient (you can send it to yourself as a test'


text:
Q: How to fetch Original Estimate fields from Jira using JirAgileR I am trying to fetch Original Estimate fields using timeoriginalestimate keyword using below code, but it is not returning the field. Although it is working fine for timespent.
library(JirAgileR, quietly = T)
library(knitr, quietly = T)
library(dplyr, quietly = T)

if (is.null(JIRABaseURL)) JIRABaseURL
if (is.null(username)) username
if (is.null(password)) password

fields1<-get_jira_issues(domain = JIRABaseURL,
username = username,
password = password,
jql_query = "project in('my_project')",
fields = c("summary","timespent", "timeoriginalestimate"),
maxResults = 150,
verbose = FALSE,
as.data.frame = TRUE)

How can I fetch original estimate, is there any specific keyword for the same?

A: According to supported_jql_fields(), this field isn't yet supported.
 JirAgileR::supported_jql_fields()

 [1] "aggregateprogress"     "aggregatetimeestimate" "aggregatetimespent"
 [4] "assignee"              "comment"               "components"
 [7] "created"               "creator"               "description"
[10] "duedate"               "environment"           "fixVersions"
[13] "issuelinks"            "issuetype"             "labels"
[16] "lastViewed"            "priority"              "progress"
[19] "project"               "reporter"              "resolution"
[22] "resolutiondate"        "status"                "summary"
[25] "timeestimate"          "timespent"             "updated"
[28] "versions"              "votes"                 "watches"
[31] "workratio"             "parent"

However, it seems to be planned in the Roadmap


text:
Q: Django Role Based Authentication based on Permission on URL instead of Permission on model class I have studied abut Django Authorization. My observation is basically Django Authentication module works fine for Authorization based on role-based Authentication based on Permission on a Model instance. But In Spring framework I found here same role-based Authentication based on Permission on URL or actually relative URL or URL pattern here like .antMatchers("/user/**").hasRoles("USER", "ADMIN") in following code snippet. Here is a code snippet of Spring Framework:
    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
        .authorizeRequests()
           .antMatchers("/static","/register").permitAll()
           .antMatchers("/user/**").hasRoles("USER", "ADMIN") // can pass multiple roles
           .antMatchers("/admin/**").access("hasRole('ADMIN') and hasIpAddress('123.123.123.123')") // pass SPEL using access method
           .anyRequest().authenticated()
           .and()
       .formLogin()
           .loginUrl("/login")
           .permitAll();
    }```

Is there any way or library in Django Similar way of Spring for Authorization based on Permission on URL? Thanks.


text:
Q: Android ListView RadioButtons I have a Custom List View where each item in the List contains a Radio Button. I want only one Radio Box in the List to be selected. How can do this ? If i place the Radio Group on the layout i inflate, each Radio Button will be added to it own group ?
Kind regards,
Mateen

A: U can set the adapter like this...
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,android.R.id.text1, names));

Refer this link it may helpfull.. http://www.vogella.de/articles/AndroidListView/article.html

A: As you have a custom adapter you can yourself uncheck the previously checked radiobutton when a other list item is selected.


text:
Q: Is it possible to perform 128-bit / 64-bit division without branching, in terms of 64-bit division? I'm working with the Algorand contract code which has a very limited scope of possible operations in their assembly code - e.g., it is not possible to control flow of the code. Basic 64 bit arithmetic operations are available.
What I need to do is to divide two 64-bit segments (as a whole 128-bit number) of a certain 128-bit integer by another 64-bit integer knowing that the result will fit within 64-bit integer. Is it possible without controlling flow of the code and only with 64-bit arithmetics?

A: I am not familiar with the Algorand language. It is certainly possible to create branch-free code for dividing an 128-bit operand by a 64-bit operand using 64-bit operations throughout. The easiest way to do this is to use long-hand division and multiplication algorithms we all learned in elementary school, but using 232 as the base, not 10. Generally speaking, this requires shifts and logical operations in addition to simple arithmetic, and this is what I assume is available in ISO-C99 code below.
One can use the existing 64-bit division to generate a close estimate of the next quotient "digit" by dividing the leading two "digits" of the dividend by the leading "digit" of the divisor, where "digit" is to be understood base 232. In TAOCP Knuth shows that the error is positive and at most 2, provided the divisor is normalized, that is, its most significant bit is set. We compute the remainder via a back-multiply and subtraction and then can check whether it is negative. If so, we lower the (partial) quotient by one and recompute the remainder.
As branching is not allowed, a mechanism is needed for selecting between two possible conditionally selecting from two operands. This can be done by computing a predicate into an integer which takes the value 0 or 1, and passing that to a 2:1 multiplexer function that multiplies one source operand with the predicate, the other one with the complement of the predicate and adds the results. In the code below this function is called mux_64().
I have tested the division code in function my_div_128_64() by comparing it to the DIV instruction of my 64-bit Intel CPU, accessing that instruction via inline assembly. The code was built with the Intel compiler version 13. I have implemented two test modes, one based on purely random operands and the other one is based on simple patterns that are useful for hitting various boundary cases. No mismatches have been found so far. More elaborate tests are possible, but this should be sufficient for a decent "smoke" test.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define PATTERN_TEST  (1)
#define MSVC_STYLE    (1)
#define GCC_STYLE     (2)
#define ASM_STYLE     (GCC_STYLE)

// our own 128-bit unsigned integer type
typedef struct
{
    uint64_t x;
    uint64_t y;
} ulonglong2;

// (a < b) ? 1 : 0
uint64_t ltu_64 (uint64_t a, uint64_t b)
{
    return ((~a & b) + ((~a ^ b) >> 1)) >> 63;
}

// (a != b) ? 1 : 0
uint64_t neq_64 (uint64_t a, uint64_t b)
{
    return ((((a ^ b) | (1ULL << 63)) - 1ULL) | (a ^ b)) >> 63;
}

// (a >= b) ? 1 : 0
uint64_t geu_64 (uint64_t a, uint64_t b)
{
    return ((a | ~b) - ((a ^ ~b) >> 1)) >> 63;
}

//#define ADDcc(a,b,cy,t0,t1) (t0=(b), t1=(a), t0=t0+t1, cy=t0<t1, t0=t0)
#define ADDcc(a,b,cy,t0,t1) (t0=(b), t1=(a), t0=t0+t1, cy=ltu_64(t0,t1), t0=t0)
#define ADDC(a,b,cy,t0,t1) (t0=(b)+cy, t1=(a), t0+t1)

//#define SUBcc(a,b,cy,t0,t1) (t0=(b), t1=(a), cy=t1<t0, t1-t0)
#define SUBcc(a,b,cy,t0,t1) (t0=(b), t1=(a), cy=ltu_64(t1,t0), t1-t0)
#define SUBC(a,b,cy,t0,t1)  (t0=(b)+cy, t1=(a), t1-t0)

// 128-bit subtraction
ulonglong2 sub_128 (ulonglong2 a, ulonglong2 b)
{
    ulonglong2 res;
    uint64_t cy, t0, t1;
    res.x = SUBcc (a.x, b.x, cy, t0, t1);
    res.y = SUBC  (a.y, b.y, cy, t0, t1);
    return res;
}

// 128-bit addition
ulonglong2 add_128 (ulonglong2 a, ulonglong2 b)
{
    ulonglong2 res;
    uint64_t cy, t0, t1;
    res.x = ADDcc (a.x, b.x, cy, t0, t1);
    res.y = ADDC  (a.y, b.y, cy, t0, t1);
    return res;
}

// branch free implementation of ((cond) ? a : b). cond must be in {0,1}
uint64_t mux_64 (uint64_t cond, uint64_t a, int64_t b)
{
    return cond * a + (1 - cond) * b;
}

// count leading zeros
uint64_t clz_64 (uint64_t x)
{
    uint64_t n = 64;
    uint64_t y;

    y = x >> 32; n = mux_64 (neq_64 (y, 0), n - 32, n); x = mux_64 (neq_64 (y, 0), y, x);
    y = x >> 16; n = mux_64 (neq_64 (y, 0), n - 16, n); x = mux_64 (neq_64 (y, 0), y, x);
    y = x >>  8; n = mux_64 (neq_64 (y, 0), n -  8, n); x = mux_64 (neq_64 (y, 0), y, x);
    y = x >>  4; n = mux_64 (neq_64 (y, 0), n -  4, n); x = mux_64 (neq_64 (y, 0), y, x);
    y = x >>  2; n = mux_64 (neq_64 (y, 0), n -  2, n); x = mux_64 (neq_64 (y, 0), y, x);
    y = x >>  1; n = mux_64 (neq_64 (y, 0), n -  2, n - x);
    return n;
}

// 64x64->128 bit unsigned multiplication
ulonglong2 my_mul_64_128 (uint64_t a, uint64_t b)
{
    ulonglong2 res;
    const uint64_t mask_lo32 = 0xffffffffULL;

    uint64_t a_lo = a & mask_lo32;
    uint64_t a_hi = a >> 32;
    uint64_t b_lo = b & mask_lo32;
    uint64_t b_hi = b >> 32;
    uint64_t p0 = a_lo * b_lo;
    uint64_t p1 = a_lo * b_hi;
    uint64_t p2 = a_hi * b_lo;
    uint64_t p3 = a_hi * b_hi;
    uint64_t cy = ((p0 >> 32) + (p1 & mask_lo32) + (p2 & mask_lo32)) >> 32;
    res.x = p0 + (p1 << 32) + (p2 << 32);
    res.y = p3 + (p1 >> 32) + (p2 >> 32) + cy;
    return res;
}

// 128/64->64 bit unsigned division
uint64_t my_div_128_64 (ulonglong2 dvnd, uint64_t dvsr)
{
    ulonglong2 prod, rem;
    uint64_t lz, q, qh, ql, rem_msb, nrm_dvsr, cy, t0, t1;

    // normalize divisor; adjust dividend accordingly (initial partial remainder)
    lz = clz_64 (dvsr);
    nrm_dvsr = dvsr << lz;
    rem.y = (dvnd.y << lz) | mux_64 (neq_64 (lz, 0), dvnd.x >> (64 - lz), 0);
    rem.x = dvnd.x << lz;

    // compute most significant quotient "digit"; TAOCP: may be off by 0, +1, +2
    qh = mux_64 (geu_64 (rem.y >> 32, nrm_dvsr >> 32), 0xffffffff, rem.y / (nrm_dvsr >> 32));

    // compute remainder; correct quotient "digit" if remainder negative
    prod   = my_mul_64_128 (qh << 32, nrm_dvsr);
    rem    = sub_128 (rem, prod);
    rem_msb= rem.y >> 63;
    qh     = mux_64 (rem_msb, qh - 1, qh);
    rem.x  = mux_64 (rem_msb, ADDcc (rem.x, nrm_dvsr << 32, cy, t0, t1), rem.x);
    rem.y  = mux_64 (rem_msb, ADDC  (rem.y, nrm_dvsr >> 32, cy, t0, t1), rem.y);
    rem_msb= rem.y >> 63;
    qh     = mux_64 (rem_msb, qh - 1, qh);
    rem.x  = mux_64 (rem_msb, ADDcc (rem.x, nrm_dvsr << 32, cy, t0, t1), rem.x);
    rem.y  = mux_64 (rem_msb, ADDC  (rem.y, nrm_dvsr >> 32, cy, t0, t1), rem.y);

    // pull down next dividend "digit"
    rem.y = (rem.y << 32) | (rem.x >> 32);
    rem.x = rem.x << 32;

    // compute least significant quotient "digit"; TAOCP: may be off by 0, +1, +2
    ql = mux_64 (geu_64 (rem.y >> 32, nrm_dvsr >> 32), 0xffffffff, rem.y / (nrm_dvsr >> 32));

    // combine partial results into complete quotient
    q = (qh << 32) + ql;

    // compute remainder; correct quotient "digit" if remainder negative
    prod   = my_mul_64_128 (q, dvsr);
    rem    = sub_128 (dvnd, prod);
    rem_msb= rem.y >> 63;
    q      = mux_64 (rem_msb, q - 1, q);
    rem.x  = mux_64 (rem_msb, ADDcc (rem.x, dvsr, cy, t0, t1), rem.x);
    rem.y  = mux_64 (rem_msb, ADDC  (rem.y,    0, cy, t0, t1), rem.y);
    rem_msb= rem.y >> 63;
    q      = mux_64 (rem_msb, q - 1, q);

    return q;
}

uint64_t ref_div_128_64 (ulonglong2 dvnd, uint64_t dvsr)
{
    uint64_t quot;
#if ASM_STYLE == MSVC_STYLE
    __asm mov rax, qword ptr [dvnd.x];
    __asm mov rdx, qword ptr [dvnd.y];
    __asm div qword ptr [dvsr];
    __asm mov qword ptr [quot], rax;
#else // ASM_STYLE
    __asm__ (
        "movq %1, %%rax\n\t"
        "movq %2, %%rdx\n\t"
        "divq %3\n\t"
        "movq %%rax, %0\n\t"
        : "=r" (quot)
        : "r" (dvnd.x), "r" (dvnd.y), "r" (dvsr)
        : "rax", "rdx");
#endif // ASM_STYLE
   return quot;
}

ulonglong2 ref_mul_64_128 (uint64_t a, uint64_t b)
{
    ulonglong2 prod;
#if ASM_STYLE == MSVC_STYLE
    __asm mov rax, qword ptr [a];
    __asm mul qword ptr [b];
    __asm mov qword ptr [prod.x], rax;
    __asm mov qword ptr [prod.y], rdx;
#else // ASM_STYLE
    __asm__(
        "movq %2, %%rax\n\t"
        "mulq %3\n\t"
        "movq %%rax, %0\n\t"
        "movq %%rdx, %1\n\t"
        : "=r" (prod.x), "=r" (prod.y)
        : "r" (a), "r" (b)
        : "rax", "rdx");
#endif // ASM_STYLE
   return prod;
}

/*
  https://groups.google.com/forum/#!original/comp.lang.c/qFv18ql_WlU/IK8KGZZFJx4J
  From: geo <gmars...@gmail.com>
  Newsgroups: sci.math,comp.lang.c,comp.lang.fortran
  Subject: 64-bit KISS RNGs
  Date: Sat, 28 Feb 2009 04:30:48 -0800 (PST)

  This 64-bit KISS RNG has three components, each nearly
  good enough to serve alone.    The components are:
  Multiply-With-Carry (MWC), period (2^121+2^63-1)
  Xorshift (XSH), period 2^64-1
  Congruential (CNG), period 2^64
*/
static uint64_t kiss64_x = 1234567890987654321ULL;
static uint64_t kiss64_c = 123456123456123456ULL;
static uint64_t kiss64_y = 362436362436362436ULL;
static uint64_t kiss64_z = 1066149217761810ULL;
static uint64_t kiss64_t;

#define MWC64  (kiss64_t = (kiss64_x << 58) + kiss64_c, \
                kiss64_c = (kiss64_x >> 6), kiss64_x += kiss64_t, \
                kiss64_c += (kiss64_x < kiss64_t), kiss64_x)
#define XSH64  (kiss64_y ^= (kiss64_y << 13), kiss64_y ^= (kiss64_y >> 17), \
                kiss64_y ^= (kiss64_y << 43))
#define CNG64  (kiss64_z = 6906969069ULL * kiss64_z + 1234567ULL)
#define KISS64 (MWC64 + XSH64 + CNG64)

#define PATTERN  (1)

int main (void)
{
    ulonglong2 dvnd, prod, diff;
    uint64_t dvsr, ref, res, count = 0;

    do {
        count++;
        do {
#if PATTERN_TEST
            ulonglong2 temp1, temp2;
            uint64_t shift, shift1, shift2;
            shift = KISS64 & 127;
            temp1.y = (shift > 63) ? (1ULL << (shift - 64)) : 0;
            temp1.x = (shift > 63) ? 0ULL : (1ULL << shift);
            shift = KISS64 & 127;
            temp2.y = (shift > 63) ? (1ULL << (shift - 64)) : 0;
            temp2.x = (shift > 63) ? 0ULL : (1ULL << shift);
            dvnd = (KISS64 & 1) ? add_128 (temp1, temp2) : sub_128 (temp1, temp2);
            shift1 = KISS64 & 63;
            shift2 = KISS64 & 63;
            dvsr = (KISS64 & 1) ? ((1ULL << shift1) + (1ULL << shift2)) :
                                  ((1ULL << shift1) - (1ULL << shift2));
#else // PATTERN_TEST
            dvnd.y = KISS64;
            dvnd.x = KISS64;
            dvsr = KISS64;
#endif // PATTERN_TEST
        } while ((dvsr == 0ULL) || (dvnd.y >= dvsr)); // guard against overflow

        ref = ref_div_128_64 (dvnd, dvsr);
        res = my_div_128_64 (dvnd, dvsr);

        prod = ref_mul_64_128 (res, dvsr);
        diff = sub_128 (dvnd, prod);

        if ((diff.y != 0) || (diff.x >= dvsr)) {
            printf ("error @ chk1: dvnd= %016llx_%016llx  dvsr=%016llx  res=%016llx ref=%016llx diff=%016llx_%016llx\n",
                    dvnd.y, dvnd.x, dvsr, res, ref, diff.y, diff.x);
            return EXIT_FAILURE;
        }
        if (res != ref) {
            printf ("error @ chk2: dvnd= %016llx_%016llx  dvsr=%016llx  res=%016llx ref=%016llx diff=%016llx_%016llx\n",
                    dvnd.y, dvnd.x, dvsr, res, ref, diff.y, diff.x);
            return EXIT_FAILURE;
        }
        if ((count & 0xffffff) == 0) printf ("\r%llu", count);
    } while (dvsr);
    return EXIT_SUCCESS;
}

If the programming language is more severely restricted, all of shifts and all logical operations, except those used inside the predicate functions neq_64(), ltu_64(), and geu_64(), can be replaced with arithmetic. Examplary ISO-C99 code is shown below. There may be programming language specific ways to implement these predicates without the use of logical operations.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define PATTERN_TEST  (0)

#define MSVC_STYLE    (1)
#define GCC_STYLE     (2)
#define ASM_STYLE     (GCC_STYLE)

#define POW2_63       (0x8000000000000000ULL)
#define POW2_32       (0x0000000100000000ULL)
#define POW2_16       (0x0000000000010000ULL)
#define POW2_8        (0x0000000000000100ULL)
#define POW2_5        (0x0000000000000020ULL)
#define POW2_4        (0x0000000000000010ULL)
#define POW2_3        (0x0000000000000008ULL)
#define POW2_2        (0x0000000000000004ULL)
#define POW2_1        (0x0000000000000002ULL)
#define POW2_0        (0x0000000000000001ULL)

// our own 128-bit unsigned integer type
typedef struct
{
    uint64_t x;
    uint64_t y;
} ulonglong2;

// (a < b) ? 1 : 0
uint64_t ltu_64 (uint64_t a, uint64_t b)
{
    return ((~a & b) + ((~a ^ b) / POW2_1)) / POW2_63;
}

// (a >= b) ? 1 : 0
uint64_t geu_64 (uint64_t a, uint64_t b)
{
    return ((a | ~b) - ((a ^ ~b) / POW2_1)) / POW2_63;
}

// (a != b) ? 1 : 0
uint64_t neq_64 (uint64_t a, uint64_t b)
{
    return ((a - b) | (b - a)) / POW2_63;
}

//#define ADDcc(a,b,cy,t0,t1) (t0=(b), t1=(a), t0=t0+t1, cy=t0<t1, t0=t0)
#define ADDcc(a,b,cy,t0,t1) (t0=(b), t1=(a), t0=t0+t1, cy=ltu_64(t0,t1), t0=t0)
#define ADDC(a,b,cy,t0,t1) (t0=(b)+cy, t1=(a), t0+t1)

//#define SUBcc(a,b,cy,t0,t1) (t0=(b), t1=(a), cy=t1<t0, t1-t0)
#define SUBcc(a,b,cy,t0,t1) (t0=(b), t1=(a), cy=ltu_64(t1,t0), t1-t0)
#define SUBC(a,b,cy,t0,t1)  (t0=(b)+cy, t1=(a), t1-t0)

// 128-bit subtraction
ulonglong2 sub_128 (ulonglong2 a, ulonglong2 b)
{
    ulonglong2 res;
    uint64_t cy, t0, t1;
    res.x = SUBcc (a.x, b.x, cy, t0, t1);
    res.y = SUBC  (a.y, b.y, cy, t0, t1);
    return res;
}

// 128-bit addition
ulonglong2 add_128 (ulonglong2 a, ulonglong2 b)
{
    ulonglong2 res;
    uint64_t cy, t0, t1;
    res.x = ADDcc (a.x, b.x, cy, t0, t1);
    res.y = ADDC  (a.y, b.y, cy, t0, t1);
    return res;
}

// branch free implementation of ((cond) ? a : b). cond must be in {0,1}
uint64_t mux_64 (uint64_t cond, uint64_t a, int64_t b)
{
    return cond * a + (1 - cond) * b;
}

// count leading zeros
uint64_t clz_64 (uint64_t x)
{
    uint64_t n = 64;
    uint64_t c, y;

    y = x / POW2_32; c = neq_64 (y, 0); n = mux_64 (c, n - 32, n); x = mux_64 (c, y, x);
    y = x / POW2_16; c = neq_64 (y, 0); n = mux_64 (c, n - 16, n); x = mux_64 (c, y, x);
    y = x / POW2_8;  c = neq_64 (y, 0); n = mux_64 (c, n -  8, n); x = mux_64 (c, y, x);
    y = x / POW2_4;  c = neq_64 (y, 0); n = mux_64 (c, n -  4, n); x = mux_64 (c, y, x);
    y = x / POW2_2;  c = neq_64 (y, 0); n = mux_64 (c, n -  2, n); x = mux_64 (c, y, x);
    y = x / POW2_1;  c = neq_64 (y, 0); n = mux_64 (c, n -  2, n - x);
    return n;
}

// compute 2**i, 0 <= i <=63
uint64_t pow2i (uint64_t i)
{
    uint64_t r = 1ULL;

    r = mux_64 ((i / POW2_5) % 2, r * POW2_32, r);
    r = mux_64 ((i / POW2_4) % 2, r * POW2_16, r);
    r = mux_64 ((i / POW2_3) % 2, r * POW2_8,  r);
    r = mux_64 ((i / POW2_2) % 2, r * POW2_4,  r);
    r = mux_64 ((i / POW2_1) % 2, r * POW2_2,  r);
    r = mux_64 ((i / POW2_0) % 2, r * POW2_1,  r);
    return r;
}

// 64x64->128 bit unsigned multiplication
ulonglong2 my_mul_64_128 (uint64_t a, uint64_t b)
{
    ulonglong2 res;

    uint64_t a_hi = a / POW2_32;
    uint64_t a_lo = a % POW2_32;
    uint64_t b_hi = b / POW2_32;
    uint64_t b_lo = b % POW2_32;
    uint64_t p0 = a_lo * b_lo;
    uint64_t p1 = a_lo * b_hi;
    uint64_t p2 = a_hi * b_lo;
    uint64_t p3 = a_hi * b_hi;
    uint64_t cy = ((p0 / POW2_32) + (p1 % POW2_32) + (p2 % POW2_32)) / POW2_32;
    res.x = p0 + (p1 * POW2_32) + (p2 * POW2_32);
    res.y = p3 + (p1 / POW2_32) + (p2 / POW2_32) + cy;
    return res;
}

// 128/64->64 bit unsigned division
uint64_t my_div_128_64 (ulonglong2 dvnd, uint64_t dvsr)
{
    ulonglong2 prod, rem;
    uint64_t lz, lz_nz, scal, shft, q, qh, ql, rem_msb, nrm_dvsr, nrm_dvsr_hi, cy, t0, t1;

    // normalize divisor; adjust dividend accordingly (initial partial remainder)
    lz = clz_64 (dvsr);
    lz_nz = neq_64 (lz, 0);
    scal = pow2i (lz);
    shft = mux_64 (lz_nz, 64 - lz, 0);
    nrm_dvsr = dvsr * scal;
    rem.y = dvnd.y * scal + mux_64 (lz_nz, dvnd.x / pow2i (shft), 0);
    rem.x = dvnd.x * scal;
    nrm_dvsr_hi = nrm_dvsr / POW2_32;

    // compute most significant quotient "digit"; TAOCP: may be off by 0, +1, +2
    qh = mux_64 (geu_64 (rem.y / POW2_32, nrm_dvsr_hi), 0xffffffff, rem.y / (nrm_dvsr_hi));

    // compute remainder; correct quotient "digit" if remainder negative
    prod   = my_mul_64_128 (qh * POW2_32, nrm_dvsr);
    rem    = sub_128 (rem, prod);
    rem_msb= rem.y / POW2_63;
    qh     = mux_64 (rem_msb, qh - 1, qh);
    rem.x  = mux_64 (rem_msb, ADDcc (rem.x, nrm_dvsr * POW2_32, cy, t0, t1), rem.x);
    rem.y  = mux_64 (rem_msb, ADDC  (rem.y, nrm_dvsr / POW2_32, cy, t0, t1), rem.y);
    rem_msb= rem.y / POW2_63;
    qh     = mux_64 (rem_msb, qh - 1, qh);
    rem.x  = mux_64 (rem_msb, ADDcc (rem.x, nrm_dvsr * POW2_32, cy, t0, t1), rem.x);
    rem.y  = mux_64 (rem_msb, ADDC  (rem.y, nrm_dvsr / POW2_32, cy, t0, t1), rem.y);

    // pull down next dividend "digit"
    rem.y = rem.y * POW2_32 + rem.x / POW2_32;
    rem.x = rem.x * POW2_32;

    // compute least significant quotient "digit"; TAOCP: may be off by 0, +1, +2
    ql = mux_64 (geu_64 (rem.y / POW2_32, nrm_dvsr_hi), 0xffffffff, rem.y / (nrm_dvsr_hi));

    // combine partial results into complete quotient
    q = qh * POW2_32 + ql;

    // compute remainder; correct quotient "digit" if remainder negative
    prod   = my_mul_64_128 (q, dvsr);
    rem    = sub_128 (dvnd, prod);
    rem_msb= rem.y / POW2_63;
    q      = mux_64 (rem_msb, q - 1, q);
    rem.x  = mux_64 (rem_msb, ADDcc (rem.x, dvsr, cy, t0, t1), rem.x);
    rem.y  = mux_64 (rem_msb, ADDC  (rem.y,    0, cy, t0, t1), rem.y);
    rem_msb= rem.y / POW2_63;
    q      = mux_64 (rem_msb, q - 1, q);

    return q;
}

uint64_t ref_div_128_64 (ulonglong2 dvnd, uint64_t dvsr)
{
    uint64_t quot;
#if ASM_STYLE == MSVC_STYLE
    __asm mov rax, qword ptr [dvnd.x];
    __asm mov rdx, qword ptr [dvnd.y];
    __asm div qword ptr [dvsr];
    __asm mov qword ptr [quot], rax;
#else // ASM_STYLE
    __asm__ (
        "movq %1, %%rax\n\t"
        "movq %2, %%rdx\n\t"
        "divq %3\n\t"
        "movq %%rax, %0\n\t"
        : "=r" (quot)
        : "r" (dvnd.x), "r" (dvnd.y), "r" (dvsr)
        : "rax", "rdx");
#endif // ASM_STYLE
   return quot;
}

ulonglong2 ref_mul_64_128 (uint64_t a, uint64_t b)
{
    ulonglong2 prod;
#if ASM_STYLE == MSVC_STYLE
    __asm mov rax, qword ptr [a];
    __asm mul qword ptr [b];
    __asm mov qword ptr [prod.x], rax;
    __asm mov qword ptr [prod.y], rdx;
#else // ASM_STYLE
    __asm__(
        "movq %2, %%rax\n\t"
        "mulq %3\n\t"
        "movq %%rax, %0\n\t"
        "movq %%rdx, %1\n\t"
        : "=r" (prod.x), "=r" (prod.y)
        : "r" (a), "r" (b)
        : "rax", "rdx");
#endif // ASM_STYLE
   return prod;
}

/*
  https://groups.google.com/forum/#!original/comp.lang.c/qFv18ql_WlU/IK8KGZZFJx4J
  From: geo <gmars...@gmail.com>
  Newsgroups: sci.math,comp.lang.c,comp.lang.fortran
  Subject: 64-bit KISS RNGs
  Date: Sat, 28 Feb 2009 04:30:48 -0800 (PST)

  This 64-bit KISS RNG has three components, each nearly
  good enough to serve alone.    The components are:
  Multiply-With-Carry (MWC), period (2^121+2^63-1)
  Xorshift (XSH), period 2^64-1
  Congruential (CNG), period 2^64
*/
static uint64_t kiss64_x = 1234567890987654321ULL;
static uint64_t kiss64_c = 123456123456123456ULL;
static uint64_t kiss64_y = 362436362436362436ULL;
static uint64_t kiss64_z = 1066149217761810ULL;
static uint64_t kiss64_t;

#define MWC64  (kiss64_t = (kiss64_x << 58) + kiss64_c, \
                kiss64_c = (kiss64_x >> 6), kiss64_x += kiss64_t, \
                kiss64_c += (kiss64_x < kiss64_t), kiss64_x)
#define XSH64  (kiss64_y ^= (kiss64_y << 13), kiss64_y ^= (kiss64_y >> 17), \
                kiss64_y ^= (kiss64_y << 43))
#define CNG64  (kiss64_z = 6906969069ULL * kiss64_z + 1234567ULL)
#define KISS64 (MWC64 + XSH64 + CNG64)

#define PATTERN  (1)

int main (void)
{
    ulonglong2 dvnd, prod, diff;
    uint64_t dvsr, ref, res, count = 0;

    do {
        count++;
        do {
#if PATTERN_TEST
            ulonglong2 temp1, temp2;
            uint64_t shift, shift1, shift2;
            shift = KISS64 & 127;
            temp1.y = (shift > 63) ? (1ULL << (shift - 64)) : 0;
            temp1.x = (shift > 63) ? 0ULL : (1ULL << shift);
            shift = KISS64 & 127;
            temp2.y = (shift > 63) ? (1ULL << (shift - 64)) : 0;
            temp2.x = (shift > 63) ? 0ULL : (1ULL << shift);
            dvnd = (KISS64 & 1) ? add_128 (temp1, temp2) : sub_128 (temp1, temp2);
            shift1 = KISS64 & 63;
            shift2 = KISS64 & 63;
            dvsr = (KISS64 & 1) ? ((1ULL << shift1) + (1ULL << shift2)) :
                                  ((1ULL << shift1) - (1ULL << shift2));
#else // PATTERN_TEST
            dvnd.y = KISS64;
            dvnd.x = KISS64;
            dvsr = KISS64;
#endif // PATTERN_TEST
        } while ((dvsr == 0ULL) || (dvnd.y >= dvsr)); // guard against overflow

        ref = ref_div_128_64 (dvnd, dvsr);
        res = my_div_128_64 (dvnd, dvsr);

        prod = ref_mul_64_128 (res, dvsr);
        diff = sub_128 (dvnd, prod);

        if ((diff.y != 0) || (diff.x >= dvsr)) {
            printf ("error @ chk1: dvnd= %016llx_%016llx  dvsr=%016llx  res=%016llx ref=%016llx diff=%016llx_%016llx\n",
                    dvnd.y, dvnd.x, dvsr, res, ref, diff.y, diff.x);
            return EXIT_FAILURE;
        }
        if (res != ref) {
            printf ("error @ chk2: dvnd= %016llx_%016llx  dvsr=%016llx  res=%016llx ref=%016llx diff=%016llx_%016llx\n",
                    dvnd.y, dvnd.x, dvsr, res, ref, diff.y, diff.x);
            return EXIT_FAILURE;
        }
        if ((count & 0xffffff) == 0) printf ("\r%llu", count);
    } while (dvsr);
    return EXIT_SUCCESS;
}

A: Not answering the main question, but solving the underlying issue.
Algorand smart contracts now support such large division directly using the opcode divmodw: https://developer.algorand.org/docs/get-details/dapps/avm/teal/opcodes/#divmodw
They also support division of up to 512-bit numbers: https://developer.algorand.org/docs/get-details/dapps/avm/teal/specification/#arithmetic-logic-and-cryptographic-operations


text:
Q: Is SimpleDateFormat.clone() thread-safe? I'm looking at legacy code and found the following:
private static final SimpleDateFormat sdf = new SimpleDateFormat("...");
...
void foo() {
    bar(date, someMoreArgs, sdf.clone());
}

where bar() then goes ahead and uses the passed SimpleDateFormat to format the given date.
Is the above code thread-safe? If multiple threads concurrently call sdf.clone(), can one of the cloned objects end up getting corrupted?
I wouldn't write the code like that myself in the first place. I know there are better ways to do this. But I'm not looking to refactor the code unless it can be proven to be not thread-safe.
Edit:
Some more information for clarification:

*

*The static object sdf itself is never used for formatting. The only operation it's ever used for is cloning. Thus, I'm not expecting its contents to change (unless the cloning operation writes some transient data inside the object).

*The clone is never used by more than one thread.

A: From the JavaDoc:

Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

So I believe that it depends on how you use that clone, but it is not assured. Cloning does not make your classes thread-safe. If the cloned object is not shared between class instances it should work with no problems, but I would not recommend this approach. However, you need a thread-safe date formatter I would suggest using Apache Commons FastDateFormat, described here.

A: Basically the clone() method doesn't give you thread safety. It just copies the properties of one object to another one. It doesn't lock or synchronize that object so if it is thread safe or not is up to the implementation. If during that copy some of the properties of the original object are changed then you might get into a strange state. If you use that cloned object in more than one threads - you still got problems
For your particular example I think the code is fine. The sdf object you are going to clone is probably never gonna change and you don't need a lock or something (it seems). You just create a new SimpleDateFormat object for each thread to ensure thread safety - or at least that's the idea - and you achieve that by using clone.
Anyway if you have spotted a problem in legacy code and you don't like it it is always better to spend some time and refactor it than to keep it like that even if you don't like it. It almost always pays off in the long term with having better and more maintainable code and not leaving that like that for the next developer to wander. For example if you have upgraded to java 8 you can use DateTimeFormatter which is thread safe or you can use some external library. Or at least create a new SimpleDateFormat(SOME_CONSTANT_FORMAT) everytime you need one instead of relying on clone of the object - because if you share just a string constant (the actual format) it is immutable and thread safe.

A: This is not an answer. But some information you may still find interesting. I did a couple of experiments.
First I had two threads formatting dates using the same SimpleDateFormat instance. After a couple of iterations they began giving incorrect results, and after a few hundred iterations one of the threads crashed. So the thread-unsafety seems very real.
Next I had one thread format dates using the original SimpleDateFormat and the other one taking clones of it and using the clones for formatting. Both threads have run for several minutes now and are still both producing correct results.
This is by no means any guarantee that this is the behaviour you will always see. The documentation is pretty clear: SimpleDateFormat is not thread safe and all access from several threads must be synchronized. So use the information at your own risk.
EDIT: Inspecting the source code seems to reveal that the clone operation copies fields in some order, but doesn't modify the original. If the original was doing any work in another thread, this might cause the clone to be in an inconsistent state after creation, which in turn might or might not affect its correct working. If the original is only used for cloning, I see no risk with the current implementation. As you say, the implementation may be changed in later Java versions, but I would consider the risk small, and the risk of thread-unsafe behaviour being introduced even smaller. All of this is pure speculation!


text:
Q: HTML5 canvas javascript brush not equal in other scale Hi i have brush Sketchy who use random function. With it i drawing on two layers first layer original size and second layer 2x bigger. In both layers i painting same drawings. At first glance u can't see any difference, but then i click button "Clear and insert backup in first square" this button just copy from second layer to first with original scale and u can see at this moment how change drawings. Because first layer not equal second layer.

/* Layer 1 */
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

/* Layer 2 */
var canvas2 = document.getElementById('canvas2');
var ctxBigger = canvas2.getContext('2d');

var coords = {};
var pencil = {};
var isDrawing = false;
var TwoTimesBigger = 2;

function getMousePosInCanvas(canvas, e) {
    var rect = canvas.getBoundingClientRect();

    return {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
    };
}

$('#canvas').on('mousedown', function(e) {
  coords = getMousePosInCanvas(canvas, e);
  isDrawing = true;
  pencil.setPreviousCoords(coords.x, coords.y);
});

$('#canvas').on('mousemove', function(e) {
  if(isDrawing) {
    coords = getMousePosInCanvas(canvas, e);
    pencil.stroke(coords.x, coords.y, TwoTimesBigger);
  }
});

$('#canvas').on('mouseup', function() {
  isDrawing = false;
});

$('#canvas').on('mouseleave', function() {
  isDrawing = false;
});

$('#pencil-simple').on('click', function() {
  pencil = new SimplePencil(ctx, ctxBigger);
});

$('#pencil-sketchy').on('click', function() {
  pencil = new SketchyPencil(ctx, ctxBigger);
});

$('#clear-insert-backup').on('click', function() {
  var tempGlobalAlpha = ctx.globalAlpha;
  ctx.globalAlpha = 1; //For redrawing
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(canvas2, 0, 0, canvas.width, canvas.height);
  ctx.globalAlpha = tempGlobalAlpha;
});

/* PENCILS */
function SimplePencil(ctx, ctxBigger) {
    this.init(ctx, ctxBigger);
}

SimplePencil.prototype = {
    ctx: null, ctxBigger: null,
    previousX: null, previousY: null,

    init: function(ctx, ctxBigger) {
        this.ctx = ctx;
        this.ctxBigger = ctxBigger;
    },
    stroke: function(x, y, TwoTimesBigger) {

        this.ctxBigger.strokeStyle = this.ctx.strokeStyle = "#000000";

        /* Layer 1 */
        this.ctx.beginPath();
        this.ctx.lineWidth = 1;
        this.ctx.moveTo(this.previousX, this.previousY);
        this.ctx.lineTo(x, y);
        this.ctx.closePath();
        this.ctx.stroke();

        /* Layer 2 */
        this.ctxBigger.beginPath();
        this.ctxBigger.lineWidth = this.ctx.lineWidth * TwoTimesBigger;
        this.ctxBigger.moveTo( this.previousX * TwoTimesBigger, this.previousY * TwoTimesBigger );
        this.ctxBigger.lineTo( x * TwoTimesBigger, y * TwoTimesBigger);
        this.ctxBigger.closePath();
        this.ctxBigger.stroke();

        this.setPreviousCoords(x, y);
    },
    setPreviousCoords: function(x, y) {
        this.previousX = x;
        this.previousY = y;
    },
}

function SketchyPencil(ctx, ctxBigger) {
    this.init(ctx, ctxBigger);
}

SketchyPencil.prototype = {
    ctx: null, ctxBigger: null,
    previousX: null, previousY: null,

    init: function(ctx, ctxBigger) {
        this.ctx = ctx;
        this.ctxBigger = ctxBigger;

        this.points = new Array();
        this.count = 0;
    },
    stroke: function(x, y, TwoTimesBigger) {
        var i, dx, dy, d;

        this.ctxBigger.strokeStyle = this.ctx.strokeStyle = "#000000";
        this.ctxBigger.globalAlpha = this.ctx.globalAlpha = 0.05;

        this.points.push([x, y]);
        this.ctx.lineWidth = 0.5;
        this.ctxBigger.lineWidth = this.ctx.lineWidth * TwoTimesBigger;

        for (i = 0; i < this.points.length; i++) {
            dx = this.points[i][0] - this.points[this.count][0];
            dy = this.points[i][1] - this.points[this.count][1];
            d = dx * dx + dy * dy;

            if (d < 8000 && Math.random() > d / 4000) {
                this.ctx.beginPath();
                this.ctx.moveTo(this.points[this.count][0] + (dx * 0.3), this.points[this.count][1] + (dy * 0.3));
                this.ctx.lineTo(this.points[i][0] - (dx * 0.3), this.points[i][1] - (dy * 0.3));
                this.ctx.stroke();
            }
        }

        for (i = 0; i < this.points.length; i++) {
            dx = this.points[i][0] - this.points[this.count][0];
            dy = this.points[i][1] - this.points[this.count][1];
            d = dx * dx + dy * dy;

            if (d < 8000 && Math.random() > d / 4000) {
                this.ctxBigger.beginPath();

                this.ctxBigger.moveTo( this.points[this.count][0] * TwoTimesBigger + (dx * (0.3 * TwoTimesBigger)), this.points[this.count][1] * TwoTimesBigger + (dy * (0.3 * TwoTimesBigger)) );
                this.ctxBigger.lineTo( this.points[i][0] * TwoTimesBigger - (dx * (0.3 * TwoTimesBigger)), this.points[i][1] * TwoTimesBigger - (dy * (0.3 * TwoTimesBigger )) );
                this.ctxBigger.stroke();
            }
        }

        this.setPreviousCoords(x, y);
        this.count++;
    },
    setPreviousCoords: function(x, y) {
        this.previousX = x;
        this.previousY = y;
    },

}
#canvas, #canvas2 {
  border: 1px #000 solid;
}

<input type="button" id="pencil-simple" value="Pencil simple">
<input type="button" id="pencil-sketchy" value="Pencil sketchy">
<input type="button" id="clear-insert-backup" value="Clear and insert backup in first square">

Press Pencil simple or Pencil sketchy and start drawing in first square, second square only for backup 2x bigger than first, After drawings with sketchy press Clear and insert backup in first square and you can see how first square not equal second.

<canvas id="canvas" width="300" height="300"></canvas>
<canvas id="canvas2" width="600" height="600"></canvas>


text:
Q: React project fails to use node modules in a git submodule I have a Javascript (typescript) project that I am using as a git submodule in a react project (also typescript).
This all works fine... until I make use of any node module in the git submodule. I tried using, for example, the node modules "moment" and "faker", but I am almost certain that it does not have anything to do with these specific node modules.
Importing for example "moment" in the submodule:
import moment from 'moment';

using it:
moment().format('DD/MM/YYYY');

and running the main react project leads to this error:
Failed to compile.

./src/project_core/node_modules/moment/moment.js
  Line 5:37:  'define' is not defined  no-undef
  Line 5:50:  'define' is not defined  no-undef

Removing moment().format('DD/MM/YYYY'); solves it.
If I just run some tests directly in the submodule and make use of for example "moment", it always works. I can use the node modules. It looks like something goes wrong once the main project uses the node modules in the git submodule.
This is how my react project looks like. As you can see the submodule project_core is added in the src folder of the main project.
├── build
│   ├── assets
│   └── static
│       ├── css
│       └── js
├── node_modules
├── public
│   └── assets
└── src
    ├── project_core
    │   ├── node_modules
    │   ├── src
    │   └── tests
    ├── ui
    ├── api
    └── utils

I know... I read everywhere that using git submodules is not recommended. I, however, just want to experiment with git submodules to learn from it.

A: It looks like you have a node module inside a node module. This probably confuses your bundler and produces the import errors. Try removing the package.json and node_modules from your project core subdirectory and see if the imports work correctly. If you want to make your core directory a library think about actually having it as a npm dependency instead of a submodule. You could still reference a git commit hash in the dependency.


text:
Q: How can I make an reference to a Shortcut Directory into PackageGroup in WIX? I have this TestProduct.wxs file with this code:
<Wix
    xmlns="http://schemas.microsoft.com/wix/2006/wi"
    xmlns:bal="http://schemas.microsoft.com/wix/BalExtension"
    xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">

    <Fragment>
        <util:RegistrySearch
            Id="ExistsSearch"
            Root="HKLM"
            Key="SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{...}"
            Win64="no"
            Result="exists"
            Variable="IsInstalled" />

    <Variable Name="IssTemplateFile" Type="string" Value="[MediaRootDirectory]\ADMIN.iss" bal:Overridable="no" Persisted="yes" />
    <Variable Name="IssFile" Type="string" Value="" bal:Overridable="no" Persisted="yes" />

        <Feature Id="ProductFeature" Title="WebPageShortcutInstaller" Level="1">
          <ComponentGroupRef Id="ProductComponents" />
        </Feature>

        <SetProperty Id="URL" Value="http://www.google.com" Sequence="execute"  Before="CreateShortcuts" />

      <PackageGroup Id="PackageGroup">
            <ExePackage
                Id="AdministratorPackage"
                SourceFile="..."
                DetectCondition="IsInstalled = 1"
                DisplayName="Administrator"
                InstallCondition="InstallationType ~= InstallationTypeServer OR InstallationType ~= InstallationTypeClient"
                Compressed="yes"
                Cache="no"
                PerMachine="yes"
                Permanent="no"
                Vital="yes"
                InstallCommand="...">

                <ExitCode Value="3010" Behavior="forceReboot" />
                <ExitCode Value="1641" Behavior="forceReboot" />

            </ExePackage>
        </PackageGroup>
    </Fragment>

    <Fragment>
      <Directory Id="TARGETDIR" Name="SourceDir">
        <Directory Id="ProgramFilesFolder">
          <Directory Id="INSTALLFOLDER" Name="WebPageShortcutInstaller" />
        </Directory>
        <Directory Id="DesktopFolder">
          <Directory Id="DesktopShortcutID" />
        </Directory>
      </Directory>
    </Fragment>

    <Fragment>
      <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
        <Component Id="cmpWebPageShortcut" Guid="{}">
          <Shortcut Directory="DesktopFolder" Id="shortcutWebPage" Name="WEb Page" Description="WebPage" Target="[URL]" Icon="IconDesktop">
            <Icon Id="IconDesktop" SourceFile="favicon.ico" />
          </Shortcut>
          <RemoveFolder Id="removeStartMenuFolder" Directory="DesktopShortcutID" On="uninstall" />
          <RegistryValue Root="HKCU" Key="..." Name="installed" Type="integer" Value="1" KeyPath="yes" />
        </Component>
      </ComponentGroup>
    </Fragment>
</Wix>

And I have another Bundle.wxs where I have a chain like this:
        <Chain>

            <!-- Server -->
            <PackageGroupRef Id="PackageGroup" />
            <RollbackBoundary />
...
        </Chain>

I want to call into my Bundle.wxs the PackageGroup and in the same time to create the icon on the destkop.
When I try to install PackageGroup the WIX installer working perfectly. My main problem is the creation of the icon on the desktop. I don't know why is not created. The ComponentGroupRef from Feature ID is not working.
I put this code into another shape, I create a MSI with Product.wxs, everytyhing is working.
<?xml version="1.0" encoding="UTF-8"?>
    <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
         xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">

        <Product Id="*" Name="WebPageShortcutInstaller" Language="1033" Version="1.0.0.0" Manufacturer="Waters" UpgradeCode="...">
            <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />

            <MediaTemplate EmbedCab="yes" />

            <Feature Id="ProductFeature" Title="WebPageShortcutInstaller" Level="1">
                <ComponentGroupRef Id="ProductComponents" />
            </Feature>

        <SetProperty Id="URL" Value="http://www.google.com" Sequence="execute"  Before="CreateShortcuts" />

      </Product>
        <Fragment>
            <Directory Id="TARGETDIR" Name="SourceDir">
                <Directory Id="ProgramFilesFolder">
                    <Directory Id="INSTALLFOLDER" Name="WebPageShortcutInstaller" />
                </Directory>
          <Directory Id="DesktopFolder">
            <Directory Id="DesktopShortcutID" />
          </Directory>
            </Directory>
        </Fragment>
        <Fragment>
            <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
          <Component Id="cmpWebPageShortcut" Guid="...">

            <Shortcut Directory="DesktopFolder" Id="shortcutWebPage" Name="Web Page" Description="WebPage" Target="[URL]" Icon="IconDesktop">
              <Icon Id="IconDesktop" SourceFile="favicon.ico" />
            </Shortcut>

            <RemoveFolder Id="removeStartMenuFolder" Directory="DesktopShortcutID" On="uninstall" />
            <RegistryValue Root="HKCU" Key="Software\..." Name="installed" Type="integer" Value="1" KeyPath="yes" />
          </Component>
            </ComponentGroup>
        </Fragment>
    </Wix>

Note: Is mandatory to use PackageGroup because I need to call the id into the . I just want to make a correct shape for the first option.

A: Bundles don't support shortcuts or components. They need to go into a Product.


text:
Q: Control characters display format in hyperterminal I am working with a serial device. On data receive, i am getting heart symbol along with actual data.
Then i decoded the ASCII value and found that it is equivalent to <ETX> (End of  text)
Why it is showing heart symbol for ETX??
What would be the display character for STX?? Is there any list available other control characters??

A: http://en.wikipedia.org/wiki/Code_page_437#Interpretation_of_code_points_1.E2.80.9331_and_127
Why does SO think the above link is 0 characters long?


text:
Q: c++ Greatest Common Divisor I am very new to C++ and am attempting create a function to implement the Euclidean algorithm that returns the greatest common divisor for two integer inputs.
The current approach I am taking keeps crashing - can you help me understand why?
int main() {
    int a = 0;
    int b = 0;

    cin >>  a;
    cin >> b;

    do {
        if ( a > b ) a = a % b;
        else if ( a < b ) b = b % a;
        else if ( a == b ) break;
    } while ( ( a || b ) != 0 );

    return 0;
}

Thanks,
David

A: Your term ( a || b ) != 0 will not resolve as you expect.
What you want to do is (a != 0) && (b != 0)
Or as Cheers and hth. - Alf suggests just a && b.

A: while ( ( a || b ) != 0 );

this is wrong. It should be
while ( a != 0 && b != 0 );

On a side note, the Euclid's algorithm can be concisely implemented recursively:
int gcd(int a, int b)
{
   return b == 0 ? a : gcd(b, a%b);
}

A: Your while condition is wrong. You cant simplify it like that.
while ( ( a || b ) != 0 );

It should look like this.
while ( ( a != 0 ) && ( b != 0 ) );

By the way, you could make an much easier approach. Something like this
int main() {

int a, b, r;

cin >> a;
cin >> b;

while ( b != 0) {
    r = a % b;
    a = b;
    b = r;
}

cout << "The GCD is " << a << endl;

}

And there is another way, it doesnt requiere code the algorithm. Just use the libstdc++ algorithm library. Libstdc++

A: Let's have a closer look at your codes, maybe you are curious what does while ( ( a || b ) != 0 ) do?
We now should evaluate ( a || b ) != 0. In C/C++ evaluation begins from right to left, but () has more priority, so at run-time we would have:
bool r1 = a || b;  // intermediate result
bool r2 = r1 != 0;
while(r2);

Steps:

*

*a || b is evaluated to true when either a or b have non-zero value.

*r1 will be casted to integer

*

*true becomes 1

*false becomes 0

*r1 != 0 is evaluated and results an boolean value (true or false)

*while decides whether it should loop or not.


text:
Q: Access Spring Cloud Stream Kafka materialized view with external client Let's pretend that my Java application using Spring Cloud Streams Kafka creates a materialized view (KTable) that will be used to fulfil get(id) request.
How can I see the data from "outside" if I would like to do some maintenance or troubleshooting? Is there a way to explore/reprocess collected data as connecting directly to materialized view (like assigning to a topic) from another external application and convert it to stream? One option is creating specialized REST API that will map request to materialized view methods. Is there a better more efficient way? Does Spring Cloud Streams provides such? May be a tool?


text:
Q: (VERI-1322) prefix of assignment pattern must be a data type Here is a snippet from my code;
always_ff @(posedge clk) begin : output_assigment // left side should only be "_q"
    if(reset_n == 1'b0 || clear == 1'b1) out_signal_q <= {8'{!(REPORT_POL)}};

But i see this error:   (VERI-1322) prefix of assignment pattern must be a data type
How can this be corrected for the assignment "out_signal_q <= {8'{!(REPORT_POL)}}"
Can you please help ?
end

A: It always helps to show declarations of all signals involved in the expression. I have to assume that REPORT_POL is a single bit and you want it replicated 8 times to assigned to out_signal_q. In that case you want to remove the ' and just write
out_signal_q <= {8{!REPORT_POL}};


text:
Q: How to print a Qt dialog or window? How do I get Qt to print a complete dialog or window?
I could dump the window contents with an  external program like xwd and print that, but I would prefer to do it all with Qt.

A: Use QPixmap::grabWidget (or QPixmap::grabWindow for external window).
Something like this:
QPixmap pix = QPixmap::grabWidget(myMainWindowWidget);

Dunno if you really mean to print it to a printer, if so:
QPrinter printer(QPrinter::HighResolution);
QPainter painter;
painter.begin(&printer);
painter.drawPixmap (0, 0, &pix);
painter.end();

A: While you can use grabWidget to get the pixmap representation of the dialog, essentially you will be printing the pixels of the pixmap, i.e. the dialog is rasterized a the screen resolution and then scaled to the printer resolution. This may or may not result in some artifacts.
Another way to do it is by using QWidget::render() function that takes a paint device. This way, you can pass your printer as the paint device. The dialog is now "drawn" onto the printer with the the printer's resolution.


text:
Q: Converting Phoenix 1.2 code to Phoenix 1.3 I know changing a Phoenix 1.2 project to Phoenix 1.3 will necessarily entails changing the file structure and the related path code.
However, I don't know some of the changes that need to the code itself apart from restructuring the files. In essence, is it required to make certain changes to the code itself? If it is required, can you please give me an example of such changes that need to be made to the code?

A: The most apparent are directory and name convention changes.
From my own experience when migrating https://github.com/Diamond/pxblog/blob/master/web/models/role.ex to Phx 1.3, you need to be careful about changes for Ecto version bump.
Sample git diff:
defmodule Pxblog.Role do
-  use Pxblog.Web, :model
+  use Ecto.Schema
+  import Ecto.Changeset


text:
Q: GridView item not changing when value is changed i have this class
public class Item {
    String image;
    String accesslevel;
    String username;
    String userjob;
    String usercompany;
    String usermail;
    Boolean etat;
    int userapartid;
    public Item(String image, String username, String userjob, String usercompany, String usermail,int userapartid,Boolean etat,String accesslevel) {
        super();
        this.userapartid=userapartid;
        this.image = image;
        this.username = username;
        this.userjob = userjob;
        this.usercompany = usercompany;
        this.usermail = usermail;
        this.etat=etat;
        this.accesslevel=accesslevel;
    }
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }
    public String getusername() {
        return username;
    }
    public void setusername(String username) {
        this.username = username;
    }
    public String getusercompany() {
        return usercompany;
    }
    public void setusercompany(String usercompany) {
        this.usercompany = usercompany;
    }
    public String getuserjob() {
        return userjob;
    }
    public void setuserjob(String userjob) {
        this.userjob = userjob;
    }
    public String getusermail() {
        return usermail;
    }
    public void setusermail(String usermail) {
        this.usermail = usermail;
    }
    public Boolean getetat() {
        return etat;
    }
    public void setetat(Boolean etat) {
        this.etat = etat;
    }

    public int getuserapartid() {
        return userapartid;
    }
    public void setuserapartid(int userapartid) {
        this.userapartid = userapartid;
    }

    public String getaccesslevel() {
        return accesslevel;
    }
    public void setaccesslevel(String accesslevel) {
        this.accesslevel = accesslevel;
    }

}

And i have a GridView filled by Item in my main application and an arraylist that contains the item
gridArray2 = new ArrayList<Item>();

for(int i=0;i<gridArray.size();i++){
     __Item = new Item(gridArray.get(i).getImage(),gridArray.get(i).getusername(),gridArray.get(i).getuserjob(),gridArray.get(i).getusercompany(),gridArray.get(i).getusermail(),gridArray.get(i).getuserapartid(),gridArray.get(i).getetat(),gridArray.get(i).getaccesslevel());

gridArray2.add(__Item);

       }
 customGridAdapter = new CustomGridViewAdapter(MainActualite.this, R.layout.row_grid_access, gridArray2);
gridView.setAdapter(customGridAdapter);

My problem is when i do this:
gridView2.get(2).setetat(true);

the value of etat in the item is not changed. What can I do to change the value of an item in an arraylist please??
Thanks!

A: When you change the data that is being provided to an adapter (in this case you are updating GridArray2 which is providing customGridAdapter with data), you always need to make sure to call notifyDataSetChanged() to let the adapter for your GridView know that the underlying dataset has changed.
More information on this function can be found here: http://developer.android.com/reference/android/widget/ArrayAdapter.html#notifyDataSetChanged()

A: Basically, to update data in gridview, you have to update the data object (can be array, list, or something. But usually a list). After you change the content (lets say, a list), you have to call customGridAdapter.notifyDataSetChanged();.
And anyway, you do not need to re-instantiate your adapter.


text:
Q: Запуск второй формы в qt Как запустить вторую форму в Qt по нажатию на кнопку на первой форме?

A: Добавляешь в public первой формы  объект класса второй формы.
Из слота кнопки в первой форме вызываешь метод show() этого обяъекта.


text:
Q: Table with selectable items in Access 2003 I need to create a form in which user can select one item from the table. Then user can click on button so data in selected row can be used in next step. I am unable to find optimal solution.
First, I don't know how to make such view/table with selectable items. Second, I don't know how to gather data from selected row. I am totally new in MS Access 2003 and VBA, maybe someone has already solved such issue or know how to do this... Thanks a lot for any help

A: It is probably best to start with a sample database and a tutorial. The Northwind Sample database ships with Access 2003 : http://support.microsoft.com/kb/824265, it is quite informative, even if the code is a little odd at times. It is quite a long run-up from where you are at the moment.

A: If you are the click around and work it out type, I would suggest first that you go to the forms tab, click the new button, choose form wizard and select a table.
Select all columns to add to your new form and finish the wizard. Then, right click it, click Form Design, and edit from there.
Otherwise maybe you need a good book because you have a bit of a curve ahead!
Good luck!

A: OK, after some time I asked my colleague how they solved this. In fact it's just a little trick. All you need to do is load data into textbox(es). So each time user clicks on some row, data are loaded. And then, when he clicks on button to proceed on next step, you got it! Nice in textbox(es). :) Can be handy...


text:
Q: It's possible to call functions in another schema from within plv8 functions? I'm trying to use plv8 to write postgres functions. Now I would like to use the pgcrypt library in a way like this:
CREATE OR REPLACE FUNCTION v01.myfunction(arg json)
RETURNS json AS
$BODY$
  var res;
  res = obj.crypt(arg.password, res);
  plv8.elog(NOTICE, res);
  ...

$BODY$
LANGUAGE plv8;

Where crypt comes with the pgcrypt library and is find in another schema. But if running I get the error:
ERROR:  ReferenceError: obj is not defined

Any idea? Thanks!

A: It's possible to call other PLV8 functions in other schemas, yes.
You're not calling the function right though. Use
var myFunction = plv8.find_function("schemaName.functionName")

var result = myFunction();

AFAIK you can only call other PLV8 functions this way, not say PLPGSQL.
You can use plv8.execute("select someFunctionInAnotherLanguage()")

A: Ok, I found it:
var pp = plv8.execute("SELECT obj.crypt($1,$2)",[arg.password, cpw]);

easy :-)


text:
Q: Что делает аннотация @EnableGlobalMethodSecurity? В документации мало про это написано, но насколько я понял, она глобально включает security на методы, но в чем тогда разница между ней и @EnableWebSecurity?

A: @EnableWebSecurity вам требуется если вы хотите написать конфигурацию HttpSecurity, WebSecurity, AuthenticationManagerBuilder.
@Override
public void configure(HttpSecurity http){
    http.authorizeRequests().antMatchers("/public/**").permitAll().anyRequest()
        .hasRole("USER").and()
        .formLogin()
        .permitAll();
}

@EnableGlobalMethodSecurity включает AOP для конкретных методов или классов с помощью аннотаций @PreAuthorized, @PostAuthorize  и т.п.
@PreAuthorize("hasRole('ADMIN')")
public List<String> getUserPasswords() {
  return userService.passwords();
}


text:
Q: Filter models on the basis of dictionary key I am facing a problem while filtering a record from the database. In my database I have records which contain a dictfield.
for eg
region is a dictionary which contains other dictionaries like
region = {'eastus': {'percentage_change': 0}, 'westus': {'percentage_change': 0}}
and I want to fetch eastus or westus.
I have tried something like this, but I am getting an empty list.
MyModel.objects.filter(region__eq='eastus')
any suggestions for this problem?

A: I believe you can achieve this with the exists operator (http://docs.mongoengine.org/guide/querying.html#query-operators)
MyModel.objects.filter(region__eastus__exists=True)

Regarding the OR, you should use the Q class (http://docs.mongoengine.org/guide/querying.html#advanced-queries), thus:
MyModel.objects.filter(Q(region__eastus__exists=True) | Q(region__westus__exists=True))

If you have keys that aren't simple (e.g including fancy character or simply a dash), you can use the __raw__ operator:
MyModel.objects.filter(__raw__={'region.a-fancy-key': {'$exists': True}})


text:
Q: Why won't my function execute I'm relatively new to python and the only other experience I've had is C++. Whenever I define a function in Python, I can't seem to execute it.
This my current code for my assignment, if possible I just want to know why my code won't execute
def birthexp(birthyear):
    product = birthyear**birthyear
    length = len(str(product))
    onesCount = str(product).count("1")
    threeCount = str(product).count("3")
    fiveCount = str(product).count("5")
    sevenCount = str(product).count("7")
    nineCount = str(product).count("9")
    sumCount = onesCount+threeCount+fiveCount+sevenCount+nineCount
    oneRation = onesCount/float(length)*100
    threeRatio = threeCount/float(length)*100
    fiveRatio = fiveCount/float(length)*100
    sevenRatio = sevenCount/float(length)*100
    nineRatio = nineCount/float(length)*100
    totalRatio = sumCount/float(length)*100
    print(str(product) + ": product after multiplying the birth year to itself.")
    print(str(onesCount) + ": number of ones found at a rate of " +str(oneRation)+ "percent.")
    print(str(threeCount) + ": number of threes found at a rate of " +str(threeRatio)+ "percent")
    print(str(fiveCount) + ": number of fives found at a rate of " +str(fiveRatio)+ "percent")
    print(str(sevenCount) + ": number of sevens found at a rate of " +str(sevenRatio)+ "percent")
    print(str(nineCount) + ": number of nine found at a rate of " +str(nineRatio)+ "percent")
    print(str(sumCount) + ": total odd numbers found at a rate of " +str(totalRatio)+ "percent")

birthyear(1990)

A: You have a typo in this line totalRatio = sumCount/floar(length)*100. You need float instead of floar.
Secondly, you have loads of missing parenthesis in almost all lines with the print function.
If you want the function to return value, you should use return instead of print's:
return (str(product)
            + ": product after multiplying the birth year to itself.\n"
            + str(onesCount)
            + ": number of ones found at a rate of " + str(oneRation) + "percent.\n"
            + str(threeCount)
            + ": number of threes found at a rate of " + str(threeRatio) + "percent\n"
            + str(fiveCount)
            + ": number of fives found at a rate of " + str(fiveRatio) + "percent\n"
            + str(sevenCount)
            + ": number of sevens found at a rate of " + str(sevenRatio) + "percent\n"
            + str(nineCount)
            + ": number of nine found at a rate of " + str(nineRatio) + "percent\n"
            + str(sumCount)
            + ": total odd numbers found at a rate of " + str(totalRatio) + "percent\n")


text:
Q: DEP0700 : DEP0700: Registration of the app failed. [0x80073CFB] Un autre utilisateur a déjà installé une version décompressée de l'application I'm doing an UWP app sur Visual studio 2019. I have two accounts on my computer (administrator and user domain) so using tortoise git i recover my projet on my administrator session, because in my administrator session i have my database working fine!
the problem is that i have everything that i switch this exception when compiling:
Error       DEP0700: Registration of the app failed. [0x80073CFB] Un autre utilisateur a déjà installé une version décompressée de l'application. L'utilisateur actif ne peut pas la remplacer par une version en package. Le package entrant en conflit se nomme ab127c45-0836-43b5-8d70-97e15946afed et a été publié par CN=xxxxx.    RecupEnquete
How i can do to avoid this kind of problems??
Maybe my .gitignore file is not good? i use the generic gitignore file
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates

# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
[Gg]enerated Files/
x64/
x86/
build/
bld/
[Bb]in/
[Oo]bj/

# Visual Studo 2015 cache/options directory
.vs/

# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*

# NUNIT
*.VisualState.xml
TestResult.xml

# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c

*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc

# Chutzpah Test files
_Chutzpah*

# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb

# Visual Studio profiler
*.psess
*.vsp
*.vspx

# TFS 2012 Local Workspace
$tf/

# Guidance Automation Toolkit
*.gpState

# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user

# JustCode is a .NET coding addin-in
.JustCode

# TeamCity is a build add-in
_TeamCity*

# DotCover is a Code Coverage Tool
*.dotCover

# NCrunch
_NCrunch_*
.*crunch*.local.xml

# MightyMoose
*.mm.*
AutoTest.Net/

# Web workbench (sass)
.sass-cache/

# Installshield output folder
[Ee]xpress/

# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html

# Click-Once directory
publish/

# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj

# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config

# Windows Azure Build Output
csx/
*.build.csdef

# Microsoft Store app package directory
AppPackages/

# Others
*.[Cc]ache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
bower_components/

# RIA/Silverlight projects
Generated_Code/

# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm

# SQL Server files
*.mdf
*.ldf

# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings

# Microsoft Fakes
FakesAssemblies/

# Node.js Tools for Visual Studio
.ntvs_analysis.dat

# Visual Studio 6 build log
*.plg

# Visual Studio 6 workspace options file
*.opt

# Files generated by samples with custom Direct2D effects
*.fxlib

# Custom ignores
gallery.xml
project.lock.json

Thanks in advance for your help


text:
Q: CSS, vertical delimeter between inline-block buttons(links) I have few button and want to add vertical delimeter(separator) between 'Button 1' and 'Button 2'. I understand that can wrap my link in div with border:

but I want my links in one line. If I add another div it starts from another line..
Here is jsfiddle:
https://jsfiddle.net/Rockietm/dtnwmdho/
Here is what I want to get:

and here is code:

        Button 1
        Button 2
        Button 3

A: You can add :after to the button and style it to look like a border
#buttons > a:after {

       content:'';
       position:absolute;
       top: 0;
       right: -10px;
       height:100%;
       width: 1px;
       background: #000;

 }

 #buttons > a:last-child:after{
        width: 0;/*remove border from the last button*/
 }

See jsfiddle

A: Similar base for answer (pseudo + absolute) with a différent approach to complete @Chiller answer's.

#buttons>a:first-child~a:before {
  content: '';
  border-left: double gray;
  position: absolute;
  top: 0;
  bottom: 0;
  left: -12px;
}

}
#buttons {
  margin-bottom: 12px;
  height: 46px;
}
#buttons>a {
  color: black;
  padding: 10px;
  margin-right: 15px;
  margin-top: 2px;
  font-size: large;
  text-decoration: none;
  display: inline-block;
  position: relative;
}

/* button colors */
#buttonone {
  background-color: #DCDCDC;
}
#buttontwo {
  background-color: #C4E2F3;
}
#buttonthree {
  background-color: #B2F0C8;
}

  Button 1
  Button 2
  Button 3

https://jsfiddle.net/dtnwmdho/3/

A: Should help you:
#buttons> a:first-child:after  {
   border-right: 1px solid black;
   content: " ";
   position: relative;
   right: -20px ;
   padding: 10px 0;
}


text:
Q: Show Matrix array in table html with python I am new in python and I am trying to show a matrix array in a table, I have my code in jQuery but I don't know how to do the same code to python, this is my code:

$('#tb').ready(
    function() {
    console.log('table loaded');
    var ar = [["1","3","22","7"],["2","4","6","8"],["3","66","16","9"],["3322","1112","2222","1231"]];
    for(var j=0;j<ar.length;j++){
      $('#tb').append('
');
      for(var k=0;k<ar.length;k++){
        $('#tb').append(''+
                          ''+
                            ar[k][j]+
                          ''+
                        '	');
      }
      $('#tb').append('
');
    }
});

Someone can help me?
Thanks in advance

A: Try this
ar = [["1","3","22","7"],["2","4","6","8"],["3","66","16","9"],["3322","1112","2222","1231"]]

html = """

{}

"""

r = ''
for x in range(len(ar)):
    r+=('
{}
'.format(
                        ''.join(["""{}	""".format(l[x]) for l in ar])))

html = html.format(r)

with open('table.html', 'w') as f:
    f.write(html)


text:
Q: Socket epoll: Will EPOLL_CTL_MOD reset the edge trigger? Start by adding a socket to an epoll set for edge triggered reading:
epoll_event ev = {};
ev.data.fd = sock;
ev.events = EPOLLIN | EPOLLET;   // edge triggered reading
epoll_ctl(efd, EPOLL_CTL_ADD, sock, &ev);

Now wait for data:
result = epoll_wait(efd, events, sizeEvents, timeoutMilliseconds);

Hypothetically, let's say there was 20+ bytes of data available.  But the subsequent code wants to parse messages off the stream in 10 byte chunks:
result = recv(sock, buffer, 10, 0);

So at this point, you're probably saying, "if he invokes epoll_wait, his code may hang or timeout even with the remaining 10 bytes in the socket stream that have yet to be read."  And you would be correct.
But instead of going back to epoll_wait, my code actually switches epoll flags so it can function for sending a response back on that same socket.
ev.data.fd = sock;
ev.events = EPOLLOUT|EPOLLET;
epoll_ctl(efd, EPOLL_CTL_MOD, sock, &ev);

Notice that EPOLLIN is no longer set.  Then the code does the standard loop of send and epoll_wait until the full response is sent.
When the message response has been set, the code goes back to reading in edge triggered mode:
 ev.data.fd = sock;
 ev.events = EPOLLIN | EPOLLET;
 epoll_ctl(efd, EPOLL_CTL_MOD, sock, &ev);

Followed by a wait:
 result = epoll_wait(efd, events, sizeEvents, timeoutMilliseconds);

Now assuming no additional data has arrived on sock since the last read off the socket, does the above epoll_wait hang (or timeout) since the edge level hasn't changed?  Or does the fact that EPOLLIN was toggled off and on again allow the edge state to be reset such that the above epoll_wait call would return immediately to indicate data available on the socket?


text:
Q: Difference between '\Z' and '\z' in java.util.regex.Pattern What is the difference between the JDK6 java.util.regex.Pattern's "Boundary matchers" '\z' and '\Z'?
Background: I was trying to read a UTF-8 encoded file's contents into a String. Came across this solution. I discovered that java.util.scanner.useDelimeter uses a java.util.regex.Pattern. The previously mentione solution proposes '\Z'.

A: According to http://docs.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html, the difference is that:
\Z  The end of the input but for the final terminator, if any
\z  The end of the input


text:
Q: ECMA CLI spec: initobj instruction description for value types The ECMA CLI spec has the following statement in the description for the initobj CLI instruction:
"If typeTok is a value type, then after this instruction is executed, the instance is ready for a constructor method to be called."
However, the following C# code (where S is a struct):
S s = default;
S s2 = new S();
S s3 = new S(5);

compiles to IL that looks something like this:
IL_0001: ldloca.s     s
IL_0003: initobj      S

IL_0009: ldloca.s     s2
IL_000b: initobj      S

IL_0011: ldloca.s     s3
IL_0013: ldc.i4.5
IL_0014: call         instance void S::.ctor(int32)

My question is, when would a compiler ever use initobj followed by calling the value type's constructor?

A:
If typeTok is a value type, then after this instruction is executed, the instance is ready for a constructor method to be called.

It means that a constructor can call a constructor after this instruction.
But, as you mentioned in the comments above there is no need to initialize the locals again before the constructor because of the localsinit flag on a method sig.

My question is, when would a compiler ever use initobj followed by calling the value type's constructor?

I can only find one case where I will require the compiler to use initobj, tell it not to use the localsinit flag.
As of this moment, SkipLocalsInitAttribute should help you reproduce the case, but the implementation of this compiler feature has not started.


text:
Q: Use of definite article before occupation I often see the definite article being omitted in texts about famous people. For instance:

Towards the end of his life, avant garde composer John Cage turned to visual art

But I also see that it is equally frequently not omitted:

In 1944 the avant-garde composer John Cage wrote "Four Walls," a 70-minute work using only the white keys of the piano

I am assuming that these are both valid. But why would you choose one over another? Is version 1 more "written" and version 2 more oral?
Edit: note that googling "by the avant garde composer John Cage" yields 3150 results and "by avant garde composer John Cage" yield 3760, so it's kind of inconclusive to say which is more common.

A: In the first sentence, John Cage moves from being 'avant garde composer' to 'turned to visual art'. Quite logically (I think) the description is applied to the man more loosely (that is, without the article) because the sense of the sentence is that said description is being weakened.
He is no longer just a composer, he is now also a visual artist.
In the second case, 'avant garde composer' defines the man John Cage who wrote the Four Walls composition. Therefore the definite article.

A: Well, the question was

But why would you choose one over another?

The general answer would be "for the same reasons as always with articles in English". That is, to communicate something.
Let's consider these chunks.
1. sailor Tom
2. Tom, the sailor
The second example implies that there might be another Tom, say, being a writer, with whom the sailor Tom should not be confused.
As mentioned in the other answer by Nigel J, your example is also "exact person vs title" emphasis case. And, as you can read following the link in the KarlG's comment, this also a matter of how to use false titles.


text:
Q: How to Comparable interface sort a List of Schema.DescribeFieldResult.getName() entries by many DescribeFieldResult properties? I use str to dynamically generate input fields on a visualforce page.  Unlike standard page layouts that come with a drag and drop layout editor, my page's positioning of input fields depends on the order of  str (page code not relevant here).
I populate and sort List<String> str using the following code:
SObjectType sObjectType = Schema.getGlobalDescribe().get('Opportunity');
Map<String,Schema.SObjectField> fields = sObjectType.getDescribe().fields.getMap();
List<String> str = new List<String>();

for(Schema.SObjectField sobjF : fields.values())
        {
            Schema.DescribeFieldResult fieldType = sobjF.getDescribe();
            if( !fieldType.isNillable() && fieldType.isAccessible()  )
                str.add(fieldType.getName());
        }
        str.sort();
        return str;

How do I replace my sort() method with a custom sort method, perhaps using Apex Comparable interface, such that str is sorted by multiple fieldType properties eg sorted by  fieldType.getType() ASC and fieldType.getLabel() ASC, rather than sorting by fieldType.getName()?   Note: I require fieldType.getName() values to comprise the str, but i am looking for ways to sort str by multiple Schema.DescribeFieldResult properties.
It would be great if someone could demonstrate how to use the Apex Comparable Interface so that the List str are sorted not by a basic str.sort() but instead by multiple fieldType properties fieldType.getType() ASC and also by fieldType.getLabel() ASC.  The answer that I'm working on would return 1 string "str" containing fieldType.getName() string values but those values would be sorted first by field type and also by field label.
UPDATE:
For a psuedo example, suppose that str.sort() return str returns these fieldType.getName() values:
{'a','d','e','f'}

The psuedo example   {'a','d','e','f'} reflects alphabetical ASC order (str.sort()) which is no good.  Instead I want to the same list elements sorted by datatype (fieldType.getType()) alpha ascending first, then label alpha ascending (fieldType.getLabel()), in other words i am looking for a way to sort str so that its ordering reflects  {'d','f','e','a'} if the getType() and getLabel() (pseudo) schema for those fieldTypes were:
'd' => checkbox, 'dogLabel'
'f' => checkbox, 'foxLabel'
'e'=> currency, 'earthwormLabel'
'a' => date, 'appleLabel'

Thanks everyone,


text:
Q: Using colormap in cycle (python) How to edit the for cycles under #ax5 and #ax6 to plot graphs in the same fashion? Now, the lower figure has no colour transit, as opposed to the upper one. The colour transit appears in the lower figure after increasing of dpi, however, some unwanted stuff also appears. Is there a scalling problem? Thank you

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
import math
fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [8, 8]

# Function for plotting parallels to curves
def get_parallels(length=.1):

    px, py = [], []

    for idx in range(len(x)-1):
        x0, y0, xa, ya = x[idx], y[idx], x[idx+1], y[idx+1]
        dx, dy = xa-x0, ya-y0
        norm = math.hypot(dx, dy) * 1/length
        dx /= norm
        dy /= norm
        px.append(x0-dy)
        py.append(y0+dx)
    return px, py

def offset(x,y, o):
    """ Offset coordinates given by array x,y by o """
    X = np.c_[x,y].T
    m = np.array([[0,-1],[1,0]])
    R = np.zeros_like(X)
    S = X[:,2:]-X[:,:-2]
    R[:,1:-1] = np.dot(m, S)
    R[:,0] = np.dot(m, X[:,1]-X[:,0])
    R[:,-1] = np.dot(m, X[:,-1]-X[:,-2])
    On = R/np.sqrt(R[0,:]**2+R[1,:]**2)*o
    Out = On+X
    return Out[0,:], Out[1,:]

dpi = 20

def offset_curve(ax, x,y, o):
    """ Offset array x,y in data coordinates
        by o in points """
    trans = ax.transData.transform
    inv = ax.transData.inverted().transform
    X = np.c_[x,y]
    Xt = trans(X)
    xto, yto = offset(Xt[:,0],Xt[:,1],o*dpi/72. )
    Xto = np.c_[xto, yto]
    Xo = inv(Xto)
    return Xo[:,0], Xo[:,1]

fig = plt.figure(constrained_layout=True)

gs = GridSpec(3, 6, figure=fig)
ax5 = fig.add_subplot(gs[1, 3:6])
ax6 = fig.add_subplot(gs[2, :3])
ax7 = fig.add_subplot(gs[2, 3:6])

cmap = plt.get_cmap('Greys_r')

# ax5
x = np.linspace(-1, 1, 100)
y = -x**2
ax5.set_ylim(-1.02, 0.3)
width_l = ax5.get_ylim()[1] - ax5.get_ylim()[0]
for t in np.linspace(0, 1, 40):
    length =  -0.1*width_l*t
    ax5.plot(*get_parallels(length=length), color=cmap(t/2 + 0.25))

# ax6
x = np.linspace(-3, 3, 100)
y = -(1/4*x**4 - 1.6*x**2)
ax6.plot(x, y)
ax6.set_xlim(ax6.get_xlim()[0]-0.5, ax6.get_xlim()[1]+0.5)
ax6.scatter(1/2*(ax6.get_xlim()[0] + ax6.get_xlim()[1]), 1.2, marker = 'o', s=900, facecolors='none')
lines = []
width_l = ax6.get_ylim()[1] - ax6.get_ylim()[0]
for t in np.linspace(0, 1, 40):
    l, = ax6.plot(x, y - t * 0.1 * width_l, color=cmap(t/2 + 0.25))
    lines.append(l)

def plot_rainbow(event=None):
    x0 = x
    y0 = y
    for i in range(len(lines)):
        xx, yy = offset_curve(ax, x0, y0, -width_l)
        lines[i].set_data(xx, yy)
        lines[i].set_linewidth(1.1*width_l)
        x0 = xx
        y0 = yy

plot_rainbow()
fig.canvas.mpl_connect("resize_event", plot_rainbow)
fig.canvas.mpl_connect("button_release_event", plot_rainbow)
plt.savefig('fig.pdf')


text:
Q: iOS Untrusted Developer error when testing app I am trying to make my own iOS applications by using Xcode 7 and iOS 9.0. I have successfully been able to install the app on my own iPod by following Xcode 7 develop for iOS without developer account however when I run the application I get this error:

I had a quick look in the Settings app but cannot find a way to allow this application that I made. How would I 'trust' this application running iOS 9?

A: Alternative way to fix this error:

*

*Open Xcode app on your Mac

*Navigate to Window > Devices

*Right click on your device > "Show Provisioning Profiles..." > and delete the profiles

*Delete the installed app on your device

*Now rebuild and install the app again

Note: In my case only "Settings > "General" > "Profiles" was shown instead of "Profiles & Device Management", and these steps solved the issue.

A: Enterprise and other certificates have to be manually trusted on iOS 9 when they didn't have to on iOS 8 and earlier.
On iOS 9 (and maybe others):

*

*Open the Settings app

*Open General

*Open Profiles (you won't see this until after the first profile is installed on an iOS device)

*Choose the affected profile and trust it

On iOS 15.7 (and maybe others):

*

*Open the Settings app

*Open General

*Open VPN & Device Management

*Choose the affected profile and trust it

If you don't see "Profiles & Device Management" then your device needs to reinstall the app or get the appropriate profile from MDM / other enrollment. Also, if your network or system blocks any outbound traffic to Apple servers for time sync, OCSP/CRL or notarization checks, you will see errors or potentially have other challenges to run apps.

A: On later versions (ios 14.4 and xcode 12.4) I've fixed with the following

*

*Open the Settings app

*Open General

*Open Device Management

*Click on Apple Develpment
From here you should be able to trust the app. :-)

A: There's a also Xcode solution for this problem.

*

*Open Xcode app on your Mac.

*Navigate to Window > Devices

*Select your device and delete the profiles.

*Delete the installed app on your device.

*Now rebuild the certificate and install the app again.

http://www.iphonehelping.com/7/how-to-fix-untrusted-enterprise-developer-error-ios-9-1

A: On iPad or iPhone using iOS 15.4.1:

*

*Select your device and build the project using XCode to the target device. "You will get the error here."

*After that open Settings.

*Find General.

*Seek VPN & Device Management section and open it.

*Click your iCloud account and trust it.

A: Might be a bit late, but to anyone still searching for a solution to this problem, I finally fixed it by turning on automatic date & time settings on the iPhone.
On your iPhone: Go to Settings  > General > Date & Time.
Then turn off and on again the "Set Automatically" setting.
For somme absurd and unknown reason that seemed to solve the problem, for me at least.
Hope it helps.
Note: I have an iPhone 7 with iOS 15.6 and i use xCode 13.4.1