问:
How can I programmatically wake up android device in Doze mode for running background processes
I have an application that runs in the background on Android device. The application  performs certain tasks which are scheduled from a control panel. Normally the tasks are performed when requested. However many times the device goes into Doze mode and the tasks are never executed.
I have tried using the PowerManager feature called wake-locks but the system ignores the wake-locks.

Doze Restrictions

Is there a way to programmatically disable Doze Mode for processing background tasks of this app but keep the screen off?


来源: stackexchange

问:
Django Show models.Model field only when a checkbox is checked
I want to add a custom in django, (i am using forms from models.Model to create it, already big parts of the code are made), that only pops up when a user selects a particular checkbox. For example a simple code like : Choose what area u want to calculate? Triangle, Rectangle etc. and whenever user Clicks on that particular checkbox (maybe a widget that is working onclick? i dont know how to set it up properly), under it will render options to add angles appear and sides :
first render:

Choose what area u want to calculate

Triangle (unchecked)

Rectangle (unchecked)

Square (unchecked)

etc.

we choose triangle and rectangle:

Triangle (checked):

a =

b =

c =

alpha =

beta =

gamma =

Rectangle (unchecked):

Square (checked):

anybody has any ideas what can I try to use to make it done?
Tried using some widgets, but could not set it up properly. Right now i just have different tabs to calculate some things that i want.

ContentLicense: CC BY-SA 4.0


问:
WebSocket connection to 'ws://localhost:9955/essence/fecf/maker-checker/notification/notify/272/ruxkoajx/websocket' failed:
We have a spring-boot application which runs on tomcat which has only back end server side code(Java). For the front end UI component runs on a different server and is connected to back end server through rest service calls.

On some event triggered on back end server, the back end server should be able to push some messages to the front end UI component through websockets.

As I do understand websockets are designed for duplex scenarios but for now we do not have a requirement of sending messages from front end UI component to back end server component.

So I tried designing our code as below to send messages from back end server component to the front end UI component.

Back end server side:

Added following piece of code to register stompclient and configure message broker,

```<code>@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/maker-checker/notification/topic");
    }
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/maker-checker/notification/ws").setAllowedOriginPatterns("*");
        registry.addEndpoint("/maker-checker/notification/ws").setAllowedOriginPatterns("*").withSockJS();
    }
}
</code>```

And I have created a Notifier class which will be called as a Java API by the events who wants to send messages to front end UI component.

```<code>@Service
public class WebSocketNotifier implements Notifier {
    private final SimpMessagingTemplate simpMessagingTemplate;

    public WebSocketNotifier(SimpMessagingTemplate simpMessagingTemplate) {
        this.simpMessagingTemplate = simpMessagingTemplate;
    }
    @Override
    public void send(String recipient, String message) {
        // TODO Auto-generated method stub
        NotificationMessage notificationMessage = new NotificationMessage(recipient, message);
         simpMessagingTemplate.convertAndSend("/maker-checker/notification/topic",
                 JsonHelper.getInstance().writeJsonValue(notificationMessage));
    }
}
</code>```

Front end UI component side

The client looks like,

```<code>var stompClient = null;

            function setConnected(connected) {

                document.getElementById('connect').disabled = connected;
                document.getElementById('disconnect').disabled = !connected;
                document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
                document.getElementById('response').innerHTML = '';
            }

            function connect() {

                var socket = new SockJS('http://localhost:9955/essence/fecf/maker-checker/notification/ws');
                stompClient = Stomp.over(socket);

                stompClient.connect({}, function(frame) {
                    setConnected(true);
                    console.log('Connected: ' + frame);
                    stompClient.subscribe('/maker-checker/notification/topic',
                    function(messageOutput) {
                        showMessageOutput(JSON.parse(messageOutput.body));
                    });
                });
            }
</code>```

But after doing this websocket connection is not being established, getting error
websocket.js:6 WebSocket connection to 'ws://localhost:9955/essence/fecf/maker-checker/notification/notify/272/ruxkoajx/websocket' failed:

Body:
We have a spring-boot application which runs on tomcat which has only back end server side code(Java). For the front end UI component runs on a different server and is connected to back end server through rest service calls.

On some event triggered on back end server, the back end server should be able to push some messages to the front end UI component through websockets.

As I do understand websockets are designed for duplex scenarios but for now we do not have a requirement of sending messages from front end UI component to back end server component.

So I tried designing our code as below to send messages from back end server component to the front end UI component.

Back end server side:

Added following piece of code to register stompclient and configure message broker,

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/maker-checker/notification/topic");
    }
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/maker-checker/notification/ws").setAllowedOriginPatterns("*");
        registry.addEndpoint("/maker-checker/notification/ws").setAllowedOriginPatterns("*").withSockJS();
    }
}

And I have created a Notifier class which will be called as a Java API by the events who wants to send messages to front end UI component.

@Service
public class WebSocketNotifier implements Notifier {
    private final SimpMessagingTemplate simpMessagingTemplate;

    public WebSocketNotifier(SimpMessagingTemplate simpMessagingTemplate) {
        this.simpMessagingTemplate = simpMessagingTemplate;
    }
    @Override
    public void send(String recipient, String message) {
        // TODO Auto-generated method stub
        NotificationMessage notificationMessage = new NotificationMessage(recipient, message);
         simpMessagingTemplate.convertAndSend("/maker-checker/notification/topic",
                 JsonHelper.getInstance().writeJsonValue(notificationMessage));
    }
}

Front end UI component side

The client looks like,

var stompClient = null;

            function setConnected(connected) {

                document.getElementById('connect').disabled = connected;
                document.getElementById('disconnect').disabled = !connected;
                document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
                document.getElementById('response').innerHTML = '';
            }

            function connect() {

                var socket = new SockJS('http://localhost:9955/essence/fecf/maker-checker/notification/ws');
                stompClient = Stomp.over(socket);

                stompClient.connect({}, function(frame) {
                    setConnected(true);
                    console.log('Connected: ' + frame);
                    stompClient.subscribe('/maker-checker/notification/topic',
                    function(messageOutput) {
                        showMessageOutput(JSON.parse(messageOutput.body));
                    });
                });
            }

But after doing this websocket connection is not being established, getting error
websocket.js:6 WebSocket connection to 'ws://localhost:9955/essence/fecf/maker-checker/notification/notify/272/ruxkoajx/websocket' failed:


问:
keydown event not recognizing the key pressed like keydown.right, keydown.left , keydown.up etc in vue3options api
event handling with options API, vue3 not working. When function is passed individually to window.addeventlistner it gets identified. I want key up, right, left, down to work.eg: @keydown="onkeydown",window.addeventlistner('keydown',this.onkeydown)
with this.onkeydown having all event functions.
code</p>


