instruction stringlengths 0 30k ⌀ |
|---|
I am working on configuring a multi-tenant web application. Each tenant will have their own User Pool in AWS Cognito, along with their own Idp configurations. In some cases we’ll use the Cognito User Pool as the primary Idp, and in other cases we’ll use a federated Idp, likely using SAML.
My question is: are there any concerns with directly integrating a 3rd party tenant’s designated User Pool with an Idp that they own and manage? Or is it preferable for us to manage an Idp on their behalf, but for which we provide a UI to add users and adjust permissions?
Regardless of who owns the Idp, we will integrate the User Pool with AWS Verified Permissions on our end to handle authorization.
|
the variable `number` is an object ID of a text object.
```python
number = canvas.create_text(400, 200, text=random.randint(10000, 100000))
```
so you're not comparing the guess with the number displayed, but rather with that object ID. (which also happens to be an int [per the tkinter docs] but that's beside the point)
what you want is maybe to generate the number first, then use it in the canvas and in your value comparison.
```python
import tkinter
import random
canvas = tkinter.Canvas(width=800, height=400)
canvas.pack()
# generate number
random_number = random.randint(10000, 100000)
# place number in canvas
number = canvas.create_text(400, 200, text=random_number)
def prec():
canvas.create_rectangle(400 - 50, 200 - 50, 400 + 50, 200 + 50, outline="white", fill="white")
canvas.after(2000, prec)
guess = input("What number was there?: ")
guess = int(guess)
# compare guess to number
if guess == random_number :
canvas.create_text(400, 100, text="Correct", font="arial 20")
else:
canvas.create_text(400, 100, text="Incorrect", font="arial 20")
canvas.mainloop()
```
if the future, consider using a debugger to see the values of all variables |
can anyone help me with getting the model I'm working in now? I have a button that should be clicked to execute a webhook, but I can't get the model in which the button is clicked. i'm new to js, so it's very difficult to understand
```
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="web.PhoneField" owl="1">
<div class="o_phone_content d-inline-flex w-100">
<t t-if="props.readonly">
<a t-if="props.value" class="o_form_uri" t-att-href="phoneHref" t-esc="props.value"/>
</t>
<t t-else="">
<input
class="o_input"
t-att-id="props.id"
type="tel"
autocomplete="off"
t-att-placeholder="props.placeholder"
t-ref="input"
/>
</t>
</div>
</t>
<t t-name="web.FormPhoneField" t-inherit="web.PhoneField" t-inherit-mode="primary">
<xpath expr="//input" position="after">
<a
t-if="props.value"
href="#"
onclick="makeCall(event)"
class="o_phone_form_link ms-3 d-inline-flex align-items-center"
t-att-data-model-name="props.modelName"
t-att-data-record-id="props.recordId"
>
<i class="fa fa-phone"></i><small class="fw-bold ms-1">Call</small>
</a>
</xpath>
</t>
</templates>
window.makeCall = function(event) {
event.preventDefault();
var $button = $(event.currentTarget);
var modelName = this.dataset.model;
var recordId = $button.attr('data-record-id');
var phone = $button.prev('input.o_input').val();
console.log('Model Name:', modelName);
// Determine context and set data accordingly
var data = {
phone: phone,
contact_id: modelName === 'res.partner' ? recordId : undefined,
lead_id: modelName === 'crm.lead' ? recordId : undefined,
};
// Example of fetching additional data if needed
if (modelName === 'crm.lead') {
odoo.define('model.func', function(require) {
var rpc = require('web.rpc');
rpc.query({
model: modelName,
method: 'read',
args: [[recordId], ['partner_id']],
}).then(function(records) {
var record = records[0];
if (record.partner_id) {
data.contact_id = record.partner_id[0];
}
// Now, make the AJAX call with the complete data object
$.ajax({
url: url,
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
success: function(response) {
console.log("Call initiated successfully", response);
},
error: function(error) {
console.error("Error initiating call", error);
}
});
});
});
} else {
// If not crm.lead or additional data not needed, make the call directly
$.ajax({
url: url,
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
success: function(response) {
console.log("Call initiated successfully", response);
},
error: function(error) {
console.error("Error initiating call", error);
}
});
}
};
```
I tried everything I could think of, looking for a model through this.model, props.model, this.dataset.model, etc. |
I have recently installed spark on my system, but I am not able to run spark-shell
these are the steps that I did:
- spark-3.5.1-bin-hadoop3-scala2.13 : installed this
- deleted older version of jdk and installed 21.0.2.0
- places respective winutils in hadoop dir
- made entries in environment vars
now the pyspark shell is working fine and the Spark UI is running as well.
When I am trying to run the spark-shell, it is throwing me 'java.nio.file.NoSuchFileException'. below is the output that I am getting.
# Output
```
Using Scala version 2.13.8 (Java HotSpot(TM) 64-Bit Server VM, Java 21.0.2)
Type in expressions to have them evaluated.
Type :help for more information.
ReplGlobal.abort: bad constant pool index: 0 at pos: 48461
ReplGlobal.abort: bad constant pool index: 0 at pos: 48461
Exception in thread "main" scala.reflect.internal.FatalError:
bad constant pool index: 0 at pos: 48461
while compiling: <no file>
during phase: globalPhase=<no phase>, enteringPhase=<some phase>
library version: version 2.13.8
compiler version: version 2.13.8
reconstructed args: -classpath -Yrepl-class-based -Yrepl-outdir C:\Users\xyz\AppData\Local\Temp\spark-07dbe56e-21ca-43d8-a131-ab0117e9c5f7\repl-90ddff5b-0bb5-4869-89d1-d9783e201afd
last tree to typer: EmptyTree
tree position: <unknown>
tree tpe: <notype>
symbol: null
call site: <none> in <none>
== Source file context for tree position ==
at scala.reflect.internal.Reporting.abort(Reporting.scala:69)
at scala.reflect.internal.Reporting.abort$(Reporting.scala:65)
at scala.tools.nsc.interpreter.IMain$$anon$1.scala$tools$nsc$interpreter$ReplGlobal$$super$abort(IMain.scala:149)
at scala.tools.nsc.interpreter.ReplGlobal.abort(ReplGlobal.scala:27)
at scala.tools.nsc.interpreter.ReplGlobal.abort$(ReplGlobal.scala:24)
at scala.tools.nsc.interpreter.IMain$$anon$1.abort(IMain.scala:149)
at scala.tools.nsc.symtab.classfile.ClassfileParser$ConstantPool.errorBadIndex(ClassfileParser.scala:407)
at scala.tools.nsc.symtab.classfile.ClassfileParser$ConstantPool.getExternalName(ClassfileParser.scala:262)
at scala.tools.nsc.symtab.classfile.ClassfileParser.readParamNames$1(ClassfileParser.scala:853)
at scala.tools.nsc.symtab.classfile.ClassfileParser.parseAttribute$1(ClassfileParser.scala:859)
at scala.tools.nsc.symtab.classfile.ClassfileParser.$anonfun$parseAttributes$6(ClassfileParser.scala:936)
at scala.tools.nsc.symtab.classfile.ClassfileParser.parseAttributes(ClassfileParser.scala:936)
at scala.tools.nsc.symtab.classfile.ClassfileParser.parseMethod(ClassfileParser.scala:635)
at scala.tools.nsc.symtab.classfile.ClassfileParser.parseClass(ClassfileParser.scala:548)
at scala.tools.nsc.symtab.classfile.ClassfileParser.$anonfun$parse$2(ClassfileParser.scala:174)
at scala.tools.nsc.symtab.classfile.ClassfileParser.$anonfun$parse$1(ClassfileParser.scala:159)
at scala.tools.nsc.symtab.classfile.ClassfileParser.parse(ClassfileParser.scala:142)
at scala.tools.nsc.symtab.SymbolLoaders$ClassfileLoader.doComplete(SymbolLoaders.scala:342)
at scala.tools.nsc.symtab.SymbolLoaders$SymbolLoader.$anonfun$complete$2(SymbolLoaders.scala:249)
at scala.tools.nsc.symtab.SymbolLoaders$SymbolLoader.complete(SymbolLoaders.scala:247)
at scala.reflect.internal.Symbols$Symbol.completeInfo(Symbols.scala:1561)
at scala.reflect.internal.Symbols$Symbol.info(Symbols.scala:1533)
at scala.reflect.internal.Definitions.scala$reflect$internal$Definitions$$enterNewMethod(Definitions.scala:47)
at scala.reflect.internal.Definitions$DefinitionsClass.String_$plus$lzycompute(Definitions.scala:1256)
at scala.reflect.internal.Definitions$DefinitionsClass.String_$plus(Definitions.scala:1256)
at scala.reflect.internal.Definitions$DefinitionsClass.syntheticCoreMethods$lzycompute(Definitions.scala:1577)
at scala.reflect.internal.Definitions$DefinitionsClass.syntheticCoreMethods(Definitions.scala:1559)
at scala.reflect.internal.Definitions$DefinitionsClass.symbolsNotPresentInBytecode$lzycompute(Definitions.scala:1590)
at scala.reflect.internal.Definitions$DefinitionsClass.symbolsNotPresentInBytecode(Definitions.scala:1590)
at scala.reflect.internal.Definitions$DefinitionsClass.init(Definitions.scala:1646)
at scala.tools.nsc.Global$Run.<init>(Global.scala:1226)
at scala.tools.nsc.interpreter.IMain.liftedTree1$1(IMain.scala:152)
at scala.tools.nsc.interpreter.IMain.global$lzycompute(IMain.scala:151)
at scala.tools.nsc.interpreter.IMain.global(IMain.scala:142)
at scala.tools.nsc.interpreter.IMain.withSuppressedSettings(IMain.scala:106)
at scala.tools.nsc.interpreter.shell.ILoop.$anonfun$run$1(ILoop.scala:954)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.scala:18)
at scala.tools.nsc.interpreter.shell.ReplReporterImpl.withoutPrintingResults(Reporter.scala:64)
at scala.tools.nsc.interpreter.shell.ILoop.run(ILoop.scala:954)
at org.apache.spark.repl.Main$.doMain(Main.scala:84)
at org.apache.spark.repl.Main$.main(Main.scala:59)
at org.apache.spark.repl.Main.main(Main.scala)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:75)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:52)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52)
at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:1029)
at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:194)
at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:217)
at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:91)
at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:1120)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:1129)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
24/04/01 01:12:33 ERROR ShutdownHookManager: Exception while deleting Spark temp dir: C:\Users\xyz\AppData\Local\Temp\spark-07dbe56e-21ca-43d8-a131-ab0117e9c5f7\repl-90ddff5b-0bb5-4869-89d1-d9783e201afd
java.nio.file.NoSuchFileException: C:\Users\xyz\AppData\Local\Temp\spark-07dbe56e-21ca-43d8-a131-ab0117e9c5f7\repl-90ddff5b-0bb5-4869-89d1-d9783e201afd
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(WindowsFileAttributeViews.java:53)
at java.base/sun.nio.fs.WindowsFileAttributeViews$Basic.readAttributes(WindowsFileAttributeViews.java:38)
at java.base/sun.nio.fs.WindowsFileSystemProvider.readAttributes(WindowsFileSystemProvider.java:197)
at java.base/java.nio.file.Files.readAttributes(Files.java:1853)
at org.apache.spark.network.util.JavaUtils.deleteRecursivelyUsingJavaIO(JavaUtils.java:124)
at org.apache.spark.network.util.JavaUtils.deleteRecursively(JavaUtils.java:117)
at org.apache.spark.network.util.JavaUtils.deleteRecursively(JavaUtils.java:90)
at org.apache.spark.util.SparkFileUtils.deleteRecursively(SparkFileUtils.scala:121)
at org.apache.spark.util.SparkFileUtils.deleteRecursively$(SparkFileUtils.scala:120)
at org.apache.spark.util.Utils$.deleteRecursively(Utils.scala:1126)
at org.apache.spark.util.ShutdownHookManager$.$anonfun$new$4(ShutdownHookManager.scala:65)
at org.apache.spark.util.ShutdownHookManager$.$anonfun$new$4$adapted(ShutdownHookManager.scala:62)
at scala.collection.ArrayOps$.foreach$extension(ArrayOps.scala:1328)
at org.apache.spark.util.ShutdownHookManager$.$anonfun$new$2(ShutdownHookManager.scala:62)
at org.apache.spark.util.SparkShutdownHook.run(ShutdownHookManager.scala:214)
at org.apache.spark.util.SparkShutdownHookManager.$anonfun$runAll$2(ShutdownHookManager.scala:188)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.scala:18)
at org.apache.spark.util.Utils$.logUncaughtExceptions(Utils.scala:1928)
at org.apache.spark.util.SparkShutdownHookManager.$anonfun$runAll$1(ShutdownHookManager.scala:188)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.scala:18)
at scala.util.Try$.apply(Try.scala:210)
at org.apache.spark.util.SparkShutdownHookManager.runAll(ShutdownHookManager.scala:188)
at org.apache.spark.util.SparkShutdownHookManager$$anon$2.run(ShutdownHookManager.scala:178)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:572)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:317)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642)
at java.base/java.lang.Thread.run(Thread.java:1583)
```
Can someone help over here? Any help will be appreciated. thanks. |
Getting error while running spark-shell on my system; pyspark is running fine |
|windows|apache-spark| |
null |
|javascript|forms|xmlhttprequest| |
I want to bind this XML:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<D:propfind xmlns:D='DAV:' xmlns:A='http://apple.com/ns/ical/'
xmlns:C='urn:ietf:params:xml:ns:caldav'>
<D:prop>
<D:resourcetype />
<D:owner />
<D:displayname />
<D:current-user-principal />
<D:current-user-privilege-set />
<A:calendar-color />
<C:calendar-home-set />
</D:prop>
</D:propfind>
```
to XML objects:
```
[XmlRoot("propfind", Namespace = DavNamepaces.davXmlNamespace)]
public class PropFindRequest()
{
[XmlElement(ElementName = "prop", Namespace = DavNamepaces.davXmlNamespace)]
public Properties Properties { get; set; } = null!;
}
[XmlRoot(ElementName="prop")]
public class Properties
{
[XmlElement(ElementName="resourcetype")]
public object Resourcetype { get; set; }
[XmlElement(ElementName="owner")]
public object Owner { get; set; }
[XmlElement(ElementName="displayname")]
public object Displayname { get; set; }
[XmlElement(ElementName="current-user-principal")]
public object Currentuserprincipal { get; set; }
[XmlElement(ElementName="current-user-privilege-set")]
public object Currentuserprivilegeset { get; set; }
[XmlElement(ElementName="calendar-color")]
public object Calendarcolor { get; set; }
[XmlElement(ElementName="calendar-home-set")]
public object Calendarhomeset { get; set; }
}
```
`Program.cs`:
```
// Add services to the container.
builder.Services
.AddControllers(options =>
{
options.OutputFormatters.RemoveType<SystemTextJsonOutputFormatter>();
options.InputFormatters.RemoveType<SystemTextJsonInputFormatter>();
})
// Adds builder.AddXmlDataContractSerializerFormatters(); && builder.AddXmlSerializerFormatters();
.AddXmlFormaterExtensions();
```
Controller:
```
[ApiController]
[Route("caldav/")]
public class CalDavController
{
[AcceptVerbs("POST")]
[ApiExplorerSettings(IgnoreApi = false)]
[Produces("application/xml")]
[Consumes("application/xml")]
public async Task<IActionResult> Propfind([FromXmlBody(XmlSerializerType = XmlSerializerType.XmlSerializer)]PropFindRequest propFindRequest,[FromHeader] int Depth)
{
throw new NotImplementedException();
}
}
```
Error:
> Error: Bad Request
> Response body
> Download
> <status>400</status>
> <title>One or more validation errors occurred.</title>
> <type>https://tools.ietf.org/html/rfc9110#section-15.5.1</type>
> <traceId>00-e1611d29682cd7e995d256c79850082d-ebfcd416977a94a7-00</traceId>
> <MVC-Errors>
> <MVC-Empty>An error occurred while deserializing input data.</MVC-Empty>
> <propFindRequest>The propFindRequest field is required.</propFindRequest>
> </MVC-Errors>
> </problem>
I was expecting that the mapping works with the annotations I added.
I tried first to change the `Request` just to match the expectations in the `Response`
Trial and error request:
```
<?xml version="1.0" encoding="UTF-8"?>
<propFindRequest>
<properties>
<resourcetype>string</resourcetype>
<owner>string</owner>
<displayname>string</displayname>
<currentuserprincipal>string</currentuserprincipal>
<currentuserprivilegeset>string</currentuserprivilegeset>
<calendarcolor>string</calendarcolor>
<calendarhomeset>string</calendarhomeset>
</properties>
</propFindRequest>
```
but it resulted in the same error, therefore I think I made a mistake but I have no clue where.
Am I missing something important?
Do I have to use `DataContractSerializer`? I thought that this should work out of the box with the default `XmlSerializer` according to MS. |
how to get a model in js for odoo 16 |
|javascript|model|odoo-16| |
null |
|file-upload|struts2|uploadify| |
I found a solution to this!!
So the problem is with the sort in this scenario.
In the below code I am using only one sort and also String prototype "[localCompare][1]"
NOTE: same can be achieved with "sort" function but "localCompare" suits well for your problem statement
const [data, setData] = useState([{ title: 'A' }, { title: 'B' }, { title: 'C' }, { title: 'D' }, { title: 'E' }]);
const [toggleFilter, setToggleFilter] = useState(false);
const sortedArray = useMemo(
() => data.sort((a, b) => (toggleFilter ? b.title.localeCompare(a.title) : a.title.localeCompare(b.title))),
[data, toggleFilter]
);
return (
<View>
<FlatList
style={styles.flatlist}
data={sortedArray}
renderItem={({ item }) => <Text>{item.title}</Text>}
keyExtractor={item => item.id}
/>
<Pressable style={styles.button} onPress={() => setToggleFilter(!toggleFilter)}>
<Text style={styles.text}>{toggleFilter ? '⬇️' : '⬆️'}</Text>
</Pressable>
</View>
);
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare |
While the form is open in the Designer go to menu Tools > Form Editor > Form Settings... In new dialog check "ID-based" check box.
When you rebuild the project all `QCoreApplication::translate` calls in `retranslateUi` will be changed to `qtTrId`. Also, all parameters in those calls will reset to empty string. If you already changed some texts to ID strings those changes will disappear. Save them somewhere before you do all this.
All GUI elements will now have an `id` property. This is where all the ID strings go. The existing `text` properties contain so called "Engineering English" texts. They show only in the Qt Designer, and they show in the Qt Linguist, essentially as if in .cpp code you add a `//%` comment before a line that defines a string for translation. They don't show in run-time. You have to fill up the .ts file. |
{"OriginalQuestionIds":[52973106,37787698],"Voters":[{"Id":16646078,"DisplayName":"e-motta"},{"Id":2901002,"DisplayName":"jezrael","BindingReason":{"GoldTagBadge":"csv"}}]} |
I have an app with about 14 screens and i need to integrate a package which will only work on android.or is there a way to add andorid only packages to flutterFlow ?
I tried adding custom functions with that package but FF was throwing abunch of errors |
how much time will take to debug flutterFlow code to flutter if i use the download code option in FlutterFlow? |
|android|flutter|flutterflow| |
null |
1. The type of the parameter `n` and of the counter `i` should be `size_t`, not `unsigned int`.
2. The type of the first two parameters should be `const char *`.
3. Although the strings are passed as pointers to `char` (with `const`), the characters should be interpreted as if they had the type `unsigned char`, per C 2018 7.24.1 3.
4. `s1` and `s2` should never be accessed beyond `n` characters, but the code tests `i < n` last, after using `s1[i]` and `s2[i]`, instead of before using them.
5. The code also accesses `s1[i]` and `s2[i]` in the `return` statement even if the loop terminated because `i` reached `n`. Besides causing the routine to access the arrays out of bounds, this also means the return value is very likely to be wrong, as it should be zero but instead will be based on evaluations of the incorrectly accessed `s1[i]` and `s2[i]`.
More theoretically:
6. It is conceivable `char` and `unsigned char` are the same width as `int` and therefore `s1[i] - s2[i]` can overflow or wrap. Instead, the values should be compared and used to select a positive, zero, or negative return value. |
I want to convert existing in-memory data (some columns and a schema) to a dataframe in Rust so it can be processed by DataFusion with its dataframe API. How can we do that?
I see the only constructor has the signature:
```
pub fn new(session_state: SessionState, plan: LogicalPlan) -> Self {
```
which requires the SessionState and LogicalPlan. However, the logical plan in my case is not known in advance.
One workaround is to write the data to disk as CSV and then read it back. Certainly it does not work for large data. |
For all major issues with eclipse, not loading, freezing, or debugger failure (that is not because of your code), try the following line:
```none
./eclipse -clean -clearPersistedState -refresh
``` |
I am trying to perform the following operations on some tensors. Currently I am using einsum, and I wonder if there is a way (maybe using dot or tensordot) to make things faster, since I feel like what I am doing is more or less some outer and inner products.
```
res1 = numpy.einsum('ij, kjh->ikjh', A, B)
res2 = np.einsum('ijk, jk->ij', C, D)
```
I have tried using tensordot and dot, and for some reason, I cannot figure the right way to set the axes...
|
Faster alternative for numpy einsum in Python |
|numpy|tensor|tensordot|einsum| |
null |
{"Voters":[{"Id":1839439,"DisplayName":"Dharman"}]} |
null |
Problem Statement :
Input Format : First line of the input contains an integer n. Second line of inputs contains the n array elements
Output format : The largest number that can be composed using all the array elements
Constraints : 1<=n<=100 and 1<=array elements<=1000
A simple sorting algorithm does not work for inputs like : 2,21
which gives the output as 212, but the largest number is 221
Hence I came up with the following algorithm :
1. Sort all the numbers in descending order with respect to their msd (most significant digit)
2. Find out ranges of elements having the same msd
3. within each range containing elements of same msd, we sort each element according to a value returned by a upgrade function. Upgrade function does not alter values of elements.
---
The upgrade function returns a value on the following basis :
if element is equal to 1000 then -1 is returned, which causes it to be placed at the end of the array
if element is single digit and is equal to the msd of its range, we return msd*100 + msd*10 + msd
if element is double digit and is equal to msd*10 + msd, we return msd*100 + msd*10 + msd
if elemment is double digit we return element*10
in other cases we return the element
---
I came up with this algorithm considering the inputs 532, 5 , 55 ,56
the maximum number should be 56,555,532
My code :
```
#include<stdio.h>
#include<stdlib.h>
void sort_msd(int arr[],int n);
void range_provider_msd(int arr[], int n); // finds out the indexes within which elements of same msd are present
void swap(int a,int b, int arr[]); // swaps array elements with index a and b in array arr[]
int msd(int n); //finds msd of n
void sort_final(int range_left,int range_right,int arr[], int msd_); //gives the final sort on the basis of upgrade function
int upgrade(int n,int msd_); //upgrades element for better comparison
int main()
{
int n; //n is number of element in array
scanf("%d",&n);
int*arr=(int*)malloc(n*sizeof(int));
for(int i=0;i<n;++i){scanf("%d",&arr[i]);}
sort_msd(arr,n); //soritng according to msd
range_provider_msd(arr,n);
for(int i=0;i<n;++i){printf("%d",arr[i]);}
return 0;
}
void sort_msd(int arr[],int n)
{
for(int i=0;i<n;++i)
{
int max_index=i,max_msd=msd(arr[i]);
for(int j=i+1;j<n;j++)
{
int compare_msd=msd(arr[j]);
if(compare_msd>max_msd)
{
max_index=j;
max_msd=compare_msd;
}
}
swap(i,max_index,arr);
}
}
int msd(int n)
{
while(n>=10)
{
n=n/10;
}
return n;
}
void swap(int a,int b, int arr[])
{
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
void range_provider_msd(int arr[], int n)
{
//following code finds out the index ranges for elements with same msd and passes them onto the sort_final function
int left_range=0,right_range=0;
for(int i=1;i<(n+1);++i) //n+1 to check for the special case for last elements being equal
{
if(msd(arr[left_range])-msd(arr[i]) == 0 && left_range<n-1 && i<n)
++right_range;
else if(right_range== n-1 && i==n) //special code when last elements are equal
{
sort_final(left_range,right_range,arr,msd(arr[left_range]));
}
else
{
sort_final(left_range,right_range,arr,msd(arr[left_range]));
left_range=right_range+1;
++right_range;
}
}
}
void sort_final(int range_left,int range_right,int arr[],int msd_)
{
for(int i=range_left;i<=range_right;++i)
{
int max_index=i;
for(int j=i+1; j<=range_right;++j)
{
if(upgrade(arr[j],msd_)>upgrade(arr[max_index],msd_))
max_index=j;
}
swap(i,max_index,arr);
}
}
int upgrade(int n, int msd_)
{
if(n==1000)
return -1;
else if(n<10 && n==msd_)
return(100*msd_ + 10*msd_ + msd_);
else if(n>=10 && n<100 && n==(10*msd_+msd_))
return(100*msd_ + 10*msd_ + msd_);
else if(n>=10 && n<100)
return(n*10);
else
return(n);
}
```
I submitted this code on my grading system and got stuck on 9th test out of 11 tests, and test does not specify what inputs I am getting stuck on. How can I find a case in which the program fails to output the right answer?
Or is there any easier and obvious method to solve this problem? I have no knowledge of data structures or something like that.
p.s This is one of my assignments from the Coursera course "algorithmic toolbox" by University of California San Diego.
|
Finding the maximum concatenate number from the list of numbers provided |
I am currently working on a Laravel project deployed using a docker-compose file. This file deploys a php-fpm container and an nginx container. The objective is to utilize GitLab CI/CD to automate the build and deployment process.
I have installed a GitLab runner instance on a local machine that runs Debian 12, and I'm using it with a shell. I'm attempting to execute various stages (build, test, and deploy) on the GitLab runner to deploy the project on another machine that will host the containers. I've reached the 'docker compose up' job, but I wonder if I'm proceeding correctly.
For the final step in my gitlab-ci file, I use scp to send the docker-compose file to the hosting machine. Then, I use ssh to execute the 'docker compose up' command to deploy it.
```
stages:
- build_dependencies
- test
- deploy_production
cache:
paths:
- vendor/
build_composer:
stage: build_dependencies
script:
- composer install -n
artifacts:
paths:
- ./vendor
pest_test:
stage: test
script:
- ./vendor/bin/pest
larastan_test:
stage: test
script:
- ./vendor/bin/phpstan analyse --memory-limit=2G --no-progress
build_docker_image:
stage: deploy_production
dependencies: []
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
script:
- docker build -t $CI_REGISTRY_IMAGE:latest
-t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA -f ./.docker/Dockerfile .
- docker push $CI_REGISTRY_IMAGE --all-tags
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: on_success
deploy_containers:
stage: deploy_production
script:
- scp /path/to/file username@a:/path/to/destination
- ssh username@IP "docker compose up -d"
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: manual
```
Also, in case you would be wondering, my php-fpm container is from a custom image where i get the whole code project inside it and i install composer dependencies without dev ones :
```
FROM composer:2.7.2 AS composer
WORKDIR /var/www/
COPY . ./
RUN composer install --ignore-platform-reqs --prefer-dist --no-scripts --no-progress --no-interaction --no-dev \
--no-autoloader
FROM php:8.2.8-fpm
ENV USER=www
ENV GROUP=www
ENV ACCEPT_EULA=Y
# Install dependencies
RUN apt-get update && apt-get install -y \
git \
curl \
libpng-dev \
libonig-dev \
libxml2-dev \
libzip-dev \
zip \
unzip \
gnupg \
gnupg2 \
nano
# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*
# Install PHP extensions
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd zip
RUN docker-php-ext-enable zip
#DRIVER SQL SRV
RUN apt-get update
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/debian/11/prod.list > /etc/apt/sources.list.d/mssql-release.list
RUN apt-get update
RUN ACCEPT_EULA=Y apt-get install -y msodbcsql18
RUN ACCEPT_EULA=Y apt-get install -y mssql-tools18
RUN echo 'export PATH="$PATH:/opt/mssql-tools18/bin"' >> ~/.bashrc
RUN apt-get install -y unixodbc-dev
RUN apt-get -y install unixodbc-dev
RUN pecl install sqlsrv pdo_sqlsrv
RUN docker-php-ext-enable sqlsrv pdo_sqlsrv
#DRIVER SQL SRV
# Get the build app
COPY --from=composer /var/www/ /var/www/
# Setup working directory
WORKDIR /var/www/
# Create User and Group
RUN groupadd -g 1000 ${GROUP} && useradd -u 1000 -ms /bin/bash -g ${GROUP} ${USER}
# Grant Permissions
RUN chown -R ${USER} /var/www
EXPOSE 9000
CMD ["php-fpm"]
```
The gitlab-ci file is not finished yet since I need to manage .env files, releases, and some more, but you get the main idea. What do you think about it? Is there any best other way in your opinion? |
How to perform CRUD operations on a static JSON array in Angular? (without API) |
|json|angular|frontend|angular-reactive-forms|crud| |
null |
In case anyone would like to prevent dismiss bottom sheet from **hardware back button on Android devices**
You have to make your own bottom sheet instead of using showBottomSheet(), like this
```
Navigator.of(context).push(
PageRouteBuilder(
opaque: false,
pageBuilder: (_, __, ___) {
return Material(
color: Colors.black.withOpacity(0.5),
child: WillPopScope(
onWillPop: () async {
return false;
},
child: YourCustomBottomSheet(),
),
);
},
),
);
``` |
I am making `MultiVector` class for Entity Component System. It is used for storing objects of different types for iterating over them efficiently.
I use vectors of bytes as raw storage and `reinterpret_cast` it to whichever type I need. Basic functionality (`push_back` by const reference and `pop_back`) seems to work.
However, when I try to implement move semantics for `push_back` (commented lines), clang gives me incomprehensible 186 lines error message, something about 'allocate is declared as pointer to a reference type'. As I understand, vector tries to `push_back` reference to T, which it cannot do because it must own contained objects.
How am I supposed to do it?
```
#include <iostream>
#include <vector>
using namespace std;
int g_class_id { 0 };
template <class T>
const int get_class_id()
{
static const int id { g_class_id++ };
return id;
}
class MultiVector {
public:
MultiVector() : m_vectors(g_class_id + 1) {}
template <typename T>
vector<T>& vector_ref() {
const int T_id { get_class_id<T>() };
if (T_id >= m_vectors.size()) {
m_vectors.resize(T_id + 1);
}
vector<T>& vector_T { *reinterpret_cast<vector<T>*>(&m_vectors[T_id]) };
return vector_T;
}
template<typename T>
void push_back(const T& value) {
vector_ref<T>().push_back(value);
}
// Move semantics, take rvalue reference
template<typename T>
void push_back(T&& value) {
vector_ref<T>().push_back(std::move(value));
}
template <typename T>
void pop_back() {
vector_ref<T>().pop_back();
}
private:
vector<vector<byte>> m_vectors;
};
template<typename T>
void show(const vector<T>& vct)
{
for (const auto& item : vct) cout << item << ' ';
cout << '\n';
}
int main(int argc, const char *argv[])
{
string hello = "hello";
string world = "world";
MultiVector mv;
mv.push_back(10);
mv.push_back(20);
mv.push_back(2.7);
mv.push_back(3.14);
mv.push_back(hello);
mv.push_back(world);
show(mv.vector_ref<int>());
show(mv.vector_ref<double>());
show(mv.vector_ref<string>());
mv.vector_ref<int>().pop_back();
show(mv.vector_ref<int>());
return 0;
}
```
Tried to replace rvalue reference `T&&` to just value `T`, does not compile too because call to `push_back` becomes ambiguous. |
For someone looking for a solution with Ionic v7, this is what you can do to apply custom CSS for toastController.
1. Specify `cssClass` property in `toastController.create()`.
const toast = await this.toastController.create({
message: 'Your Toast Message',
duration: 2000,
cssClass: 'toast-success'
});
2. In your `global.scss`, specify your styles.
ion-toast.toast-success {
&::part(container) {
background: #24a148;
color: #fff;
border-color: #24a148;
border-radius: 4px;
}
} |
After referring to another laravel project from a friend I was able to find the issue here. The problem was actually that I was initiating the tooltips within a function in my <script> tags. Placing the initialization code inside of $(function() {}); or $(document).ready(function(){}); caused the tooltips not to function. The init code had to be placed inside <script> with no function surrounding it (basically literally right below my <script> tag) to work. |
Here is a response I found from Google: [Google's Response][1]
Pasting text here for convenience and incase it gets "disabled" LOL!
> If an account is closed because of inactivity then I am afraid there
> is no way to recover it. A number of warnings are sent to the account
> owner before the account is closed.
>
> The dormant account policy does
> allows you to open a new account:
> https://support.google.com/googleplay/android-developer/answer/9899234
> but you will need to use a different account/email address.
You will also need to use a different Developer name when creating your new account, so if you used your real name you are tough out of luck and must now use a dev handle name, perhaps something like: JonDoeNotDetedByGoogle.
[1]: https://support.google.com/googleplay/android-developer/thread/208102688/my-developer-account-was-closed-due-to-inactivity-but-we-have-an-active-app-how-do-i-get-access?hl=en |
I have a socket.io server which listens to sockets:
io.on('connection', (socket) => {
socket.on('myEvent', function(data){
socket.emit('eventReceived', { status: 1 });
});
});
I know that Node.js and Socket.IO is not working in multithreading, so I wonder how to effectively handle multiple clients, sending a myEvent at the same time.
I've read a few things about Clusters. Would it be as easy as just adding the following code infront of my project?
const cluster = require('cluster');
const os = require('os');
const socketIO = require('socket.io');
if (cluster.isMaster) {
const numCPUs = os.cpus().length;
console.log(`Master ${process.pid} is running`);
// Fork workers
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
} else {
//my socket code
}
I've also read a few things about Redis, how would it be useful in such a case? Is it effective on an Raspberry Pi?
Thanks for any help :) |
How to Socket.IO Multithreading on a Raspberry Pi? |
|node.js|redis|socket.io|cluster-computing| |
Using the parameter ```end``` and setting the length of your series should do the trick.
x <- c(1,2,3)
x_ts <- ts(x,start=1,end=length(x)) |
More efficient alternatives that don't need to go through select on a specific table:
```js
const [{ id }] = await dataSource.query("SELECT NEXTVAL('users_id_seq') AS id");
```
OR
```js
const [{ id }] = await userRepository.query("SELECT NEXTVAL('users_id_seq') AS id");
```
**NOTE:** When using `select` from `createQueryBuilder`, you are not just getting the next value in the sequence, you are actually bringing a next value to each row of the select in this table (Repository), that is, it is a column in the select. |
Finding the Topic of Each Post |
|sql|postgresql| |
I am using the following code to call my REST API from SQL Server but I am getting empty string in the response message. I put a breakpoint in visual studio on getTravelerInfoById method but it is also not triggered. Can you please check and let me know what am I doing wrong?
DECLARE @URL NVARCHAR(MAX) = 'https://localhost:7128/api/TravelerBase/getTravelerInfoById';
DECLARE @Object AS INT;
DECLARE @ResponseText AS VARCHAR(8000);
DECLARE @Body AS VARCHAR(8000) =
'{
"var1": "2024-03-16 16:56:59",
"var2": "+0200",
"var3": "856"
}'
EXEC sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
EXEC sp_OAMethod @Object, 'open', NULL, 'post',
@URL,
'false'
EXEC sp_OAMethod @Object, 'setRequestHeader', null, 'Content-Type', 'application/json'
EXEC sp_OAMethod @Object, 'send', null, @body
EXEC sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
SELECT @ResponseText As 'ResponseText'
IF CHARINDEX('false',(SELECT @ResponseText)) > 0
BEGIN
SELECT @ResponseText As 'Message'
END
ELSE
BEGIN
SELECT @ResponseText As 'customer Details'
END
EXEC sp_OADestroy @Object
I enabled the procedures as below:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
I tried a GET api https://localhost:7128/api/TravelerBase/getVersion as well but it is also not triggered.
I also tried the following simple API that gives version number but its also giving empty string.
Declare @Object as Int;
Declare @ResponseText as Varchar(8000);
--Code Snippet
Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
'https://vps-7034f481.vps.ovh.net/simat/simatapi/api/TravelerBase/getVersion', --Your Web Service Url (invoked)
'false'
Exec sp_OAMethod @Object, 'send'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
Select @ResponseText
Exec sp_OADestroy @Object
Thanks. |
i am integrating tailwind with flowbite react but this error occured
npm ERR! code 1
npm ERR! path C:\\Users\\ASUS\\OneDrive\\Desktop\\Sankalp\\Frontend\\node_modules\\flowbite-react
npm ERR! command failed
npm ERR! command C:\\WINDOWS\\system32\\cmd.exe /d /s /c bun run build
npm ERR! 'bun' is not recognized as an internal or external command,
npm ERR! operable program or batch file.
npm ERR! A complete log of this run can be found in: C:\\Users\\ASUS\\AppData\\Local\\npm-cache\\\_logs\\2024-03-31T07_04_56_478Z-debug-0.log
PS C:\\Users\\ASUS\\OneDrive\\Desktop\\Sankalp\\Frontend\>
i am expecting tailwinnd and flowbite work properly but not working |
A complete log of this run can be found in |
|tailwind-css|flowbite| |
null |
|java|spring|spring-boot|spring-retry| |
I need to print the bounding box coordinates of a walking person in a video. Using YOLOv5 I detect the persons in the video. Each person is tracked. I need to print each person's bounding box coordinate with the frame number. Using Python how to do this.
The following is the code to detect, track persons and display coordinates in a video using YOLOv5.
```
#display bounding boxes coordinates
import cv2
from ultralytics import YOLO
# Load the YOLOv8 model
model = YOLO('yolov8n.pt')
# Open the video file
cap = cv2.VideoCapture("Shoplifting001_x264_15.mp4")
#get total frames
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(f"Frames count: {frame_count}")
# Initialize the frame id
frame_id = 0
# Loop through the video frames
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
if success:
# Run YOLOv8 tracking on the frame, persisting tracks between frames
results = model.track(frame, persist=True,classes=[0])
# Visualize the results on the frame
annotated_frame = results[0].plot()
# Print the bounding box coordinates of each person in the frame
print(f"Frame id: {frame_id}")
for result in results:
for r in result.boxes.data.tolist():
if len(r) == 7:
x1, y1, x2, y2, person_id, score, class_id = r
print(r)
else:
print(r)
# Display the annotated frame
cv2.imshow("YOLOv5 Tracking", annotated_frame)
# Increment the frame id
frame_id += 1
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord("q"):
break
else: # Break the loop if the end of the video is reached
break
# Release the video capture object and close the display window
cap.release()
cv2.destroyAllWindows()
```
The above code is working and display the coordinates of tracked persons.
But the problem is in some videos it is not working properly
0: 384x640 6 persons, 1292.9ms
Speed: 370.7ms preprocess, 1292.9ms inference, 20.8ms postprocess per image at shape (1, 3, 384, 640)
Frame id: 0
[849.5707397460938, 103.34817504882812, 996.0990600585938, 371.2213439941406, 1.0, 0.9133888483047485, 0.0]
[106.60043334960938, 74.8958740234375, 286.6423645019531, 562.144287109375, 2.0, 0.8527513742446899, 0.0]
[221.3446044921875, 60.8421630859375, 354.4775390625, 513.18017578125, 3.0, 0.7955091595649719, 0.0]
[472.7821044921875, 92.33056640625, 725.2569580078125, 632.264404296875, 4.0, 0.7659056782722473, 0.0]
[722.457763671875, 222.010986328125, 885.9102783203125, 496.00372314453125, 5.0, 0.7482866644859314, 0.0]
[371.93310546875, 46.2138671875, 599.2041625976562, 437.1387939453125, 6.0, 0.7454277873039246, 0.0]
This output is correct.
But for another video there are only three people in the video but at the beginning of the video at 1st frame identify as 6 person.
0: 480x640 6 persons, 810.5ms
Speed: 8.0ms preprocess, 810.5ms inference, 8.9ms postprocess per image at shape (1, 3, 480, 640)
Frame id: 0
[0.0, 10.708396911621094, 37.77726745605469, 123.68929290771484, 0.36418795585632324, 0.0]
[183.0453338623047, 82.82539367675781, 231.1952667236328, 151.8341522216797, 0.2975049912929535, 0.0]
[154.15158081054688, 74.86528778076172, 231.10934448242188, 186.2017822265625, 0.23649221658706665, 0.0]
[145.61187744140625, 69.76246643066406, 194.42532348632812, 150.91973876953125, 0.16918501257896423, 0.0]
[177.25042724609375, 82.43289947509766, 266.5430908203125, 182.33889770507812, 0.131477952003479, 0.0]
[145.285400390625, 69.32669067382812, 214.907470703125, 184.0771026611328, 0.12087596207857132, 0.0]
Also, the output does not show the person ID here. Only display coordinates, confidence score, and class id. What is the reason for that?
|
I’m making an in app purchase for my game on Steam. On my server I use python 3. I’m trying to make an https request as follows:
conn = http.client.HTTPSConnection("partner.steam-api.com")
orderid = uuid.uuid4().int & (1<<64)-1
print("orderid = ", orderid)
key = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason
steamid = "xxxxxxxxxxxxxxxxxxx" # omitted for security reason
pid = "testItem1"
appid = "480"
itemcount = 1
currency = 'CNY'
amount = 350
description = 'testing_description'
urlSandbox = "/ISteamMicroTxnSandbox/"
s = f'{urlSandbox}InitTxn/v3/?key={key}&orderid={orderid}&appid={appid}&steamid={steamid}&itemcount={itemcount}¤cy={currency}&itemid[0]={pid}&qty[0]={1}&amount[0]={amount}&description[0]={description}'
print("s = ", s)
conn.request('POST', s)
r = conn.getresponse()
print("InitTxn result = ", r.read())
I checked the s in console, which is:
```
s = /ISteamMicroTxnSandbox/InitTxn/v3/?key=xxxxxxx&orderid=11506775749761176415&appid=480&steamid=xxxxxxxxxxxx&itemcount=1¤cy=CNY&itemid[0]=testItem1&qty[0]=1&amount[0]=350&description[0]=testing_description
```
However I got a bad request response:
```
InitTxn result = b"<html><head><title>Bad Request</title></head><body><h1>Bad Request</h1>Required parameter 'orderid' is missing</body></html>"
````
How to solve this? Thank you!
BTW I use almost the same way to call GetUserInfo, except changing parameters and replace POST with GET request, and it works well. |
When in Map using the !! operator, Sonar cube issues warning [s6611 "Map" values should be accessed safely][1]. One solution from Sonar is to use getValue, which will throw a NoSuchElementException if the key is not found.
val a = mapOf<Int, Map<String, String>>()
a[999]!!["x"] // NullPointerException
a.getValue(999)["x"] // NoSuchElementException: Key 999 is missing in the map.
What is the benefit of NoSuchElementException other than reporting the value of a key that is not found?
[1]: https://rules.sonarsource.com/kotlin/RSPEC-6611/ |
There is a problem with the above most-voted answer: https://stackoverflow.com/a/76364984/13973939
**Problem**
Many packages are still using `package=` definition inside their `AndroidManifest.xml` so if you add namespace directly it will give error for all those packages to remove the `package=` property, which obviously is not feasible.
**Solution**
If you are using Gradle v8.x.x above then you have two options. Either:
1) **[RECOMMENDED]** Downgrade your gradle to v7.x.x something. Not all packages support v8 at the moment so you can upgrade it later.
2) If for any reason you don't want to downgrade. You can add the following subprojects script. **NOTE:** Using subprojects is a workaround and not a good practice. If not absolutely required I would suggest doing option 1.
Add this to your `android/build.gradle` file:
```
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
// The below script
subprojects {
afterEvaluate { project ->
if (project.hasProperty('android')) {
project.android {
if (namespace == null) {
namespace project.group
}
}
}
}
}
// till here
subprojects {
project.evaluationDependsOn(':app')
}
```
This will add the namespace to only any packages that can support it. |
using the standard csv (not pandas) you can skip as many header lines you need using the 'next' command in a for-loop. The code below shows how to open a file and skip the number of lines you need (5 in that example)
import csv
reader = csv.reader(open('test.csv'), delimiter=';')
for row in range(5):
next(reader) # skip header line
# start displaying for the 6th row
for row in reader:
print(row)
if the header had a variable number of row, you could then loop in the reader file and detect the line you need which contains the actual header of your data by checking the value of the 1st column to search for the header name :
import csv
reader = csv.reader(open('test.csv'), delimiter=';')
for row in reader:
# check the row is not empty and check for 1st column (row[0])
if row !=[] and row[0] == 'first_col_header':
print (row)
|
Please do not ban, I have read other similar questions but they dont work out for me.
I Created a Pivot Table but cant manage to sort it by sales ("Ventas") .
```
'Try to sort (Not Working)
With ptTable
.PivotFields("Ventas").AutoSort xlDescending, "Total Ventas"
End With
```
```
Sub CrearTablaDinamicaaaa()
Dim ws_Source As Worksheet
Dim ws_Dest As Worksheet
Dim ptCache As PivotCache
Dim ptTable As PivotTable
Dim rangoDatos As Range
Dim lastRow As Long
Dim ptTableName As String
Set ws_Source = ThisWorkbook.Sheets("Base Ventas Asistidos")
Set ws_Dest = ThisWorkbook.Sheets("Deporte")
ptTableName = "TablaDinamicaVentas"
' Define range where to place the Pivot Table
lastRow = ws_Source.Cells(ws_Source.Rows.Count, "A").End(xlUp).Row
Set rangoDatos = ws_Source.Range("A1:L" & lastRow)
' Crear un Pivot Cache
Set ptCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rangoDatos)
' Crete Pivot Table
Set ptTable = ptCache.CreatePivotTable(TableDestination:=ws_Dest.Range("H40"), TableName:=ptTableName)
' Configure Pivot Table
With ptTable
'Filter
.PivotFields("División").Orientation = xlPageField
.PivotFields("División").Position = 1
'Filter
.PivotFields("Semana").Orientation = xlPageField
.PivotFields("Semana").Position = 2
'Rows
.PivotFields("SKU").Orientation = xlRowField
.PivotFields("SKU").Position = 1
'Create Values of "Ventas" (Sales)
With .PivotFields("Ventas")
.Orientation = xlDataField
.Function = xlSum
.Position = 1
.Name = "Total Ventas"
End With
End With
' Refresh
ptTable.RefreshTable
'Try to sort (Not Working)
With ptTable
.PivotFields("Ventas").AutoSort xlDescending, "Total Ventas"
End With
' Refresh
ptTable.RefreshTable
End Sub
```
|
Sort Sales of Pivot Table with VBA |
|excel|vba| |
null |
The two following changes are necessary:
First, in the init of MainWindow, you need the get the instance of PandasModel visible to the whole class:
self.model = PandasModel(self.df)
Second, when you want the filtered_df from the PandasModel instance, you have to specify the instance (here self.model):
def display_filtered_map(self):
print(self.model.filtered_df) |
C# XML ModelBinding - ASP.NET Core 8 Web API - required field not found |
|c#|xml|asp.net-core-webapi|model-binding|.net-8.0| |
Try this:
```
from selenium.webdriver.firefox.service import Service as FirefoxService
firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference("browser.download.folderList", 2)
firefox_profile.set_preference("browser.download.manager.showWhenStarting", False)
# firefox_profile.set_preference("browser.download.dir", str(output_directory))
firefox_profile.set_preference(
"browser.helperApps.neverAsk.saveToDisk", "application/zip")
service = FirefoxService(firefox_profile = firefox_profile)
browser = webdriver.Firefox(
service= service,
options = firefox_options
)
```
|
In C# I have a class like this:
public class BClass
{
public int Ndx { get; set; }
public string Title { get; set; }
}
This is then used within this class
public class AClass
{
public int Ndx { get; set; }
public string Author { get; set; }
public BClass[] Titles { get; set; }
}
Now when I populate author I do not know how many titles they have until run time so the number of instances of `AClass.Titles` there will be, so my question is how do I initialise this every time, please?
Thanks in advance |
How do I initialise a class within a class |
I am using pg-promise for performing a multi row insert to insert around 8 million records and facing the following error:
Error: Connection terminated unexpectedly
at Connection.<anonymous> (/usr/src/app/node_modules/pg/lib/client.js:132:73)
at Object.onceWrapper (node:events:509:28)
at Connection.emit (node:events:390:28)
at Socket.<anonymous> (/usr/src/app/node_modules/pg/lib/connection.js:63:12)
at Socket.emit (node:events:390:28)
at TCP.<anonymous> (node:net:687:12)
I have already tried to configure the connection with parameters like idleTimeoutMillis, connectionTimeoutMillis (also tried adding and removing parameters like keepAlive, keepalives_idle, statement_timeout, query_timeout) and still facing the issue.
`const db = pgp({
host: host,
port: port,
database: database,
user: user,
password: pass,
idleTimeoutMillis: 0, // tried with multiple values
connectionTimeoutMillis: 0, // tried with multiple values
keepAlive: true,
keepalives_idle: 300,
statement_timeout: false,
query_timeout: false,
});` |
Connection terminated unexpectedly while performing multi row insert using pg-promise |
|javascript|node.js|node-modules|pg-promise| |
null |
I was having a similar issues and did the following which vixed it
I added the type
const value = await this.cacheManager.get<string>('key');
And additionally I update my cachemodule register to include the store
import * as redisStore from 'cache-manager-redis-store';
CacheModule.register({
store: redisStore,
host: config.redisHost,
port: 6379,
}),
|
I am trying to download file on click of notification button but when application is in background then api call is not working.
Notification Code:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo as! [String: AnyObject]
switch response.actionIdentifier {
case "DownloadDutyPlanAction":
print("Download tap")
downloadDutyPlanFromNotification(fetchCompletionHandler: nil)
completionHandler()
case "CancelAction":
print("Cancel tap")
default:
completionHandler()
}
}
func downloadFromNotification(fetchCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)?) {
let downloadPDFOperation = PDFDownloadOperation.init() { result in
switch result {
case .success:
DispatchQueue.main.async {
}
completionHandler?(UIBackgroundFetchResult.newData)
case .failure:
completionHandler?(UIBackgroundFetchResult.newData)
}
}
QueueManager.shared.enqueueNotification(downloadPDFOperation)
}
Network class:
private var task: URLSessionTask?
private var session = URLSession.init(configuration: URLSessionConfiguration.default, delegate: NSURLSessionPinningDelegate(), delegateQueue: nil)
func request(forDownloadUrl route: EndPoint, completion: @escaping NetworkDownloadRouterCompletion) {
do {
let request = try self.buildRequest(from: route)
task = session.downloadTask(with: request) { localURL, response, error in
if let tempLocation = localURL {
completion(response, error, tempLocation)
} else {
completion(response, error, nil)
}
}
} catch {
completion(nil, error, nil)
}
self.task?.resume()
} |
Good evening,
I am trying to parallelize a code that sums plus one to all the elements of a vector `M`, with a ThreadPool (the pool is standard and it is implemented in the book Parallel Programming Concepts Snd Practice). So I defined a function `sum_plus_one(x,M)` that takes as arguments `x`: the position of the vector, and the vector `M`. The code is the following:
#include <iostream>
#include <vector>
#include <thread>
#include <hpc_helpers.hpp>
#include <threadPool.hpp>
int main(int argc, char *argv[]) {
// define a Thread Pool with 8 Workers
ThreadPool TP(5);
auto sum_plus_one = [](const uint64_t x, const std::vector<uint64_t> &M) {
return M[x]+1;
};
uint64_t N = 10; // dimension of the vector
// allocate the vector
std::vector<uint64_t> M(N);
std::vector<std::future<uint64_t>> futures;
// init function
auto init=[&]() {
for(uint64_t i = 0; i< N; ++i) {
M[i] = 1;
}
};
init();
// enqueue the tasks in a linear fashion
for (uint64_t x = 0; x < N; ++x) {
futures.emplace_back(TP.enqueue(sum_plus_one, x, &M));
}
// wait for the results
for (auto& future : futures)
std::cout << future.get() << std::endl;
return 0;
}
But I get the following error `error: no matching member function for call to 'enqueue'
futures.emplace_back(TP.enqueue(somma, x, &M)); candidate template ignored: substitution failure [with Func = (lambda at UTWavefrontTP.cpp:20:15) &, Args = <unsigned long long &, std::vector<unsigned long long> *>]: no type named 'type' in 'std::result_of<(lambda at UTWavefrontTP.cpp:20:15) &(unsigned long long &, std::vector<unsigned long long> *)>'
auto enqueue(Func && func, Args && ... args) -> std::future<Rtrn> {`
I am approaching this type of things as a beginner and I am a bit struggling finding the solution. Seems like the pointers are all okay, and that `enqueue` cannot find the function that sums to one all the elements.
|
I'm using net core 8.0, and for this issue I had to install ```Microsoft.AspNetCore.Identity.UI``` package and add ```.AddDefaultUI();``` to my ```builder.Services.AddIdentity<AppUser, IdentityRole>```
.
```c#
// Identity
builder.Services.AddIdentity<AppUser, IdentityRole>(options =>
{
options.User.RequireUniqueEmail = true;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredLength = 12;
options.SignIn.RequireConfirmedEmail = false;
})
.AddEntityFrameworkStores<ApplicationDBContext>()
.AddDefaultUI();
```
also I have ```app.MapIdentityApi<AppUser>();```to map all auth enpoints.
and this fixed my issue. |
it seems to me you could achieve your goal by means of formulas
if you insert one column and one row you could use this formula
=IF(SUM(G$5:G5)<G$2;IF(SUM(F6:$F6)<8;1;"");"")
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/we5Ul.png |
You can use a regex to check if the key is found in the string. The [preg_match][1] function allows to test a regular expression.
$array = ['cat' => 0, 'dog' => 1];
$string = 'I like cats';
foreach ($array as $key => $value) {
//If the key is found, prints the value and breaks
if (preg_match("/".preg_quote($key, '/')."/", $string)) {
echo $value . PHP_EOL;
break;
}
}
**EDIT:**
As said in comment, [strpos][2] could be better! So, using the same code, you can just replace preg_match:
$array = ['cat' => 0, 'dog' => 1];
$string = 'I like cats';
foreach ($array as $key => $value) {
//If the key is found, prints the value and breaks
if (false !== strpos($string, $key)) {
echo $value . PHP_EOL;
break;
}
}
[1]: http://php.net/manual/en/function.preg-match.php
[2]: http://php.net/manual/en/function.strpos.php |
Try this:
```
plt.plot(range(1, len(rfecv.cv_results_["mean_test_score"]) + 1), rfecv.cv_results_["mean_test_score"], color='#303F9F', linewidth=3)
``` |
Started getting below exception(at runtime) after I migrated my code from java 11 to java 17. Had to upgrade to using jakarta from javax during this process.
**Full stacktrace-**
```
Caused by: org.springframework.oxm.UncategorizedMappingException: Unknown JAXB exception
at org.springframework.oxm.jaxb.Jaxb2Marshaller.convertJaxbException(Jaxb2Marshaller.java:958) ~[spring-oxm-6.1.5.jar:6.1.5]
at org.springframework.oxm.jaxb.Jaxb2Marshaller.getJaxbContext(Jaxb2Marshaller.java:519) ~[spring-oxm-6.1.5.jar:6.1.5]
at org.springframework.oxm.jaxb.Jaxb2Marshaller.afterPropertiesSet(Jaxb2Marshaller.java:485) ~[spring-oxm-6.1.5.jar:6.1.5]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1833) ~[spring-beans-6.1.5.jar:6.1.5]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782) ~[spring-beans-6.1.5.jar:6.1.5]
... 44 common frames omitted
Caused by: org.glassfish.jaxb.runtime.v2.runtime.IllegalAnnotationsException: 3 counts of IllegalAnnotationExceptions
at org.glassfish.jaxb.runtime.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:83) ~[jaxb-runtime-4.0.5.jar:4.0.5 - cb19596]
at org.glassfish.jaxb.runtime.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:421) ~[jaxb-runtime-4.0.5.jar:4.0.5 - cb19596]
at org.glassfish.jaxb.runtime.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:255) ~[jaxb-runtime-4.0.5.jar:4.0.5 - cb19596]
at org.glassfish.jaxb.runtime.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1115) ~[jaxb-runtime-4.0.5.jar:4.0.5 - cb19596]
at org.glassfish.jaxb.runtime.v2.ContextFactory.createContext(ContextFactory.java:144) ~[jaxb-runtime-4.0.5.jar:4.0.5 - cb19596]
at org.glassfish.jaxb.runtime.v2.ContextFactory.createContext(ContextFactory.java:246) ~[jaxb-runtime-4.0.5.jar:4.0.5 - cb19596]
at org.glassfish.jaxb.runtime.v2.JAXBContextFactory.createContext(JAXBContextFactory.java:58) ~[jaxb-runtime-4.0.5.jar:4.0.5 - cb19596]
at jakarta.xml.bind.ContextFinder.find(ContextFinder.java:322) ~[jakarta.xml.bind-api-4.0.2.jar:4.0.2]
at jakarta.xml.bind.JAXBContext.newInstance(JAXBContext.java:392) ~[jakarta.xml.bind-api-4.0.2.jar:4.0.2]
at jakarta.xml.bind.JAXBContext.newInstance(JAXBContext.java:349) ~[jakarta.xml.bind-api-4.0.2.jar:4.0.2]
at org.springframework.oxm.jaxb.Jaxb2Marshaller.createJaxbContextFromContextPath(Jaxb2Marshaller.java:542) ~[spring-oxm-6.1.5.jar:6.1.5]
at org.springframework.oxm.jaxb.Jaxb2Marshaller.getJaxbContext(Jaxb2Marshaller.java:505) ~[spring-oxm-6.1.5.jar:6.1.5]
``` |
|mysql|left-join| |
I've a big trouble, since 4 hour's I tried to introduce, my credentials on git, but every single time I try, the command line give me this error
[enter image description here](https://i.stack.imgur.com/9xj4J.png)
But it don't let me introduce the credentials, and all because I forgot that I had to put my Access Token, now I can't do anything, just because I can't push my work on git, a simple solution is changing the repo to a public one, but the code is not finish...
Please somebody help me
To find a solution to my little problem |
How can I reintroduce username an password on git using fedora? |
|git|github|console|fedora| |
null |
I’m using `cjoint` package for the first time to analyze the results of a conjoint experiment I ran f few years ago. I’m able to produce the table in my R console, but does anyone know how I can produce the table in LaTeX, e.g. with `texreg()`? I’m copying my code below.
Women_Committee_women <- amce(
picked_A ~ A_female + A_reserved_seat + A_edu + A_prev_exp + A_married +
B_female + B_reserved_seat + B_edu + B_prev_exp + B_married,
data=Women_Committee_what_women_think,
cluster=TRUE,
respondent.id="ID",
design=candidate_design
) |
I have created a custom SAML application in the Google Admin panel for my workspace account to allow users to login via SSO to an application using their Google Workspace credentials. Currently only users of my organisation can login to this application. I want to make it so that users of an external organisation can also login to this application using their Google Workspace credentials using SSO. How do I do this?
Tried:
I have created a Google Group and all users who should have access to this application (both internal and external organisation users) and turned on access to this Google Group in the access settings of the custom SAML app.
Expected:
Both internal and external users should be able to login to the application.
Result:
Only internal users are able to login to the application using their credentials. When an external user tries to login they are shown 403 - app_not_configured_for_user error |
The following are the related lines of my query that I have a problem I cannot resolve:
IF (servicesalesdetailsopen_v.complaintcode LIKE 'IVWIP', 'Y', 'N') as intflag
LEFT JOIN servicesalesdetailsopen_v
ON servicesalesopen_v.ronumber = servicesalesdetailsopen_v.ronumber and servicesalesopen_v.vehid = servicesalesdetailsopen_v.vehid and servicesalesdetailsopen_v.cora_acct_code = 'XXX-S'
The query brings back accurate results but line by line for detailed line items within the servicesalesdetailsopen table. I only want a Y set as intflag if IVWIP is on ANY row in the servicesalesopen_v.complaintcode for the repair orders and it brings back every line item with a Y or an N for each line. I would like the result in one line by RO.
How do I accomplish one line results by RO?
This is ongoing. I don't want to have to address it when it's imported into another database. |
So i have this register api created
````
@PostMapping("/register")
public ResponseEntity<String> register(@RequestBody RegisterRequest registerRequest){
if (userRepository.findByEmail(registerRequest.getEmail())!=null){
return new ResponseEntity<>("Email already exist",HttpStatus.BAD_REQUEST);
}
User user = new User();
user.setEmail(registerRequest.getEmail());
user.setName(registerRequest.getName());
user.setLastName(registerRequest.getLastName());
user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
userRepository.save(user);
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(registerRequest.getEmail(), registerRequest.getPassword())
);
return new ResponseEntity<>(jwtUtil.generateToken(
registerRequest.getEmail(),
userRepository.findByEmail(registerRequest.getEmail()).getId(),
registerRequest.getName() +" "+registerRequest.getLastName()
)
,HttpStatus.OK
);
}
```````
This works fine without any error when i got and run my react project and go to the register page i am not able to register a user.
Also when i hit the same api on postman using
{
"name": "Alice",
"lastName": "Smith",
"email": "alice@example.com",
"password": "password123"
}
i get a error on console like
```
Invalid character found in method name [0x160x030x010x000xf70x010x000x000xf30x030x030x0e0xbca0x910x010xf8.0xc40x840xbecS<0xb5w`"0xf1M0xbe0xa10xcd0xf830xf3y0x8a0x110xc80xf80xca6 ]. HTTP method names must be tokens
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:419) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:271) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
2024-03-26 17:11:04.733 INFO 9612 --- [nio-8080-exec-6] o.apache.coyote.http11.Http11Processor : Error parsing HTTP request header
Note: further occurrences of HTTP request parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in method name [0x160x030x010x000xf70x010x000x000xf30x030x030xc930xfa0xfc0xc70xbd0xf80xfcK0x1b=R0x00t0xf60x1fN0xe1m0x100x84>0x830xf0d0xc8H0xf3e0xb3KC ]. HTTP method names must be tokens
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:419) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:271) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.68.jar:9.0.68]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
````
i have already checked that i am using "post" and there isnt any special characters
I HAVE CHANGED HTTPS TO HTTP AND NOW I AM NOT GETTING THE SAME ERROR RATHER GETTING THE 401 error on postman and still not able to register on the web browser |
Thanks For the suggestions, I was able to solve it using below code:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
var data2 = ecres.TrimEnd(padding).Replace('-', '+').Replace('_', '/').PadRight(4 * ((ecres.Length + 3) / 4), '=');
byte[] plainBytes = Convert.FromBase64String(data2);//Encoding.UTF8.GetBytes(ecres);
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
string salt = "220120221623321";
String passphrase = "vdKnilESoIqCGc";
var saltBytes = new byte[16];
var ivBytes = new byte[16];
Rfc2898DeriveBytes rfcdb = new System.Security.Cryptography.Rfc2898DeriveBytes(passphrase, Encoding.UTF8.GetBytes(salt), 65536, HashAlgorithmName.SHA256);
saltBytes = rfcdb.GetBytes(32);
var tempBytes = iv;
Array.Copy(tempBytes, ivBytes, Math.Min(ivBytes.Length, tempBytes.Length));
var rij = new RijndaelManaged(); //SymmetricAlgorithm.Create();
rij.Mode = CipherMode.CBC;
rij.Padding = PaddingMode.PKCS7;
// rij.FeedbackSize = 128;
// rij.KeySize = 256;
// rij.BlockSize = 256;
rij.Key = saltBytes;
rij.IV = iv;
SymmetricAlgorithm sa = rij;
var bytesDec = sa.CreateDecryptor().TransformFinalBlock(plainBytes, 0, plainBytes.Length);
// var decryptedText = Encoding.Unicode.GetString(bytesDec);
var decryptedText = Encoding.UTF8.GetString(bytesDec);
<!-- end snippet -->
|
Solution to your problem:(MYSQL 8.0)
WITH CTE AS
(
SELECT dp1.DID,
dp1.Description,
dp1.uid as uid1,
dp2.uid as uid2,
COUNT(*) OVER(PARTITION BY dp1.DID,dp1.UID) as total_participants,
COUNT(r.type in ('club member','family') or dp1.UID = dp2.UID)
OVER(PARTITION BY dp1.DID,dp1.UID) as related_participants
FROM day_package dp1
LEFT JOIN day_package dp2
ON dp1.did = dp2.did
LEFT JOIN related r
ON dp1.UID = r.person1_uid AND dp2.UID = r.person2_UID
)
SELECT DISTINCT DID,
Description,
related_participants as Participant_Count
FROM CTE
WHERE related_participants = total_participants
AND total_participants != 1
ORDER BY DID,Participant_Count
DB Fiddle link - https://dbfiddle.uk/tcV6ob2I |
|c++|module|package|c++20| |
I have json data that is structured like this, which I want to turn into a data frame:
{
"data": {
"1": {
"Conversion": {
"id": "1",
"datetime": "2024-03-26 08:30:00"
}
},
"50": {
"Conversion": {
"id": "50",
"datetime": "2024-03-27 09:00:00"
}
}
}
}
My usual approach would be to use json_normalize, like this:
`df = pd.json_normalize(input['data'])`
My goal is to have a table/dataframe with just the columns "id" and "datetime".
How do I skip the numbering level below data and go straight to Conversion? I would imagine something like this (which clearly doesn't work):
`df = pd.json_normalize(input['data'][*]['Conversion'])`
What is the best way to achieve this? Any hints are greatly appreciated!
|
I've created a class for a binary search tree called `BSTree`. I want to create a class for AVL tree called `AVLTree` and inherit `BSTree` class. But when I override a virtual method from `BSTree` class in `AVLTree` class and want to perform type casting from `BSTree` to `AVLTree` using round brackets notation, for example, `AVLTree node = (AVLTree)base.SomeMethod(...)`, the error **System.InvalidCastException: "Unable to cast object of type 'BSTree.BSTree' to type 'BSTree.AVLTree'."** occurs.
My `BSTree` class looks like this (I remained only necessary part of it):
```
class BSTree
{
public int Value { get; private set; }
public BSTree Left { get; set; }
public BSTree Right { get; set; }
public BSTree Parent { get; set; }
public BSTree(int value) { Value = value; }
protected virtual BSTree InsertBase(int value)
{
BSTree node = this, parent = null;
while (node != null)
{
if (value == node.Value) return null;
parent = node;
node = value > node.Value ? node.Right : node.Left;
}
node = new BSTree(value);
node.Parent = parent;
if (value > parent.Value) parent.Right = node;
else parent.Left = node;
return node;
}
public virtual void Insert(int value) { InsertBase(value); }
}
```
My `AVLTree` class (with a function for inserting only) looks like this:
```
class AVLTree : BSTree
{
public int BalanceFactor { get; set; }
public AVLTree(int value) : base(value) { }
protected override BSTree InsertBase(int value)
{
AVLTree node = (AVLTree)base.InsertBase(value); // error happens there
// following operations that calculate balance factors for all ancestors
return node;
}
}
```
I want `AVLTree` nodes to be inserted in exact the same manner as `BSTree` nodes, but `AVLTree` nodes need to have also a `BalanceFactor` property, apart from `Left`, `Right` and `Parent`, that come from `BSTree` class
|
System.InvalidCastException while inheriting a class |
|c#|oop|inheritance|polymorphism| |
null |
I have three tables: users, roles, and user_role (a linking table). I need to retrieve a user's roles in a readable form. Using the linking table, I need to extract all the necessary data from the roles table for a specific user. For this, I use:
```php
public function roles()
{
return $this->belongsToMany(RolesModel::class, 'user_role', 'user_id', 'role_id');
}
```
However, I get an empty array as output, even though there is definitely data in the database.
I checked for data availability this way:
```php
$user_role = UserRoleModel::where('user_id', $this->id)->first();
$role = RolesModel::where('_id', $user_role->role_id)->first();
```
And the result was the role I needed. What am I doing wrong in the `belongsToMany()` query? |
Laravel: Using belongsToMany relationship with MongoDB |
|php|laravel|mongodb|mql|laravel-mongodb| |