instruction
stringlengths 0
30k
⌀ |
---|
I am trying to make a strip plot where each row is colored by the variable "ident" and then the points change transparency based on variable "Pvalue" however I want to have a threshold where only points with pvalue <0.1 are colored the rest should be a light grey color.
So far I tried the following:
p = ggplot(da_results, aes(x=ident, y=logFC,color = ident)) +
geom_jitter()+coord_flip()+geom_point(alpha = da_results$PValue) + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.background = element_blank(), axis.line = element_line(colour = "black"))+geom_hline(yintercept = 0)
which gives me everything except for the pvalue thresholds. |
Trying to make a strip plot in R where each row is color by identity and points changes transparency based on another variable |
|ggplot2|rstudio| |
null |
I'm trying to make a localhost only webapp using Dash. I know things like electron exist for this, but I'm more comfortable with dash and pyinstaller for my internal application. I want to open something in a separate window and control it from another window and vice versa. I notice spotify is able to do this in open.spotify.com. They even have the time on a playing song synced in all the windows at once.
How are they doing it? Is it WebWorkers? |
How does spotify keep the track timer and controls synched across multiple browser windows? |
|javascript|html|web-worker| |
null |
null |
null |
null |
null |
Firstly, rename `sort_object` to a relation-based name, rather than an action name, as more fitting for this bi-directional lookup (especially since there is no [sort][1] involved):
```prolog
object_basket(Object, Basket) :-
object(Object, Type),
basket(Basket, Type).
```
Then, can use [maplist][2]:
```prolog
?- Objects = [pencil, apple, eraser, book, mouse, mp3, ipad],
maplist(object_basket, Objects, Baskets).
Objects = [pencil, apple, eraser, book, mouse, mp3, ipad],
Baskets = [tall_basket, round_basket, tall_basket, tall_basket, red_basket, red_basket, red_basket].
```
[1]: https://www.swi-prolog.org/pldoc/doc_for?object=sort/2
[2]: https://www.swi-prolog.org/pldoc/man?predicate=maplist/3 |
Well one of the console log happens each time the button `onClick` callback is clicked, and the other is an unintentional side-effect, so there's no correlation really to the React component rendering to the DOM. Move that one into a `useEffect` hook to see/check the rendering behavior.
```jsx
import { useState, useEffect } from 'react';
export function App(props) {
const [count, setCount] = useState(1);
useEffect(() => {
console.log(count)
});
const clickHandle = () => {
console.log('handle');
setCount(1000);
}
return (
<div onClick={clickHandle}>click me</div>
);
}
```
See [Bailing out of a state update][1] from the legacy docs for explanation:
> If you update a State Hook to the same value as the current state,
> React will bail out without rendering the children or firing effects.
> (React uses the [Object.is comparison algorithm][2].)
>
> Note that React may still need to render that specific component again
> before bailing out. That shouldn’t be a concern because React won’t
> unnecessarily go “deeper” into the tree. If you’re doing expensive
> calculations while rendering, you can optimize them with **useMemo**.
Basically, if you enqueue a state update that is the same value/reference as the current state it may trigger one additional component rerender, but no more than this and it doesn't render deeper into the ReactTree.
[1]: https://legacy.reactjs.org/docs/hooks-reference.html#bailing-out-of-a-state-update
[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description |
|android|logging| |
For the SLT (set less than) instruction, according to the RISC-V instruction set architecture it should be implemented as the following:
" Place the value 1 in register rd if register rs1 is less than register rs2 when both are treated as signed numbers, else 0 is written to rd."
[![enter image description here][1]][1]
so review the ISA you tring to implement to know the correct way of implementing it.
if your ISA is similar to RISC-v, you should correct your 1- bit ALU to be:
module OneBitALU(a, b, cin, ainv, binv, less, op, result,
cout, set);
input a, b, cin;
input ainv, binv;
input less;
input [1:0] op;
output result;
output cout;
output set;
wire aneg, bneg;
reg result;
reg tmp;
reg set;
assign aneg = ainv ? ~a : a;
assign bneg = binv ? ~b : b;
assign less = (a>b)? 1'b1: 1'b0 ; // new line
FullAdder fulladder(aneg, bneg, cin, tmp, cout);
always @ (*) begin
case(op)
2'b00: result = aneg & bneg;
2'b01: result = aneg | bneg;
2'b10: result = tmp;
2'b11: result = less;
default: result = 1'b0;
endcase
end
endmodule
[1]: https://i.stack.imgur.com/FqZeH.png |
This can be handled in Angular on the component side instead of the html by using this routine.
- The reference to the collection is made
- A subscription to that reference is created.
- we then check each document to see if the field we are looking for is empty
- Once the empty field is found, we store that document id in a class variable.
First, create a service .ts component to handle the backend work (this component can be useful to many other components: Firestoreservice.
This component will contain these exported routines (see this post for that component firestore.service.ts:
https://stackoverflow.com/questions/51336131/how-to-retrieve-document-ids-for-collections-in-angularfire2s-firestore
In your component, import this service and make a private firestoreservice: Firestoreservice; reference in your constructor.
Done!
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
this.firestoreData = this.firestore.getCollection(this.dataPath); //where dataPath = the collection name
this.firestoreData.subscribe(firestoreData => {
for (let dID of firestoreData ) {
if (dID.field1 == this.ClassVariable1) {
if (dID.field2 == '') {
this.ClassVariable2 = dID.id; //assign the Firestore documentID to a class variable for use later
}
}
}
} );
<!-- end snippet -->
|
{"Voters":[{"Id":2764255,"DisplayName":"Nikos Paraskevopoulos"},{"Id":522444,"DisplayName":"Hovercraft Full Of Eels"},{"Id":4216641,"DisplayName":"Turing85"}]} |
I am a pygame beginner and i was working on my first game after some training. I am making a clicker game in which you buy factories that generate revenue. The twist is that there are taxes and you have to manage resources to survive to the next day. The issue seems to be that the timer is detached and is located inside of a function however i don't know how and where to put it besides that place. I tried to put the function setup all over the place but it doesn't seem to affect it.
Note, this is my first post on stacks overflow so sorry for any issues with the question.
```
import pygame
GREEN = (3, 158, 16)
YELLOW = (255, 221, 0)
RED = (255, 0, 17)
BLACK = (18, 16, 16)
WHITE = (250, 250, 250)
WIDTH = 300
HEIGHT = 300
FPS = 60
F_HEIGHT = HEIGHT - 60
def price_check():
global color, factory_limit
check_factory_limit()
if factory_limit == False:
if money >= factory_price:
color = GREEN
else:
color = RED
if factory_limit == True:
color = RED
def draw_factory(width, height):
set_factory_timer()
for i in factories:
bought_factory = pygame.draw.rect(screen, RED, (width, height, 40, 40))
factory_timer = small_font.render(f'{int(money_timer/10000)}', False, WHITE)
factory_timer_rect = factory_timer.get_rect(topleft = (width, height))
screen.blit(factory_timer, factory_timer_rect)
width += 50
#problem area
def set_factory_timer():
global money_timer, factory_timers
for i in factory_timers:
pygame.time.set_timer(money_timer, 3000)
def check_factory_limit():
global factory_limit
if factory_price >= 400:
limit = small_font.render('Factory Limit reached', False, WHITE)
limit_rect = limit.get_rect(midtop = (WIDTH/2, F_HEIGHT))
screen.blit(limit, limit_rect)
factory_limit = True
return factory_limit
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
dt = clock.tick(FPS)/1000
running = True
money = 0
base_font = pygame.font.Font('fonts/Minecraft.ttf', 50)
small_font = pygame.font.Font('fonts/Minecraft.ttf', 20)
Game_States = True
factory_price = 150
factories = []
factory_limit = False
factory_timers = []
#timer
#problem area
money_timer = pygame.USEREVENT + 1
#Written
return_back = small_font.render('Back on the grind', False, GREEN)
return_rect = return_back.get_rect(topleft = (10, 10))
title = small_font.render('Small factory', False, GREEN)
title_rect = title.get_rect(midright = (WIDTH/2, HEIGHT/2))
while running:
pygame.key.set_repeat(0, 0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if Game_States:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
money += 1
if event.type == pygame.MOUSEBUTTONUP:
if Shop_rect.collidepoint(event.pos):
Game_States = False
else:
Game_States = True
if event.type == money_timer:
money += 25
else:
if event.type == pygame.MOUSEBUTTONUP:
if return_rect.collidepoint(event.pos):
Game_States = True
else:
Game_States = False
if buy_rect.collidepoint(event.pos):
check_factory_limit()
if color == GREEN:
money -= factory_price
factory_timers.append(money_timer)
factory_price += factory_price
factories.append('factory')
set_factory_timer()
if Game_States:
screen.fill('black')
money_maker_font = base_font.render(f'{int(money)}$', False, GREEN)
money_rect = money_maker_font.get_rect(center = (WIDTH/2, HEIGHT/2))
screen.blit(money_maker_font, money_rect)
Shop_Button = base_font.render('Shop', False, YELLOW)
Shop_rect = Shop_Button.get_rect(center = (WIDTH/3, HEIGHT/6))
screen.blit(Shop_Button, Shop_rect)
draw_factory(25, 200)
else:
screen.fill(YELLOW)
screen.blit(return_back, return_rect)
factory = pygame.draw.rect(screen, RED, (int(WIDTH/2), int(HEIGHT/2), 40, 40))
screen.blit(title, title_rect)
price_check()
buy = small_font.render(f'BUY? {factory_price}$', False, BLACK)
buy_rect = buy.get_rect(topright = (140, 170))
border_rect = buy_rect.inflate(8,8)
button = pygame.draw.rect(screen, color, buy_rect)
button_2 = pygame.draw.rect(screen, color, border_rect, 10, 6)
screen.blit(buy, buy_rect)
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
``` |
I can't set up a timer in my clicker game |
|python|pygame|pygame-clock| |
null |
I am fairly new to PHP & laravel so looking for some assistance.
For example , i have a table in mySQL database that stores comments by a user. The values for this table are userId,bookId & Comment. I essentially want to build a function in my controller where it will retrieve a list of comments for a specific bookId. So if bookId 'cm123' has a total of 7 comments for that book , then my function should retreive all 7 comments with a HTTP GET request. This route is strictly going into the API route , we are not using any view for this ,so forms & such for input are not needed-- rather the parameters will be manually inputted when testing the request in Postman.
**Again , the end result i am aiming for is that the API returns a list of book comments stored in the database given a specific bookId input**
Below are my model , route & controller classes (I do already have a function for this called "SHOW" but it is not working) :
**Contoller**
```
<?php
namespace App\Http\Controllers;
use App\Models\CreateComment;
use App\Models\BookRating;
use Illuminate\Http\Request;
class BookRatingController extends Controller
{
/**
* Display the specified resource.
*/
public function show(string $bookId): View
{
return view('CreateComment.Comment', [
'Comment' => CreateComment::findOrFail($bookId)
]);
} // return list of comments
```
**Model**
```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CreateComment extends Model
{
use HasFactory;
protected $fillable =
[
'Comment',
'userId',
'bookId'
];
}
```
**Route**
```
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookRatingController;
use App\Http\Models\BookRating;
use App\Http\Models\CreateComment;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('CreateRating',[BookRatingController::class, 'CreateRating']);//adding a bookrating to database API -- POST METHOD--
Route::post('CreateComment',[BookRatingController::class, 'CreateComment']);
Route::get('show/{$bookId}',[BookRatingController::class,'show']);
``` |
React Native emulator suddenly stops connecting to the Metro server |
|node.js|react-native|android-studio| |
null |
It is just as simple as [@Holger][1] has [commented][2] to the question above.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class FileChooserWithLimitedFilesSelection {
private JPanel panel;
private JFileChooser fileChooser;
private JButton btnFileChooser;
private File[] limitedFilesSelection;
public FileChooserWithLimitedFilesSelection() {
limitedFilesSelection = new File[3];
panel = new JPanel();
btnFileChooser = new JButton("Browse...");
btnFileChooser.addActionListener(new ButtonHandler());
panel.add(btnFileChooser);
}
private class ButtonHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (fileChooser == null) {
fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addPropertyChangeListener(new LimitSelectionHandler());
}
int returnedValue = fileChooser.showDialog(null, "Select files");
//
}
}
private class LimitSelectionHandler implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
File[] selectedFiles = fileChooser.getSelectedFiles();
int currentSelectionLength = selectedFiles.length;
if (currentSelectionLength == 3) {
for (int i = 0; i < limitedFilesSelection.length; i++) {
limitedFilesSelection[i] = selectedFiles[i];
}
} else if (currentSelectionLength > 3) {
fileChooser.setSelectedFiles(limitedFilesSelection);
JOptionPane.showMessageDialog(fileChooser, "Only 3 selected files allowed.", "File chooser",
JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FileChooserWithLimitedFilesSelection fcwrfs = new FileChooserWithLimitedFilesSelection();
frame.add(fcwrfs.panel);
frame.pack();
frame.setVisible(true);
});
}
}
[1]: https://stackoverflow.com/users/2711488/holger
[2]: https://stackoverflow.com/questions/77913661/how-to-fix-deselection-behavior-of-limited-selection-jfilechooser-setselectedfil?noredirect=1#comment137361027_77913661 |
While doing simple `print` found one issue:
```
>>> print("123456".count(""))
7
```
Why it print 7 instead of 6? |
I have a VM which can be accessed via bastion. I want to write a policy definition to deny the access if the user is NOT a member of a specific user group. I started with the following part, but not sure how to continue with the user and user group part in the definition.
{
"mode": "All",
"policyRule": {
"if": {
"allOf": [
{
"field": "type",
"equals": "Microsoft.Network/bastionHosts"
},
{
"field": "name",
"in": [
"test-vm-bastion"
]
}
]
},
"then": {
"effect": "deny"
}
},
"parameters": {}
}
I need to correct/complete the definition for the given purpos mentioned up. |
Azure policy definition to allow the access to a VM via Bastion only for users of a specific user group |
|azure|azure-policy|azure-security| |
The error message you're encountering indicates an issue with node-gyp, which is used to build native addons for Node.js projects. Here's how to troubleshoot and potentially fix it:
Force Python 3 for node-gyp:
Set the PYTHON environment variable to your Python 3 executable path before running npm install:
export PYTHON=/path/to/your/python3 # Replace with actual path
npm install --save-dev parcel
Try reinstalling node-gyp globally:
npm uninstall -g node-gyp
npm install -g node-gyp |
Is there any chance of data leakage while splitting dataset in this way:
def split_dataset(ds, train_ratio=0.8, val_ratio=0.1, test_ratio=0.1, shuffle=True):
# Get dataset size
dataset_size = len(ds)
# Calculate split sizes
train_size = int(train_ratio * dataset_size)
val_size = int(val_ratio * dataset_size)
test_size = dataset_size - train_size - val_size
# Shuffle dataset if required
if shuffle:
ds = ds.shuffle(dataset_size)
# Split dataset
train_dataset = ds.take(train_size)
val_dataset = ds.skip(train_size).take(val_size)
test_dataset = ds.skip(train_size + val_size).take(test_size)
return train_dataset, val_dataset, test_dataset
Training a deep learning model
Just surprised by the model's accuracy, it's over 98%. |
I have a fixed record file with several millions of records containing sales for several thousands customers. I need to generate file with one record for each customer containing customer id, sales count and sales total.
I've just started to learn COBOL and I do not have idea what is a "COBOL way" to do that.
Obvious way in other programming languages will be to use some kind of map, but COBOL lacks such structures. COBOL arrays is out of question from performance reasons.
Other solution that comes to my mind is utilizing database, but it seems overkill for such trivial task.
Could someone point me in the right direction? |
Record grouping and aggregation |
|cobol| |
null |
Retrieving list of values from MYSQL data base based on input value(LARAVEL 10 )(GET HTTP METHOD) |
|php|mysql|laravel|api|http| |
I'm encountering a problem with scheduling Prometheus pods on AWS EKS Fargate within my Kubernetes cluster. Here are the details of my setup:
I have configured an AWS EKS Fargate profile named terraform_eks_fargate_profile_monitoring for my Prometheus namespace (monitoring). Here's the relevant Terraform configuration:
```
resource "aws_eks_fargate_profile" "terraform_eks_fargate_profile_monitoring" {
fargate_profile_name = "monitoring"
cluster_name = aws_eks_cluster.terraform_eks_cluster.name
pod_execution_role_arn = aws_iam_role.terraform_eks_fargate_pods.arn
subnet_ids = aws_subnet.terraform_eks_vpc_private_subnets[*].id
selector {
namespace = "monitoring"
}
}
```
I've deployed Prometheus using Helm with the following command:
```
helm install prometheus prometheus-community/prometheus -n monitoring
```
However, when I describe the pods, I receive the following warning:
```
Name: prometheus-prometheus-node-exporter-4kvv7
Namespace: monitoring
Priority: 0
Service Account: prometheus-prometheus-node-exporter
Node: <none>
Labels: app.kubernetes.io/component=metrics
app.kubernetes.io/instance=prometheus
app.kubernetes.io/managed-by=Helm
app.kubernetes.io/name=prometheus-node-exporter
app.kubernetes.io/part-of=prometheus-node-exporter
app.kubernetes.io/version=1.7.0
controller-revision-hash=9bd9c77f
helm.sh/chart=prometheus-node-exporter-4.31.0
pod-template-generation=1
Annotations: cluster-autoscaler.kubernetes.io/safe-to-evict: true
Status: Pending
IP:
IPs: <none>
Controlled By: DaemonSet/prometheus-prometheus-node-exporter
Containers:
node-exporter:
Image: quay.io/prometheus/node-exporter:v1.7.0
Port: 9100/TCP
Host Port: 9100/TCP
Args:
--path.procfs=/host/proc
--path.sysfs=/host/sys
--path.rootfs=/host/root
--path.udev.data=/host/root/run/udev/data
--web.listen-address=[$(HOST_IP)]:9100
Liveness: http-get http://:9100/ delay=0s timeout=1s period=10s #success=1 #failure=3
Readiness: http-get http://:9100/ delay=0s timeout=1s period=10s #success=1 #failure=3
Environment:
HOST_IP: 0.0.0.0
Mounts:
/host/proc from proc (ro)
/host/root from root (ro)
/host/sys from sys (ro)
Conditions:
Type Status
PodScheduled False
Volumes:
proc:
Type: HostPath (bare host directory volume)
Path: /proc
HostPathType:
sys:
Type: HostPath (bare host directory volume)
Path: /sys
HostPathType:
root:
Type: HostPath (bare host directory volume)
Path: /
HostPathType:
QoS Class: BestEffort
Node-Selectors: kubernetes.io/os=linux
Tolerations: :NoSchedule op=Exists
node.kubernetes.io/disk-pressure:NoSchedule op=Exists
node.kubernetes.io/memory-pressure:NoSchedule op=Exists
node.kubernetes.io/network-unavailable:NoSchedule op=Exists
node.kubernetes.io/not-ready:NoExecute op=Exists
node.kubernetes.io/pid-pressure:NoSchedule op=Exists
node.kubernetes.io/unreachable:NoExecute op=Exists
node.kubernetes.io/unschedulable:NoSchedule op=Exists
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Warning FailedScheduling 21m default-scheduler 0/5 nodes are available: 1 Too many pods. preemption: 0/5 nodes are available: 5 No preemption victims found for incoming pod.
Warning FailedScheduling 15s (x6 over 20m) default-scheduler 0/7 nodes are available: 1 Too many pods. preemption: 0/7 nodes are available: 7 No preemption victims found for incoming pod.
```
I get this on all the node-exporter pods. The pushgateway and metrics pod runs fine
I'm not sure that the resource requests and limits specified in the Prometheus pod configuration are compatible with Fargate.
Since i used
```
helm install prometheus prometheus-community/prometheus -n monitoring
```
it has the default resource specifications for the Prometheus server container. |
AWS EKS Fargate pod scheduling issue with Prometheus deployment |
|amazon-web-services|kubernetes|terraform|amazon-eks| |
null |
This error:
> Microsoft.Data.SqlClient.SqlException
HResult=0x80131904
Message=A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - The certificate chain was issued by an authority that is not trusted.)
Source=Core Microsoft SqlClient Data Provider
<<StackTrace:>>
Inner Exception 1:
Win32Exception: The certificate chain was issued by an authority that is not trusted.
started appearing today when my application tried to connect to the local SQL Server via this connection string:
> "Data Source=ZEKE-XI;Initial Catalog=PIM;Integrated Security=True"
Nothing that I know of has changed on my PC since yesterday when this error did not occur. Looking at some suggestions in related posts, I tried setting "Server Authentication" to "SQL Server and Windows authentication" but that did not resolve the problem.
SSMS works just fine.
What could be the problem?
|
How to Solve Error Associated with Trusted Authority |
|sql-server| |
Based on site https://allurereport.org/docs/cucumberjvm/ I tried to configure allure reports
to project with junit5 and cucumber. Unfortunatelly report is not beeing generated.
Other reports (cucumber, junit) works correctly and are present.
This is my build.gradle.kts file:
```
plugins {
id("java")
id("io.qameta.allure") version "2.11.2"
}
apply(plugin = "io.qameta.allure")
group = "org.example"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
}
val allureVersion = "2.24.0"
val aspectJVersion = "1.9.22"
val agent: Configuration by configurations.creating {
isCanBeConsumed = true
isCanBeResolved = true
}
dependencies {
agent("org.aspectj:aspectjweaver:${aspectJVersion}")
testImplementation(platform("org.junit:junit-bom:5.10.2"))
testImplementation("org.junit.jupiter:junit-jupiter")
testImplementation("org.junit.jupiter:junit-jupiter-params:5.10.2")
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.2")
testImplementation("org.junit.jupiter:junit-jupiter-engine:5.10.2")
testImplementation("org.junit.platform:junit-platform-suite:1.10.2")
testImplementation("org.slf4j:slf4j-api:2.0.9")
testImplementation("ch.qos.logback:logback-classic:1.5.3")
testImplementation("org.assertj:assertj-core:3.25.3")
testImplementation("io.cucumber:cucumber-junit-platform-engine:7.16.1")
testImplementation("io.cucumber:cucumber-java:7.16.1")
testImplementation("org.apache.commons:commons-collections4:4.4")
testImplementation(platform("io.qameta.allure:allure-bom:$allureVersion"))
testImplementation("io.qameta.allure:allure-cucumber7-jvm")
testImplementation("io.qameta.allure:allure-junit-platform")
}
tasks.test {
useJUnitPlatform()
jvmArgs = listOf(
"-javaagent:${agent.singleFile}"
)
}
```
I have also in
``` /src/test/resources/ ```
allure.properties file with:
```
allure.results.directory=build/allure-results
```
I installed also:
```
npm install --save-dev allure-commandline
```
in project root directory .
At the end after executing command:
```
./gradlew clean build test
```
in intellij under windows
cucumber.html file is created but not allure report.
In directory
```
build\allure-results
```
only 2 files appears:
```
a437a757-9ea3-4eba-a064-12069f40c081-container.json
executor.json
```
Am I doing something incorrectly? Everything looks good.
**Edit:**
I tried to run exemplary solution ( https://github.com/allure-examples/allure-cucumber7-junit-platform-gradle-kts )
but it also ends without html file report in directory
build/allure-results , only few json files are created in this directory. |
### `Point` class
Let's start with a point class, in proper Java style:
```java
class Point {
private int[] components;
public Point(int... components) {
this.components = components;
}
public int getDimension() {
return components.length;
}
public int getComponent(int i) {
return components[i];
}
public void setComponent(int i, int v) {
components[i] = v;
}
}
```
### Sorting by axis
Indeed we need a comparator for this. In old school Java this is a bit of a ceremony - we have to write an `AxisComparator<Point>` class with an `axis` field which then compares based on component:
```java
class AxisComparator<Point> implements Comparator<Point> {
private int axis;
public AxisComparator(int axis) {
this.axis = axis;
}
public int compare(Point p, Point q) {
return Integer.compare(p.getComponent(axis), q.getComponent(axis));
}
}
```
You could then use this as `new AxisComparator(k)`.
In "modern" Java, you could get away with a one-liner:
```java
Comparator.comparingInt((Point p) -> p.getComponent(k));
```
[`Arrays.sort`](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-T:A-java.util.Comparator-) accepts a comparator.
### `KdTree` class
We will want to distinguish between the tree - which stores a potentially `null` (in case of an empty tree) pointer to the root - and tree nodes. The tree nodes should get a recursive `private` constructor, taking the array and the axis we want to split on and producing a k-d-tree which splits on that axis. The tree should get a public constructor taking an array of points.
```java
class KdTree {
record Node(int axis, Node left, Node right, Point pivot) {
// Note: points is mutated (sorted by axis)
static Node build(Point[] points, int axis) {
if (points.length == 0)
return null; // empty node
Arrays.sort(points, Comparator.comparingInt((Point p) -> p.getComponent(axis)));
var mid = points.length / 2;
var leqPoints = Arrays.copyOf(points, mid);
var geqPoints = Arrays.copyOfRange(points, mid, points.length);
var nextAxis = (axis + 1) % points[0].getDimension();
return Node(axis, build(leqPoints, nextAxis), build(geqPoints, nextAxis), points[mid]);
}
}
private Node root;
public KdTree(Point[] points) {
root = Node.build(points.clone(), 0);
}
// Implement operations on your k-d-tree, like finding the nearest neighbor to a point here
}
```
### Better algorithms
This "naive" algorithm of sorting by an axis for each split is not ideal in terms of performance; it incurs O(n log n) costs at each of the O(log n) levels of the trees, resulting in O(n (log n)²), which is not bad, but also not optimal.
I have implemented all three approaches in Lua a while ago [here](https://github.com/TheAlgorithms/Lua/blob/61ec71e6e6458c5f773c7f36eafc95e6c63fce0d/src/data_structures/k_d_tree.lua). If you don't know Lua, read it as pseudocode.
#### Presorting
One option to optimize this is to *pre-sort* the points by each of the k axes, incurring costs of O(k n log n) for the pre-sorting, and then filtering the k pre-sorted lists into left & right parts as you split, incurring kn costs for each split, for a tree of depth O(log n), resulting in O(k n log n). This can be better than O(n (log n)²) if n is big and k is small (say, 2, 3 or 4).
To be more precise: What you pre-sort are either (pointers to) instances of a `Point` class, or indices (if you opt for the `PointArray`-based solution). So you end up with `k` pre-sorted arrays of `Point`s / `int` indices.
When you split, you *mark* all points left to the median. If you have an array of `Point`s, one approach would be to add a boolean `_marked` field to the `Point` class. This field then lets you filter the points along all other axes, splitting them into "marked" and "unmarked" points (except the pivot). For looser coupling, you would probably want to create a `MarkablePoint` class extending `Point` and convert all points to that initially (*before* presorting), or you might prefer a `HashSet` of marked points (by reference). For indices, you could also use a `HashSet`, or a boolean array.
#### Median of medians
The asymptotically optimal option is to use a *linear time* median selection algorithm ([median of medians](https://en.wikipedia.org/wiki/Median_of_medians)). Using this, you get O(n) costs for O(log n) layers, for a total of O(n log n).
### Out-of-band representation (low-level optimizations)
Representing an array of points as, well, an array of points *is* definitely the most idiomatic, straightforward, simple way to implement this in an OOP language like Java. I'd stick to this for an initial implementation unless you have a good reason not to. I would not prematurely optimize this.
As you said, you want to keep the components of a point together, and that is cumbersome to do if you store separate arrays of components.
But if you do have to optimize this at a low-level (maybe you have determined that the points eat up too much memory, or the heap allocation, GC or indirection overhead is too large or the cache locality is too bad) by using multiple arrays, write yourself something like a `PointArray` class which manages an array of k arrays of components. Sorting could simply sort a permutation of indices into these k arrays (well, after the first split of these indices, it is only a permutation of the restricted set of indices, but you get the idea).
This could look like this:
```java
class PointArray {
private int[][] points; // points[i][j] = i-th coordinate of j-th point
private int[] indices; // into points
public PointArray(int[][] points) {
this.points = points;
int n = points[0].length;
assert n > 0;
for (int i = 1; i < points.length; i++)
assert points[i].length == n;
indices = new int[n];
for (int i = 1; i < n; i++)
indices[i] = i;
}
private PointArray(int[] indices, int[][] points) {
this.indices = indices;
this.points = points;
}
public int getDimension() {
return points.length;
}
public int getLength() {
return indices.length;
}
public int getComponent(int pointIdx, int axis) {
return points[axis][indices[pointIdx]];
}
public Point getPoint(int i) {
var components = new int[getDimension()];
for (int axis = 0; axis < components.length; axis++)
components[axis] = getComponent(i, axis);
return new Point(components);
}
public void sortByAxis(int axis) {
Arrays.sort(indices, Comparator.comparingInt((int i) -> points[axis][i]));
}
// To slice the array, it suffices to slice the indices.
// We do not have to slice the points.
public PointArray slice(int from, int to /*exclusive*/) {
return new PointArray(Arrays.copyOfRange(indices, from, to), points);
}
}
```
Really this approach isn't all that different from having an array of points, except instead of pointers to heap-allocated points, we have indices into our "array-allocated" matrix of point coordinates. This requires some small changes to our k-d-tree:
```java
class KdTree {
record Node(int axis, Node left, Node right, Point pivot) {
// Note: points is mutated (sorted by axis)
static Node build(PointArray points, int axis) {
if (points.getLength() == 0)
return null; // empty node
points.sortByAxis(axis);
var mid = points.getLength() / 2;
var leqPoints = points.slice(0, mid);
var geqPoints = points.slice(0, points.getLength());
var nextAxis = (axis + 1) % points.getDimension();
return Node(axis, build(leqPoints, nextAxis), build(geqPoints, nextAxis), points.getPoint(mid));
}
}
private Node root;
public KdTree(int[][] points) {
root = Node.build(new PointArray(points), 0);
}
// Implement operations on your k-d-tree, like finding the nearest neighbor to a point here
}
``` |
I was wondering if there is a way to replace variables in PowerShell script block with their value that is defined in a scope. I also don't want to replace variables that are not available in the scope. My goal is to get a Script block that is "self contained" as much as possible.
```
$outerVariable = "hello"
$Command = {
Write-Host "$outerVariable"
$innerVariable = "world"
Write-Host "$innerVariable"
}
$Command = [scriptblock]::Create($ExecutionContext.InvokeCommand.ExpandString($Command.ToString()))
$Command
````
It results in:
```
Write-Host "hello"
= "world"
Write-Host ""
```
But I want this:
```
Write-Host "hello"
$innerVariable = "world"
Write-Host "$innerVariable"
``` |
PowerShell replace variables with their values defined in the context, but don't touch unknown variables |
|powershell| |
I got stuck, i making some searchview for find my dummy item but still didnt work, anyone know how it works ? this is my dummy data
```
interface DummyMusicDataSource {
fun getMusicData(context: Context): List<Music>
}
class DummyMusicDataSourceImpl() : DummyMusicDataSource {
override fun getMusicData(context: Context): List<Music> {
return mutableListOf(
Music(
title = "title",
imgUrl = "https://raw.githubusercontent.com/ryhanhxx/img_asset/main/IMG_MATERI_3.jpg",
desc = context.getString(R.string.desc_materi_1),
videoUrl = "https://www.youtube.com/watch?v=XpwWeAsXnvA",
),
)
}
}
```
Heres my problem, i dont know how to make my searchview work for find my dummy data, i wanna find it when i type the title on searchview
```
class MateriFragment : Fragment() {
private lateinit var binding: FragmentMateriBinding
private val adapter: MateriAdapter by lazy {
MateriAdapter(AdapterLayoutMode.LINEAR){ materi: Materi ->
navigateToDetailFragment(materi)
}
}
private val datasource: DummyMateriDataSource by lazy {
DummyMateriDataSourceImpl()
}
private fun navigateToDetailFragment(materi: Materi) {
MateriActivity.startActivity(requireContext(), materi)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentMateriBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupList()
setupSwitch()
}
private fun setSearchView(){
//TODO: Searchview for dummy
}
private fun setupList() {
val span = if(adapter.adapterLayoutMode == AdapterLayoutMode.LINEAR) 1 else 2
binding.rvMateri.apply {
layoutManager = GridLayoutManager(requireContext(),span)
adapter = this@MateriFragment.adapter
}
adapter.setItems(datasource.getMateriData(requireContext()))
}
private fun setupSwitch() {
binding.swGrid.setOnCheckedChangeListener { _, isChecked ->
(binding.rvMateri.layoutManager as GridLayoutManager).spanCount = if (isChecked) 2 else 1
adapter.adapterLayoutMode = if(isChecked) AdapterLayoutMode.GRID else AdapterLayoutMode.LINEAR
adapter.refreshList()
}
}
}
```
this is my MateriAdapter for my recycleview
```
class MateriAdapter (
var adapterLayoutMode: AdapterLayoutMode,
private val onClickListener: (Materi) -> Unit
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val dataDiffer = AsyncListDiffer(this, object : DiffUtil.ItemCallback<Materi>() {
override fun areItemsTheSame(oldItem: Materi, newItem: Materi): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Materi, newItem: Materi): Boolean {
return oldItem.hashCode() == newItem.hashCode()
}
})
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
AdapterLayoutMode.GRID.ordinal -> (GridMateriViewHolder(
binding = ItemCardGridBinding.inflate(
LayoutInflater.from(parent.context), parent, false
), onClickListener
))
else -> {
LinearMateriViewHolder(
binding = ItemCardListBinding.inflate(
LayoutInflater.from(parent.context), parent, false
), onClickListener
)
}
}
}
override fun getItemCount(): Int = dataDiffer.currentList.size
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder as ViewHolderBinder<Materi>).bind(dataDiffer.currentList[position])
}
override fun getItemViewType(position: Int): Int {
return adapterLayoutMode.ordinal
}
fun setItems(data: List<Materi>) {
dataDiffer.submitList(data)
}
fun refreshList() {
notifyItemRangeChanged(0, dataDiffer.currentList.size)
}
}
``` |
How to make searchview works for find my dummy data |
|android|kotlin|search|searchview|dummy-variable| |
I am trying to make a Menu filled with font styles for a particular font. In the code below I have one attempt that is commented out. The code just below correctly prints the styles but I can't get the ForEach() to work. GetFontStyles() seams to return an array of arrays and that internal array contains several fields including the font name, font style and some ID numbers. Note the member[1] which is was used to pull the style.
struct AddFontStyleItems: View {
var dm: DrawModel
init(_ dm: DrawModel ) { self.dm = dm }
var body: some View {
var fontStyles = getFontStyles(for: dm.curFont )
// ForEach(fontStyles, id: \.self) { curStyle in
// Button( "xxx" ) {
// print( "Style: \(curStyle)")
// // print("Type of Member: \(type(of: member)) - \(member[1])")
// }
// }
Button( "xxx" ) {
let fontStyles = NSFontManager.shared.availableMembers(ofFontFamily: dm.curFont)
print("-\nFont: \(dm.curFont)")
if let members = fontStyles {
for member in members {
print("Style for: \(dm.curFont) - \(member[1])")
}
}
}
}
}
func getFontStyles(for fontFamily: String) -> [String] {
let fontManager = NSFontManager.shared
guard let availableMembers = fontManager.availableMembers(ofFontFamily: fontFamily) else {
return []
}
return availableMembers.compactMap { member in
return member as? String
}
}
|
How do I get the font styles on MacOS using Swift? |
|swift|menu| |
Put a for loop iteration in a Bootstrap group list button click
I have a lab about addEventListener, where in a click of a button shows your for loop with office locations.
const grupList = document.querySelector("ul");
console.log(grupList);
const listItems = document.querySelector("li");
console.log(listItems);`
const offices = document.getElementById("ofLocations");
let officeLocations = ["New York", "London", "Paris", "Tokyo", "Sydney"];
```function getOfficeLocations (arr){
``` for (let i = 0; i < arr.length; i++) {
`console.log(arr[i]);
```offices.addEventListener("click", getOfficeLocation {
})
}
}
`getOfficeLocation(officeLocations);`
This is what I have done so far. |
|python| |
I have followed an example on how to create a Chrome extension using Vue.js.
[vuejs based extension][1]
It is working fine, and now I would like to pass the URL of an actual tab (for instance) from a background script to the popup page.
I placed console.log statements in the onMessage and onClicked events in background.js, but these listeners don't receive anything. The onInstalled listener works.
I am relatively new to Vue.js and browser extensions, so I feel a bit lost.
Can you help me with what's missing or what's wrong in my code?
**manifest.json**
```
{
"manifest_version": 3,
"name": "Random Quote",
"version": "1.0.0",
"description": "Browser extension that fetch a random quote from zenquotes.io",
"host_permissions": ["https://zenquotes.io/"],
"permissions": ["activeTab", "scripting"],
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/icon-16x16.png",
"48": "images/icon-48x48.png",
"192": "images/icon-128x128.png"
}
},
"background": {
"service_worker": "js/background.js"
}
}
```
**background.js**
```
chrome.runtime.onMessage.addListener(function () {
console.log("onMessage.addListener");
});
chrome.action.onClicked.addListener(function (tab) {
console.log("onClicked.addListener");
});
chrome.runtime.onInstalled.addListener(() => {
console.log('Hello, World!');
});
```
**popup.html**
```
<!DOCTYPE html>
<html lang="en_US">
<head>
<title>Random Quote</title>
<link rel="stylesheet" type="text/css" href="css/popup.css" />
<meta charset="UTF-8">
</head>
<body>
<div id="app"></div>
<script src="js/popup.js"></script>
</body>
</html>
```
**popup.vue**
```
<template>
<div class="container">
<h1 class="title text-center">Random Quote</h1>
<blockquote class="quote-card">
<p>
{{ state.quote }}
</p>
<cite> {{ state.author }} </cite>
</blockquote>
<blockquote class="quote-card">
here show URL of the currect Tab
</blockquote>
</div>
</template>
<script>
export default {
data() {
return {
state: {
quote: "",
author: "",
},
};
},
async created() {
try {
const response = await fetch("https://zenquotes.io/api/random");
const data = await response.json();
if (Array.isArray(data) && data.length > 0) {
this.state.quote = data[0].q; // Extract the quote from the response
this.state.author = data[0].a;
} else {
this.state.quote = "Failed to fetch quote.";
}
} catch (error) {
console.error(error);
this.state.quote = "Error occurred while fetching quote.";
}
},
};
</script>
```
**popup.js**
```
import { createApp } from "vue";
import Popup from "./Popup.vue";
console.log("popup.js - 1");
createApp(Popup).mount("#app");
console.log("popup.js - 2");
```
**webpack.mix.js**
```
let mix = require("laravel-mix");
mix
.setPublicPath("./")
.sass("src/sass/popup.scss", "dist/css")
.js("src/js/popup.js","dist/js")
.js("src/js/background.js","dist/js")
.vue()
.copy("src/images/", "dist/images")
.options({
processCssUrls: false,
});
```
**mix-manifest.json**
```
{
"/dist/js/popup.js": "/dist/js/popup.js",
"/dist/js/background.js": "/dist/js/background.js",
"/dist/css/popup.css": "/dist/css/popup.css",
"/dist/images/icon-128x128.png": "/dist/images/icon-128x128.png",
"/dist/images/icon-16x16.png": "/dist/images/icon-16x16.png",
"/dist/images/icon-48x48-off.png": "/dist/images/icon-48x48-off.png",
"/dist/images/icon-48x48.png": "/dist/images/icon-48x48.png"
}
```
**package.json**
```
{
"name": "randomquote",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --env=production --config=node_modules/laravel-mix/setup/webpack.config.js",
"prod": "npm run production"
},
"author": "",
"license": "ISC",
"dependencies": {
"cross-env": "^7.0.3",
"laravel-mix": "^6.0.49",
"postcss": "^8.4.33",
"sass": "^1.70.0",
"sass-loader": "^14.0.0",
"vue": "^3.4.15",
"vue-loader": "^17.4.2",
"vue-template-compiler": "^2.7.16"
}
}
```
[1]: https://javascript.plainenglish.io/how-to-create-vuejs-based-chrome-extension-645d6fe9bf53 |
vue.js and chrome extension, getting data from background script |
|javascript|vue.js|google-chrome-extension| |
As of now, I can define a default (for example, in my model for an Integer column I can say `default=0`) and this default will be respected if I insert from my application through SQLAlchemy. However, in the MySQL schema, the default will be NULL. Is there a way to make the SQLAlchemy defaults be set in the schema too? |
Can I make SQLAlchemy defaults apply in the schema too? |
|python|mysql|sqlalchemy|schema|default| |
|reactjs|typescript|next.js| |
We have a K8s cluster where for communication/networking we are using istio's service mesh which has mTLS enabled. Currently there is no such authentication between any services in our cluster, thus any service can call any other service within a cluster.
So my doubt is somehow if one of my container's security is compromised will mTLS helps in stopping lateral attack in other pod? As per me same is not possible only with mTLS and we will need some other way may be explicit authentication b/w services or network policy.
Any doc/reference will be helpful. |
In kubernetes would istios's mTLS helps in stopping lateral attack in other pod if a pod's security is compromised |
|kubernetes|security|mtls| |
I am debugging a crash and i see following behaviour -
When i attach GDB to the process and do info registers, i see the following value for esp -
esp 0xfd2475d0 0xfd2475d0
Upon doing a disassembly of code where it is crashing, I see it's storing to memory pointed-to by the stack pointer -
81c886a: c7 04 24 2c f9 8a 0c movl $0xc8af92c,(%esp)
And if i view maps file in `/proc/<PID>/maps`, I see stack address range as -
fff39000-fff59000 rwxp 7ffffffde000 00:00 0 [stack]
Clearly, value of `ESP 0xfd2475d0` in GDB is not in sync with the stack address in maps file.
Can this be a reason for crash. I think it should be as i am getting SIGSEGV. Also, how do I resolve this issue? |
Segfault with ESP outside the [stack] range in /proc/pid/maps? |
|assembly|x86|crash|stack-overflow|stack-memory| |
I have an array declared above the beginning of a for loop as: `$array = array();`.
Now, in the for loop I start inserting values into it.
At some point I make one of its index as another array as `$array[$j]=array();`
And insert some values like, `$array[$j][$l] = id;` and so on.
Now, when I use `print_r($array);` inside the loop I get the expected value of the array.
But outside the loop this newly created array (2-D) is getting lost and I am getting only a 1-D array as an output.
Can someone please tell me where the problem could lie? |
This is considered as anti pattern in modern React ecosystem.
According to single responsibility principle
keep your business logic in a simple way with custom hooks (Use prototype inheritance in it, if required), To store API calls use Tanstack Query and to store global data use Jotai (Atoms). This libraries are very easy to learn and maintain.
You don't need to write Redux (action, reducers and store), Redux toolkit and other boilerplate codes today. Even you learn this concepts it was not so useful in other stacks.
Even today many React interviewers asks for Redux questions, I hope they will update their projects with the mentioned best practices soon. |
This can be handled in Angular on the component side instead of the html by using this routine.
- The reference to the collection is made
- A subscription to that reference is created.
- we then check each document to see if the field we are looking for is empty
- Once the empty field is found, we store that document id in a class variable.
First, create a service .ts component to handle the backend work (this component can be useful to many other components: Firestoreservice.
This component will contain these exported routines (see this post for that component firestore.service.ts:
https://stackoverflow.com/questions/51336131/how-to-retrieve-document-ids-for-collections-in-angularfire2s-firestore
In your component, import this service and make a private firestore: Firestoreservice; reference in your constructor.
Done!
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
this.firestoreData = this.firestore.getCollection(this.dataPath); //where dataPath = the collection name
this.firestoreData.subscribe(firestoreData => {
for (let dID of firestoreData ) {
if (dID.field1 == this.ClassVariable1) {
if (dID.field2 == '') {
this.ClassVariable2 = dID.id; //assign the Firestore documentID to a class variable for use later
}
}
}
} );
<!-- end snippet -->
|
I'm trying to create a test to check the correct behaviout of my service object,
```ruby
def api_call_post(connection, message, url)
pp message
response = connection.post do |conn|
conn.url url
conn.body = message
conn.headers = @headers
end
check_response(response)
end
...
```
this is the test :
```ruby
test "create a title" do
body = { "name" => 'some name',
"external_id" =>'004',
"title_type" =>'feature',
"tags" => 'some tag' }.to_json
puts body
stub_request(:post, "some web")
.with(body: body )
.to_return(status: 201, body: "Created", headers: {})
response = MovidaApi.new(payload).create_title
assert response.success?
assert_equal "Created", response.body
end
...
```
The problem comes when I include the `.with` in the stub, (without it's working ok),
I printed statements and the output are exactly the same.
The error is:
Error:
MovidaApiTest#test_create_a_title:
WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled. Unregistered request: POST some web with headers
{'Accept'=>'application/json', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Length'=>'0', 'Content-Type'=>'application/json', 'User-Agent'=>'Ruby'}
What i'm doing wrong?
I tried to use the snippet suggested but still don't work.
I expect the test to pass |
|database|wpf|pdf|webbrowser-control|memorystream| |
null |
So I'm trying to run a CMD check for a package I want to upload to CRAN but when running it on my Windows 11 cmd I get the following error:
```
* using log directory 'C:/Users/Zick/Documents/YEAB/YEAB-master/YEAB.Rcheck'
* using R version 4.3.3 (2024-02-29 ucrt)
* using platform: x86_64-w64-mingw32 (64-bit)
* R was compiled by
gcc.exe (GCC) 12.3.0
GNU Fortran (GCC) 12.3.0
* running under: Windows 11 x64 (build 22631)
* using session charset: UTF-8
* using option '--as-cran'
* checking for file 'YEAB/DESCRIPTION' ... OK
* this is package 'YEAB' version '0.1.0'
* package encoding: UTF-8
* checking CRAN incoming feasibility ... WARNING
Maintainer: 'Emmanuel Alcala <jealcala@gmail.com>'
New submission
Non-FOSS package license (CC-BY-4.0 + file LICENSE)
Unknown, possibly misspelled, fields in DESCRIPTION:
'Extdata'
Strong dependencies not in mainstream repositories:
rethinking
The Date field is over a month old.
* checking package namespace information ... OK
* checking package dependencies ... OK
* checking if this is a source package ... OK
* checking if there is a namespace ... OK
* checking for executable files ... OK
* checking for hidden files and directories ... OK
* checking for portable file names ... OK
* checking serialization versions ... OK
* checking whether package 'YEAB' can be installed ... ERROR
Installation failed.
See 'C:/Users/Zick/Documents/YEAB/YEAB-master/YEAB.Rcheck/00install.out' for details.
* DONE
Status: 1 ERROR, 1 WARNING
See
'C:/Users/Zick/Documents/YEAB/YEAB-master/YEAB.Rcheck/00check.log'
for details.
```
And when I open the "00install.out" file I get this error:
```
installing *source* package 'YEAB' ...
using staged installation
R
data
inst
byte-compile and prepare package for lazy loading
Error : 'library' is not an exported object from 'namespace:foreach'
Error: unable to load R code in package 'YEAB'
Execution halted
ERROR: lazy loading failed for package 'YEAB'
removing 'C:/Users/Zick/Documents/YEAB/YEAB-master/YEAB.Rcheck/YEAB'
```
The problem is that I'm not importing any function named "library" from the "foreach" namespace. What is more, if I'm not wrong, the "library" function comes from the "base" package, so I don't understand why I'm getting this error. My NAMESPACE file looks like this:
```
export(KL_div)
export(ab_range_normalization)
export(addalpha)
export(balci2010)
export(berm)
export(biexponential)
export(box_dot_plot)
export(bp_km)
export(bp_opt)
export(ceiling_multiple)
export(curv_index_fry)
export(curv_index_int)
export(den_histogram)
export(entropy_kde2d)
export(eq_hyp)
export(event_extractor)
export(exhaustive_lhl)
export(exhaustive_sbp)
export(exp_fit)
export(f_table)
export(fleshler_hoffman)
export(fwhm)
export(gaussian_fit)
export(gell_like)
export(get_bins)
export(hist_over)
export(hyperbolic_fit)
export(ind_trials_opt)
export(mut_info_discret)
export(mut_info_knn)
export(n_between_intervals)
export(objective_bp)
export(read_med)
export(sample_from_density)
export(trapezoid_auc)
export(unity_normalization)
export(val_in_interval)
importFrom(foreach,"%dopar%")
importFrom(foreach,foreach)
importFrom(MASS,kde2d)
importFrom(Polychrome,createPalette)
importFrom(cluster, clusGap)
importFrom(dplyr,between)
importFrom(dplyr,lag)
importFrom(infotheo,discretize)
importFrom(infotheo,mutinformation)
importFrom(magrittr,"%>%")
importFrom(minpack.lm,nls.lm)
importFrom(rmi,knn_mi)
importFrom(scales,show_col)
importFrom(sfsmisc,integrate.xy)
importFrom(zoo,rollapply)
importFrom(ggplot2, ggplot, aes, geom_point)
importFrom(grid, unit)
importFrom(gridExtra, grid.arrange)
importFrom(rethinking, HPDI)
importFrom(stats, median, optim, coef, fitted, approx, integrate, quantile)
importFrom("grDevices", "col2rgb", "grey", "rgb")
importFrom("graphics", "abline", "arrows", "axis", "box", "boxplot",
"grid", "hist", "layout", "lines", "mtext", "par",
"polygon", "stripchart", "text")
importFrom("stats", "approx", "bw.SJ", "coef", "cor", "density",
"fitted", "integrate", "lm", "loess", "median", "na.omit",
"nls", "nls.control", "optim", "pnorm", "quantile",
"rbinom", "runif")
importFrom("utils", "read.table", "stack", "tail", "write.csv")
importFrom(grid, unit, gpar, grid.polygon, grid.text, grid.layout, grid.newpage, pushViewport, viewport, grid.rect, grid.points, grid.xaxis, grid.yaxis, grid.segments)
importFrom(minpack.lm, "nls.lm.control")
importFrom(utils, "stack", "write.csv")
importFrom(ggplot2, theme_gray, element_line, element_blank, element_text)
importFrom(cluster, pam)
importFrom(dplyr, group_by, summarise)
```
I've looked all over the internet for a solution and tried to update the "foreach" package to it's latest version but to no avail. What is more strange is that if I delete these lines:
```
importFrom(foreach,"%dopar%")
importFrom(foreach,foreach)
```
from the NAMESPACE file I still get the same 'library' is not an exported object from 'namespace:foreach' error.
Have somebody else found this problem?
I'm quite new in R package development so I'm sorry if I turn out to be making a rookie mistake here. |
Unable to paste exe from a virtual machine to another virtual machine.
I have installed vmware tool on both computers.
[![enter image description here][1]][1]
help me.
[1]: https://i.stack.imgur.com/mK3mb.png |
On the VMware. Unable to paste exe from a virtual machine to another virtual machine |
|copy-paste|vmware| |
i am trying to get application context for showToast but not able to get it here is my code, always getting error :
>lateinit property appContext has not been initialized
```
package com.coding.APPNAVIGATION.MenuAndNavigationDrawer
import android.app.Application
import android.content.Context
open class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
MainApplication.appContext = applicationContext
}
companion object {
lateinit var appContext : Context
}
}
```
```
package com.coding.APPNAVIGATION.MenuAndNavigationDrawer.Utils
import android.widget.Toast
import com.coding.APPNAVIGATION.MenuAndNavigationDrawer.MainApplication
object Utils{
fun showToast(message : String){
Toast.makeText(MainApplication.appContext, message, Toast.LENGTH_LONG).show()
}
}
```
i want to get application context to run showToast anywhere within the project |
|android|kotlin| |
null |
For starters I think you need to add the full path of your mp3 file. For example:
pygame.mixer_music.load('/home/pi/Desktop/myfile.mp3') |
null |
null |
So I'm trying to run a CMD check for a package I want to upload to CRAN but when running it on my Windows 11 cmd I get the following error:
```
* using log directory 'C:/Users/Zick/Documents/YEAB/YEAB-master/YEAB.Rcheck'
* using R version 4.3.3 (2024-02-29 ucrt)
* using platform: x86_64-w64-mingw32 (64-bit)
* R was compiled by
gcc.exe (GCC) 12.3.0
GNU Fortran (GCC) 12.3.0
* running under: Windows 11 x64 (build 22631)
* using session charset: UTF-8
* using option '--as-cran'
* checking for file 'YEAB/DESCRIPTION' ... OK
* this is package 'YEAB' version '0.1.0'
* package encoding: UTF-8
* checking CRAN incoming feasibility ... WARNING
Maintainer: 'Emmanuel Alcala <jealcala@gmail.com>'
New submission
Non-FOSS package license (CC-BY-4.0 + file LICENSE)
Unknown, possibly misspelled, fields in DESCRIPTION:
'Extdata'
Strong dependencies not in mainstream repositories:
rethinking
The Date field is over a month old.
* checking package namespace information ... OK
* checking package dependencies ... OK
* checking if this is a source package ... OK
* checking if there is a namespace ... OK
* checking for executable files ... OK
* checking for hidden files and directories ... OK
* checking for portable file names ... OK
* checking serialization versions ... OK
* checking whether package 'YEAB' can be installed ... ERROR
Installation failed.
See 'C:/Users/Zick/Documents/YEAB/YEAB-master/YEAB.Rcheck/00install.out' for details.
* DONE
Status: 1 ERROR, 1 WARNING
See
'C:/Users/Zick/Documents/YEAB/YEAB-master/YEAB.Rcheck/00check.log'
for details.
```
And when I open the "00install.out" file I get this error:
```
* installing *source* package 'YEAB' ...
** using staged installation
** R
** data
** inst
** byte-compile and prepare package for lazy loading
Error : 'library' is not an exported object from 'namespace:foreach'
Error: unable to load R code in package 'YEAB'
Execution halted
ERROR: lazy loading failed for package 'YEAB'
* removing 'C:/Users/Zick/Documents/YEAB/YEAB-master/YEAB.Rcheck/YEAB'
```
The problem is that I'm not importing any function named "library" from the "foreach" namespace. What is more, if I'm not wrong, the "library" function comes from the "base" package, so I don't understand why I'm getting this error. My NAMESPACE file looks like this:
```
export(KL_div)
export(ab_range_normalization)
export(addalpha)
export(balci2010)
export(berm)
export(biexponential)
export(box_dot_plot)
export(bp_km)
export(bp_opt)
export(ceiling_multiple)
export(curv_index_fry)
export(curv_index_int)
export(den_histogram)
export(entropy_kde2d)
export(eq_hyp)
export(event_extractor)
export(exhaustive_lhl)
export(exhaustive_sbp)
export(exp_fit)
export(f_table)
export(fleshler_hoffman)
export(fwhm)
export(gaussian_fit)
export(gell_like)
export(get_bins)
export(hist_over)
export(hyperbolic_fit)
export(ind_trials_opt)
export(mut_info_discret)
export(mut_info_knn)
export(n_between_intervals)
export(objective_bp)
export(read_med)
export(sample_from_density)
export(trapezoid_auc)
export(unity_normalization)
export(val_in_interval)
importFrom(foreach,"%dopar%")
importFrom(foreach,foreach)
importFrom(MASS,kde2d)
importFrom(Polychrome,createPalette)
importFrom(cluster, clusGap)
importFrom(dplyr,between)
importFrom(dplyr,lag)
importFrom(infotheo,discretize)
importFrom(infotheo,mutinformation)
importFrom(magrittr,"%>%")
importFrom(minpack.lm,nls.lm)
importFrom(rmi,knn_mi)
importFrom(scales,show_col)
importFrom(sfsmisc,integrate.xy)
importFrom(zoo,rollapply)
importFrom(ggplot2, ggplot, aes, geom_point)
importFrom(grid, unit)
importFrom(gridExtra, grid.arrange)
importFrom(rethinking, HPDI)
importFrom(stats, median, optim, coef, fitted, approx, integrate, quantile)
importFrom("grDevices", "col2rgb", "grey", "rgb")
importFrom("graphics", "abline", "arrows", "axis", "box", "boxplot",
"grid", "hist", "layout", "lines", "mtext", "par",
"polygon", "stripchart", "text")
importFrom("stats", "approx", "bw.SJ", "coef", "cor", "density",
"fitted", "integrate", "lm", "loess", "median", "na.omit",
"nls", "nls.control", "optim", "pnorm", "quantile",
"rbinom", "runif")
importFrom("utils", "read.table", "stack", "tail", "write.csv")
importFrom(grid, unit, gpar, grid.polygon, grid.text, grid.layout, grid.newpage, pushViewport, viewport, grid.rect, grid.points, grid.xaxis, grid.yaxis, grid.segments)
importFrom(minpack.lm, "nls.lm.control")
importFrom(utils, "stack", "write.csv")
importFrom(ggplot2, theme_gray, element_line, element_blank, element_text)
importFrom(cluster, pam)
importFrom(dplyr, group_by, summarise)
```
I've looked all over the internet for a solution and tried to update the "foreach" package to it's latest version but to no avail. What is more strange is that if I delete these lines:
```
importFrom(foreach,"%dopar%")
importFrom(foreach,foreach)
```
from the NAMESPACE file I still get the same 'library' is not an exported object from 'namespace:foreach' error.
Have somebody else found this problem?
I'm quite new in R package development so I'm sorry if I turn out to be making a rookie mistake here. |
This CORS thing can be a headache to set especially for the first time. But by being precise you can do.
In your `Program.cs` file, make the following change. Notice that there are two changes to be made one above and another below the `var app = ...` statement:
```
builder.Services.AddCors(policyBuilder =>
policyBuilder.AddDefaultPolicy(policy =>
policy.WithOrigins("*").AllowAnyHeader().AllowAnyMethod())
);
var app = builder.Build();
app.UseCors();
```
If you are specifying an actual origin, make sure you include the `http` part for example:
```
...
policy.WithOrigins("http://localhost:3000")
```
Your web browser code making the request should also be in point. Here is the request in javascript using axios:
```
import axios from "axios";
const api = 'http://localhost:5000'
/**
*
* @returns {TransferHeader[]}
*/
export const fetchTransfers = async () => {
const { data } = await axios({
method: 'get',
url: `${api}/api/transfers`,
// withCredentials: true
})
console.log(data)
return data
}
```
|
{"OriginalQuestionIds":[201323],"Voters":[{"Id":14098260,"DisplayName":"Alexander Nenashev"},{"Id":1377002,"DisplayName":"Andy"},{"Id":535480,"DisplayName":"James","BindingReason":{"GoldTagBadge":"javascript"}}]} |
Easy on MYSQL Workbench. Create a new MySQL user and fill the "Limit to Host Matching" with your IP. Is % by default.
 |
**I am integrate laravel paypal by using srmklive laravel-paypal package (in sandbox and localhost) and send data from form to
paypal function and receive the error**
public function paypal(Request $request)
{
$provider = new PayPalClient;
$provider->setApiCredentials(config('paypal'));
$paypalToken = $provider->getAccessToken();
dd($paypalToken);
......
}
**recieve the eroor when dump and die at this stage and (in case of full code it automatically redirect to cancel route) .**
> Error Received : array:1 [▼ //
> app\Http\Controllers\PaypalController.php:23 "error" => " cURL error
> 60: SSL certificate problem: unable to get local issuer certificate
> (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for
> https://api-m.sandbox.paypal.com/v1/oauth2/token ◀ " ] |
laravel paypal ssl eror, package used srmklive / laravel-paypal |
|laravel|paypal| |
You have to inform IDE that which file is run setting file and you can do that by
1. Click on Test
2. Configure Run setting
3. Select solution wide run settings file
and select the file which is your run setting file
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/JsNCd.png |
I want to make the effect of the scrollview moving along when the view pops up like this:
[](https://i.stack.imgur.com/f68Kg.gif)
However, when I scroll the scrollview to the bottom, the following effect occurs:
[](https://i.stack.imgur.com/V6L3Z.gif)
I don't know why the value passed into setContentOffset is different from the contentOffset.
ScrollViewWrapper<Content: View>: UIViewRepresentable:
```
public func makeUIView(context: UIViewRepresentableContext<ScrollViewWrapper>) -> UIScrollView {
let view = UIScrollView()
view.delegate = context.coordinator
view.clipsToBounds = false
view.contentInsetAdjustmentBehavior = .never
// Instantiate the UIHostingController with the SwiftUI view
let controller = UIHostingController(rootView: content())
controller.view.translatesAutoresizingMaskIntoConstraints = false // Disable autoresizing
view.addSubview(controller.view)
// Set constraints for the controller's view
NSLayoutConstraint.activate([
controller.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
controller.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
controller.view.topAnchor.constraint(equalTo: view.topAnchor),
controller.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
controller.view.widthAnchor.constraint(equalTo: view.widthAnchor)
])
return view
}
public func updateUIView(_ uiView: UIScrollView, context: UIViewRepresentableContext<ScrollViewWrapper>) {
let newoffset = CGPoint(x: 0, y: self.contentOffset.y + uiView.contentOffset.y)
if newoffset.y > self.contentOffset.y{
uiView.setContentOffset(newoffset, animated: true)
}
}
```
ContentView
```
VStack(spacing:0){
Color.blue
.opacity(0.8)
.frame(height: 100)
.zIndex(1)
ScrollViewWrapper(contentOffset: $contentOffset, scrollViewHeight: $scrollViewHeight, visibleHeight: $scrollViewVisibleHeight) {
VStack {
ForEach(1..<51, id: \.self) { index in
Text("Item \(index)")
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.background(.green)
}
Button("test"){
withAnimation(.bouncy){
pop.toggle()
contentOffset = CGPoint(x: 0, y: pop ? 250 : -250)
}
}
.frame(maxWidth: .infinity, maxHeight: pop ? 300 : 50)
.padding(10)
.background(.black)
.opacity(0.8)
}
.ignoresSafeArea(.all)
.background(.red)
}
```
Edit:
I found that there is no any issue when ```setContentOffset(_, animated: false)```, and ```withAnimation() set to nil```.
Is there any solution with animation? |
Put a for loop iteration in a boostrap group list at button click |
I process a TEXT log file that contains, among other items, date in this form: 'January 20, 2021 5:26:19 pm'.
I don't have zone information. The system runs in complete isolation, such as offline mode, or no connectivity to the internet. Zero connectivity to the outside world.
I want to save this information to the database for further time comparison such look at logs which are greater than this time.
So, I save it to the POSTGRES database in a column of type timestamp.
When needed I retrieve from database convert to LocalDataTime and use it.
What is the right way or better way of saving this information to the database? |
Saving time to database in the absence of Zone information |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.