问:
Why does matplotlib draw `Title` artists over one another in an animation using `FuncAnimation` (but the same doesn't happen with a `plot`)?
Consider the following animation in python written in a file test.py

```<code>import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

fig, ax = plt.subplots()
title = fig.suptitle("Test _")

p, = ax.plot([0,2], [0,1])

def anim(i):
    title.set_text("Test %d" % i)
    p.set_data([np.random.rand(),i], [np.random.rand(),i])

ani = FuncAnimation(fig, anim, 10, blit=False)
plt.show()
</code>```

This works as expected when I run it from the command line python test.py and also from an interactive shell: a line segment with changing start and end point is animated.

Now let's set blit=True

```<code>import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mpl
import numpy as np
import time

fig, ax = plt.subplots()

p, = ax.plot([0,2], [0,1])

def init_func():
    return p,

def anim(i):
    p.set_data([np.random.rand(),i], [np.random.rand(),i])
    return p,

ani = FuncAnimation(fig, anim, 10, blit=True, init_func=init_func)
plt.show()
</code>```

This also works both on command line and interactive shell.

However, I would like to animate the title of the plot.

```<code>import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mpl
import numpy as np
import time

fig, ax = plt.subplots()
title = ax.set_title("Initial Title")

p, = ax.plot([0,2], [0,1])

def init_func():
    return p, title

def anim(i):
    title.set_text("3D Test %d" % i)
    p.set_data([np.random.rand(),i], [np.random.rand(),i])
    return p, title

ani = FuncAnimation(fig, anim, 100, blit=True, init_func=init_func)
plt.show()
</code>```

This almost works but it two things happen:

in interactive shell, the title stays fixed with "Initial Title". It doesn't update

from the command line, the titles do appear and update but they all overlap each other (there is apparently no erasing previous titles when redrawing the new ones).

As you can see, the plot itself doesn't have this issue.

Why does this happen only with the Title artist?

Finally consider the following variant of this code

```<code>import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mpl
import numpy as np
import time

fig, ax = plt.subplots()
title = ax.set_title("50")

p, = ax.plot([0,2], [0,1])

def init_func():
    return p,

def anim(i):
    title.set_text("3D Test %d" % i)
    p.set_data([np.random.rand(),i], [np.random.rand(),i])
    return p,

ani = FuncAnimation(fig, anim, 100, blit=True, init_func=init_func)
plt.show()
</code>```

Here we are calling title.set_text in each update function, but the title artist is not returned so as far as I know FuncAnimation does not consider it as an artist to redraw.

Nonetheless, what happens is that

from the command line the title does get updated but the plot is animated for a few frames and then disappears.

from the interactive shell, the title just stays stuck on the initial title but the plot does work.

What is happening here?

Body:
Consider the following animation in python written in a file test.py

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np

fig, ax = plt.subplots()
title = fig.suptitle("Test _")

p, = ax.plot([0,2], [0,1])

def anim(i):
    title.set_text("Test %d" % i)
    p.set_data([np.random.rand(),i], [np.random.rand(),i])

ani = FuncAnimation(fig, anim, 10, blit=False)
plt.show()

This works as expected when I run it from the command line python test.py and also from an interactive shell: a line segment with changing start and end point is animated.

Now let's set blit=True

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mpl
import numpy as np
import time

fig, ax = plt.subplots()

p, = ax.plot([0,2], [0,1])

def init_func():
    return p,

def anim(i):
    p.set_data([np.random.rand(),i], [np.random.rand(),i])
    return p,

ani = FuncAnimation(fig, anim, 10, blit=True, init_func=init_func)
plt.show()

This also works both on command line and interactive shell.

However, I would like to animate the title of the plot.

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mpl
import numpy as np
import time

fig, ax = plt.subplots()
title = ax.set_title("Initial Title")

p, = ax.plot([0,2], [0,1])

def init_func():
    return p, title

def anim(i):
    title.set_text("3D Test %d" % i)
    p.set_data([np.random.rand(),i], [np.random.rand(),i])
    return p, title

ani = FuncAnimation(fig, anim, 100, blit=True, init_func=init_func)
plt.show()

This almost works but it two things happen:

in interactive shell, the title stays fixed with "Initial Title". It doesn't update

from the command line, the titles do appear and update but they all overlap each other (there is apparently no erasing previous titles when redrawing the new ones).

As you can see, the plot itself doesn't have this issue.

Why does this happen only with the Title artist?

Finally consider the following variant of this code

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib as mpl
import numpy as np
import time

fig, ax = plt.subplots()
title = ax.set_title("50")

p, = ax.plot([0,2], [0,1])

def init_func():
    return p,

def anim(i):
    title.set_text("3D Test %d" % i)
    p.set_data([np.random.rand(),i], [np.random.rand(),i])
    return p,

ani = FuncAnimation(fig, anim, 100, blit=True, init_func=init_func)
plt.show()

Here we are calling title.set_text in each update function, but the title artist is not returned so as far as I know FuncAnimation does not consider it as an artist to redraw.

Nonetheless, what happens is that

from the command line the title does get updated but the plot is animated for a few frames and then disappears.

from the interactive shell, the title just stays stuck on the initial title but the plot does work.

What is happening here?


问:
talend thmap get value of outer loop element
I'm just starting out with thMap.
So far I have successfully mapped an X12 835 message to output structures.  That works no problem.

I have also successfully acquired the LoopIndex of the current loop using the LoopIndex() function.

My challenge:
I need to get the value of an element from the enclosing loop.

In the attached image, everything in green is working.
I'm trying to get the value down the red line.
My goal is to do this assignment

```<code>gsRecord.parent_id = enclosing loop isaRecord.id
</code>```

The documentation explains some things but I don't see examples putting it together.

Does anyone have any good examples, videos or suggestions?

Update from 12/9/22

Here is something I have tried.  Providing this example in hopes someone recognizes a specific issue to help move me forward.  Any input would be appreciated.

Per this screenshot

I am attempting to output in gsRecord.parent_id the loopIndex of the parent loop (isaRecord).

This gives me the following error

"An reference in an LoopIndex/Variable was made to an either an input
map element or an output map element that is not in the context of the
reference.  Use an enclosing looping output map element here.(msg #1202)"

Given the reference to 'enclosing looping output map element here' it feels like the gsRecord is not properly defined as a child of the isaRecord.
However the definition of the gsRecord is in reference to the isaRecord as in this screenshot.

It feels like there is some combination of LoopIndex and EnclosedContext that I could use to accomplish this but I'm unable to find any in-depth documentation on the functions.

Any help would be appreciated.

Body:
I'm just starting out with thMap.
So far I have successfully mapped an X12 835 message to output structures.  That works no problem.

I have also successfully acquired the LoopIndex of the current loop using the LoopIndex() function.

My challenge:
I need to get the value of an element from the enclosing loop.

In the attached image, everything in green is working.
I'm trying to get the value down the red line.
My goal is to do this assignment

gsRecord.parent_id = enclosing loop isaRecord.id

The documentation explains some things but I don't see examples putting it together.

Does anyone have any good examples, videos or suggestions?

Update from 12/9/22

Here is something I have tried.  Providing this example in hopes someone recognizes a specific issue to help move me forward.  Any input would be appreciated.

Per this screenshot

I am attempting to output in gsRecord.parent_id the loopIndex of the parent loop (isaRecord).

This gives me the following error

"An reference in an LoopIndex/Variable was made to an either an input
map element or an output map element that is not in the context of the
reference.  Use an enclosing looping output map element here.(msg #1202)"

Given the reference to 'enclosing looping output map element here' it feels like the gsRecord is not properly defined as a child of the isaRecord.
However the definition of the gsRecord is in reference to the isaRecord as in this screenshot.

It feels like there is some combination of LoopIndex and EnclosedContext that I could use to accomplish this but I'm unable to find any in-depth documentation on the functions.

Any help would be appreciated.


问:
google chrome extension not injecting html to the page
I am creating a chrome extension. It injects a chat to the page of the user choice.
It works on all websites I checked but does not on a specific one.
I have a component called , when I click the button to inject the chat in the Popup.html it sends console.log to the page, from that component, but the component is not being rendered for some reason.
That's the page https://p.priority-connect.online/webui/P3A3E/

I tried to render it on another websites and it worked well.
Created console.log inside the component and received result inside the website console but not a rendered component.

that's my manifest file

```<code>    {
  "manifest_version": 3,
  "name": "WhatsApp Chat",
  "description": "A chrome extension boilerplate built with React 17, Webpack 5, and Webpack Dev Server 4",
  "options_page": "options.html",
  "background": {
    "service_worker": "background.bundle.js"
  },
  "action": {
    "default_popup": "popup.html",
    "default_icon": "icon-34.png"
  },
  "icons": {
    "128": "icon-128.png"
  },
  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*",
        "<all_urls>"
      ],
      "js": [
        "contentScript.bundle.js"
      ],
      "css": [
        "content.styles.css"
      ]
    }
  ],
  "devtools_page": "devtools.html",
  "web_accessible_resources": [
    {
      "resources": [
        "content.styles.css",
        "icon-128.png",
        "icon-34.png",
        "assets/img/*"
      ],
      "matches": [
        "<all_urls>"
      ]
    }
  ]
}
</code>```

Body:
I am creating a chrome extension. It injects a chat to the page of the user choice.
It works on all websites I checked but does not on a specific one.
I have a component called , when I click the button to inject the chat in the Popup.html it sends console.log to the page, from that component, but the component is not being rendered for some reason.
That's the page https://p.priority-connect.online/webui/P3A3E/

I tried to render it on another websites and it worked well.
Created console.log inside the component and received result inside the website console but not a rendered component.

that's my manifest file

    {
  "manifest_version": 3,
  "name": "WhatsApp Chat",
  "description": "A chrome extension boilerplate built with React 17, Webpack 5, and Webpack Dev Server 4",
  "options_page": "options.html",
  "background": {
    "service_worker": "background.bundle.js"
  },
  "action": {
    "default_popup": "popup.html",
    "default_icon": "icon-34.png"
  },
  "icons": {
    "128": "icon-128.png"
  },
  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*",
        "<all_urls>"
      ],
      "js": [
        "contentScript.bundle.js"
      ],
      "css": [
        "content.styles.css"
      ]
    }
  ],
  "devtools_page": "devtools.html",
  "web_accessible_resources": [
    {
      "resources": [
        "content.styles.css",
        "icon-128.png",
        "icon-34.png",
        "assets/img/*"
      ],
      "matches": [
        "<all_urls>"
      ]
    }
  ]
}


问:
Calculate the half-maximal inhibitory concentration IC50
I have a task to create my own code to find IC50 with given in advance C, v1, H, n, and V function. I managed to create the following code:

```<code># added inhibitor value
C=c(0,0.3,1.5,3.5,19.5)

# compline inhibitor results vector percentages
v1 = c (0.00, 0.00, 0.00, 0.25, 0.90)

v1 = v1 + runif(length(v1), min = -0.1, max = 0.1)

# H and n values
H = 1
n = 1

# Define the V() function
V <- function(C, H, n) {
  1 / (1 + (C / H)^n)
}

# Define the x_dense2 vector
x_dense2 = seq(0, 10, by = 0.1)

y_spa2 = V(C, H, n)
# Generate random noise and add it to the observed response values
v1 = v1 + runif(length(v1), min = -0.1, max = 0.1)

# Interpolate the noisy data using linear interpolation
y_dense2 = approx(v1, y_spa2, xout = x_dense2, method = "linear")$y

# Find the x-coordinate where y_dense2 first crosses 0.5
x_cross = x_dense2[which(y_dense2 <= 0.5)[1]]

# The x-coordinate is the IC50 value
IC50 = x_cross

# Plot the interpolated curve
plot(x_dense2, y_dense2, type = "l")

# Add a vertical line at the IC50 value
abline(v = IC50, col = "green")
</code>```

My code gives some results but I'm not sure if it's correct. I don't know how to test it any other way. I have no other data for the IC50. That's why I am asking for help in testing my code and possibly correcting errors if there are any in my code.

Body:
I have a task to create my own code to find IC50 with given in advance C, v1, H, n, and V function. I managed to create the following code:

# added inhibitor value
C=c(0,0.3,1.5,3.5,19.5)

# compline inhibitor results vector percentages
v1 = c (0.00, 0.00, 0.00, 0.25, 0.90)

v1 = v1 + runif(length(v1), min = -0.1, max = 0.1)

# H and n values
H = 1
n = 1

# Define the V() function
V <- function(C, H, n) {
  1 / (1 + (C / H)^n)
}

# Define the x_dense2 vector
x_dense2 = seq(0, 10, by = 0.1)

y_spa2 = V(C, H, n)
# Generate random noise and add it to the observed response values
v1 = v1 + runif(length(v1), min = -0.1, max = 0.1)

# Interpolate the noisy data using linear interpolation
y_dense2 = approx(v1, y_spa2, xout = x_dense2, method = "linear")$y

# Find the x-coordinate where y_dense2 first crosses 0.5
x_cross = x_dense2[which(y_dense2 <= 0.5)[1]]

# The x-coordinate is the IC50 value
IC50 = x_cross

# Plot the interpolated curve
plot(x_dense2, y_dense2, type = "l")

# Add a vertical line at the IC50 value
abline(v = IC50, col = "green")

My code gives some results but I'm not sure if it's correct. I don't know how to test it any other way. I have no other data for the IC50. That's why I am asking for help in testing my code and possibly correcting errors if there are any in my code.


问:
Multithreaded Java job deadlock on DB insert
I am experiencing deadlock when running newly implemented job. I'll try to insert all minimum relevant parts of the code

Job

```<code>    final BlockingQueue<Runnable> BLOCKING_QUEUE = new ArrayBlockingQueue<>(10);
    final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(10, 10, 60, TimeUnit.HOURS, BLOCKING_QUEUE, new BlockWhenQueueFull());

    protected void doExecute() {
        records = service.getBatchRecordsToProcess(batchSize); // Load 500 records from DB by main thread
            for (Record record: records) {
                EXECUTOR.execute(() -> { // Take thread out of pool and make it process the record
                    service.processRecord(record);
                });
            }
        }
    }

    class BlockWhenQueueFull implements RejectedExecutionHandler {
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                Thread.sleep(200); // If all threads are busy then put main thread to sleep and after 200 ms try once again
            } catch (InterruptedException interruptedException) {
                LOGGER.debug(interruptedException.getMessage(), interruptedException);
            }
            executor.execute(r);
        }
    }
</code>```

Service

```<code>    public List<Record> getBatchRecordsToProcess(int batchSize) {
        return dao.getRecordsToProcess(batchSize);
    }

    public void processRecord(Record record) {
        processContent(record);
        writeToFs(record);
        markAsProcessed(record);
    }

    public void processContent(Record record) {
        // business logic
        NewRecord newRecord = new NewRecord(record);
        dao.insertNewRecord(newRecord);
    }

    private synchronized void writeToFs(Record record) throws IOException {
        // Create folders and files on FS and write there contents
    }

    private void markAsProcessed(Record record) {
        dao.markRecordAsProcessed(record);
    }
</code>```

