instruction stringlengths 0 30k ⌀ |
|---|
Consider something like [Google Input Tools](https://www.google.com/inputtools/) for instance, which can transliterate text in multiple languages using the Latin script. As you type a word, it interactively autocompletes it, showing you multiple possible results.
My question is, do the major OSs (i.e. Linux, macOS and Windows) enable developers to implement something like [Google Input Tools](https://www.google.com/inputtools/) system-wide? Such that a user can get the autocomplete service with a popup next to any text input field in any OS application?
The "autocomplete popup" needn't appear automatically, but could rather be enabled with a keyboard shortcut. Moreover, it needn't modify the target text field itself in real-time, but rather use a buffer of its own that can be easily copied to the original text field. Thus the ability to (1) detect the text field the cursor is located in and (2) copy text to said text field could be paired with the UI of something like Spotlight on macOS to achieve decent results.
However, I lack any knowledge about OS user-interface programming and thus I'm unsure if what I'm trying to achieve here is _universally_ supported by all major OSs. |
In c++, It's possible to use some tricks with the help of constexpr, to write a MACRO that encrypts strings in compile-time, and decrypts them in runtime, and we could use something like `ENCRYPT("MyString")` to achieve this. An example is the following header file:
https://github.com/skadro-official/skCrypter/blob/master/files/skCrypter.h
Is this also possible in Rust? I want to encrypt my strings in compile time, and decrypt them in runtime. |
You can use a guard to prevent recursive calls
``` vb
Private m_updating As Boolean
```
Then in the TextChanged event handlers check, set and reset the guard. Here
`HEX_TextChanged` as an example
``` vb
Private Sub HEX_TextChanged(sender As Object, e As EventArgs) Handles HEX.TextChanged
If Not m_updating Then
m_updating = True
Try
' TODO: put your conversion and updating logic here.
' (Don't remove or add event handlers)
Finally
m_updating = False
End Try
End If
End Sub
```
The Try-Finally statement makes sure the guard is reset in any case, even if an exception should occur or the code was left prematurely with a Return-statement.
Implement this in `HEX_TextChanged`, `DECDEC_TextChanged`, `bin_TextChanged` and `oct2_TextChanged`.
The `KeyPress` methods do not require a guard or removing/adding the event handlers, because they are only filtering keys and do not update other TextBoxes (this is what raises the TextChanged events and caused the recursive calls).
You can also slightly simplify them by directly assigning the Boolean value:
``` vb
Private Sub bin_KeyPress(sender As Object, e As KeyPressEventArgs) Handles bin.KeyPress
e.Handled = Not (e.KeyChar = "0"c OrElse e.KeyChar = "1"c OrElse
Char.IsControl(e.KeyChar))
End Sub
```
I didn't check whether your actual filtering or conversion logic is correct. |
flatpak creation issue for old version of Wine (6.13) |
|wine|flatpak|flatpak-builder| |
I am trying to use Ruby to emulate an `append` function from DrRacket. However, when I try it, I get `((1 2 3) . 99)` instead of `(1 2 3 . 99)`. Is it possible to correctly emulated `append` with a preexisting list, or do I need to make a copy of it first? Please reply at your earliest convenience.
|
I'm struggling to get the correct keyboard to show and be able to insert numbers and the decimal symbol but I'm faced with a strange situation.
This is what i got with Android Studio using Java code:
[![enter image description here][1]][1]
Here the xml code to show this keypad:
<EditText
android:id="@+id/editTextNumberDecimal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="1dp" />
So in this case everything works fine, i can digit numbers and dot to separate decimals.
Using Visual Studio with Net Xamarin and Syncfusion the keypad change like this:
[![enter image description here][2]][2]
The Keypad Show the negative sign and the dot.
I can insert in the negative sign doing double tap as the first char but not the dot.
The dot is never get showed on the textbox.
here is the xml code to call the numeric keypad:
<control:BorderlessEntry
x:Name="StretchRatioLenEntry"
Placeholder="(Es. 3,3)"
Keyboard= "Numeric"
Style="{StaticResource BorderlessEntryStyle}"
Text="{Binding StretchRatioLen.Value}" PlaceholderColor="#7B7B7B">
<Entry.Behaviors>
<behaviour:NumberEntryBehavior IsValid="{Binding StretchRatioLen.IsValid}" />
</Entry.Behaviors>
</control:BorderlessEntry>
So do you have any suggestion?
Thanks for your help.
[1]: https://i.stack.imgur.com/oxV0Y.png
[2]: https://i.stack.imgur.com/7wDQ1.png |
|reactjs|react-state| |
A normal user **(Note: I mean only the user, and not a programmer or developer)** doesn't need to know how many arguments or what arguments are required. It is the responsibility of the developer to give the program user friendly. For instance, for giving the approximate age of a user, user is asked to give only the year of birth. Whereas, if the program needs to give the accurate age, the user will be asked to give date, month and year of birth.
In either cases, the user doesn't need to remember what arguments to give. Because, the user is going to answer only the questions they are asked.
Coming to the second part of the question, Being a programmer, if you don't know which argument to write first and which next, There are better ways to call a function.
you can very well call a function like `function_name(age=25, name='Pratik Vaidhya')`. Here the order of the arguments doesn't matter if you mention the arguments' name as well. But remember, you must stick to the spelling and capitalisation as per the syntax. |
I could solve the same error by instructing the scm plugin to use the 'github' server for the credentials.
This can be done by adding the following property in the `pom.xml`:
<properties>
<project.scm.id>github</project.scm.id>
</properties>
In my Maven `settings.xml` I have the following configuration for the github server:
<server>
<id>github</id>
<username>$GITHUB_ACTOR</username>
<password>$GITHUB_TOKEN</password>
</server> |
I am trying to work with llama index and constantly i coming across the error of loading the document.
#Load and index the data with the simpleDirectoryReader of Llama Index
reader = SimpleDirectoryReader(input_files=["./modals/llamaindex test/data/paul_graham_essay.txt"])
docs = readr.load_data()
print(f"Loaded{len(docs)}docs") this is my code.
[Basically the error says document is not in the desired location and dont know the exact reason why is it so.](https://i.stack.imgur.com/Ia9BI.png)
I am trying to provide the llama index with the document and then ask question regarding that. I am strictly following the website and completely new with this AI and coding.
|
How can i import the document in Llamaindex |
|artificial-intelligence|huggingface-transformers|llama-index| |
null |
I generate a PDF file and the unicode text appears in macos preview but not acrobat.
I have the following `fdf` file
```
%FDF-1.2
1 0 obj
<<
/FDF
<<
/Fields [
<<
/T (name)
/V <FEFF0793>
>>]
>>
>>
endobj
trailer
<<
/Root 1 0 R
>>
%%EOF
```
The main thing is `FEFF0793` which is `utf16be` encoded, and it should render the `ޓ` character (https://www.compart.com/en/unicode/U+0793)
```
pdftk form4.pdf fill_form fdf output 6.pdf
```
My [form4.pdf][1]
When I view it in MacOS preview, it doesn't appear until I click
[![enter image description here][2]][2]
[![enter image description here][3]][3]
but in acrobat it appears as a bullet point
[![enter image description here][4]][4]
Here is the fonts embedded. Whats the problem here? Why doesn't it appear in acrobat?
The font is from here: https://fonts.google.com/noto/specimen/Noto+Sans+Thaana
It's added to my MacOS fontbook, so not sure whats happening here. What if I had custom fonts that aren't part of my fontbook but I want to use their unicode values. What do I do here?
[![enter image description here][5]][5]
[1]: https://www.mediafire.com/file/jnbkbpd18ebynkd/form4.pdf/file
[2]: https://i.stack.imgur.com/ZmNpmt.png
[3]: https://i.stack.imgur.com/yktDKt.png
[4]: https://i.stack.imgur.com/5CqgNt.png
[5]: https://i.stack.imgur.com/r6lMrm.png |
pdftk unicode works in preview but not adobe acrobat |
|pdf|unicode|utf-8|pdftk| |
We're in the process of upgrading our PHP Laravel system, and one of the key concerns is the compatibility of passwords between the old and new systems. The passwords in the old system are encrypted, and we need to ensure a smooth transition to the new encryption method without causing disruption to users' access. What would be the best approach or workaround to handle this situation effectively in PHP Laravel?
Any insights or suggestions would be greatly appreciated. |
How to Safely Migrate Encrypted Passwords During a PHP Laravel System Upgrade? |
|php|laravel-8|bcrypt|password-encryption| |
For smoother interaction of my application with the user I need to know when my program can see **the whole flow** of keyboard events from the user, and when this flow is interrupted. I’m testing my approach on a simple top-level with only a (subclassed) Rich Edit control inside. It turns out that checking for `WM_KILLFOCUS` and `WM_SETFOCUS` messages *is not enough*: these messages do not arrive when the text edit window wants to show menus. These menus “eat” the keypresses/keyreleases, but no “expected” message notifies me about this situation.
For the right-mouse-button menu I thought that monitoring `WM_INITMENU`, `WM_INITMENUPOPUP`, `WM_UNINITMENUPOPUP`, `WM_ENTERMENULOOP`, `WM_EXITMENULOOP`, `WM_SYSCOMMAND`, `WM_COMMAND`, `WM_MENUCOMMAND`, `WM_MENUSELECT`, `WM_ACTIVATE`, `WM_ACTIVATEAPP`, `WM_MENUCHAR` would give me “plenty of warnings” about what is going to happens. To my surprise, only `WM_MENUCOMMAND` (“marked as failure”) is received! Well, very strange — but I can live with it.
However, I cannot detect `Alt`-tapping (which moves the focus to “the icon for window’s menu” of the main window) *at all*: the next key-down event is (typically¹⁾) eaten, and **no mentioned message** arrives… For example, `Alt`-tap `f` gives key-down and key-up for `Alt`, but only key-up for `f`.
> ¹⁾ “Typical” since pressing *appropriate* keys (say, down-arrow) in this situation visualizes the “window’s menu”. However “a random key” would “cancel the focus stealing”. — However, the price is that one key-down event disappears.
So now **my questions**: the show-stopper for *now* is the detection of the focus moving to the icon for window’s menu. Can an application detect this moment? The second question is to understand why for the context menu (e.g., tapping on the `Apps` key) I do not get anything before the `MENUCOMMAND` event.
**Finally**: eventually, (if it works) I would prefer my code to be in a library — so it would need cohabitation with a multitude of ways.to “manage the window”. What I discussed above shows that (apparently) in Windows *there is a way* to steal focus without notifications. This means that there may be “other situations” — others than two types of menus discussed above — which would give the same kind of trouble to my code. So my third **Question:** is there a robust way to work around such situations? (And: how such situations are implemented via Windows APIs?!) |
null |
null |
null |
null |
null |
null |
I cannot reproduce your error since it would be impossible without the source data to run it through, but I am 99.99% sure about what is happening just by looking at the code. The issue is the use of GridSearchCV here.
CV stands for cross-validation. This means that in order to evaluate the performance of a single grid point (for each combination of hyperparameters), three different models are trained for three different splits of data (that is the cv=3 you have passed in the args), then a final result in accurary is the average of them all. The process would look like something like this conceptually:
* [first of data 1/3 (**test**), second of data 1/3 (**train**), third of data 1/3 (**train**)] -> accuracy 80%
* [first of data 1/3 (**train**), second of data 1/3 (**test**), third of data 1/3 (**train**)] -> accuracy 82%
* [first of data 1/3 (**train**), second of data 1/3 (**train**), third of data 1/3 (**test**)] -> accuracy 85%
The total estimated performance would be (80+82+85)/3=82.33%. Now, I would guess that by the book you are studying and the level of your code you already know that. The real problem lays in that **the train/test splits are done in the beggining of the pipeline**. This make sense to avoid data leaking, since if you want to impute some NA value by the mean for example, you want to use the mean of only the data of the train set on each split and not the whole data since that would contaminate the train split information of the test set.
In a one-hot encoding you must perform the encoding before the split. Imagine what happens when you are unlucky in one of this automatic splits. There is a label in the test set that does not appear in the train set. That label is missing in the train set so there is no encoding for it, so now applying that encoding to the test set yields an error. Apply the one hot encoding before (maybe as a pre-pipeline) and the use the Grid Search with CV on the rest of teh pipeline, that should fix that. |
[EDIT] since 17.1 you can now use a [signal as input](https://angular.io/guide/signal-inputs#signal-inputs). There is no need for `@Input()` anymore:
```typescript
firstName = input<string>(); //InputSignal<string|undefined>
```
Previous answer below:
It's not yet ready, you can however convert a regular input into a signal one using this helper:
```typescript
//signal-property.helper.ts
import { signal, Signal } from '@angular/core';
const cacheMap = Symbol('Cached values');
function getObservableMap<T extends Object, K extends keyof T>(
obj: T
): Map<K, Signal<T[K]>> {
// upsert the cacheMap
return ((obj as any)[cacheMap] =
(obj as any)[cacheMap] ?? new Map<any, any>());
}
function isUsingAccessor<T extends Object, K extends keyof T>(
obj: T,
variable: K
): boolean {
// the prototype of the object (and not the own property) is holding information about the object getters at the time of the construction
const prototypeOfObject = Object.getPrototypeOf(obj);
const descriptorOfPrototype = Object.getOwnPropertyDescriptor(
prototypeOfObject,
variable
);
return (
!!descriptorOfPrototype &&
('get' in descriptorOfPrototype || 'set' in descriptorOfPrototype)
);
}
function checkIsNotAccessor<T extends Object, K extends keyof T>(
obj: T,
variable: K
): void {
if (isUsingAccessor(obj, variable)) {
throw new Error('Listening value accessors is not supported');
}
}
function createSignalProperty<T extends Object, K extends keyof T>(
obj: T,
variable: K
): Signal<T[K]> {
const defaultDescriptor: PropertyDescriptor =
Object.getOwnPropertyDescriptor(obj, variable) ??
defaultPropertyDescriptor();
const aSignal = signal<T[K]>(undefined as any);
checkIsNotAccessor(obj, variable);
const { enumerable, configurable } = defaultDescriptor;
const descriptor: PropertyDescriptor = {
configurable,
enumerable,
get: () => defaultDescriptor.value,
set: (nextValue) => {
defaultDescriptor.value = nextValue;
aSignal.set(nextValue);
},
};
const isValueAlreadyDeclared = 'value' in defaultDescriptor;
if (isValueAlreadyDeclared) {
aSignal.set(defaultDescriptor.value);
}
Object.defineProperty(obj, variable, descriptor);
return aSignal.asReadonly();
}
function defaultPropertyDescriptor(): PropertyDescriptor {
return {
configurable: true,
enumerable: true,
writable: true,
};
}
export function asSignal<T extends Object, K extends keyof T>(
obj: T,
property: K
): Signal<T[K]> {
const map = getObservableMap(obj);
if (!map.has(property)) {
map.set(property, createSignalProperty(obj, property));
}
// casting is mandatory
return map.get(property)! as Signal<T[K]>;
}
```
usage is as follows:
```typescript
import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { asSignal } from '../../../shared/helpers/signal/signal-property.helper';
@Component({
selector: 'app-sub-test',
standalone: true,
imports: [CommonModule],
template: '{{valueSignal()}}', // print the signal
styleUrls: ['./sub-test.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SubTestComponent {
@Input()
value!: string;
valueSignal = asSignal(this, 'value'); // here is a signal of value
}
```
|
You can use type hints to make sure that pycharm knows the type of dynamically created objects:
class Dialog(QDialog):
def __init__(self):
super(Dialog, self).__init__()
loadUi("dialog.ui", self)
self.table: QTableView = self.findChild(QTableView, "tableView")
or without the unecessary `findChild`
class Dialog(QDialog):
def __init__(self):
super(Dialog, self).__init__()
loadUi("dialog.ui", self)
self.tableView: QTableView |
You're using `actions/github-script@v6` to run shell commands. It's not meant for that.
Try this way:
name: Update version
on:
push:
tags:
- 'v*' # Trigger only in case of new tag
jobs:
update_version:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Update version
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git config --global user.email "jdbdsj@gmail.com"
git config --global user.name "Github actions"
echo "Release Tag: ${{ github.ref_name }}"
release_tag="${{ github.ref_name }}"
# Update the value in the specified file (replace with your details)
sed -i "s/const version = .*/const version = \"$release_tag\"/" ./hackkerRankSolutions/version.go
git add version.go
git commit -m "Update version to $release_tag in actions.yaml"
git push origin main
|
## Why is not running?
Basically, is not usual to use CMD and ENTRYPOINT **together**. If you do that, the cmd instructions are appended to the entrypoint as simple arguments. In your case something like this:
```
ENTRYPOINT["/entrypoint.sh", "/bin/bash", "-c", "/log-agent.sh"]
```
More details here
- https://stackoverflow.com/questions/47648775/docker-entrypoint-and-cmd-together
## Explanation
In docker, only one foreground process can run. Several processes in just one container is not a good practice.
[Docker official web says :](https://docs.docker.com/config/containers/multi-service_container/)
> It is generally recommended that you separate areas of concern by using **one service per container**
Also to have several processes inside of one container is called: Fat container
Anyway you have these alternatives:
## #1 Supervisor
With supervisor, you can run several process in one container. For example: postgress + java. In your case, the supervisor config file could be like this
```
[program:java]
command=/entrypoint.sh
autorestart=false
autostart=true
process_name=java-app
[program:java]
command=/log-agent.sh
autorestart=false
autostart=true
process_name=agent
```
More details here:
https://stackoverflow.com/questions/70308825/how-to-package-several-services-in-one-docker-image/70326121#70326121
## #2 Send agent to background
- First the java and agent launch should be in your entrypoint.sh
- The agent should be launched to the background before java
Something like this
```
#launch agent
bash /log-agent.sh > /dev/null 2>&1 &
#launch java app
java -jar ....
```
- And your Dockerfile should end with `ENTRYPOINT ["/entrypoint.sh"]`
Notes:
- I tried with nohup but it doesn't works with scripts inside a container: https://stackoverflow.com/questions/49470044/not-able-to-start-2-tasks-using-dockerfile-cmd
|
`selectedBook = aStoreItems[i];` is never executed. It is dead code. When `return` is executed, the function exits and executes no other statements in that function are executed.
You should just not have that `selectedBook` variable. Instead *use* what the function returns at the calling side. So in the second part of your code do:
```
const selectedBook = getBookById(bookSelection);
console.log("return is(in add to cart function) " + selectedBook);
```
As a side note, this also defines `selectedBook` as a *local* variable, which is preferable over global variables. |
I'm trying to rejigger my usage of web worker pooling to eliminate redundant server requests. In my existing solution, I'm loading workers pretty straightforwardly like this:
```js
const worker = new Worker(`${src}?v=${version}`);
```
This happens `N` times for each worker pool. WebPack has no problem with this. But, in production, the `N` requests are superfluous, wasteful, and seem to introduce a little unnecessary latency. So, I'd like to get rid of them. To that end, I'm trying to load my worker code with a cached/debounced `fetch()` and feed the contents into the worker with a blob URL.
```js
const worker = getBundleDataURI(src).then(uri => {
return new Worker(uri);
});
```
Functionally, the worker is loading and operational. But locally, WebPack is now trying and failing to reconnect to `ws://0.0.0.0:9999/ws` on repeat, *flooding* the console with errors in the process.
How do make it stop?
---
My current workaround is *essentially* to use blobs only in staging + prod:
```js
const isLocal = checkIfHostnameIsLocalhost(); // more or less
if (isLocal) {
const worker = new Worker(src);
} else {
const worker = getBundleDataURI(src).then(uri => {
return new Worker(uri);
});
}
```
But, because I'm running slightly different code in dev environments, this comes with the risk of caching catastrophic regressions *late* (possibly even in production). |
I wrote a SnippingWidget function and linked it to the main code. After executing this function, my application crashes with an error. I looked up what the error is with try and it says: "PyQt5.QtCore.pyqtSignal' object has no attribute 'emit'". I want this function to just hide itself when finished, meaning it can be reused. Initially the same error came up, but with "closed", I was able to solve it. But I don't understand what to do with emit....
Here is the code for my function:
```
from PyQt5 import QtCore, QtGui, QtWidgets
class SnippingWidget(QtWidgets.QDialog):
def __init__(self):
super(SnippingWidget, self).__init__()
self.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
self.setStyleSheet("background:transparent;")
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.outsideSquareColor = "red"
self.squareThickness = 2
self.start_point = QtCore.QPoint()
self.end_point = QtCore.QPoint()
self.selected_area = None
# Установка размеров окна в соответствии с размерами экрана
screen_geometry = QtWidgets.QApplication.desktop().screenGeometry()
self.setGeometry(screen_geometry)
def mousePressEvent(self, event):
self.start_point = event.pos()
self.end_point = event.pos()
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.CrossCursor)
self.update()
def mouseMoveEvent(self, event):
self.end_point = event.pos()
self.update()
def mouseReleaseEvent(self, QMouseEvent):
r = QtCore.QRect(self.start_point, self.end_point).normalized()
self.hide()
self.selected_area = r
QtWidgets.QApplication.restoreOverrideCursor()
self.closed.emit()
self.start_point = QtCore.QPoint()
self.end_point = QtCore.QPoint()
def paintEvent(self, event):
trans = QtGui.QColor(22, 100, 233)
r = QtCore.QRectF(self.start_point, self.end_point).normalized()
qp = QtGui.QPainter(self)
trans.setAlphaF(0.2)
qp.setBrush(trans)
outer = QtGui.QPainterPath()
outer.addRect(QtCore.QRectF(self.rect()))
inner = QtGui.QPainterPath()
inner.addRect(r)
r_path = outer - inner
qp.drawPath(r_path)
qp.setPen(
QtGui.QPen(QtGui.QColor(self.outsideSquareColor), self.squareThickness)
)
trans.setAlphaF(0)
qp.setBrush(trans)
qp.drawRect(r)
```
For "closed", I defined a closed signal:
`closed = QtCore.pyqtSignal()` |
I have a ViewPager 2 inside a plannerFragment, which calls 2 fragments: one (localeChoosingFragment) contains a recyclerview for the user to choose a locale, and another to choose places within that locale (localeExploringFragment). A ViewModel (japanGuideViewModel) stores the data (as MutableLiveData), including the int currentLocaleBeingViewed. When the user chooses a locale, this is updated, and an observer in the plannerFragment causes one of the tabs in the PlannerFragment to update with the name of that locale. Clicking that tab the loads the localeExploringFragment for that locale.
When the observer in the plannerFragment is triggered, the tab is updated. This causes the recyclerview in the localeChoosingFragment to reset to the first position. As a workaround I have tried using a Handler to automatically scroll the recyclerview to the correct place (according to the ViewModel) but I am confused and concerned about why this is happening. Before using the ViewPager2, I added both (localeChoosingFragment and localeExploringFragment) to a framelayout manually, and tried show/hide and attach/detach, but had the same problem (the recyclerview resetting to the first position).
Does anyone know why this could be? It seems a small thing, but I am concerned that there is something going on I don't and should know about, especially this early in the project.
The recyclerview is not recreated, and nor is notifyDataSet changed.
That ViewPager 2 is actually part of a fragment that is selected from another ViewPager 2, but I don't think that's what's causing the problem.
I will attach a cleaned up version of my code.
Here is the plannerFragment:
public class PlannerFragment extends Fragment {
Context mContext;
JapanGuideViewModel japanGuideViewModel;
View plannerFragmentView;
ViewPager2 plannerFragmentViewPager2;
TabLayout tabLayout;
public static final String TAG = "JapanGuideTAG";
public PlannerFragment() {
Toast.makeText(mContext, "New Planner Fragment, empty constructor", Toast.LENGTH_SHORT).show();
}
public PlannerFragment(Context mContext, JapanGuideViewModel japanGuideViewModel) {
this.japanGuideViewModel = japanGuideViewModel;
this.mContext = mContext;
Log.d(TAG, "New Planner Fragment, arguments passed");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "oncreate in planner fragment");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "oncreateview in planner fragment");
plannerFragmentView = inflater.inflate(R.layout.fragment_planner, container, false);
return plannerFragmentView;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d(TAG, "onViewCreated in PlannerFragment");
plannerFragmentViewPager2 = plannerFragmentView.findViewById(R.id.plannerFragmentViewPager2);
tabLayout = plannerFragmentView.findViewById(R.id.plannerFragmentTabLayout);
PlannerFragmentViewPager2Adaptor plannerFragmentViewPager2Adaptor = new PlannerFragmentViewPager2Adaptor(getChildFragmentManager(), getLifecycle(), mContext, japanGuideViewModel);
plannerFragmentViewPager2.setAdapter(plannerFragmentViewPager2Adaptor);
plannerFragmentViewPager2.setUserInputEnabled(false);
TabLayoutMediator.TabConfigurationStrategy tabConfigurationStrategy = new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
Log.d(TAG, "onConfigure in tabConfigurationStrategy");
if (position == 0) {
Log.d(TAG, "Chooser");
tab.setText("Explore Prefectures");
} else if (position == 1) {
tab.setText("Explore Chosen Prefecture");
}
}
};
Log.d(TAG, "attachingTabLayoutMediator");
new TabLayoutMediator(tabLayout, plannerFragmentViewPager2, tabConfigurationStrategy).attach();
Observer dataDownloadedObserver = new Observer() {
@Override
public void onChanged(Object o) {
if (japanGuideViewModel.getDataDownloaded().getValue() > 0) {
Log.d(TAG, "onChanged called in data downloaded observer. Value is " + japanGuideViewModel.getDataDownloaded().getValue());
japanGuideViewModel.getCurrentLocaleBeingViewed().setValue(0);
}
}
};
Observer localeToExploreChangedObserver = new Observer() {
@Override
public void onChanged(Object o) {
Log.d(TAG, "localeChangedObserver in planner fragment");
TabLayout.Tab tab = tabLayout.getTabAt(1);
if (tab != null) {
Log.d(TAG, "the tab is" + tab.getPosition());
// THIS IS WHERE THE PROBLEM OCCURS.
// If this line (setting the text) is removed, the recyclerview in
// localeChoosingFragment does not reset to the first position.
tab.setText(japanGuideViewModel.getLocaleNamesArray().getValue().get(japanGuideViewModel.getCurrentLocaleBeingViewed().getValue()));
}
}
};
japanGuideViewModel.getCurrentLocaleBeingViewed().observe(getViewLifecycleOwner(), localeToExploreChangedObserver);
japanGuideViewModel.getDataDownloaded().observe(getViewLifecycleOwner(), dataDownloadedObserver);
} //onViewCreated
public class PlannerFragmentViewPager2Adaptor extends FragmentStateAdapter {
Context mContext;
JapanGuideViewModel japanGuideViewModel;
public PlannerFragmentViewPager2Adaptor(FragmentManager fragmentManager, Lifecycle lifecycle, Context mContext, JapanGuideViewModel japanGuideViewModel) {
super(fragmentManager, lifecycle);
this.japanGuideViewModel = japanGuideViewModel;
this.mContext = mContext;
Log.d(TAG, "full constructor in planner fragment");
}
@NonNull
@Override
public Fragment createFragment(int position) {
Log.d(TAG, "createFragment called in plannerFragment. Position is ");
switch (position) {
case 0:
Log.d(TAG, "planner fragment, case 0, localechoosingfragment");
LocaleChoosingFragment localeChoosingFragment = new LocaleChoosingFragment(mContext, japanGuideViewModel);
return localeChoosingFragment;
case 1:
Log.d("planner fragment localeExploringFragmentTAG", "case 1");
LocaleExploringFragment localeExploringFragment = new LocaleExploringFragment(mContext, japanGuideViewModel);
return localeExploringFragment;
default:
Log.d(TAG, "default constructor so returning localeChoosingFragment");
localeChoosingFragment = new LocaleChoosingFragment(mContext, japanGuideViewModel);
return localeChoosingFragment;
}
}
@Override
public int getItemCount() {
return 2;
}
}
}
And here is the localeChoosingFragment:
public class LocaleChoosingFragment extends Fragment {
JapanGuideViewModel japanGuideViewModel;
Context mContext;
View localeChoosingFragmentView;
public static final String TAG = "JapanGuideTAG";
RecyclerView localeChoosingRecyclerView;
LinearLayoutManager recyclerViewLayoutManager;
LocaleChoosingRecyclerViewAdaptor localeChoosingAdaptor;
SnapHelperOneByOne SnapHelper;
public LocaleChoosingFragment() {
Log.d(TAG, "EMPTY constructor called for localeChoosingFragment");
}
public LocaleChoosingFragment(Context mContext, JapanGuideViewModel japanGuideViewModel) {
this.japanGuideViewModel = japanGuideViewModel;
this.mContext = mContext;
Log.d(TAG, "constructor called for localeChoosingFragment");
Toast.makeText(mContext, "Creating a new localeChoosingFragment", Toast.LENGTH_SHORT).show();
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate in localeChoosingFragment");
super.onCreate(savedInstanceState);
Log.d(TAG, "creating a NEW LOCALECHOOSING RECYCLERVIEW");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.d(TAG, "onCreateView called in LocalChoosingFragment");
localeChoosingFragmentView = inflater.inflate(R.layout.fragment_locale_choosing, container, false);
localeChoosingRecyclerView = localeChoosingFragmentView.findViewById(R.id.localeChoosingRecyclerView);
return localeChoosingFragmentView;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d(TAG, "onviewcreated in locale choosing fragment.");
localeChoosingAdaptor = new LocaleChoosingRecyclerViewAdaptor(mContext, japanGuideViewModel);
SnapHelper = new SnapHelperOneByOne();
recyclerViewLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
localeChoosingRecyclerView.setLayoutManager(recyclerViewLayoutManager);
localeChoosingRecyclerView.setAdapter(localeChoosingAdaptor);
SnapHelper.attachToRecyclerView(localeChoosingRecyclerView);
// localeChoosingRecyclerView.scrollToPosition(japanGuideViewModel.getCurrentLocaleBeingViewed().getValue());
}
public class LocaleChoosingRecyclerViewAdaptor extends RecyclerView.Adapter {
Context mContext;
JapanGuideViewModel japanGuideViewModel;
Button exploreNowButton;
Button wontGoHereButton;
TextView localeNameTextView;
TextView localeDescriptionTextView;
ImageView localePhotoImageView;
TextView localePhotoCaptionTextView;
public LocaleChoosingRecyclerViewAdaptor() {
Log.d(TAG, "localeChoosingAdaptor created with empty constructor");
}
public LocaleChoosingRecyclerViewAdaptor(Context mContext, JapanGuideViewModel japanGuideViewModel) {
this.mContext = mContext;
this.japanGuideViewModel = japanGuideViewModel;
Log.d(TAG, "localeChoosingAdaptor created with full constructor");
}
@NonNull
@Override
public LocaleChoosingAdaptorHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Log.d(TAG, "oncreateviewholder in localechoosingfragment");
View view = LayoutInflater.from(mContext).inflate(R.layout.locale_recyclerview_holder, parent, false);
return new LocaleChoosingAdaptorHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder called in localeChoosingFragment. The position is " + position + " and the total size is " + getItemCount());
localeNameTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderHeadingTextview);
localeNameTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(position).getLocaleName());
localeDescriptionTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderDescriptionTextView);
if (japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getLocaleDescription() != null) {
localeDescriptionTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getLocaleDescription());
}
localePhotoImageView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderImageView);
if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().size() != 0)) {
if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL() != null) && (!(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL().equals("")))) {
Glide.with(mContext).load(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL()).into(localePhotoImageView);
}
localePhotoCaptionTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderPhotoCaptionTextView);
if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption() != null) && (japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption() != "")) {
localePhotoCaptionTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption());
}
}
exploreNowButton = holder.itemView.findViewById(R.id.LocaleRecyclerviewHolderExploreNowButton);
wontGoHereButton = holder.itemView.findViewById(R.id.LocaleRecyclerviewHolderWontGoHereButton);
exploreNowButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "Explore now button clicked. Setting the locale to explore to " + japanGuideViewModel.getCurrentLocaleBeingViewed().getValue());
japanGuideViewModel.getCurrentLocaleBeingViewed().setValue(holder.getAdapterPosition());
}
});
} //bind
@Override
public int getItemCount() {
return japanGuideViewModel.getLocalesDetailsArray().getValue().size();
}
} //recyclerview adaptor
public class LocaleChoosingAdaptorHolder extends RecyclerView.ViewHolder {
TextView localeNameTextView;
TextView localeDescriptionTextView;
Button exploreNowButton;
Button wontGoHereButton;
public LocaleChoosingAdaptorHolder(@NonNull View itemView) {
super(itemView);
Log.d(TAG, "localechoosing recyclerview holder constructor called");
localeNameTextView = itemView.findViewById(R.id.localeRecyclerviewHolderHeadingTextview);
localeDescriptionTextView = itemView.findViewById(R.id.localeRecyclerviewHolderDescriptionTextView);
exploreNowButton = itemView.findViewById(R.id.LocaleRecyclerviewHolderExploreNowButton);
wontGoHereButton = itemView.findViewById(R.id.LocaleRecyclerviewHolderWontGoHereButton);
}
}
}
I was not expecting the RecyclerView in LocaleChoosingFragment to reset to the first position when the observer in the plannerFragment is trigg`your text`ered by the observer on currentLocaleBeingViewed in the View model. Everything else works as expected.
|
Your approach seem okay for implementing entity auditing in spring boot. However
1. Your AuditorAware implementation looks appropriate for fetching the current user. Ensure that it correctly handles scenarios where the user is not authenticated or the current user cannot be determined.
2. Using a MappedSuperclass for your AuditableEntity is a valid approach. However, you could also consider using an @Embeddable class that contains audit fields and embed it within your entities. This approach keeps your entity classes cleaner and allows for easier reuse if you have multiple auditable entities. Here is an example on how to implement it [https://www.baeldung.com/spring-jpa-embedded-method-parameters#:~:text=We%20represent%20a%20composite%20primary,field%20of%20the%20%40Embeddable%20type.][1]
3. it's not advisable to have a one-to-many relationship between AuditableEntity and User for the reasons you mentioned. If you must tie it to the user entitity then, Storing only the ID of the user in the AuditableEntity is a more appropriate approach.
[1]: https://www.baeldung.com/spring-jpa-embedded-method-parameters#:~:text=We%20represent%20a%20composite%20primary,field%20of%20the%20%40Embeddable%20type. |
For install **cudatoolkit and cudnn** by Anaconda you can use these following command `conda install -c conda-forge cudatoolkit=11.2 cudnn=8.1.0`
You must aware the **tensorflow version** must be less than **2.11**
For check if the everything installed properly
1) In command prompt check `nvidia-smi` command. if shows command not found you must install the latest GPU driver
2) Use this python script to config the GPU in programming
import tensorflow as tf
if tf.config.list_physical_devices('GPU'):
print('GPU is available.')
else:
print('GPU is NOT available. Make sure TensorFlow version less than 2.11 and Installed all GPU drivers.')
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.compat.v1.Session(config=config) |
I'm trying to build a work schedule tracker, starting with the header. A picture attachement shows how the design will look once completed [Schedule Header Cosmetics](https://i.stack.imgur.com/DtFf0.png)
I have three classes so far,
- InputWindow: A Toplevel window for a user to select a month and year from two comboboxes
- App: the main window, based on the user selections in InputWindow, App should load a header consisting of the elements in container TitleFrame
- TitleFrame: a frame consisting of the app title, the selected month and selected year on the left, and a grid consisting of weekdays for the month in the first row, day numbers of the month on the second row, and crew shifts as "D" or "N" on the third row.
Here is the code:
`# PEP8 Compliant Guidance
# Standard Library Imports
import tkinter as tk
from tkinter import ttk
import datetime
# Third-Party Library Imports
# Local Application/Library Specific Imports
import functions
class InputWindow(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
# Customize the top-level window as needed
self.title("Schedule Selection")
self.geometry("400x500")
# widgets, labels, and other elements for user selections
currentdate = datetime.datetime.now()
currentmonth = currentdate.strftime("%B")
currentyear = currentdate.strftime("%Y")
# Month Selection
self.select_schedule_month = ttk.Combobox(self, values=functions.months_list())
self.select_schedule_month.set(currentmonth)
self.select_schedule_month.pack()
# Year Selection
self.select_schedule_year = ttk.Combobox(self, values=functions.years_list())
self.select_schedule_year.set(currentyear)
self.select_schedule_year.pack()
# Button to confirm selections and open the main application window
sel_button = tk.Button(self, text="Confirm", command=self.confirm_selections)
sel_button.pack()
def confirm_selections(self):
# Perform validation and check if the proper selections are made
# If selections are valid, hide the top-level window and open the main application window
if self.selections_are_valid():
self.selected_month = self.select_schedule_month.get()
self.selected_year = self.select_schedule_year.get()
self.withdraw() # Hide the top-level window
self.master.deiconify() # Show the main application window
def selections_are_valid(self):
# Implement your logic to validate selections
# Return True if selections are valid, False otherwise
return True
# The Main App Window - 35 columns | 5 rows
class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Schedule Window")
self.geometry("1300x300")
self.open_input_window()
# title frame
self.title_frame = TitleFrame(self)
self.title_frame.grid(column=0, row=0, columnspan=35, padx=10, pady=10)
def open_input_window(self):
self.input_window = InputWindow(self)
# self.wait_window(self.input_window) # Wait for the top-level window to close
self.handle_input_window_selections()
def handle_input_window_selections(self):
if self.input_window is not None:
selected_month = self.input_window.selected_month
selected_year = self.input_window.selected_year
# Use the selected month and year to perform any necessary operations
print(selected_month, selected_year)
# title frame
self.title_frame = TitleFrame(self)
self.title_frame.grid(column=0, row=0, columnspan=35, padx=10, pady=10)
# Schedule Header: Includes - Title, Calendar, Shifts, Crew Name, and Crew ID
class TitleFrame(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.config(borderwidth=1, relief="raised", width=1300)
self.grid(column=0, row=0, columnspan=35, padx=10, pady=10)
self.title_label = tk.Label(self, text="Overtime Schedule", font=("Calibri", 22))
self.title_label.config(padx=462)
self.title_label.grid(column=0, row=0, columnspan=24, sticky="w")
self.ID_detection_label = tk.Label(self, text=f"Current User: {functions.get_user_id()}",
font=("Calibri", 12))
# self.ID_detection_label.config(bg="black", fg="white")
self.ID_detection_label.grid(column=34, row=0, sticky="e")
self.Calendar_Month_hdr = tk.Label(self, text="Schedule Calendar", font=("Calibri", 12))
self.Calendar_Month_hdr.grid(column=0, row=1)
# self.Calendar_Month_hdr.configure(bg="black", fg="white")
"""Need to add a calendar widget for this feature"""
self.Calendar_Month_label = tk.Label(self, text="Selected Month", font=("Calibri", 12))
self.Calendar_Month_label.grid(column=0, row=2)
self.Calendar_Year_label = tk.Label(self, text="Selected year", font=("Calibri", 12))
self.Calendar_Year_label.grid(column=0, row=3)
# Top Level Selector
class SelectorFrame(tk.Toplevel):
def __init__(self, parent):
super().__init__(parent)
pass
app = App()
app.withdraw() # Hide the main application window
app.mainloop()`
initially the app ran fine until I attempted to create the variables from the combobox selections in InputWindow and use them in TitleFrame as labels. I'm very new at python and tkinter and wanted to experiment with calling the variables from another class before attempting to update class labels.
InputWindow Line 42 & 43 - initial assignment
```
self.selected_month = self.select_schedule_month.get()
self.selected_year = self.select_schedule_year.get()
```
Calling to App Line 71-75 to print the values selected in InputWindow
```
def handle_input_window_selections(self):
if self.input_window is not None:
selected_month = self.input_window.selected_month
selected_year = self.input_window.selected_year
# Use the selected month and year to perform any necessary operations
print(selected_month, selected_year)
```
All local import functions work as expected when tested
The error I'm seeing when trying to call the selected_month/selected_year variables is an AttributeError. I'm not sure how to call selections from outside of class so I need some education on this, but even removing these variables from the equasion, I still can't get the Toplevel window to appear.
```
Exception has occurred: AttributeError
'InputWindow' object has no attribute 'selected_month'
File "C:\Users\edit\OneDrive\Py Scripts\Tkinter GUI\Schedule App\Schedule_GUI.py", line 71, in handle_input_window_selections
selected_month = self.input_window.selected_month
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\edit\OneDrive\Py Scripts\Tkinter GUI\Schedule App\Schedule_GUI.py", line 67, in open_input_window
self.handle_input_window_selections()
File "C:\Users\edit\OneDrive\Py Scripts\Tkinter GUI\Schedule App\Schedule_GUI.py", line 58, in __init__
self.open_input_window()
File "C:\Users\edit\OneDrive\Py Scripts\Tkinter GUI\Schedule App\Schedule_GUI.py", line 116, in <module>
app = App()
^^^^^
AttributeError: 'InputWindow' object has no attribute 'selected_month'
```
Thank you for any help, I certainly have a lot to learn. |
Tkinter App - My Toplevel window is not appearing. App is stuck in mainloop |
|python|python-3.x|class|tkinter|ttk| |
null |
I am making Android application that displays contents that is copied from USB storage disk.
The problem is when USB storage disc is connected to device, Media Player `onCompletion()` is immediately called although movie now playing is not finished yet.
I want to fix this problem not to call `onCompletion()` when USB is connected.
Thanks in advance.
```kotlin
class PlayerViewModel(application: Application, repository: GCSRepository) : ViewModel(), USBDownloadListener,
MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
override fun onDownloadFinished(unusedFiles: MutableSet<String>) {
// some codes here...
}
override fun onCompletion(mp: MediaPlayer?) {
// some codes here...
}
}
```
```kotlin
class USBIOManager(context: Context) {
init {
registerReceiver(context)
}
private fun registerReceiver(context: Context) {
unRegisterReceiver(context)
mUsbReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// some codes here...
updateUSBFiles(context)
// some codes here...
}
}
}
private fun updateUSBFiles(context: Context) {
// some codes here...
downloadListener?.onDownloadFinished(existingInternalStorageFiles)
// some codes here...
}
```
```kotlin
interface USBDownloadListener {
fun onDownloadFinished(unusedFiles : MutableSet<String>)
}
```
|
I have a React frontend application configured with a proxy in the package.json file pointing to my Flask backend running on http://localhost:2371. However, when making requests to fetch data from the backend using fetch("/members"), the frontend seems to be fetching data from localhost:5173 (the address on which the react site is running) instead of the expected localhost:2371. I've double-checked the proxy configuration
(Here is my package.json):
"name": "react-frontend",
"private": true,
"proxy": "http://localhost:2371",
"version": "0.0.0",
"type": "module",
and ensured that the backend server is running, but I'm still encountering this issue. What could be causing the frontend to fetch data from the unexpected localhost address instead of the configured proxy? The code works if I fetch from the whole address ("http://localhost:2371/members"), but it would be simpler to just write "/members". Do I need to import the package.json to my App.tsx to make it work or is it alredy somehow connected?
Here is my backend script:
from flask import Flask, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/members")
def members():
return jsonify({"members": ["Luka", "Baga", "Simun"]})
if __name__ == "__main__":
app.run(debug=True, port=2371)
Any insights or suggestions for troubleshooting would be greatly appreciated. Thank you! |
The structure of your query is not correct. There are a lot of ways to fix this problem, but essentially you need to separate the data call from the component display instead of trying to do both all at once.
This is usually done with React Hooks, and there are numerous examples out there of how to accomplish this. [Like this one](https://medium.com/nerd-for-tech/fetching-api-using-useeffect-hook-in-react-js-7b9b34e427ca).
The thing to notice about that approach is that it uses the `useState` and `useEffect` hooks to separate the problem into several parts. This approach has the benefit of being reusable and scalable, as it can be easily adjusted to solve any data-fetching problem.
So in the example given in the link I posted, the solution is broken into different pieces:
// Library imports
// Component definition
function someFunction () {
// useEffect hook for polling
useEffect(() => {
// Check to see if data needs to update and if it does
// call getPost()
}, [])
// useState hook for managing state and making
// it available to the rest of the component
const [someState, setSomeState] = useState(state)
const getPost() => {
// This is where the data call happens,
// Query the API and
// pass the results are passed to someState
}
// merge the results of someState() with the UI
render(
// map the data in someState
// to the UI elements.
)
}
Generally speaking, you're going to want to separate your concerns as much as you can when computer programming. If you're trying to grab state, set state, and render state all in one big chunk of code, it's probably time to slow down and re-think your approach to handle each problem one at a time.
Try re-writing your component in something closer to this form and ask again and I'm glad to help you get where you're going.
|
onCompletion(mp: MediaPlayer?) is unintentionally called after USB storage is connected |
|android|kotlin|usb|android-mediaplayer| |
It looks like you are missing the program database (PDB files).
You have to invoke the linker with the /DEBUG option.
Since you are using SCons - you have the edit your configuration file and add the /DEBUG linker options. |
For install **cudatoolkit and cudnn** by Anaconda you can use these following command `conda install -c conda-forge cudatoolkit=11.2 cudnn=8.1.0`
You must aware the **tensorflow version** must be less than **2.11**
For check if the everything installed properly
1) In command prompt check `nvidia-smi` command. if shows command not found you must install the latest GPU driver
2) Use this python script to config the GPU in programming
---
import tensorflow as tf
if tf.config.list_physical_devices('GPU'):
print('GPU is available.')
else:
print('GPU is NOT available. Make sure TensorFlow version less than 2.11 and Installed all GPU drivers.')
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.compat.v1.Session(config=config) |
{"Voters":[{"Id":2442831,"DisplayName":"Lino"},{"Id":7015400,"DisplayName":"Peter Haddad"},{"Id":2851937,"DisplayName":"Jay"}]} |
In the openned directory there is a sub directory that contains many files (millions). This is for a good reason. Still, the vscode server keeps searching through these files for potential Python environments, and this takes forever.
Moving this sub directory to a different location solved the problem. |
I am trying to develop a plugin to export markdown file to PDF.
Here is a sample markdown content:
```
# What is Obsidian ?
Obsidian is a **markdown** editor.
```
I am using `marked` library to convert `markdown => html string` after which using `html` function of `JSPDF` library to convert to PDF and save
The code snippet is as follows:
```
const pdf = new jsPDF()
//converting markDown text to html
const htmlContent = await marked(markedDownContent);
pdf.html(htmlContent, {
callback: (doc) => {
doc.save("output.pdf");
},
x: 0,
y: 0,
margin: 10
});
```
However, the text generated in PDF is poorly formatted as seen below:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/POGm6.png
I need help in fixing the styling of the text generated in the PDF document.
**Edit**
As mentioned in the comments, the `html` generated is as follows:
<h1>What is Obsidian ?</h1>
<p>Obsidian is a <strong>markdown</strong> editor.</p> |
{"Voters":[{"Id":807126,"DisplayName":"Doug Stevenson"},{"Id":209103,"DisplayName":"Frank van Puffelen"},{"Id":2851937,"DisplayName":"Jay"}],"SiteSpecificCloseReasonIds":[13]} |
IIUC, you can build a directed graph with [`networkx`](https://networkx.org), then find the [`shortest_path`](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.generic.shortest_path.html#networkx.algorithms.shortest_paths.generic.shortest_path) between each node and `'0'`, then use that to map the `path_variable`:
```
import networkx as nx
G = nx.from_pandas_edgelist(df, source='m_eid', target='eid',
create_using=nx.DiGraph)
s = df.set_index('eid')['path_variable']
mapper = {n: '|'.join(s.get(x, '') for x in
nx.shortest_path(G, source='0',
target=n)[1:])
for n in df['eid'].unique()
}
df['complete_path'] = df['eid'].map(mapper)
```
Output:
```
eid m_eid level path_variable complete_path
0 1 0 0 0 0
1 2 1 1 0 0|0
2 3 1 1 1 0|1
3 4 2 2 0 0|0|0
4 5 2 2 1 0|0|1
5 6 2 2 2 0|0|2
6 7 3 2 0 0|1|0
7 8 3 2 1 0|1|1
8 9 3 2 2 0|1|2
9 10 3 2 3 0|1|3
10 11 4 3 0 0|0|0|0
11 12 4 3 1 0|0|0|1
12 13 10 3 0 0|1|3|0
```
Graph:
[![organization graph, networkx graphviz][1]][1]
[1]: https://i.stack.imgur.com/1PZMQ.png |
'PyQt5.QtCore.pyqtSignal' object has no attribute 'emit' |
|qtpy| |
null |
I'm trying to add recession bands to this graph:
[The Taylor (1993) rule for the US and the Fed Funds rate, 1960-2023](https://i.stack.imgur.com/UJIa6.png)
I'm not sure where to start. Here's what I've got currently:
```
p <- ggplot(df, aes(date, fedfunds, group = 1, color="red"))+
geom_line( size=1.2, alpha=1, linetype=2)+
geom_line( data = df2, aes(x = date, y = taylor_rule, color="blue"), size=1.2, alpha=1, linetype=1) +
ggtitle("The Taylor (1993) rule for the US and the Fed Funds rate, 1960-2023")+
xlab("Year") + ylab("Interest Rate and Taylor Rate")+
ylim(-5,20)+
scale_color_hue(labels = c("Taylor Rule", "Federal Funds Rate"))+
theme(legend.position="bottom")
#This renders the graph in the first image. The data used is quarterly:
> df
FEDFUNDS PCEPI UNRATE date inflationgap unemploymentgap taylor_rule
1 3.9333333333333331 1.6955100000000001 5.1333333333333329 1960-01-01 -0.30449 1.1333333 1.55442167
2 3.6966666666666668 1.81114 5.2333333333333334 1960-04-01 -0.18886 1.2333333 1.54223667
3 2.9366666666666665 1.5806800000000001 5.5333333333333332 1960-07-01 -0.41932 1.5333333 1.21700667
4 2.2966666666666669 1.47695 6.2666666666666666 1960-10-01 -0.52305 2.2666667 0.65180833
5 2.0033333333333334 1.5333399999999999 6.7999999999999998 1961-01-01 -0.46666 2.8000000 0.30667000
6 1.7333333333333334 0.99473999999999996 7 1961-04-01 -1.00526 3.0000000 -0.10263000
7 1.6833333333333333 0.97816999999999998 6.7666666666666666 1961-07-01 -1.02183 2.7666667 0.05241833
8 2.3999999999999999 0.64354999999999996 6.2000000000000002 1961-10-01 -1.35645 2.2000000 0.28177500
9 2.4566666666666666 0.89122000000000001 5.6333333333333329 1962-01-01 -1.10878 1.6333333 0.80227667
10 2.6066666666666669 1.26149 5.5333333333333332 1962-04-01 -0.73851 1.5333333 1.05741167
11 2.8466666666666667 1.16794 5.5666666666666664 1962-07-01 -0.83206 1.5666667 0.98730333
12 2.9233333333333333 1.3677999999999999 5.5333333333333332 1962-10-01 -0.63220 1.5333333 1.11056667
13 2.9666666666666668 1.2206699999999999 5.7666666666666666 1963-01-01 -0.77933 1.7666667 0.87366833
14 2.9633333333333334 1.0209900000000001 5.7333333333333334 1963-04-01 -0.97901 1.7333333 0.79716167
15 3.3300000000000001 1.2403599999999999 5.5 1963-07-01 -0.75964 1.5000000 1.07018000
16 3.4533333333333331 1.30339 5.5666666666666664 1963-10-01 -0.69661 1.5666667 1.05502833
17 3.4633333333333334 1.49129 5.4666666666666668 1964-01-01 -0.50871 1.4666667 1.21897833
18 3.4900000000000002 1.5534300000000001 5.2000000000000002 1964-04-01 -0.44657 1.2000000 1.43671500
19 3.4566666666666666 1.3948700000000001 5 1964-07-01 -0.60513 1.0000000 1.49743500
20 3.5766666666666667 1.35467 4.9666666666666668 1964-10-01 -0.64533 0.9666667 1.50066833
#Bit messy but it results in a plot.
#Here is an example of the data I am using for the recession bands. I edited it such that the dates with a "1" are in its own column and the ones with a "0" are also in its own column.
> print(REC2, n=183)
# A tibble: 183 × 2
Peak Trough
<date> <date>
1 1969-04-01 1967-10-01
2 1969-07-01 1968-01-01
3 1969-10-01 1968-04-01
4 1970-01-01 1968-07-01
5 1970-04-01 1968-10-01
6 1970-07-01 1969-01-01
7 1970-10-01 1971-01-01
8 1973-10-01 1971-04-01
9 1974-01-01 1971-07-01
10 1974-04-01 1971-10-01
11 1974-07-01 1972-01-01
12 1974-10-01 1972-04-01
13 1975-01-01 1972-07-01
14 1979-04-01 1972-10-01
15 1979-07-01 1973-01-01
16 1979-10-01 1973-04-01
17 1980-01-01 1973-07-01
18 1980-04-01 1975-04-01
19 1981-04-01 1975-07-01
20 1981-07-01 1975-10-01
21 1981-10-01 1976-01-01
22 1982-01-01 1976-04-01
23 1982-04-01 1976-07-01
24 1989-10-01 1976-10-01
25 1990-01-01 1977-01-01
26 1990-04-01 1977-04-01
27 1990-07-01 1977-07-01
28 1990-10-01 1977-10-01
29 1991-01-01 1978-01-01
30 2001-01-01 1978-04-01
31 2001-04-01 1978-07-01
32 2001-07-01 1978-10-01
33 2007-10-01 1979-01-01
34 2008-01-01 1980-07-01
35 2008-04-01 1980-10-01
36 2008-07-01 1981-01-01
37 2008-10-01 1982-07-01
38 2009-01-01 1982-10-01
39 2009-04-01 1983-01-01
40 2020-01-01 1983-04-01
41 2020-04-01 1983-07-01
42 NA 1983-10-01
43 NA 1984-01-01
44 NA 1984-04-01
45 NA 1984-07-01
46 NA 1984-10-01
47 NA 1985-01-01
48 NA 1985-04-01
49 NA 1985-07-01
50 NA 1985-10-01
51 NA 1986-01-01
52 NA 1986-04-01
53 NA 1986-07-01
54 NA 1986-10-01
55 NA 1987-01-01
56 NA 1987-04-01
57 NA 1987-07-01
58 NA 1987-10-01
59 NA 1988-01-01
60 NA 1988-04-01
61 NA 1988-07-01
62 NA 1988-10-01
63 NA 1989-01-01
64 NA 1989-04-01
65 NA 1989-07-01
66 NA 1991-04-01
67 NA 1991-07-01
68 NA 1991-10-01
69 NA 1992-01-01
70 NA 1992-04-01
71 NA 1992-07-01
72 NA 1992-10-01
73 NA 1993-01-01
74 NA 1993-04-01
75 NA 1993-07-01
76 NA 1993-10-01
77 NA 1994-01-01
78 NA 1994-04-01
79 NA 1994-07-01
80 NA 1994-10-01
81 NA 1995-01-01
82 NA 1995-04-01
83 NA 1995-07-01
84 NA 1995-10-01
85 NA 1996-01-01
86 NA 1996-04-01
87 NA 1996-07-01
88 NA 1996-10-01
89 NA 1997-01-01
90 NA 1997-04-01
91 NA 1997-07-01
92 NA 1997-10-01
93 NA 1998-01-01
94 NA 1998-04-01
95 NA 1998-07-01
96 NA 1998-10-01
97 NA 1999-01-01
98 NA 1999-04-01
99 NA 1999-07-01
100 NA 1999-10-01
101 NA 2000-01-01
102 NA 2000-04-01
103 NA 2000-07-01
104 NA 2000-10-01
105 NA 2001-10-01
106 NA 2002-01-01
107 NA 2002-04-01
108 NA 2002-07-01
109 NA 2002-10-01
110 NA 2003-01-01
111 NA 2003-04-01
112 NA 2003-07-01
113 NA 2003-10-01
114 NA 2004-01-01
115 NA 2004-04-01
116 NA 2004-07-01
117 NA 2004-10-01
118 NA 2005-01-01
119 NA 2005-04-01
120 NA 2005-07-01
121 NA 2005-10-01
122 NA 2006-01-01
123 NA 2006-04-01
124 NA 2006-07-01
125 NA 2006-10-01
126 NA 2007-01-01
127 NA 2007-04-01
128 NA 2007-07-01
129 NA 2009-07-01
130 NA 2009-10-01
131 NA 2010-01-01
132 NA 2010-04-01
133 NA 2010-07-01
134 NA 2010-10-01
135 NA 2011-01-01
136 NA 2011-04-01
137 NA 2011-07-01
138 NA 2011-10-01
139 NA 2012-01-01
140 NA 2012-04-01
141 NA 2012-07-01
142 NA 2012-10-01
143 NA 2013-01-01
144 NA 2013-04-01
145 NA 2013-07-01
146 NA 2013-10-01
147 NA 2014-01-01
148 NA 2014-04-01
149 NA 2014-07-01
150 NA 2014-10-01
151 NA 2015-01-01
152 NA 2015-04-01
153 NA 2015-07-01
154 NA 2015-10-01
155 NA 2016-01-01
156 NA 2016-04-01
157 NA 2016-07-01
158 NA 2016-10-01
159 NA 2017-01-01
160 NA 2017-04-01
161 NA 2017-07-01
162 NA 2017-10-01
163 NA 2018-01-01
164 NA 2018-04-01
165 NA 2018-07-01
166 NA 2018-10-01
167 NA 2019-01-01
168 NA 2019-04-01
169 NA 2019-07-01
170 NA 2019-10-01
171 NA 2020-07-01
172 NA 2020-10-01
173 NA 2021-01-01
174 NA 2021-04-01
175 NA 2021-07-01
176 NA 2021-10-01
177 NA 2022-01-01
178 NA 2022-04-01
179 NA 2022-07-01
180 NA 2022-10-01
181 NA 2023-01-01
182 NA 2023-04-01
183 NA 2023-07-01
#The peaks represent periods of recession, and the troughs are periods not in recession.
```
This might be helpful: https://www.r-bloggers.com/2011/08/use-geom_rect-to-add-recession-bars-to-your-time-series-plots-rstats-ggplot/.
This is where I started but I haven't gotten any results out of it. I copied this line:
```
pp = p + geom_rect(data=REC2, aes(xmin=Peak, xmax=Trough, ymin=-Inf, ymax=+Inf), fill='pink', alpha=0.2)
```
But it gives this error:
```
Error in `geom_rect()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 3rd layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (183)
✖ Fix the following mappings: `x` and `y`
Run `rlang::last_trace()` to see where the error occurred.
```
|
The answer was posted [here][1]
[1]: https://github.com/browserify/pbkdf2/pull/98
Apparently, browserify injects the variables when compiling so global and process are different. Global is the node and process is the browser process. I fixed the issue by changing process.versions and process.versions.node to global.process.versions global.process.versions.node, respectively. Here is the new code:
```
console.log(global.process.versions.node)
var current = typeof nodeVersion === 'undefined'
? global.process.versions && global.process.versions.node
: nodeVersion;
``` |
I am trying to write a little program, which is resistant against buffer overflow and similar vulnerabilities.
Since we cannot trust the user input, I thought it would be a good idea to concatenate all the strings that are inputted into one string and then pass it to a static path, which is a bash script in the same folder and then add all the parameters/flags/arguments (e.g. ./script.sh test1 test2 test3 test4).
My logic on paper is the following:
1. Check whether the number of argc is 5 exactly (so program name + the 4 arguments), if not - exit immediately
2. The specific char array for 5 strings (so array elements) with a max length of 4096 bytes length is initialized.
3. Since `argv[0]` is equal to the program name, we need to skip it. Hence the loop starts at 1 (first argument) and ends at argc-1. So good so far
4. We append the argv[1] string the ending `.key` in-memory.
5. We `memcpy` all the strings to make it safe to use
6. For each iteration we don't forget to add the null terminator at the end of the string.
7. After we have all the arguments safe to use we concat it in the function parse_output and call the bash script called script.sh and add all the required arguments
8. We return the output from the `script.sh 4argshere` to the user
I tried freeing the memory like in the comments but it seems to not work or I have errors somewhere else.
My segfaulting Proof of Concept:
```
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define BUFSIZE 1000
char *concatenate(size_t size, char *array[size], const char *joint);
char *concatenate(size_t size, char *array[size], const char *joint){
size_t jlen, lens[size];
size_t i, total_size = (size-1) * (jlen=strlen(joint)) + 1;
char *result, *p;
for(i=0;i<size;++i){
total_size += (lens[i]=strlen(array[i]));
}
p = result = malloc(total_size);
for(i=0;i<size;++i){
memcpy(p, array[i], lens[i]);
p += lens[i];
if(i<size-1){
memcpy(p, joint, jlen);
p += jlen;
}
}
*p = '\0';
return result;
}
int parse_output(char *safeargv[]) {
char safeargs = *concatenate(5, safeargv, " ");
char cmd[BUFSIZE];
snprintf(cmd, BUFSIZE, "./script.sh %s", safeargs);
char buf[BUFSIZE] = {0};
FILE *fp;
if ((fp = popen(cmd, "r")) == NULL) {
printf("Error opening pipe!\n");
//free(safeargs);
return -1;
}
while (fgets(buf, BUFSIZE, fp) != NULL) {
printf("OUTPUT: %s", buf);
}
if (pclose(fp)) {
printf("Command not found or exited with error status\n");
//free(safeargs);
return -1;
}
//free(safeargs);
return 0;
}
int main(int argc, char *argv[]) {
if(argc != 5) {
exit(1);
}
char *safeargv[5][4096];
for (int i = 1; i < argc - 1; i++) {
if (i == 1)
strcat(argv[1], ".key");
for (int x = 0; x < strlen(argv[i]); x++) {
char *unsafe_string = argv[i];
size_t max_len = 4096;
size_t len = strnlen(unsafe_string, max_len) + 1;
char *x = malloc(len * sizeof(char));
if (x != NULL) {
strncpy(x, unsafe_string, len);
x[len-1] = '\0'; // Ensure null-termination
strcpy(safeargv[i], x);
free(x);
}
}
}
parse_output(safeargv);
return 0;
}
```
The warnings I get while compiling:
```
chal.c: In function 'main':
chal.c:78:32: warning: passing argument 1 of 'strcpy' from incompatible pointer type [-Wincompatible-pointer-types]
78 | strcpy(safeargv[i], x);
| ~~~~~~~~^~~
| |
| char **
In file included from chal.c:2:
/usr/include/string.h:141:39: note: expected 'char * restrict' but argument is of type 'char **'
141 | extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
| ~~~~~~~~~~~~~~~~~^~~~~~
chal.c:83:18: warning: passing argument 1 of 'parse_output' from incompatible pointer type [-Wincompatible-pointer-types]
83 | parse_output(safeargv);
| ^~~~~~~~
| |
| char * (*)[4096]
chal.c:32:24: note: expected 'char **' but argument is of type 'char * (*)[4096]'
32 | int parse_output(char *safeargv[]) {
| ~~~~~~^~~~~~~~~~
```
It seems only my argc check works, because if I call ./programname abc abc abc abc it segfaults. Also what's the proper way to detect an error, if for case there's a typo in the argument for the script?
What mistake(s) did I make?
My last `ltrace` lines:
```
strlen(" ") = 1
strlen(nil <no return ...>
```
It looks as if it would try to detect the length of a null character or similar. |
I wrote a SnippingWidget function and linked it to the main code. After executing this function, my application crashes with an error. I looked up what the error is with try and it says: "PyQt5.QtCore.pyqtSignal' object has no attribute 'emit'". I want this function to just hide itself when finished, meaning it can be reused. Initially the same error came up, but with "closed", I was able to solve it. But I don't understand what to do with emit....
Here is the code for my function:
```
from PyQt5 import QtCore, QtGui, QtWidgets
class SnippingWidget(QtWidgets.QDialog):
closed = QtCore.pyqtSignal()
def __init__(self):
super(SnippingWidget, self).__init__()
self.setAttribute(QtCore.Qt.WA_NoSystemBackground, True)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)
self.setStyleSheet("background:transparent;")
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.outsideSquareColor = "red"
self.squareThickness = 2
self.start_point = QtCore.QPoint()
self.end_point = QtCore.QPoint()
self.selected_area = None
# Установка размеров окна в соответствии с размерами экрана
screen_geometry = QtWidgets.QApplication.desktop().screenGeometry()
self.setGeometry(screen_geometry)
def mousePressEvent(self, event):
self.start_point = event.pos()
self.end_point = event.pos()
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.CrossCursor)
self.update()
def mouseMoveEvent(self, event):
self.end_point = event.pos()
self.update()
def mouseReleaseEvent(self, QMouseEvent):
r = QtCore.QRect(self.start_point, self.end_point).normalized()
self.hide()
self.selected_area = r
QtWidgets.QApplication.restoreOverrideCursor()
self.closed.emit()
self.start_point = QtCore.QPoint()
self.end_point = QtCore.QPoint()
def paintEvent(self, event):
trans = QtGui.QColor(22, 100, 233)
r = QtCore.QRectF(self.start_point, self.end_point).normalized()
qp = QtGui.QPainter(self)
trans.setAlphaF(0.2)
qp.setBrush(trans)
outer = QtGui.QPainterPath()
outer.addRect(QtCore.QRectF(self.rect()))
inner = QtGui.QPainterPath()
inner.addRect(r)
r_path = outer - inner
qp.drawPath(r_path)
qp.setPen(
QtGui.QPen(QtGui.QColor(self.outsideSquareColor), self.squareThickness)
)
trans.setAlphaF(0)
qp.setBrush(trans)
qp.drawRect(r)
```
For "closed", I defined a closed signal:
`closed = QtCore.pyqtSignal()` |
**1st solution** - automatic.
The PyCharm plugin **"PyCharm Help"** allows you to automatically download web help for offline use: when help is invoked, pages are delivered via a built-in Web server.
This solution has drawbacks - for me, it downloaded help only for one version of Python, but not for newer versions which I use in parallel.
Also, in that version of Python help, the local search doesn't work.
**2nd solution** - better, very flexible, but manual.
1. Download [Python's HTML help][1] and unpack it into the folder with the corresponding version name, e.g., for Windows to "C:\py_help_server\3.12".
*Folder "py_help_server" will become root folder for our server, and "3.12" naming should correspond online help's URL format.*
2. Run cmd as admin and run such commands:
cd C:\py_help_server\3.12
python -m http.server 80 --bind 127.0.0.1
3. For Chrome/Brave, download the plugin "Requestly - Intercept, Modify & Mock HTTP Requests". In its settings, go to "HTTP Rules", then "My Rules", click "New Rule" with the type "Replace String".
And create a rule like this:
If the URL contains "https://docs.python.org/3.12/", replace "https://docs.python.org/" with "http://127.0.0.1/".
Now, all pages of Python help for the 3.12 version will be redirected to our local server, which we started in the step 2.
This works for me like a charm. I tried to edit the hosts file too, but that didn't work for me at all.
Also, this last method has an advantage over the "PyCharm Help" plugin - the local web help's search function works well!
[1]: https://docs.python.org/3/download.html
|
I want to create private channel on Laravel + React with Pusher (I want to create chast online). I found issues like [here][1] and others but it doesn't solve my problem. Looks on my code.
useEffect(() => {
Pusher.logToConsole = true;
const pusher = new Pusher("***", {
cluster: "eu",
broadcaster: "pusher",
appId: "***",
key: "***",
secret: "***",
auth: {
headers: {
Accept: "application/json",
Authorization: "Bearer x9O***", //I added that manually becouse I'm using http only cookies
},
},
authEndpoint: "http://localhost/broadcasting/auth",
});
const channel = pusher.subscribe("laravel-chat");
channel.bind("message", function (data) {
const jsonData = JSON.parse(JSON.stringify(data));
setMessages((prevMessages) => [
...prevMessages,
{ message: jsonData.message },
]);
});
}, []);
I'm not sure that this code is corrently but it doesn't work. Here `Authorization: "Bearer x9O***"` I added token manually becouse I doesn't store my token in frontend. I'm using http only cookie instead. My Message event at this moment looks like this
class Message implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
public $username;
public function __construct($message, $username)
{
$this->message = $message;
$this->username = $username;
}
/**
* Get the channels the event should broadcast on.
*
* @return array<int, \Illuminate\Broadcasting\Channel>
*/
public function broadcastOn(): array
{
return [
new PrivateChannel('laravel-chat'),
];
// return ['laravel-chat'];
}
public function broadcastAs()
{
return 'message';
}
}
I don't have any errors but this messages doesn't displat. Should you fix my code?
[1]: https://stackoverflow.com/questions/74003743/how-to-use-private-channel-in-laravel-pusher-js |
Privsate channel doesn;t display messages - propably it's problem with authentication |
|reactjs|laravel|frontend| |
You can use the `text` query parameter to reduce the number of icons.
Since Material icons rely on ligatures you need to enter the names of the desired icons (See [list of icons][1]).
E.g for filtering to `close` and `search` icon we append this query parameter:
```
&text=closesearch
```
We can also remove duplicate characters (e.g "s", "e")
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.material-symbols-outlined {
font-family: 'Material Symbols Outlined';
font-weight: normal;
font-style: normal;
display: inline-block;
-webkit-font-feature-settings: 'liga';
}
<!-- language: lang-html -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0,0&text=closearch" />
<div class="material-symbols-outlined">close</div>
<div class="material-symbols-outlined">search</div>
<!-- end snippet -->
The new subset font file is only ~ 4KB
[1]: https://fonts.google.com/icons |
|assembly|multiplication|riscv|integer-overflow| |
I wanted today to compile my c++ code on windows, I get an undefined reference to all box2D part of my code.
Here's my Makefile :
```
linux: main.o
g++ main.o -o main -O2 -Wall -lbox2d -lraylib -lGL -lm -lpthread -ldl -lrt -lX11
./main
windows:
g++ -I../include -L../lib ../main.cpp -o main.exe -O2 -Wall -lraylib -lbox2d -lopengl32 -lgdi32 -lwinmm
main.o: ../main.cpp
g++ -c ../main.cpp
cleanl:
rm ./*.o ./main
cleanw:
rm ./*.o ./main.exe
```
Also here's my tree structure :
Project/
├─ build/
│ ├─ Makefile
├─ include/
│ ├─ raylib.h
│ ├─ box2d/
│ │ ├─ *all box2D headers
├─ lib/
│ ├─ libbox2d.a
│ ├─ libraylib.a
├─ .gitignore
├─ main.cpp
Here's the error that I get :
```
PS C:\Users\henri\Documents\Calyspo\build> g++ -I../include -L../lib ../main.cpp -o main.exe -O2 -Wall -lraylib -lbox2d -lopengl32 -lgdi32 -lwinmm
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0x82): undefined reference to `b2World::b2World(b2Vec2 const&)'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0xe0): undefined reference to `b2PolygonShape::b2PolygonShape()'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0x14f): undefined reference to `b2PolygonShape::SetAsBox(float, float)'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0x17e): undefined reference to `b2World::CreateBody(b2BodyDef const*)'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0x196): undefined reference to `b2Body::CreateFixture(b2FixtureDef const*)'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0x1a3): undefined reference to `b2Body::SetFixedRotation(bool)'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0x1f1): undefined reference to `b2PolygonShape::SetAsBox(float, float)'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0x203): undefined reference to `b2World::CreateBody(b2BodyDef const*)'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0x210): undefined reference to `b2Body::CreateFixture(b2FixtureDef const*)'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0x344): undefined reference to `b2World::Step(float, int, int)'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0x673): undefined reference to `b2World::~b2World()'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/13.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\henri\AppData\Local\Temp\ccCw6djM.o:main.cpp:(.text.startup+0x6e2): undefined reference to `b2World::~b2World()'
collect2.exe: error: ld returned 1 exit status
```
I tried a lot of configuration in my Makefile to make it work but nothing worked. |
Instead of adding a generic parameter for the value, add it for the key, and by using [indexed access types](https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html) get the correct type for the value:
```
function changeHandler<T extends keyof Data>(field: T, value: Data[T]) {
data = {...data, [field]: value}
}
```
Testing:
```
changeHandler("a", "aa"); // no error
changeHandler("b", 11); // no error
changeHandler("a", 1); // error
changeHandler("b", "b"); // error
```
[playground](https://www.typescriptlang.org/play?ts=5.0.4#code/JYOwLgpgTgZghgYwgAgCJzHZBvAUM5OALmQGcwpQBzAbn2QCMSQBXAWwejoF9dcAbCGGQATDMTTjkAXhwSARHHkAaRiQCM3OrhgsQCMMAD2IZAgAWcEFQgAJKyMFQAPABVkEAB6QQI0sgBrCABPIxhJTAA+AAoYYAh+ERJXVQA3OH4WCBJ0TABtVwBdAEocejFMGRwAOlqKuFU8uISRQpJ0zIheXlwLKxt7XydoxRVkRSVimmQAehnkECMPKCgjKF7LazsHYfkGMfV1Kdn5xeXV9Y3+7aHoEaVVI+m587WrrcHHO72xn+OX6AXPgIEykIyCar8IxUaL1YpAA)
|
For any Eclipse version starting from 2022-03 (4.23) you can download from the Eclipse Marketplace [OmniFish tools][1], since Glassfish tools doesn't seem to be maintained and does not support Glassfish 7.
Also note that you need to download [Glassfish 7][2].
After you install OmniFish tools and restart Eclipse you can find the 'Glassfish' option when you create a new Runtime Environment. From there you just need to indicate the Glassfish 7 path you just downloaded.
[1]: https://marketplace.eclipse.org/content/omnifish-tools-eclipse-glassfish
[2]: https://glassfish.org/download |
Update new version Released: Feb 17, 2024.
py -m pip install feast |
Since you already know where the repository is and which type of file you are looking for, the use of `find` is not optimal. you could simply use a for loop instead:
for file in ./build/html/*.html;do ../emojize_pngorsvg.py ${file} > ${file}; done;
Not sure why you would need to change the extension, delete the original file and rename the file as the original since the standard output operator > directly permits overiding file contents. |
I have a collection of a few thousand characters. Each character has eight localized fields and nine different supported languages. Below is an example of the schema I am using populated with sample data (just with a smaller document).
```
db.characters.insertMany([
{
"key": 123,
"attack": 1337,
"numberField3": 30
"translations": {
"en": {
"name": "Englishh name"
"description": "English description"
},
"es": {
"name": "Spanish name"
"description": "Spanish description"
}
}
},...
])
```
How can I make a query that returns a document containing the non-localized fields and the localized fields from the specified language?
pseudo-query: ```db.characteres.find({"key":123}).addAll("translations.en")``` would return:
```
{
"key": 123,
"attack": 1337,
"numberField3": 30
"name": "Englishh name"
"description": "English description"
}
```
Thank you for looking at this. First time mongodb user and data-modeling noob here
**UPDATE**
I just found an example (thanks ChatGPT) that would do what I need using $project. Is there a more performant way of doing this? or possibly shorter solution (each document has 8 localized fields I will have to add into $project); can I project the fields I want then add_all fields from translation.en to the root level? that would be a more generalized way to achieve what I am trying to do with localization in a query
```
db.characters.aggregate([
{
$match: {
"key": 123
}
},
{
$project: {
"_id": 0,
"key": 1,
"attack": 1,
"numberField3": 1,
"name": "$translations.en.name",
"description": "$translations.en.description"
}
}
])
```
**UPDATE #2**
Upon further prodding ChatGPT gave me this. Can anyone confirm this is a proper pipeline or know of a better way to do this? I can not currently connect to the db due to other reasons
```
db.characters.aggregate([
{
$match: {
"key": 123
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: ["$$ROOT", "$translations.en"]
}
}
},
{
$project: {
"translations": 0
}
}
])
``` |
My 2 cents for OS X including write that handles extensions + offscreen image drawing (method 2); one can verify with NSGraphicsContext.currentContextDrawingToScreen()
```swift
func createCGImage() -> CGImage? {
//method 1
let image = NSImage(size: NSSize(width: bounds.width, height: bounds.height), flipped: true, drawingHandler: { rect in
self.drawRect(self.bounds)
return true
})
var rect = CGRectMake(0, 0, bounds.size.width, bounds.size.height)
return image.CGImageForProposedRect(&rect, context: bitmapContext(), hints: nil)
//method 2
if let pdfRep = NSPDFImageRep(data: dataWithPDFInsideRect(bounds)) {
return pdfRep.CGImageForProposedRect(&rect, context: bitmapContext(), hints: nil)
}
return nil
}
func PDFImageData(filter: QuartzFilter?) -> NSData? {
return dataWithPDFInsideRect(bounds)
}
func bitmapContext() -> NSGraphicsContext? {
var context : NSGraphicsContext? = nil
if let imageRep = NSBitmapImageRep(bitmapDataPlanes: nil,
pixelsWide: Int(bounds.size.width),
pixelsHigh: Int(bounds.size.height), bitsPerSample: 8,
samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
colorSpaceName: NSCalibratedRGBColorSpace,
bytesPerRow: Int(bounds.size.width) * 4,
bitsPerPixel: 32) {
imageRep.size = NSSize(width: bounds.size.width, height: bounds.size.height)
context = NSGraphicsContext(bitmapImageRep: imageRep)
}
return context
}
func writeImageData(view: MyView, destination: NSURL) {
if let dest = CGImageDestinationCreateWithURL(destination, imageUTType, 1, nil) {
let properties = imageProperties
let image = view.createCGImage()!
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) {
CGImageDestinationAddImage(dest, image, properties)
CGImageDestinationFinalize(dest)
}
}
}
``` |
Your `FragmentContainer` has a height of `wrap_content` meaning it won't respect the constraints set by `constraintTop_toBottomOf` (and similar) attributes.
Using `0dp` (`MATCH_CONSTRAINT`) as its height is the key. Please read more about it [here][1].
> ... The first two works in a similar fashion as other layouts. The last one will resize the widget in such a way as matching the constraints that are set. If margins are set, they will be taken in account in the computation.
```
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@id/adView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/appbar"
app:navGraph="@navigation/nav_graph" />
```
[1]: https://developer.android.com/reference/androidx/constraintlayout/widget/ConstraintLayout#:~:text=The%20first%20two%20works%20in%20a%20similar%20fashion%20as%20other%20layouts.%20The%20last%20one%20will%20resize%20the%20widget%20in%20such%20a%20way%20as%20matching%20the%20constraints%20that%20are%20set.%20If%20margins%20are%20set%2C%20they%20will%20be%20taken%20in%20account%20in%20the%20computation. |
The top rated answer does not work with the new Reflectation implementation in e.g. Java 21 that uses MethodHandles and ignores the flags value on the Field abstraction object.
One solution is to use Unsafe, however with [this JEP](https://openjdk.org/jeps/8323072) Unsafe and the important `long objectFieldOffset(Field f)` and
`long staticFieldOffset(Field f)` methods are getting deprecated for removal so for example this will not work in the future:
```java
final final Unsafe unsafe = //..get Unsafe (...and add subsequent --add-opens statements for this to work)
final Field ourField = Example.class.getDeclaredField("changeThis");
final Object staticFieldBase = unsafe.staticFieldBase(ourField);
final long staticFieldOffset = unsafe.staticFieldOffset(ourField);
unsafe.putObject(staticFieldBase, staticFieldOffset, "it works");
```
I do not recommend this but it is possible in Java 21 with the new reflection implementation when making heavy use of the internal API if really needed.
See my answer [here](https://stackoverflow.com/a/77705202/23144795) on how to leverage the internal API to set a final field in Java 21 without Unsafe.
|
I want to use multiple PMMLs to keep the transformation of the data and the application of the model separate. Here is the code I am using. I am doing this because I want to include some kind of winsorizing on my data.
```
train_stats = {}
continous_domains = []
for cont in con_vars:
# REMOVE -1 values to not distort the quantiles
cont_val = np.asarray(train_data_sub[train_data_sub[cont] != -1][cont])
_95 = np.percentile(cont_val[~np.isnan(cont_val)], 95)
_05 = np.percentile(cont_val[~np.isnan(cont_val)], 5)
_50 = np.percentile(cont_val[~np.isnan(cont_val)], 50)
train_stats[cont] = [_05, _50, _95]
continous_domains.append(
([cont], [
ContinuousDomain(
missing_values = [-1],
missing_value_treatment="as_value",
missing_value_replacement= _50,
outlier_treatment ='as_extreme_values',
low_value = _05,
high_value = _95,
dtype = float
)
]))
data_mapper = DataFrameMapper(continous_domains, df_out=True)
data_mapper.fit(train_data_sub)
data_mapper.transform(train_data_sub)
pmml_pipeline = PMMLPipeline(steps = [
('DataframeMapper', data_mapper)])
path_name = f"Trafo_{str(datetime.now().strftime('%Y_%m_%d_%H-%M'))}.pmml"
sklearn2pmml(pmml_pipeline, path_name, debug=True)
```
It kinda works but the returned .pmml file only includes the data dictionary without the specifications of the setted high/low values etc.
Interestingly when I am putting a LogisticRegression inside the Pipeline I get a correct looking PMML but there are only two outputs and I actually want to get all the transformed values from the Dataframe Mapper.
Can anyone help me here? Really struggling to find a solution.
Thank you so much and best regards
Paul |
How to transform Dataframe Mapper to PMML? |
null |
I am trying to build my object using the below Json payload(which is being fetched from external API), now when ever i use any get method(i.e: jsonObject.getString() or jsonObject.getBoolean(), jsonObject.getObject()) and
if the value present for the key is null,I am getting an exception that "the value is not a string/boolean/Jsonobject"
now how can i handle this, since if the value is present in object 1 on the above array index 0, it may/maynot present in another object at index 1
here I can apply null checks to resolve this issue, but this object has more than 40 key value pairs and add these many null checks may become cumbersome, is there any better way to resolve this?
```Json
{
"data":[
{
"employer_name":"Dice",
"employer_logo":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQKlgydP7sElaJC9qPrtNHwBhyTMHYgii1RPWsy&s=0",
"employer_website":null,
"employer_company_type":"Information",
"job_publisher":"LinkedIn",
"job_id":"8yv3oA_2-UYAAAAAAAAAAA==",
"job_employment_type":"CONTRACTOR",
"job_title":"Web Developer - 6-month Contract - Houston Hybrid",
"job_apply_link":"https://www.linkedin.com/jobs/view/web-developer-6-month-contract-houston-hybrid-at-dice-3624857671",
"job_apply_is_direct":false
},
{
"employer_name":"Dicenvskjvks",
"employer_logo":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQKlgydP7sElaJC9qPrtNHwBhyTMHYgii1RPWsy&s=0",
"employer_website":"https://www.someUrl.com",
"employer_company_type":"Information",
"job_publisher":"LinkedIn",
"job_id":"8yv3oA_2-UYAAAAAAAAAAA==",
"job_employment_type":null,
"job_title":"Web Developer - 6-month Contract - Houston Hybrid",
"job_apply_link":"https://www.linkedin.com/jobs/view/web-developer-6-month-contract-houston-hybrid-at-dice-3624857671",
"job_apply_is_direct":false
}
]
}
```
My code:
```Java
public static List<Response> parseJServer1Response(String responseBody) throws ParseException, JsonProcessingException {
JSONObject responseObject = new JSONObject(responseBody);
JSONArray data = responseObject.getJSONArray("data");
List<Response> response = new ArrayList<>();
for (int i = 0; i < data.length(); i++) {
JSONObject jsonObject = data.getJSONObject(i);
JSearch job = Response.builder()
.companyName(jsonObject.getString("employer_name"))
.companyLogo(jsonObject.getString("employer_logo"))
.companyType(jsonObject.getString("employer_company_type"))
.jobPublisher(jsonObject.getString("job_publisher"))
....
....
....
....
....
....
.build();
response.add(job);
}
return response;
}
``` |
The extension operates via Java still it would seem, so it carries it's own jdk (and thus it's own CACERTS)
C:\Users\<me>\.vscode\extensions\oracle.sql-developer-23.4.1-win32-x64\dbtools\jdk\lib\security\cacerts
Just import your signing root for the TLS connection into the cacerts above using keytool
keytool -importcert -keystore C:\Users\<me>\.vscode\extensions\oracle.sql-developer-23.4.1-win32-x64\dbtools\jdk\lib\security\cacerts -storepass changeit -file .\hostroot.crt -alias 'db-tls-root' |
I was given this solution:
open the Registry editor by pressing Windows logo key then pressing R.
When the RUN box opens, type regedit there then click OK.
Then navigate to this path:Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Common\Security
If you do not have the Security key there, that looks like a folder, please create it. If the Security key is there, just add the DWORD (32-bit) Value named DisableHyperlinkWarning then set it to 1.
This worked! |
I have a Next.js app with the following structure:
```
.
├── next.config.js
└── src /
└── app/
├── page.tsx
└── getYoutubeTranscript/
└── getYoutubeTranscript.tsx
```
`next.config.js` has the following policy defined:
```
// @ts-check
/** @type {import('next').NextConfig} */
const nextConfig = {
async headers() {
return [
{
// matching all API routes
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" }, //http://localhost:3000
{ key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
}
}
module.exports = nextConfig
```
`page.tsx` is a client component that uses the `getYoutubeTranscript` server component to fetch a Youtube transcript. But when this code executes I get the client-side error:
```
Access to fetch at 'https://www.youtube.com/watch?v=<ID>' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
```
Looks like I misconfigured CORS in `next.config.js` -- any tips here to further diagnose?
----
**Update #1:** I don't see a Host listed in the Request Headers of my call from Developer Console? [This answer](https://stackoverflow.com/a/59353387/3899919) implies when Host != Origin that causes the error
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/DY8Vn.png |
Not directly related to OP question but just to complete @mrhn answer.
When working with an array of data you want to all convert to DTO, you can use `::collect()` like so;
```php
$ratings = Rating::collect($request->input("rating"));
```
It then gives you access to all [Laravel `Collection` methods](https://laravel.com/docs/11.x/collections#available-methods).
see [Spatie docs](https://spatie.be/docs/laravel-data/v4/as-a-resource/from-data-to-array#content-using-collections) |
I've encountered a challenge with handling keyboard suggestions in a `contentEditable` element, specifically the unwanted spacing that occurs when selecting suggested text from a virtual keyboard. Here's an approach I've developed that seems to mitigate this issue:
**Approach:**
The strategy involves storing the `textContent` immediately, clearing the `textContent`, and then replacing it after a slight delay. This delay helps avoid unwanted spaces from keyboard suggestions while maintaining the suggestion feature.
**Code Solution:**
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<html>
<style>
#sp {
outline: none;
white-space: pre-wrap;
position: relative;
font-family: monospace; /* Ensures consistent spacing */
background: #f3f3f3;
}
</style>
<span autocapitalize="none" contentEditable=true id="sp" >continue...</span>
</html>
<!-- language: lang-js -->
const outspanin = document.getElementById('sp');
let handleglobaldblC = function (e) {
// Get the content of the span
var content = outspanin.textContent;
let caretPos = window.getSelection().anchorOffset;
const sub = content.slice(caretPos);
const val2 = content.slice(0, caretPos);
outspanin.textContent = "";
// Delay before replacing back
setTimeout(() => {
outspanin.textContent = val2 + sub;
setCaretPosition(val2.length);
}, 50);
}
function setCaretPosition(pos) {
let range = document.createRange();
let sel = window.getSelection();
range.setStart(outspanin.childNodes[0], pos);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
outspanin.addEventListener('input', handleglobaldblC);
<!-- end snippet -->
**Limitations:**
The delay time is critical. If too short, unexpected behaviors such as loss of textContent or character repetition may occur. If too long, it can make editing feel unresponsive.
The current delay is set to 50ms, which seems to be a good balance, but further experimentation may be necessary to optimize for different devices and browsers.
**Conclusion:**
This method is not without its challenges, and there may be edge cases that require additional handling. However, it opens up a path for further research and potential improvements. If you have insights or improvements on this approach, your contributions would be greatly appreciated!
|
* **Chrome/Edge/Opera Only**: [`navigator.storage.estimate().usageDetails`][1] provides a breakdown by storage type, but it's not supported in Firefox/Safari (see [browser compatibility][2])
>Note: The returned values are not exact: between compression, deduplication, and obfuscation for security reasons, they will be imprecise.
--------
* In **Chrome DevTools**, the **Application** tab provides a breakdown of storage by type; click the "Clear storage" view in the top left and a graph should appear. This is useful for local debugging, but not understanding storage usage "in the wild"
[1]: https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/estimate#usagedetails
[2]: https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/estimate#browser_compatibility |
I am trying to perform a network meta-analysis. The network contains 3 subnetworks. Therefore I decided to use netmeta::discomb to perform an additive analysis. This worked without error in another project, but not with the new studies.
My current dataset contains 9 studies over a total of 10 treatments (all two-armed, continuous outcome) . The data was transformed from the arm-based to the contrast-based design using netmeta::pairwise. When calling the method netmeta::discomb, the error appears that the dimensions of the edge-vertex incidence matrices B and C are non-conformable. I guess, the warning about the missing separator will later become a problem.
The help says: *By default, the matrix C is calculated internally from treatment names.* Passing a C-matrix myself was also unsuccessful.
I would like to be able to create a reasonable overview at the end, i.e. with
--summary(m1.netmeta)-, --netgraph(m1.netmeta)- and --forest(m1.netmeta,...)-.
If required, I can also provide the data and script from the previous project. Maybe it will help.
The minimal code used is below. This is session info:
R version 4.3.2 (2023-10-31 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19045)
Matrix products: default
I appreciate any help and will be happy to answer any questions.
```
library(netmeta)
df <- data.frame(study= c('study 1', 'study 1', 'study 2', 'study 2', 'study 3', 'study 3',
'study 4', 'study 4', 'study 5', 'study 5', 'study 6', 'study 6',
'study 7', 'study 7', 'study 8', 'study 8', 'study 9', 'study 9'),
stud_ind= c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2),
comparators= c(1, 2, 3, 2, 1, 2, 4, 2, 5, 0, 6, 2, 7, 2, 6, 2, 8, 9),
n_probands= c(14, 14, 15, 15, 9, 9, 19, 19, 21, 21, 27, 27, 15, 15, 18, 19, 14, 11),
mean= c(3.13, 3.47, 2.36, 3.61, 2.89, 2.78, 2.36, 2.36, 2.64, 5.00, 3.24,
3.28, 1.53, 1.53, 3.07, 2.89, 3.00, 3.30),
sd= c(2.06, 1.74, 1.99, 1.95, 1.97, 1.29, 1.32, 1.32, 1.68,
2.75, 1.21, 1.17, 1.20, 1.20, 2.23, 2.56, 1.53, 1.52))
# long to wide + contrast based
df_wide = df %>%
pivot_wider(names_from=c(stud_ind), values_from=c(comparators, n_probands, mean, sd))
p1 <- pairwise(list(comparators_1, comparators_2),
TE = list(mean_1, mean_2), seTE = list(sd_1, sd_2),
data = df_wide, sm = "MD", reference.group = "2")
# look at network
nc1 <- netconnection(
data=p1,
sep.trts = ":",
nchar.trts = 500,
title = "",
warn = FALSE,
)
print(nc1)
#################################
m1.netmeta <- discomb(TE = TE,
seTE = seTE,
treat1= treat1,
treat2= treat2,
studlab = study,
data = p1,
sm = "MD",
fixed = FALSE,
random = TRUE,
reference.group = "2",
details.chkmultiarm = FALSE,
sep.trts = " vs. ")
# results in error:
# Error in B.matrix %*% C.matrix : non-conformable arguments
# In addition: Warning message:
# No treatment contains the component separator '+'.
#################################
# try with 'own' C.matrix
C <- rbind(c(1, 0, 0, 0, 0, 0, 0, 0, 0), # 0
c(0, 1, 0, 0, 0, 0, 0, 0, 0), # 1
c(0, 0, 1, 0, 0, 0, 0, 0, 0), # 2
c(0, 0, 0, 1, 0, 0, 0, 0, 0), # 3
c(0, 0, 0, 0, 1, 0, 0, 0, 0), # 4
c(0, 0, 0, 0, 0, 1, 0, 0, 0), # 5
c(0, 0, 0, 0, 0, 0, 1, 0, 0), # 6
c(0, 0, 0, 0, 0, 0, 0, 1, 0), # 8
c(0, 0, 0, 0, 0, 0, 0, 0, 1)) # 9
colnames(C)<-c("0","1","2","3","4","5","6","8","9")
rownames(C)<-c("0","1","2","3","4","5","6","8","9")
m2.netmeta <- discomb(TE = TE,
seTE = seTE,
treat1= treat1,
treat2= treat2,
studlab = study,
data = p1,
sm = "MD",
fixed = FALSE,
random = TRUE,
reference.group = "2",
details.chkmultiarm = FALSE,
sep.trts = " vs. ",
C.matrix = C)
# results in error:
# Error in B.matrix %*% C.matrix : non-conformable arguments
# In addition: Warning message:
# No treatment contains the component separator '+'.
```
|
How can I solve non-conformable arguments in R netmeta::discomb (Error in B.matrix %*% C.matrix)? |
|r|meta-analysis| |
null |
I found this code on web, and it works on retina. Paste here, hope can help someone.
```objective-c
NSImage *computerImage = [NSImage imageNamed:NSImageNameComputer];
NSInteger size = 256;
NSBitmapImageRep *rep = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
pixelsWide:size
pixelsHigh:size
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bytesPerRow:0
bitsPerPixel:0];
[rep setSize:NSMakeSize(size, size)];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:rep]];
[computerImage drawInRect:NSMakeRect(0, 0, size, size) fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
[NSGraphicsContext restoreGraphicsState];
NSData *data = [rep representationUsingType:NSPNGFileType properties:nil];
``` |
Use the following:
python setup.py install --prefix=<your path> |
I'm very new to JS. I'm trying to return a matched value from user input from a global array (aStoreItems) for a theoretical online book store. The array consists of objects passed through a constructor.
```
// Function to find object by ID value
function getBookById(id) {
console.log("Variable being passed in(in getbookbyid function)= " + id)
console.log(" type Variable being passed in(ingetbookbyid function)= " + typeof (id))
for (var i = 0; i < aStoreItems.length; ++i) {
if (aStoreItems[i].bID == id) {
return aStoreItems[i];
selectedBook = aStoreItems[i];
}
}
};
// Sample of object in array
var ID23 = new StoreItem("ID23", "The Slow Regard of Silent Things", 12.99, 50, 1, "Fiction", 1.99, ["Great story", 5], "Desc", "<img src='./imgs/the_slow_regard_of_silent_things.jpeg' />");
```
Now I'm trying to implement an add to cart function that passes a user typed value and passes it through the getBookById() function.
Right now I'm just trying to pass the variable created by the users input to find the book that they want to add to cart
```
function addToCart() {
var bookSelection = document.getElementById("pID").value;
console.log("user typed (in add to cart function) " + bookSelection);
getBookById(bookSelection);
console.log("return is(in add to cart function) " + selectedBook);
};
```
console output shows this:
user typed (in add to cart function) ID23
Variable being passed in(in get book by id function)= ID23
type Variable being passed in(in get book by id function)= string
return is(in add to cart function) undefined
I don't know where I'm going wrong and other solutions researched are not fairing any better
Thanks to all for you help!
|
You get many out of bounds
The following model works better
range J = 0..5;
range R = 1..3;
range T = 1..10;
int P[J] = [0,1,2,3,4];
int d[J] = [1, 1, 3, 5, 2];
int EF[J] = [1, 2, 1, 1, 1];
int LF[J] = [2, 3, 4, 6, 2];
dvar int x[J][T];
subject to {
forall(j in J, i in {P[j]})
sum (t in EF[j]..LF[j]:t in T) ((t - d[j]) * x[j][t]) -
sum (t in EF[i]..LF[i]:t in T) t * x[i][t] >= 0;
}
and later on with your second model, the following works fine
// Example data
range J = 0..5;
range R = 1..3;
range T = 1..10;
int P[J] = [0,1,2,3,4];
int d[J] = [1, 1, 3, 5, 2];
int EF[J] = [1, 2, 1, 1, 1];
int LF[J] = [2, 3, 4, 6, 2];
int Tbar = sum(j in J) d[j];
// Resource usage matrix
int u[J][R] = [[1, 0, 2],
[1, 1, 1],
[1, 1, 0],
[2, 0, 3],
[1, 1, 2]];
// Resource availability
int a[R]= [1,2,3];
// Decision Variables
dvar boolean x[J][T];
dexpr int CT = sum(j in J, t in EF[j]..LF[j]:t in T)t*x[j][t];
minimize CT;
subject to {
forall(j in J)
sum (t in EF[j]..LF[j]:t in T) x[j][t] <= 1;
forall(j in J, i in {P[j]}) //no job must be started before all its predecessors have been completed.
sum (t in EF[j]..LF[j]:t in T) ((t - d[j]) * x[j][t]) -
sum (t in EF[i]..LF[i]:t in T) t * x[i][t] >= 0;
forall(r in R, t in 1..Tbar) {
sum(j in J) u[j][r] * sum(q in maxl(t, EF[j])..minl(t + d[j] - 1, LF[j])) x[j][q] <= a[r];
}
} |
I am working on a project in which execution at some size of data requires additional heap space, The actual problem is that I tried multiple approaches to solve but all in vain.
At first, I started by editing my launch.json file since I am using VSCode, tried adding the Xmx parameter to the vmArgs.
nothing, I added a portion of code to my Main class which goes as follows:
System.out.println("====================================================================");
System.out.println("JVM arguments:");
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> jvmArgs = runtimeMxBean.getInputArguments();
for (String arg : jvmArgs) {
System.out.println(arg);
}
// Print actual heap size used by the JVM
System.out.println("Max Memory: " + (Runtime.getRuntime().maxMemory() / (1024 * 1024)) + " MB");
// Your application code goes here
System.out.println("====================================================================");
long maxMemory = rutime.maxMemory();
System.out.println("Max Memory: " + maxMemory / (1024 * 1024) + " MB");
This code displays jvm Arguments and of course actual max memory to be used by JAVA on my system.
It is initially set at 1896 MB. Output:
====================================================================
JVM arguments:
-XX:+ShowCodeDetailsInExceptionMessages
Max Memory: 1896 MB
====================================================================
Max Memory: 1896 MB
I tried adding the JAVA-OPTS variable to the system. Nothing changed after re-executing.
```
./././.>"C:\Program Files\Java\jdk-15.0.2\bin\java.exe" -Xmx2G -cp <path_to_my_main_class> Main
```
tried executing from terminal and specifying the Xmx value, and my `Main` class weren't recognized, even though I multiple-checked syntax, path and class name, same thing on cmd and vscode terminal (windows 11).
And still when I execute under VScode the main class runs correctly before returning the `java.lang.outOfMemoryerror`.
also I noticed that I had two different version of java on my pc by executing the command:
```
>where java
C:\Program Files\Common Files\Oracle\Java\javapath\java.exe
C:\Program Files (x86)\Common Files\Oracle\Java\javapath\java.exe
```
while VSCode execution starts this way:
```
PS D:\Studies\M1\S2\TPs\méth\Projet Méta> d:; cd 'd:\Studies\M1\S2\TPs\méth\Projet Méta'; & 'C:\Program Files\Java\jdk-15.0.2\bin\java.exe' '-XX:+ShowCodeDetailsInExceptionMessages' '-cp' 'C:\Users\wahee\AppData\Roaming\Code\User\workspaceStorage\bdc4f5af61bc4e992a3808de6bdc92e9\redhat.java\jdt_ws\Projet Méta_de071d7c\bin' 'Main'
```
seems to specify another java instance. that I added to path system variable, and still nothing (made sure to constantly restart my PC)
I browsed stack overflow, google, and pushed chatGPT to his limits to a point it's just keeps apologizing and repeating steps over and over again...
I also accessed the control panel to add `-Xmx` and `-Xms` arguments within a java interface using a specific dialogue box with no change.
I am running on a x64 architecture. What Am I missing in all this? Or should I try something else?
|
null |
I am working on a WordPress site and while integrating SMTP with the site, I used (EASY WP SMTP & WP Mail SMTP) with 3 different SMTP credentials. When I try to send a test mail over SMTP, it gives me an error (Connection Timeout), and simple SMTP is also not working. I tried to add SMTP and create a test form (contact form) and check, but it didn't send the mail. I am using the BookingPress Plugin, and in that, I also tried SMTP & wp-default, but both are not working. Here is the full error log by Easy WP SMTP:
also i have increased the timeout limit from (10 - 60)
Versions:
WordPress: 6.4.3
WordPress MS: No
PHP: 8.1.27
Easy WP SMTP: 2.2.0
Params:
Mailer: smtp
Constants: No
ErrorInfo: SMTP Error: Could not connect to SMTP host. Failed to connect to serverSMTP server error: Failed to connect to server SMTP code: 110 Additional SMTP info: Connection timed out
Host: pop3.mailtrap.io
Port: 1100
SMTPSecure: tls
SMTPAutoTLS: bool(true)
SMTPAuth: bool(true)
Server:
OpenSSL: OpenSSL 1.1.1w 11 Sep 2023
Apache.mod_security: No
Debug:
Email Source: Easy WP SMTP
Mailer: Other SMTP
SMTP Error: Could not connect to SMTP host. Failed to connect to serverSMTP server error: Failed to connect to server SMTP code: 110 Additional SMTP info: Connection timed out
SMTP Debug:
2024-03-13 05:58:39 Connection: opening to pop3.mailtrap.io:1100, timeout=30, options=array()
2024-03-13 05:59:09 Connection failed. Error #2: stream_socket_client(): Unable to connect to pop3.mailtrap.io:1100 (Connection timed out) [/home/gur1yt4rjmck/public_html/mortgage.cybertrontechnologies.ca/wp-includes/PHPMailer/SMTP.php line 397]
2024-03-13 05:59:09 SMTP ERROR: Failed to connect to server: Connection timed out (110)
SMTP Error: Could not connect to SMTP host. Failed to connect to server
please help me with this issue
[Log Image](https://i.stack.imgur.com/kOizs.png)
i want to send the bookingpress notification with smtp and other forms info with smtp but stuck with this error
|
i was expecting to migrate project App from JDK11/SDK33 to JDK 17/SDK 34 but fails everytime,
i have been for days tring to find the correct configuration..
My console error output:
```
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring project ':flutter_native_image'.
> Could not create an instance of type com.android.build.api.variant.impl.LibraryVariantBuilderImpl.
> Namespace not specified. Specify a namespace in the module's build file. See https://d.android.com/r/tools/upgrade-assistant/set-namespace for information about setting the namespace.
If you've specified the package attribute in the source AndroidManifest.xml, you can use the AGP Upgrade Assistant to migrate to the namespace value in the build file. Refer to https://d.android.com/r/tools/upgrade-assistant/agp-upgrade-assistant for general information about using the AGP Upgrade Assistant.
* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights
```
script: android/app/build.gradle
```
plugins {
id "com.android.application"
id "kotlin-android"
id "dev.flutter.flutter-gradle-plugin"
}
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
android {
namespace "com.ivc.lili"
compileSdk 34
ndkVersion "25.1.8937393"
// ndkVersion flutter.ndkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = '17'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.ivc.lili"
minSdkVersion 21
targetSdkVersion 34
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
//signingConfig signingConfigs.release
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
```
script: android/build.gradle
```
plugins {
id "com.android.application"
id "kotlin-android"
id "dev.flutter.flutter-gradle-plugin"
}
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
android {
namespace "com.ivc.lili"
compileSdk 34
ndkVersion "25.1.8937393"
// ndkVersion flutter.ndkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = '17'
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.ivc.lili"
minSdkVersion 21
targetSdkVersion 34
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
//signingConfig signingConfigs.release
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
```
script: android/settings.gradle
```
pluginManagement {
def flutterSdkPath = {
def properties = new Properties()
file("local.properties").withInputStream { properties.load(it) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
return flutterSdkPath
}
settings.ext.flutterSdkPath = flutterSdkPath()
includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle")
}
include ":app"
apply from: "${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle/app_plugin_loader.gradle"
```
script: wrapper.properties
```
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
```
My Android Studio configuration with empty project to run apps form physical device: [](https://i.stack.imgur.com/Gud5z.jpg) | [](https://i.stack.imgur.com/jUigY.jpg)
Im clearly new to Flutter and Android dev, just wanna make this thing run, please. |
Flutter run JDK 17/SDK 34 migration issue 'flutter_native_image' |
|java|android|flutter|dart|gradle| |