DAO

```<code>    @Transactional(readOnly = true)
    public List<Record> getRecordsToProcess(int batchSize) {
        return jdbcTemplate.query(SELECT_BATCH,
                new Object[]{batchSize},
                new RecordMapper());
    }

    @Transactional
    public void insertNewRecord(NewRecord newRecord) {
        jdbcTemplate.update(
                INSERT_NEW_RECORD,
                newRecord.getDate(),
                // values
        );
    }

    @Transactional
    public void markRecordAsProcessed(Record record) {
        jdbcTemplate.update(UPDATE_PROCESSED, record.getId());
    }
</code>```

Thread Dump

First state applies for all 10 Threads.

```<code>"pool-2-thread-10@8925" prio=5 tid=0x44 nid=NA waiting for monitor entry
  java.lang.Thread.State: BLOCKED
     waiting for main@1 to release lock on <0x27c9> (a java.util.concurrent.ConcurrentHashMap)
     ...
     at com.dao.NewRecordDao$$EnhancerBySpringCGLIB$$ec63bd65.insertContent(<generated>:-1)

"main@1" prio=5 tid=0x1 nid=NA sleeping
  java.lang.Thread.State: TIMED_WAITING
      at java.lang.Thread.sleep(Thread.java:-1)
      at com.job.BlockWhenQueueFull.rejectedExecution(Job.java:130) *pointing to Thread.sleep(200);
      at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
          at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
          at com.job.BlockWhenQueueFull.rejectedExecution(Job.java:134) *pointing to executor.execute(r);

</code>```

After the execution the job processes usually couple thousands of records and gets stuck - the main Thread just waits via RejectedExecutionHandler because all worker Threads are stuck. It looks like the worker threads are locked on newRecordDao.insertContent(newRecord); but the table does not have any foreign keys and no table is referencing columns in this table. Index is just on PK.

The question is - Is it possible to get a deadlock on Oracle table when multiple threads are concurrently inserting data (NewRecords), but no reads / updates are performed on this table? The table does not have generated PK - records are inserted with id in a random order (source table has tens of million of records so I do not want to perform costly ordering because of performance). Isolation level appears to be READ COMMITTED.

Is it required for method which writes onto filesystem (tmpfs / xfs) to be synchronized?

Initially I thought it would be problem of synced method for writing to filesystem but if I get the Thread Dump right it is an issue with insert into DB. I have no idea why should the DB inserts be the problem in this case.

Body:
I am experiencing deadlock when running newly implemented job. I'll try to insert all minimum relevant parts of the code

Job

    final BlockingQueue<Runnable> BLOCKING_QUEUE = new ArrayBlockingQueue<>(10);
    final ThreadPoolExecutor EXECUTOR = new ThreadPoolExecutor(10, 10, 60, TimeUnit.HOURS, BLOCKING_QUEUE, new BlockWhenQueueFull());

    protected void doExecute() {
        records = service.getBatchRecordsToProcess(batchSize); // Load 500 records from DB by main thread
            for (Record record: records) {
                EXECUTOR.execute(() -> { // Take thread out of pool and make it process the record
                    service.processRecord(record);
                });
            }
        }
    }

    class BlockWhenQueueFull implements RejectedExecutionHandler {
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                Thread.sleep(200); // If all threads are busy then put main thread to sleep and after 200 ms try once again
            } catch (InterruptedException interruptedException) {
                LOGGER.debug(interruptedException.getMessage(), interruptedException);
            }
            executor.execute(r);
        }
    }

Service

    public List<Record> getBatchRecordsToProcess(int batchSize) {
        return dao.getRecordsToProcess(batchSize);
    }

    public void processRecord(Record record) {
        processContent(record);
        writeToFs(record);
        markAsProcessed(record);
    }

    public void processContent(Record record) {
        // business logic
        NewRecord newRecord = new NewRecord(record);
        dao.insertNewRecord(newRecord);
    }

    private synchronized void writeToFs(Record record) throws IOException {
        // Create folders and files on FS and write there contents
    }

    private void markAsProcessed(Record record) {
        dao.markRecordAsProcessed(record);
    }

DAO

    @Transactional(readOnly = true)
    public List<Record> getRecordsToProcess(int batchSize) {
        return jdbcTemplate.query(SELECT_BATCH,
                new Object[]{batchSize},
                new RecordMapper());
    }

    @Transactional
    public void insertNewRecord(NewRecord newRecord) {
        jdbcTemplate.update(
                INSERT_NEW_RECORD,
                newRecord.getDate(),
                // values
        );
    }

    @Transactional
    public void markRecordAsProcessed(Record record) {
        jdbcTemplate.update(UPDATE_PROCESSED, record.getId());
    }

Thread Dump

First state applies for all 10 Threads.

"pool-2-thread-10@8925" prio=5 tid=0x44 nid=NA waiting for monitor entry
  java.lang.Thread.State: BLOCKED
     waiting for main@1 to release lock on <0x27c9> (a java.util.concurrent.ConcurrentHashMap)
     ...
     at com.dao.NewRecordDao$$EnhancerBySpringCGLIB$$ec63bd65.insertContent(<generated>:-1)

"main@1" prio=5 tid=0x1 nid=NA sleeping
  java.lang.Thread.State: TIMED_WAITING
      at java.lang.Thread.sleep(Thread.java:-1)
      at com.job.BlockWhenQueueFull.rejectedExecution(Job.java:130) *pointing to Thread.sleep(200);
      at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
          at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
          at com.job.BlockWhenQueueFull.rejectedExecution(Job.java:134) *pointing to executor.execute(r);

After the execution the job processes usually couple thousands of records and gets stuck - the main Thread just waits via RejectedExecutionHandler because all worker Threads are stuck. It looks like the worker threads are locked on newRecordDao.insertContent(newRecord); but the table does not have any foreign keys and no table is referencing columns in this table. Index is just on PK.

The question is - Is it possible to get a deadlock on Oracle table when multiple threads are concurrently inserting data (NewRecords), but no reads / updates are performed on this table? The table does not have generated PK - records are inserted with id in a random order (source table has tens of million of records so I do not want to perform costly ordering because of performance). Isolation level appears to be READ COMMITTED.

Is it required for method which writes onto filesystem (tmpfs / xfs) to be synchronized?

Initially I thought it would be problem of synced method for writing to filesystem but if I get the Thread Dump right it is an issue with insert into DB. I have no idea why should the DB inserts be the problem in this case.


问:
Vuejs3 show Bootstrap5 modal
I am trying to display a bootstrap modal in Vue3

```<code>import { Modal } from 'bootstrap';
mounted() {
 var galleryModal = new Modal(document.getElementById('waitingModal'));
 galleryModal.show();
}
<div class="modal fade" tabindex="-1" role="dialog" id="waitingModal">
    <div class="modal-dialog modal-dialog-centered justify-content-center" role="document">
        <span class="fa fa-spinner fa-spin fa-3x"></span>
    </div>
</div>
</code>```

But it always gives me this error

Uncaught (in promise) TypeError: Cannot read properties of undefined
(reading 'backdrop')

Title: Vuejs3 show Bootstrap5 modal

Body:
I am trying to display a bootstrap modal in Vue3

import { Modal } from 'bootstrap';
mounted() {
 var galleryModal = new Modal(document.getElementById('waitingModal'));
 galleryModal.show();
}

But it always gives me this error

Uncaught (in promise) TypeError: Cannot read properties of undefined
(reading 'backdrop')


问:
How to create integration tests for worker services in Node.js
I have a Node.js app that runs as a worker service in an infinite loop to perform regular tasks.
It connects to two different APIs and a MySQL database.
I created a mock server for both APIs and I have a SQL script to create a ready database image for the desired tests.

So, the idea is to test the App with the actual connections to the database and to the mock server for the APIs.

For a web app, there's Cypress. For an app like this, how is it done?


问:
Error:Update Sonarlint local storage for connection "localhost"
I am running sonarqube container in docker but when I am trying to bind my project in eclipse it gives the follwing error;
Update Sonarlint local storage for connection 'localhost' has encountered a problem.
An internal error occured during "Update sonarlint local storage for connection 'localhost'".

I have tried with all the permissions in sonarqube that won't wored.
How can I resolve this issue?


问:
DecodeError: Error parsing message with type 'tensorflow.GraphDef' - while saving tensorflow retrieval model
I am trying to load weights from an epoch checkpoint while training a Tensorflow Recommenders Deep Retrieval model and then save the model.
When trying to save the model, it gives the following error:

```<code>[libprotobuf ERROR google/protobuf/wire_format_lite.cc:581] String field 'tensorflow.TensorShapeProto.Dim.name' contains invalid UTF-8 data when parsing a protocol buffer. Use the 'bytes' type if you intend to send raw bytes.
---------------------------------------------------------------------------
DecodeError                               Traceback (most recent call last)
/tmp/ipykernel_8016/3029885622.py in <module>
      1 brute_model.save(destination_path)

/opt/conda/lib/python3.7/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     68             # To get the full stack trace, call:
     69             # `tf.debugging.disable_traceback_filtering()`
---> 70             raise e.with_traceback(filtered_tb) from None
     71         finally:
     72             del filtered_tb

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in _as_graph_def(self, from_version, add_shapes)
   3525           data = pywrap_tf_session.TF_GetBuffer(buf)
   3526       graph = graph_pb2.GraphDef()
-> 3527       graph.ParseFromString(compat.as_bytes(data))
   3528       # Strip the experimental library field iff it's empty.
   3529       if not graph.library.function:

DecodeError: Error parsing message with type 'tensorflow.GraphDef'
</code>```

Here, brute_model is the index generated by tfrs.layers.factorized_top_k.BruteForce(query_model).index_from_dataset(tf.data.Dataset.zip((unique_labels.batch(50), unique_labels.batch(50).map(candidate_model))))

Body:
I am trying to load weights from an epoch checkpoint while training a Tensorflow Recommenders Deep Retrieval model and then save the model.
When trying to save the model, it gives the following error:

[libprotobuf ERROR google/protobuf/wire_format_lite.cc:581] String field 'tensorflow.TensorShapeProto.Dim.name' contains invalid UTF-8 data when parsing a protocol buffer. Use the 'bytes' type if you intend to send raw bytes.
---------------------------------------------------------------------------
DecodeError                               Traceback (most recent call last)
/tmp/ipykernel_8016/3029885622.py in <module>
      1 brute_model.save(destination_path)

/opt/conda/lib/python3.7/site-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     68             # To get the full stack trace, call:
     69             # `tf.debugging.disable_traceback_filtering()`
---> 70             raise e.with_traceback(filtered_tb) from None
     71         finally:
     72             del filtered_tb

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in _as_graph_def(self, from_version, add_shapes)
   3525           data = pywrap_tf_session.TF_GetBuffer(buf)
   3526       graph = graph_pb2.GraphDef()
-> 3527       graph.ParseFromString(compat.as_bytes(data))
   3528       # Strip the experimental library field iff it's empty.
   3529       if not graph.library.function:

DecodeError: Error parsing message with type 'tensorflow.GraphDef'

Here, brute_model is the index generated by tfrs.layers.factorized_top_k.BruteForce(query_model).index_from_dataset(tf.data.Dataset.zip((unique_labels.batch(50), unique_labels.batch(50).map(candidate_model))))


问:
Center a container row on bootstrap
I read online that you can use the below code to center a row in a container using bootstrap, but I haven't been able to get it to work and I think it might have something to do with the css.

Below is the current code. There was no .portfolio in the template and it won't let me add it.

.portfolio #portfolio-flters {
  padding: 0;
  width: 50%;
  margin: auto;
  list-style: center;
  text-align: center;
  border-radius: 50px;
}

.portfolio #portfolio-flters li {
  cursor: pointer;
  display: inline-block;
  padding: 10px 15px;
  font-size: 15px;
  font-weight: 500;
  line-height: 1;
  text-transform: uppercase;
  color: #444444;
  width: 50%;
  margin: auto;
  margin-bottom: 5px;
  transition: all 0.3s ease-in-out;
  font-family: "Poppins", sans-serif;
}

.portfolio #portfolio-flters li:hover,
.portfolio #portfolio-flters li.filter-active {
  color: #593d4a;
}

.portfolio #portfolio-flters li:last-child {
  margin-right: 0;
}

.portfolio .portfolio-item {
  margin-bottom: 30px;
}

.portfolio .portfolio-item .portfolio-info {
  opacity: 0;
  position: absolute;
  left: 30px;
  right: 30px;
  margin: auto;
  width: 20%;
  text-align: center;
  bottom: 0;
  z-index: 3;
  transition: all ease-in-out 0.3s;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px;
}

.portfolio .portfolio-item .portfolio-info h4 {
  font-size: 12px;
  color: #fff;
  font-weight: 600;
  color: #191919;
}

.portfolio .portfolio-item .portfolio-info p {
  color: #4c4c4c;
  font-size: 14px;
  margin-bottom: 0;
}

.portfolio .portfolio-item .portfolio-info .preview-link,
.portfolio .portfolio-item .portfolio-info .details-link {
  position: absolute;
  right: 40px;
  font-size: 24px;
  top: calc(50% - 18px);
  color: #333333;
}

.portfolio .portfolio-item .portfolio-info .preview-link:hover,
.portfolio .portfolio-item .portfolio-info .details-link:hover {
  color: #593d4a;
}

.portfolio .portfolio-item .portfolio-info .details-link {
  right: 10px;
}

.portfolio .portfolio-item .portfolio-links {
  opacity: 0;
  left: 0;
  right: 0;
  text-align: center;
  z-index: 3;
  position: absolute;
  transition: all ease-in-out 0.3s;
}

.portfolio .portfolio-item .portfolio-links a {
  color: #fff;
  margin: 0 2px;
  font-size: 28px;
  display: inline-block;
  transition: 0.3s;
}

.portfolio .portfolio-item .portfolio-links a:hover {
  color: #593d4a;
}

.portfolio .portfolio-item:hover .portfolio-info {
  opacity: 1;
  bottom: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
<section id="dataviz/wordclouds" class="portfolio">
  <p></p>
  <div class="container">
    <h3>Word Clouds</h3>

    <div class="portfolio-container" data-aos="fade-up" data-aos-delay="150">
      <div class="row justify-content-center">
        <div class="col-lg-4 portfolio-item filter-wc">
          <img src="https://via.placeholder.com/300x100" class="img-fluid" alt="">
          <div class="portfolio-info">
            <h4>20 Nov</h4>
          </div>
        </div>

        <div class="col-lg-4 portfolio-item filter-wc">
          <img src="https://via.placeholder.com/300x100" class="img-fluid" alt="">
          <div class="portfolio-info">
            <h4>21 Nov</h4>
          </div>
        </div>

        <div class="col-lg-4 portfolio-item" filter-wc>
          <img src="https://via.placeholder.com/300x100" class="img-fluid" alt="">
          <div class="portfolio-info">
            <h4>22 Nov</h4>
          </div>
        </div>

        <div class="col-lg-4 portfolio-item filter-wc">
          <img src="https://via.placeholder.com/300x100" class="img-fluid" alt="">
          <div class="portfolio-info">
            <h4>23 Nov</h4>
          </div>
        </div>

        <div class="col-lg-4 portfolio-item filter-wc">
          <img src="https://via.placeholder.com/300x100" class="img-fluid" alt="">
          <div class="portfolio-info">
            <h4>24 Nov</h4>
          </div>
        </div>
      </div>
    </div>
</section></code>```

And this is an image of the problem, the last row isn't centered:

Thank you so much in advance for the help!

Title: Center a container row on bootstrap

Body:
I read online that you can use the below code to center a row in a container using bootstrap, but I haven't been able to get it to work and I think it might have something to do with the css.

Below is the current code. There was no .portfolio in the template and it won't let me add it.

.portfolio #portfolio-flters {
  padding: 0;
  width: 50%;
  margin: auto;
  list-style: center;
  text-align: center;
  border-radius: 50px;
}

.portfolio #portfolio-flters li {
  cursor: pointer;
  display: inline-block;
  padding: 10px 15px;
  font-size: 15px;
  font-weight: 500;
  line-height: 1;
  text-transform: uppercase;
  color: #444444;
  width: 50%;
  margin: auto;
  margin-bottom: 5px;
  transition: all 0.3s ease-in-out;
  font-family: "Poppins", sans-serif;
}

.portfolio #portfolio-flters li:hover,
.portfolio #portfolio-flters li.filter-active {
  color: #593d4a;
}

.portfolio #portfolio-flters li:last-child {
  margin-right: 0;
}

.portfolio .portfolio-item {
  margin-bottom: 30px;
}

.portfolio .portfolio-item .portfolio-info {
  opacity: 0;
  position: absolute;
  left: 30px;
  right: 30px;
  margin: auto;
  width: 20%;
  text-align: center;
  bottom: 0;
  z-index: 3;
  transition: all ease-in-out 0.3s;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px;
}

.portfolio .portfolio-item .portfolio-info h4 {
  font-size: 12px;
  color: #fff;
  font-weight: 600;
  color: #191919;
}

.portfolio .portfolio-item .portfolio-info p {
  color: #4c4c4c;
  font-size: 14px;
  margin-bottom: 0;
}

.portfolio .portfolio-item .portfolio-info .preview-link,
.portfolio .portfolio-item .portfolio-info .details-link {
  position: absolute;
  right: 40px;
  font-size: 24px;
  top: calc(50% - 18px);
  color: #333333;
}

.portfolio .portfolio-item .portfolio-info .preview-link:hover,
.portfolio .portfolio-item .portfolio-info .details-link:hover {
  color: #593d4a;
}

.portfolio .portfolio-item .portfolio-info .details-link {
  right: 10px;
}

.portfolio .portfolio-item .portfolio-links {
  opacity: 0;
  left: 0;
  right: 0;
  text-align: center;
  z-index: 3;
  position: absolute;
  transition: all ease-in-out 0.3s;
}

.portfolio .portfolio-item .portfolio-links a {
  color: #fff;
  margin: 0 2px;
  font-size: 28px;
  display: inline-block;
  transition: 0.3s;
}

.portfolio .portfolio-item .portfolio-links a:hover {
  color: #593d4a;
}

.portfolio .portfolio-item:hover .portfolio-info {
  opacity: 1;
  bottom: 20px;
}

<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">

Word Clouds

20 Nov

21 Nov

22 Nov

23 Nov

24 Nov

And this is an image of the problem, the last row isn't centered:

Thank you so much in advance for the help!


问:
Maven copy dependencies working correct in windows but not in linux
I have spring boot project which uses thin jar plugin to copy dependencies. I am copying all the dependencies in one folder. I was not getting any class not found error before as jars were present in respective folder. It was working both in windows and linux. I updated spring boot version to 2.7.5. While building in windows all jars are present in form of thin jars. No error. But while building in linux jar from repository is not getting copy to respective folder. for e.g spring-context-support jar is missing in /org/springframework/spring-context-support/5.3.24/ location.
In maven repository this jars is present. But in linux while copying to common folder only pom is getting copied. So I am getting class not found error.
But in windows its working correctly.

I cross check setting.xml. But still not able to point what is happening.


问:
Why am I getting this error with add_patch()?
I am trying to create a rectangle that will cover the extremas of my graphs. 'peak_index' is the location of the peaks, and they will mark the peaks with 'x'. However, I would like to create shaded rectangles around them to show tolerances for my project. However, I keep getting this error. I will show the part of my code producing the error below. I tried re-installing the libraries, using '.gcaadd_patch(), and not using the list of left,bottom, etc. Nothing works, so I guess I don't understand the issue. Can yall help?

TypeError: 'int' object is not subscriptable

```<code>    fig, ax = plt.subplots(nrows=4, ncols=1, figsize=(10, 15))

    ax[0].plot(plot_data.index, vlwf, color='green', label='VLWf')
    ax[0].set_title('Vertical Load Waveform')
    ax[0].set_ylabel('N')
    ax[0].plot(plot_data.index, iso_max, color='red', label='ISO Max')
    ax[0].plot(plot_data.index, iso_min, color='red', label='ISO Min')
    ax[0].legend()
    ax[0].plot(peak_index, vlwf[peak_index], "x")
    ax[0].plot(axoccur_concern, vlwf[axoccur_concern], "o", color='red')
    ax_zero = ax[0]
    for i in peak_index:
        left, bottom, width, height = (i-30,vlwf[peak_index]-0.05*vlwf[peak_index]-0.05, 60, vlwf[peak_index]+0.05*vlwf[peak_index]-0.05)
        rect = mpatches.Rectangle((left,bottom),width,height,
                                  alpha = 0.1,
                                  facecolor = 'red')
        ax_zero.add_patch(rect)
</code>```

Body:
I am trying to create a rectangle that will cover the extremas of my graphs. 'peak_index' is the location of the peaks, and they will mark the peaks with 'x'. However, I would like to create shaded rectangles around them to show tolerances for my project. However, I keep getting this error. I will show the part of my code producing the error below. I tried re-installing the libraries, using '.gcaadd_patch(), and not using the list of left,bottom, etc. Nothing works, so I guess I don't understand the issue. Can yall help?

TypeError: 'int' object is not subscriptable

    fig, ax = plt.subplots(nrows=4, ncols=1, figsize=(10, 15))

    ax[0].plot(plot_data.index, vlwf, color='green', label='VLWf')
    ax[0].set_title('Vertical Load Waveform')
    ax[0].set_ylabel('N')
    ax[0].plot(plot_data.index, iso_max, color='red', label='ISO Max')
    ax[0].plot(plot_data.index, iso_min, color='red', label='ISO Min')
    ax[0].legend()
    ax[0].plot(peak_index, vlwf[peak_index], "x")
    ax[0].plot(axoccur_concern, vlwf[axoccur_concern], "o", color='red')
    ax_zero = ax[0]
    for i in peak_index:
        left, bottom, width, height = (i-30,vlwf[peak_index]-0.05*vlwf[peak_index]-0.05, 60, vlwf[peak_index]+0.05*vlwf[peak_index]-0.05)
        rect = mpatches.Rectangle((left,bottom),width,height,
                                  alpha = 0.1,
                                  facecolor = 'red')
        ax_zero.add_patch(rect)


问:
A code trying to find winners of an election in each year, state and district only those who won by a margin of 5%
It looks like this code is trying to find the winners of an election in each year, state, and district, only including those who won by a margin of 5% or less.

Im trying to create a code that finds the winners an election in each year, state and district, only including those who won by a margin of 5% or less. I have created the following code but repeatedly get error, and i cant seem to understand why. Can someone please help me understand what im doing wrong? :)

```<code>tab_relevant %>%
  group_by(year, state, district) %>%
  {
    if (tab_relevant$candidatevotes/tab_relevant$totalvotes <= 0.05) {
      slice_max(tab_relevant$candidatevotes)
    } else {
      return(FALSE)
    }
  } -> winner

</code>```

Body:
It looks like this code is trying to find the winners of an election in each year, state, and district, only including those who won by a margin of 5% or less.

Im trying to create a code that finds the winners an election in each year, state and district, only including those who won by a margin of 5% or less. I have created the following code but repeatedly get error, and i cant seem to understand why. Can someone please help me understand what im doing wrong? :)

tab_relevant %>%
  group_by(year, state, district) %>%
  {
    if (tab_relevant$candidatevotes/tab_relevant$totalvotes <= 0.05) {
      slice_max(tab_relevant$candidatevotes)
    } else {
      return(FALSE)
    }
  } -> winner


问:
use grep and cut command to get output of each line in next line
```<code>$ cat hello.txt
shreenivasa hi hello this is test mail
shreenivasa how are you man
</code>```

if i run in terminal

```<code>$ cat hello.txt | grep shreenivasa | cut -d ' ' -f 2-
</code>```

its giving following output

```<code>hi hello this is test mail
how are you man
</code>```

but if i write it as script in hello.sh like below

```<code>#!/bin/bash
hi=`cat hello.txt | grep shreenivasa | cut -d ' ' -f 2-`
echo $hi
</code>```

output for ./hello.sh is

```<code>hi hello this is test mail how are you man.
</code>```

I want to print "how are you man" in next line
like

```<code>hi hello this is test mail
how are you man
</code>```

tried $hi\n didn't work

Body:
$ cat hello.txt
shreenivasa hi hello this is test mail
shreenivasa how are you man

if i run in terminal

$ cat hello.txt | grep shreenivasa | cut -d ' ' -f 2-

its giving following output

hi hello this is test mail
how are you man

but if i write it as script in hello.sh like below

#!/bin/bash
hi=`cat hello.txt | grep shreenivasa | cut -d ' ' -f 2-`
echo $hi

output for ./hello.sh is

hi hello this is test mail how are you man.

I want to print "how are you man" in next line
like

hi hello this is test mail
how are you man

tried $hi\n didn't work


问:
MySQL returns 'BLOB' data instead 'abcd' string
Return BLOB instead 'abcd'
When I'm studying SQL by MySQL Server. In 'Learning SQL' book, this query will return 'abcd'.Mine is 'BLOB' instead.

I tried to search Google but I didn't find my problem I need. How can I solve this?


问:
How to write a efficient POJO Serializer with field renaming in Flink?
I am in the process of writing a new Flink job that ingests JSON data from a Kafka source. I am "stuck" with using Flink 1.15.2. But apart from this very free. I would like to stick to the DataStream API, mostly of a learning experience.

My data looks like this:

```<code>{ "SomeField": 123, "someOtherField": 4554, "another_different_field": 34543}
</code>```

As you can see there are multiple different naming schemas present. Inside of my Flink job and further downstream I would like to clean this up. But how to do this efficiently? Create my own POJOSerializer?

Or just the type hints? E.g. something like this:

```<code>public class MyDataTypeInfoFactory extends TypeInfoFactory<MyData> {
  @Override
  public TypeInformation<MyData> createTypeInfo(
      Type t, Map<String, TypeInformation<?>> genericParameters) {
    return Types.POJO(MyData.class, new HashMap<>(...)); // some code here?
  }
}
</code>```

Or go with JSONKeyValueDeserializationSchema and then map the objects?

Any pointers?

Body:
I am in the process of writing a new Flink job that ingests JSON data from a Kafka source. I am "stuck" with using Flink 1.15.2. But apart from this very free. I would like to stick to the DataStream API, mostly of a learning experience.

My data looks like this:

{ "SomeField": 123, "someOtherField": 4554, "another_different_field": 34543}

As you can see there are multiple different naming schemas present. Inside of my Flink job and further downstream I would like to clean this up. But how to do this efficiently? Create my own POJOSerializer?

Or just the type hints? E.g. something like this:

public class MyDataTypeInfoFactory extends TypeInfoFactory<MyData> {
  @Override
  public TypeInformation<MyData> createTypeInfo(
      Type t, Map<String, TypeInformation<?>> genericParameters) {
    return Types.POJO(MyData.class, new HashMap<>(...)); // some code here?
  }
}

Or go with JSONKeyValueDeserializationSchema and then map the objects?

Any pointers?


问:
React Typescript - Odd ESLint Error: "ESLint: Unsafe assignment of an `any` value."
Code I'm getting this error on:

(value: Partial<IColumnTypes>) => {value.link_text}

ONLY in the href attr is value (the object) underlined red saying "ESLint: Unsafe assignment of an any value." while the property "link_href" and value.link_text is not underlined.

The types:

interface IColumnTypes extends ILink, IRecordValue {}
type Partial<T> = { [A in keyof T]?: T[A]

This is confusing because I'm only getting this error when I have ILink, IRecordValue exported from a .d.ts file and I DO NOT get this error when I include these interfaces directly in the components file instead of importing them.

Anyone know what's going on? Thanks!


问:
Pinia Stores not running as expected on my desktop but run fine on my laptop
I work with a team that use Pinia for state management across a Vue ( & vuetify ) application, everything works fine on their machines and on my laptop. However, when I am using my desktop pinia doesn't seem to work and I am certain that I've set up the application the same way on both devices,I've even re-setup the env on my desktop multiple times.

When I load an application on my laptop I see  "currentUser" store installed  and I am able to access it as expected with no issues, the Pinia tab appears in my Vue devtools too.

When I load the application on my desktop I do not see a 'store installed' prompt and everything is passed as a ref __v_isRef: true but the Pinia tab still appears in my Vue devtools...

If I console.log() a value in the store I get the response I'd expect but, when I console.log() a variable in the store on my desktop I get the following:

{
  value: false,
  __V_isRef: true,
  get value: function value(){},
  set value: function value(){},
}```
</div>
</div>
</p>
<p>Now for another spanner, the code below works perfectly fine if I run it in something like codepen leading me to think its something with node / vue / vuetify, how could I check if it is?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    const useCounterStore = Pinia.defineStore('counter', {
      state() {
        return {
          value: 0
        }
      },
      actions: {
        increment(state) {
          this.value++
        },
      }
    })

    Vue.use(Pinia.PiniaVuePlugin)
    new Vue({
        el: '#app',
        vuetify: new Vuetify(),
        pinia: Pinia.createPinia(),
        computed: {
          ...Pinia.mapState(useCounterStore, ['value'])
        },
        methods: {
          ...Pinia.mapActions(useCounterStore, ['increment', 'incrementBugged'])
        },
    })</code>```

<!DOCTYPE html>

    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.x/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">

    <v-app>
        <v-main>
            <v-container>Count is: {{ value }}</v-container>
            <button @click="increment">Click here, works on both my desktop and laptop</button>
        </v-main>
    </v-app>

```

Please LMK if you need any additional information :)

Body:
I work with a team that use Pinia for state management across a Vue ( & vuetify ) application, everything works fine on their machines and on my laptop. However, when I am using my desktop pinia doesn't seem to work and I am certain that I've set up the application the same way on both devices,I've even re-setup the env on my desktop multiple times.

When I load an application on my laptop I see  "currentUser" store installed  and I am able to access it as expected with no issues, the Pinia tab appears in my Vue devtools too.

When I load the application on my desktop I do not see a 'store installed' prompt and everything is passed as a ref __v_isRef: true but the Pinia tab still appears in my Vue devtools...

If I console.log() a value in the store I get the response I'd expect but, when I console.log() a variable in the store on my desktop I get the following:

{
  value: false,
  __V_isRef: true,
  get value: function value(){},
  set value: function value(){},
}

Now for another spanner, the code below works perfectly fine if I run it in something like codepen leading me to think its something with node / vue / vuetify, how could I check if it is?

    const useCounterStore = Pinia.defineStore('counter', {
      state() {
        return {
          value: 0
        }
      },
      actions: {
        increment(state) {
          this.value++
        },
      }
    })

    Vue.use(Pinia.PiniaVuePlugin)
    new Vue({
        el: '#app',
        vuetify: new Vuetify(),
        pinia: Pinia.createPinia(),
        computed: {
          ...Pinia.mapState(useCounterStore, ['value'])
        },
        methods: {
          ...Pinia.mapActions(useCounterStore, ['increment', 'incrementBugged'])
        },
    })

<!DOCTYPE html>

    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@6.x/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">

    <v-app>
        <v-main>
            <v-container>Count is: {{ value }}</v-container>
            <button @click="increment">Click here, works on both my desktop and laptop</button>
        </v-main>
    </v-app>

Please LMK if you need any additional information :)


问:
While using Windows Form application, unable to save first record to sql database, while subsequent record is being saved
I am practicing Windows Form application. Using Group box to enable all the textbox after clicking Add new button. When i click the save button, I am unable to save the first record, while the subsequent record is being saved. I am using  tableadaptor, bindingsource to connect and update table and dataset.

my SQL database has ID as a primary key and marked as identity with auto increment. When I click

```<code>private void save_btn_Click(object sender, EventArgs e)
{
    try
    {
        this.bindingSource1.EndEdit();
        //-----------------------------
        int r;
        r=this.sa_In_LettersTableAdapter1.Update(this.letters1.Sa_In_Letters);
        if (r > 0)
        {
            System.Windows.Forms.MessageBox.Show(r.ToString()+" Recored is Saved.");
        }
        else
        {
            System.Windows.Forms.MessageBox.Show("Sorry! Recored is not Saved.");
        }

    }
    catch (Exception ex)
    {

        System.Windows.Forms.MessageBox.Show("Error :" + ex.Message);
    }

    enable_add_edit_delete_btn();
}
</code>```

Body:
I am practicing Windows Form application. Using Group box to enable all the textbox after clicking Add new button. When i click the save button, I am unable to save the first record, while the subsequent record is being saved. I am using  tableadaptor, bindingsource to connect and update table and dataset.

my SQL database has ID as a primary key and marked as identity with auto increment. When I click

private void save_btn_Click(object sender, EventArgs e)
{
    try
    {
        this.bindingSource1.EndEdit();
        //-----------------------------
        int r;
        r=this.sa_In_LettersTableAdapter1.Update(this.letters1.Sa_In_Letters);
        if (r > 0)
        {
            System.Windows.Forms.MessageBox.Show(r.ToString()+" Recored is Saved.");
        }
        else
        {
            System.Windows.Forms.MessageBox.Show("Sorry! Recored is not Saved.");
        }

    }
    catch (Exception ex)
    {

        System.Windows.Forms.MessageBox.Show("Error :" + ex.Message);
    }

    enable_add_edit_delete_btn();
}


问:
SSL for company internal Intranet (.NET Core Razor)
I set up a local Intranet site for our company on a new web server running IIS 10. I did this using .NET Core Razor pages where I get the logged on Windows user and grant/deny access based on their User ID being in specific Active Directory groups via SQL ADSI queries.

I issued a self-signed certificate which was working just fine until the recent Chrome update which no longer accepts my self-signed cert. The cert still works in Edge. Most of what I find for Chrome is a work-around telling people to just type, "thisisunsafe", which works but is not a valid solution.
The only other info I can find is advice to get the 3rd party SSL cert, even though all of this is behind our firewall. I did this, and that's not working either.

I don't understand why I can't use a self-signed cert for my own internal site. What is the best practice to manage the security for an Internal company intranet and the cert process needed?


问:
Rails GraphQL path mount differently for public and private query/mutations
I have a Ruby on Rails app and I have integrated Graphql. As I saw on the documentation we have to mount it to a controller that will handle query and mutations.

I currently have two controllers. One that require authorization (for private query/mutations that require an authenticated user) and another one to handle public mutations like (signup).

I want to create two routes for my GraphQL ide. So far I have been serving my private query/mutations to the endpoint /graphiql.

I want to create another one, like /graphiql/public that will serve my public query/mutations

```<code>mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "graphql"
post "/graphql", to: "graphql#execute"
</code>```

And I also want to add something like:

```<code>mount GraphiQL::Rails::Engine, at: "/graphiql/public", graphql_path: "/graphql/public"
post "/graphql/public", to: "graphql#execute_public"
</code>```

Rails does not let me mount GraphiQL::Rails::Engine two times becasue it gets confused which one to use.

Please help me how to handle this situation.

Body:
I have a Ruby on Rails app and I have integrated Graphql. As I saw on the documentation we have to mount it to a controller that will handle query and mutations.

I currently have two controllers. One that require authorization (for private query/mutations that require an authenticated user) and another one to handle public mutations like (signup).

I want to create two routes for my GraphQL ide. So far I have been serving my private query/mutations to the endpoint /graphiql.

I want to create another one, like /graphiql/public that will serve my public query/mutations

mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "graphql"
post "/graphql", to: "graphql#execute"

And I also want to add something like:

mount GraphiQL::Rails::Engine, at: "/graphiql/public", graphql_path: "/graphql/public"
post "/graphql/public", to: "graphql#execute_public"

Rails does not let me mount GraphiQL::Rails::Engine two times becasue it gets confused which one to use.

Please help me how to handle this situation.


问:
Form Data missing on Microsoft Edge on iPhones
I have a java web application which works well on all devices, all browsers except for Microsoft Edge on iPhones. On Edge on iPhones, as the user fills in the input fields and proceeds to the next page, all data except for the date fields get lost. This problem doesn't occur all the time. Sometimes, all information is saved properly and nothing gets lost. Has anyone faced similar issue? Is there a way to get developer tools in Edge on iPhones to debug and see if anything comes up?</p>


问:
variable not recognised when plotting graph
I have a user input function to extract 3 rows of data from a table and assigned this data to the variable 'all_sectors'. When I try to use this variable to plot the data on a bar chart it comes up with the following error message:

Unrecognized function or variable 'all_sectors'.

Error in train_fares_script (line 36)
y = all_sectors ;

My code to select the data is:

```<code>if year == 2004
    all_sectors = readmatrix("train_fares.xlsx",'sheet','2004','range','A1:A3')
elseif year == 2005
    year = 2005
    all_sectors = readmatrix("train_fares.xlsx",'sheet','2005','range','A1:A3')
</code>```

My code to plot this on a bar graph is:

x = categorical({'London and South East','Long Distance','Regional'});
y = all_sectors ;
bar(x,y)
How can I fix this so the variable is recognised?

Ive tried copying and pasting the variable name to ensure it is spelled correctly and changed the name to see if that would work but it hasn't.

Body:
I have a user input function to extract 3 rows of data from a table and assigned this data to the variable 'all_sectors'. When I try to use this variable to plot the data on a bar chart it comes up with the following error message:

Unrecognized function or variable 'all_sectors'.

Error in train_fares_script (line 36)
y = all_sectors ;

My code to select the data is:

if year == 2004
    all_sectors = readmatrix("train_fares.xlsx",'sheet','2004','range','A1:A3')
elseif year == 2005
    year = 2005
    all_sectors = readmatrix("train_fares.xlsx",'sheet','2005','range','A1:A3')

My code to plot this on a bar graph is:

x = categorical({'London and South East','Long Distance','Regional'});
y = all_sectors ;
bar(x,y)
How can I fix this so the variable is recognised?

Ive tried copying and pasting the variable name to ensure it is spelled correctly and changed the name to see if that would work but it hasn't.


问:
Request consent for iOS in Flutter
I want to request consent using UMP SDK in iOS app. I followed this article. In short, I did following.

main.dart:

```<code>void main() {
  requestConsent();
  MobileAds.instance.initialize();
  runApp(const MyApp());
  ...
}

void requestConsent() {
  final params = ConsentRequestParameters();
  ConsentInformation.instance.requestConsentInfoUpdate(
    params,
    () async {
      if (await ConsentInformation.instance.isConsentFormAvailable()) {
        loadForm();
      }
    },
    (error) {});
}

void loadForm() {
   ConsentForm.loadConsentForm((consentForm) async {
     var status = await ConsentInformation.instance.getConsentStatus();
     if (status == ConsentStatus.required) {
       consentForm.show((formError) {
         loadForm();
       });
     }
  },
  (formError) {});
}
</code>```

The consent is working as expected. The dialog window is displayed (in fact, two dialog windows in iOS - consent and app tracking). My question is, how to set non-personalized ads in case consent is not given? The documentation is really brief in this topic:

final AdRequest = AdRequest(nonPersonalizedAds: true);

Where to find the information, whether the user gave consent to display PA/NPA? In loadConsentForm(), there is ConsentStatus.obtained only, but this only tells me that user submitted the consent form, not the result. Thank you for any help or guidance.

Title: Request consent for iOS in Flutter

Body:
I want to request consent using UMP SDK in iOS app. I followed this article. In short, I did following.

main.dart:

void main() {
  requestConsent();
  MobileAds.instance.initialize();
  runApp(const MyApp());
  ...
}

void requestConsent() {
  final params = ConsentRequestParameters();
  ConsentInformation.instance.requestConsentInfoUpdate(
    params,
    () async {
      if (await ConsentInformation.instance.isConsentFormAvailable()) {
        loadForm();
      }
    },
    (error) {});
}

void loadForm() {
   ConsentForm.loadConsentForm((consentForm) async {
     var status = await ConsentInformation.instance.getConsentStatus();
     if (status == ConsentStatus.required) {
       consentForm.show((formError) {
         loadForm();
       });
     }
  },
  (formError) {});
}

The consent is working as expected. The dialog window is displayed (in fact, two dialog windows in iOS - consent and app tracking). My question is, how to set non-personalized ads in case consent is not given? The documentation is really brief in this topic:

final AdRequest = AdRequest(nonPersonalizedAds: true);

Where to find the information, whether the user gave consent to display PA/NPA? In loadConsentForm(), there is ConsentStatus.obtained only, but this only tells me that user submitted the consent form, not the result. Thank you for any help or guidance.


问:
How to display only one route with a waypoint using Google Map API Kotlin Android
I'm trying to draw a route from a source point (lat/lng) to a destination point (lat/lng) with 1 waypoint (lat/lng) using Google Map API for Kotlin Android. I have the code working to display the route without a waypoint (first image), however, when I try to route with a waypoint, I'm being shown two routes (second image). With one route being the correct route incorporating the waypoint and the other route ignoring all roads (which I want to remove). I've pasted my code for the getDirectionsURL function below as well.

Google Map Without Waypoint

Google Map With Waypoint

Get Directions Function Code

Origin coordinate: 36.2360317,-89.7556867
Waypoint coordinate: 38.509135,-90.625198
Destination coordinate: 38.629709,-90.405355

I tried to use the GetDirectionsUrl function to display a route with a waypoint. When I executed the code, I got the route to display with the waypoint but there is a second route displayed that ignores all roads (that I want to remove).

I'm not sure what's causing the error when mapping with a waypoint so any help would be appreciated!


问:
Golang GSheet get range of cells where cell is blank for a given column and update them with value
I am trying to fetch a gsheet detail where there are 3 columns say column A, B and C.

```<code>   A    B    C
0  1    2    3
1  4    5    6
2  7    8
3  9    10
4  11   12
</code>```

Here I need to fetch data from row no. 2 till the end where the column C value is blank along with row indexes.

```<code>readRange := "Sheet1!A:C"
   resp1, err := srv.Spreadsheets.Values.Get(spreadsheetId, readRange).Do()
    if err != nil {
        log.Fatalf("Unable to retrieve data from sheet: %v", err)
    }
    if len(resp1.Values) == 0 {
        fmt.Println("No data found.")
    } else {
        for _, row := range resp1.Values {
            fmt.Printf("%s, %s\n", row[0], row[1])
        }
    }
</code>```

So how can I apply filter here in Golang to get the rows from row no.2 where column C value is blank.
And later update those cells with some value.

Body:
I am trying to fetch a gsheet detail where there are 3 columns say column A, B and C.

   A    B    C
0  1    2    3
1  4    5    6
2  7    8
3  9    10
4  11   12

Here I need to fetch data from row no. 2 till the end where the column C value is blank along with row indexes.

readRange := "Sheet1!A:C"
   resp1, err := srv.Spreadsheets.Values.Get(spreadsheetId, readRange).Do()
    if err != nil {
        log.Fatalf("Unable to retrieve data from sheet: %v", err)
    }
    if len(resp1.Values) == 0 {
        fmt.Println("No data found.")
    } else {
        for _, row := range resp1.Values {
            fmt.Printf("%s, %s\n", row[0], row[1])
        }
    }

So how can I apply filter here in Golang to get the rows from row no.2 where column C value is blank.
And later update those cells with some value.


问:
Nested queries in sqlalchemy
I have the following python code

```<code>>>> p = select(PurchaseLine.id).where(PurchaseLine.purchase_id == Purchase.id)
</code>```

which produces the following SQL when executing:

```<code>>>> print(p)
SELECT purchase_lines.id
FROM purchase_lines, purchases
WHERE purchase_lines.purchase_id = purchases.id
</code>```

I want to use p in another query but because sqlalchemy produces the two tables in the from clause, the SQL code does not work. This code:

```<code>SELECT purchase_lines.id
FROM purchase_lines
WHERE purchase_lines.purchase_id = purchases.id
</code>```

works perfectly when writing raw SQL on the console. This select statement works as a correlated subquery. How can I remove one of the two tables that SQLAlchemy produces?

Title: Nested queries in sqlalchemy

Body:
I have the following python code

>>> p = select(PurchaseLine.id).where(PurchaseLine.purchase_id == Purchase.id)

which produces the following SQL when executing:

>>> print(p)
SELECT purchase_lines.id
FROM purchase_lines, purchases
WHERE purchase_lines.purchase_id = purchases.id

I want to use p in another query but because sqlalchemy produces the two tables in the from clause, the SQL code does not work. This code:

SELECT purchase_lines.id
FROM purchase_lines
WHERE purchase_lines.purchase_id = purchases.id

works perfectly when writing raw SQL on the console. This select statement works as a correlated subquery. How can I remove one of the two tables that SQLAlchemy produces?


问:
Tinymodels' step_unknown is not carried over in after tuning
I use step_unknown as a quick imputation method for missing values by assigning them as a new level - 'unknown'. I expect that after training the workflow, the recipe should be fully estimated and ready to be applied for the test set. Factor variables with missing values in the test set should be recoded with the new 'unknown' level. However, this is not true as can be seen in the following toy example:

var x2 contains missing value and it is not recoded as 'unknown'. hence, the random forest model (ranger) coerces these into NA.

Set up toy dataset

```<code>set.seed(135)
df <- data.frame(
  x1 = rnorm(100),
  x2 = base::sample(c('a','b','c','d'), 100, replace = T),
  y = base::sample(c('p','n'), size = 100, replace = T)
)

na_idx <- replicate(2,sample(c(0,1),100, replace =T, prob = c(0.9,0.2)))

df$x1[na_idx[,1]==1] = NA
df$x2[na_idx[,2]==1] = NA

colSums(is.na(df))

df_split <-  initial_split(df, strata = y)
df_train <- training(df_split)
df_test <- testing(df_split)

# Set fold
df_fold <- vfold_cv(df_train, v = 5)
</code>```

Set up recipe with step_unknown

```<code>base_rec <- recipe(y ~ x1 + x2,
                 data = df) %>%
  step_meanimpute(all_numeric(), -all_outcomes()) %>%
  step_unknown(-all_outcomes(), -all_numeric())
</code>```

A quick look of the recipe after prep(). It detects missing values in var x2 and recoded them as "unknow"

```<code>> base_rec %>% prep()
Data Recipe

Inputs:

      role #variables
   outcome          1
 predictor          2

Training data contained 100 data points and 29 incomplete rows.

Operations:

Mean Imputation for x1 [trained]
Unknown factor level assignment for x2 [trained]
</code>```

**Set up random forest model and workflow **

```<code># Set engine
rf_eng <- rand_forest(
  mtry = tune(),
  trees = 500,
  min_n = tune(),
  mode = 'classification'
  ) %>%
  set_engine('ranger', importance = 'impurity')

# Set wf
wflow_rf <-
  workflow() %>%
  add_model(rf_eng) %>%
  add_recipe(base_rec)
</code>```

Tuning

```<code>tune_res <- tune_grid(
  wflow_rf,
  resamples = df_fold,
  grid = 2,
  metrics = metric_set(accuracy,roc_auc,f_meas),
  control = control_grid(verbose = T)
)
</code>```

Result indicates that in fold 2, missing values in var x2 were not recoded as "unknow" and they were considered as novel levels

```<code>> tune_res$.notes
[[1]]
# A tibble: 0 x 1
# … with 1 variable: .notes <chr>

[[2]]
# A tibble: 2 x 1
  .notes
  <chr>
1 model 1/2 (predictions): Novel levels found in column 'x2': NA. The levels have been removed, and values have been coerced to 'NA'.
2 model 2/2 (predictions): Novel levels found in column 'x2': NA. The levels have been removed, and values have been coerced to 'NA'.
</code>```

A quick check of fold 2 training data and test data. we see that NA exist in training data. Hence, the recipe should pick up this and recode x2 for the test data of fold2. However, it seems to ignore it

Training data

```<code>> df_fold$splits$`2`$data %>%
+     slice(df_fold$splits$`2`$in_id) %>%
+     select(x2) %>%
+     table(useNA = 'ifany')
.
   a    b    c    d <NA>
  14   18   11   11    7
</code>```

Test data

```<code>> df_fold$splits$`2`$data %>%
+     slice(-df_fold$splits$`2`$in_id) %>%
+     select(x2) %>%
+     table(useNA = 'ifany')
.
   a    b    c    d <NA>
   3    5    2    0    5
</code>```
```<code></code>```

Body:
I use step_unknown as a quick imputation method for missing values by assigning them as a new level - 'unknown'. I expect that after training the workflow, the recipe should be fully estimated and ready to be applied for the test set. Factor variables with missing values in the test set should be recoded with the new 'unknown' level. However, this is not true as can be seen in the following toy example:

var x2 contains missing value and it is not recoded as 'unknown'. hence, the random forest model (ranger) coerces these into NA.

Set up toy dataset

set.seed(135)
df <- data.frame(
  x1 = rnorm(100),
  x2 = base::sample(c('a','b','c','d'), 100, replace = T),
  y = base::sample(c('p','n'), size = 100, replace = T)
)

na_idx <- replicate(2,sample(c(0,1),100, replace =T, prob = c(0.9,0.2)))

df$x1[na_idx[,1]==1] = NA
df$x2[na_idx[,2]==1] = NA

colSums(is.na(df))

df_split <-  initial_split(df, strata = y)
df_train <- training(df_split)
df_test <- testing(df_split)

# Set fold
df_fold <- vfold_cv(df_train, v = 5)

Set up recipe with step_unknown

base_rec <- recipe(y ~ x1 + x2,
                 data = df) %>%
  step_meanimpute(all_numeric(), -all_outcomes()) %>%
  step_unknown(-all_outcomes(), -all_numeric())

A quick look of the recipe after prep(). It detects missing values in var x2 and recoded them as "unknow"

> base_rec %>% prep()
Data Recipe

Inputs:

      role #variables
   outcome          1
 predictor          2

Training data contained 100 data points and 29 incomplete rows.

Operations:

Mean Imputation for x1 [trained]
Unknown factor level assignment for x2 [trained]

**Set up random forest model and workflow **

# Set engine
rf_eng <- rand_forest(
  mtry = tune(),
  trees = 500,
  min_n = tune(),
  mode = 'classification'
  ) %>%
  set_engine('ranger', importance = 'impurity')

# Set wf
wflow_rf <-
  workflow() %>%
  add_model(rf_eng) %>%
  add_recipe(base_rec)

Tuning

tune_res <- tune_grid(
  wflow_rf,
  resamples = df_fold,
  grid = 2,
  metrics = metric_set(accuracy,roc_auc,f_meas),
  control = control_grid(verbose = T)
)

Result indicates that in fold 2, missing values in var x2 were not recoded as "unknow" and they were considered as novel levels

> tune_res$.notes
[[1]]
# A tibble: 0 x 1
# … with 1 variable: .notes <chr>

[[2]]
# A tibble: 2 x 1
  .notes
  <chr>
1 model 1/2 (predictions): Novel levels found in column 'x2': NA. The levels have been removed, and values have been coerced to 'NA'.
2 model 2/2 (predictions): Novel levels found in column 'x2': NA. The levels have been removed, and values have been coerced to 'NA'.

A quick check of fold 2 training data and test data. we see that NA exist in training data. Hence, the recipe should pick up this and recode x2 for the test data of fold2. However, it seems to ignore it

Training data

> df_fold$splits$`2`$data %>%
+     slice(df_fold$splits$`2`$in_id) %>%
+     select(x2) %>%
+     table(useNA = 'ifany')
.
   a    b    c    d <NA>
  14   18   11   11    7

Test data

> df_fold$splits$`2`$data %>%
+     slice(-df_fold$splits$`2`$in_id) %>%
+     select(x2) %>%
+     table(useNA = 'ifany')
.
   a    b    c    d <NA>
   3    5    2    0    5


问:
Cannot login using OKTA on Posit workbench running on Kubernetes
It is my understanding that Posit workbench needs a home folder for any user for the login to work. However, I can't manually create a new user and would like to automate this process. I am thinking that I need to create a new user and add the home directory for any user that logs in using pam and sssd. Here is my OKTA integration

```<code>server:
    rserver.conf:
      server-health-check-enabled: 1
      auth-pam-sessions-enabled: 1
      admin-enabled: 1
      www-port: 8787
      server-project-sharing: 1
      launcher-address: 127.0.0.1
      launcher-port: 5559
      launcher-sessions-enabled: 1
      launcher-default-cluster: Kubernetes
      monitor-graphite-enabled: 1
      monitor-graphite-host: 127.0.0.1
      monitor-graphite-port: 9109
      monitor-graphite-client-id: rstudio
      server-shared-storage-path: /home/posit-wb-shared-storage
      auth-saml: 1
      auth-saml-metadata-url: <my metadata url>
      auth-saml-sp-attribute-username: NameID
</code>```

There are some areas where I think I can implement this which are

config.startupUserProvisioning

config.userProvisioning

config.pam

I'm using the official posit workbench helm chart to deploy it on AWS EKS.

Body:
It is my understanding that Posit workbench needs a home folder for any user for the login to work. However, I can't manually create a new user and would like to automate this process. I am thinking that I need to create a new user and add the home directory for any user that logs in using pam and sssd. Here is my OKTA integration

server:
    rserver.conf:
      server-health-check-enabled: 1
      auth-pam-sessions-enabled: 1
      admin-enabled: 1
      www-port: 8787
      server-project-sharing: 1
      launcher-address: 127.0.0.1
      launcher-port: 5559
      launcher-sessions-enabled: 1
      launcher-default-cluster: Kubernetes
      monitor-graphite-enabled: 1
      monitor-graphite-host: 127.0.0.1
      monitor-graphite-port: 9109
      monitor-graphite-client-id: rstudio
      server-shared-storage-path: /home/posit-wb-shared-storage
      auth-saml: 1
      auth-saml-metadata-url: <my metadata url>
      auth-saml-sp-attribute-username: NameID

There are some areas where I think I can implement this which are

config.startupUserProvisioning

config.userProvisioning

config.pam

I'm using the official posit workbench helm chart to deploy it on AWS EKS.


问:
how can I generate a report for custom events for google analytics 4 report api?
I was using UA analytics like this before:

```<code>// javascript event
ga('set', 'dimension1', artist);
</code>```
```<code># Ruby report params
metric = Metric.new(expression: 'ga:hits')
dimension = Dimension.new(name: 'ga:dimension1')
order_by = OrderBy.new(field_name: 'ga:hits', sort_order: 'DESCENDING')
range = DateRange.new(start_date: '30daysAgo', end_date: 'yesterday')

# Report request
rr = ReportRequest.new
rr.view_id = VIEW_ID
rr.metrics = [metric]
rr.dimensions = [dimension]
rr.order_bys = [order_by]
rr.page_size = NUM_ARTISTS + 1
rr.date_ranges = [range]

grr = GetReportsRequest.new
grr.report_requests = [rr]

response = @client.batch_get_reports(grr)

</code>```

Then migrated to GA4:

```<code>// javascript event
gtag('event', 'artist', {
    'artist': artist
});
</code>```

I can see the GA4 website Reports > Engagement > Events the events collected.

```<code>Parameter Name
Artist
Parameter Value    Count
The Cure           3529
New Order          2480
...
</code>```

(numbers made up)

I am using the same json credentials file that I was using before.

How can I retrieve those values with the API report? I tried tweaking the params I had for UA but no results.

If I change my ruby code to this, it complaints with Google::Apis::ClientError (badRequest: Invalid value 'eventCount' for metric parameter.)

```<code>metric = Metric.new(expression: 'eventCount')
dimension = Dimension.new(name: 'customEvent:artist')
order_by = OrderBy.new(field_name: 'eventCount', sort_order: 'DESCENDING')
range = DateRange.new(start_date: "#{last_days+1}daysAgo", end_date: 'today')

# Report request
...
</code>```

And If I use the GA4 query explorer with:

```<code>Metrics: eventCount
Dimensions: customEvent:artist
Order by: eventCount desc
</code>```

I get this:

```<code>customEvent:artist  eventCount
(not set)           9962
</code>```

Body:
I was using UA analytics like this before:

// javascript event
ga('set', 'dimension1', artist);

# Ruby report params
metric = Metric.new(expression: 'ga:hits')
dimension = Dimension.new(name: 'ga:dimension1')
order_by = OrderBy.new(field_name: 'ga:hits', sort_order: 'DESCENDING')
range = DateRange.new(start_date: '30daysAgo', end_date: 'yesterday')

# Report request
rr = ReportRequest.new
rr.view_id = VIEW_ID
rr.metrics = [metric]
rr.dimensions = [dimension]
rr.order_bys = [order_by]
rr.page_size = NUM_ARTISTS + 1
rr.date_ranges = [range]

grr = GetReportsRequest.new
grr.report_requests = [rr]

response = @client.batch_get_reports(grr)

Then migrated to GA4:

// javascript event
gtag('event', 'artist', {
    'artist': artist
});

I can see the GA4 website Reports > Engagement > Events the events collected.

Parameter Name
Artist
Parameter Value    Count
The Cure           3529
New Order          2480
...

(numbers made up)

I am using the same json credentials file that I was using before.

How can I retrieve those values with the API report? I tried tweaking the params I had for UA but no results.

If I change my ruby code to this, it complaints with Google::Apis::ClientError (badRequest: Invalid value 'eventCount' for metric parameter.)

metric = Metric.new(expression: 'eventCount')
dimension = Dimension.new(name: 'customEvent:artist')
order_by = OrderBy.new(field_name: 'eventCount', sort_order: 'DESCENDING')
range = DateRange.new(start_date: "#{last_days+1}daysAgo", end_date: 'today')

# Report request
...

And If I use the GA4 query explorer with:

Metrics: eventCount
Dimensions: customEvent:artist
Order by: eventCount desc

I get this:

customEvent:artist  eventCount
(not set)           9962


问:
What is the best solution to make a simple FIFO python queue with FastAPI?
I have a project of API that is a simple queue of objects provided by REST.
The workflow is not very complex :

1 - The API receive a REST request : a JSON task containing 1 or more subtasks.

2 - The API insert these subtasks into the queue.

3 - The API take the first subtask of the queue, process it (it simply launch a Gitlab Pipeline on the project store in the subtask) and **wait for this task to finish ** before process the next subtask. It should be in order.

4 - When all subtasks are over, make a request on Jira to switch the status of task on finish.

If a subtask fall in error, all the task should be aborted, task status on error and pass to the next task.

I coded a program with FastAPI that uses a database with a combinaison of status and a table tasks and subtasks.
But I find this code very unreadable and the process of checking for new objects is really not friendly (it's not a simply .get() on a queue).

Moreover, it forces me to use a database when I do not store anything.

I look at Celery and other "queue framework" but they all seems to do asynchronous processing. My requirements are less complex and I require to stay in a synchronous way.

I was questionning myself if there were not another simple solution which can respond to my requirement and allow me to drop my database ? Using the Queue class integrated in Python for example ?

Thank you in advance


问:
Find the maximum XOR of two numbers in a growing array of integers
Random integers are added to an array. Each time an integer is added, the maximum XOR of any two numbers from the array of all previous numbers should be output.

For example:

Input: 3 2 5 2

Output: 0 1 7 7

I was able to come up with a simple algorithm of complexity O((n^2) / 2). Is there a faster approach?

I know there are approaches with complexity O(n*log(n)) and even O(n) for a static array.
https://www.geeksforgeeks.org/maximum-xor-of-two-numbers-in-an-array/

But is there any way to apply them to this problem?


问:
Unity HDRP. SSR reflection is clipped and has strange noise. How to Fix?
I started use Unity3d HD Rendering Pipeline to make reflections for my materials. But when I using Screen Space Reflections I have two problems:

Reflections has strange noise.

Reflections are somehow being clipped and it depends on camera position.

My Unity version is 2020.3.29f1. And HDRP version is 10.8.1

You can see it in this screenshot:

How can I fix this issue?


问:
Can you do a quadratic regression analysis with the following independent variables age, bmi, and smoker status?
I have a project where I have age, bmi, and smoker status as my independent variables and medical expense as our dependent variable. Could I perform a quadratic regression analysis with those independent variables?

I tried a multiple quadratic regression analysis in excel but not sure if its correct?


问:
Group background color drawing over minor/major gridlines
using a Vis.js Timeline, I have a group timeline wherein I'm setting the background color of the group, but the color is over-riding the vis-grid minor/major gridlines such that they don't show.

My group className is "Baseline" and I've tried CSS .vis-time-axis.baseline .vis-grid.vis-minor.baseline with no luck...

I've tried all sorts of other CSS trickery but can't get the minor/major gridlines to show.  Here is my code.  Help is appreciated!

var groups = new vis.DataSet([
  { id: 0, content: 'Solution #0', value: 0, className: "baseline" },
  { id: 1, content: 'Solution #1', value: 1 },
        ]);
var items = new vis.DataSet([
  { id: 0, group: 0, content: 'AAA', start: new Date(2020, 04, 06), end: new Date(2020, 06, 01), type: 'range' },
  { id: 1, group: 0, content: 'BBB', start: new Date(2020, 04, 06), end: new Date(2020, 04, 06), type: 'point' },
  { id: 2, group: 0, content: 'CCC', start: new Date(2020, 06, 15), end: new Date(2021, 09, 22), type: 'range' },
  { id: 22, group: 1, content: 'AAA', start: new Date(2020, 04, 06), end: new Date(2020, 06, 01), type: 'range' },
  { id: 23, group: 1, content: 'BBB', start: new Date(2020, 06, 15), end: new Date(2021, 09, 22), type: 'range' },
  { id: 24, group: 1, content: 'CCC', start: new Date(2021, 09, 22), end: new Date(2021, 09, 27), type: 'range' },
]);

var container = document.getElementById('visualization');
var options = {};
var timeline = new vis.Timeline(container,items,groups,options);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body,
html {
    font-family: sans-serif;
    background-color: black;

}
.vis-item .vis-item-overflow {
    overflow: visible;
}
.vis-group.baseline {
    font-family: sans-serif;
    font-style: italic;
    font-size: 11pt;
    background-color: #b1a3a3;
}
.baseline {
    font-family: sans-serif;
    font-style: italic;
    font-size: 11pt;
}
.vis-time-axis .vis-text {
    box-sizing: border-box;
    color: #ffffff;
    overflow: hidden;
    padding: 3px;
    position: absolute;
    white-space: nowrap
}
.vis-time-axis .vis-grid.vis-minor {
    border-color: #ececee
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis-timeline-graph2d.min.css" rel="stylesheet"/>

```

Body:
using a Vis.js Timeline, I have a group timeline wherein I'm setting the background color of the group, but the color is over-riding the vis-grid minor/major gridlines such that they don't show.

My group className is "Baseline" and I've tried CSS .vis-time-axis.baseline .vis-grid.vis-minor.baseline with no luck...

I've tried all sorts of other CSS trickery but can't get the minor/major gridlines to show.  Here is my code.  Help is appreciated!

var groups = new vis.DataSet([
  { id: 0, content: 'Solution #0', value: 0, className: "baseline" },
  { id: 1, content: 'Solution #1', value: 1 },
        ]);
var items = new vis.DataSet([
  { id: 0, group: 0, content: 'AAA', start: new Date(2020, 04, 06), end: new Date(2020, 06, 01), type: 'range' },
  { id: 1, group: 0, content: 'BBB', start: new Date(2020, 04, 06), end: new Date(2020, 04, 06), type: 'point' },
  { id: 2, group: 0, content: 'CCC', start: new Date(2020, 06, 15), end: new Date(2021, 09, 22), type: 'range' },
  { id: 22, group: 1, content: 'AAA', start: new Date(2020, 04, 06), end: new Date(2020, 06, 01), type: 'range' },
  { id: 23, group: 1, content: 'BBB', start: new Date(2020, 06, 15), end: new Date(2021, 09, 22), type: 'range' },
  { id: 24, group: 1, content: 'CCC', start: new Date(2021, 09, 22), end: new Date(2021, 09, 27), type: 'range' },
]);

var container = document.getElementById('visualization');
var options = {};
var timeline = new vis.Timeline(container,items,groups,options);

body,
html {
    font-family: sans-serif;
    background-color: black;

}
.vis-item .vis-item-overflow {
    overflow: visible;
}
.vis-group.baseline {
    font-family: sans-serif;
    font-style: italic;
    font-size: 11pt;
    background-color: #b1a3a3;
}
.baseline {
    font-family: sans-serif;
    font-style: italic;
    font-size: 11pt;
}
.vis-time-axis .vis-text {
    box-sizing: border-box;
    color: #ffffff;
    overflow: hidden;
    padding: 3px;
    position: absolute;
    white-space: nowrap
}
.vis-time-axis .vis-grid.vis-minor {
    border-color: #ececee
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.21.0/vis-timeline-graph2d.min.css" rel="stylesheet"/>