instruction stringlengths 0 30k ⌀ |
|---|
Managed to produce a simple example. Tried lots of Googling but none of the answers helped.
simple test code:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(TestController.class)
@ContextConfiguration(classes={SimpleTestConfig.class})
public class Producing404ExampleTest {
@Autowired
private MockMvc mvc;
@Test
public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception {
mvc.perform(get("/login"))
.andExpect(status().isOk());
}
}
The test controller:
@Controller
public class TestController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model ) {
model.addAttribute("app_name", "testing");
model.addAttribute("page_description", "login page");
return "login";
}
}
Configured with SimpleTestConfig:
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@SpringBootConfiguration
public class SimpleTestConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
HTTP
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/static**", "/logout/**", "/login/**", "/health/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().permitAll()
);
return http.build();
}
}
Run the test and get the result:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /login
Parameters = {}
Headers = []
Body = null
Session Attrs = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.servlet.resource.NoResourceFoundException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = No static resource login.
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", X-Content-Type-Options:"nosniff", X-XSS-Protection:"0", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Status
Expected :200
Actual :404
If the bean is commented out in the config test passes.
Windows 10, JDK 21, Springboot 3.2.3, Junit Jupiter
Been confused for 2 days now any assistance is much appreciated. |
Connect ssh to cisco switch with ansible |
|ssh|ansible|ssh-keys|cisco|cisco-ios| |
null |
If I use std::size and sizeof() for a char array , it gives the same value . So are those same for char array ? I think these 2 work differently for different types , but are they same for char ?
So are those same for char array ? I think these 2 work differently for different types , but are they same for char ? |
Is std::size and sizeof same for a char array? |
|c++|arrays|char| |
null |
I am working on a project in the Node.js environment that via dbus-native interfaces with Connman. What I need to do is create some code that allows it to connect to a secure wifi network. I went to implement the Agent and the RequestInput function and from another file I go to call the Connect(), but once it is called it goes the loop and won't connect. I pass the passphrase statically from the code. Has anyone done something similar before?
Agent implementation:
```
const dbus = require('dbus-native');
const systemBus = dbus.systemBus();
const passphrase = 'pass_ex';
const agent = {
Release: function() {
console.log('Agent released');
},
ReportError: function(path, error){
console.log('Agent error reported: ', path, error);
},
requestBrowser: function(path){
console.log('Agent requests browser:', path);
},
RequestInput: function(path, fields, callback){
console.log('Agent requests input:', path, fields);
let response = {};
console.log('fields[0][0]:', fields[0][0]);
console.log('Ingresso if...');
console.log(fields[0][0].toString() === 'Passphrase');
if(fields[0][0].toString() === 'Passphrase'){
console.log(fields[0]);
response["Passphrase"] = passphrase;
console.log(response);
callback(response);
}
else{
console.log('If scartato');
callback({});
}
//return response;
},
Cancel: function(){
console.log('Agent cancelled');
}
};
systemBus.exportInterface(agent, '/net/connman/Agent', {
name: 'net.connman.Agent',
methods: agent,
signals: {},
properties: {}
});
const managerService = systemBus.getService('net.connman');
managerService.getInterface('/', 'net.connman.Manager', (err, manager) => {
if(err){
console.log('Error getting manager interfce:', err);
return;
}
manager.RegisterAgent('/net/connman/Agent',
function(err){
if(err){
console.log('Error registering agent:', err);
}
else{
console.log('Agent registered');
}
});
});
```
Connect() call:
```
const dbus = require('dbus-native');
const systemBus = dbus.systemBus();
const wifiService =
systemBus.getService('net.connman');
async function wifiConnect(){
try{
const wifiProps = await new Promise((resolve, reject) => {
wifiService.getInterface('/net/connman/service/wifi_ex12345', 'net.connman.Service', (err, wifiProps) => {
if(err){
console.log('Error getting wifi service interface:',err);
reject(err);
return;
}
resolve(wifiProps);
});
});
const props = await new Promise((resolve, reject) => {
wifiProps.GetProperties((err, props) => {
if(err){
console.log('Error getting properties:', err);
reject(err);
return;
}
resolve(props);
});
});
const state = props[2][1][1][0].toString();
console.log(state);
if(state === 'idle'){
await new Promise((resolve, reject) => {
wifiProps.Connect(err => {
if(err){
console.log('Error connecting to wifi', err);
reject(err);
return;
}
resolve();
});
});
return 'Connected';
}
else{
throw new Error('Already connect');
}
}
catch(error){
throw error;
}
}
wifiConnect()
.then(result => console.log(result))
.catch(error => console.error(error));
```
|
i want to turn windows firewall on and off from java code so to do this need to execute cmd command with admin privilege to do this please any one help me
i tried this but it is not running as admin public void execute_cmd2() {
Process exec = Runtime.getRuntime().exec("cmd");
OutputStream outputStream = exec.getOutputStream();
InputStream inputStream = exec.getInputStream();
PrintStream printStream = new PrintStream(outputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
printStream.println("netsh advfirewall set allprofile state off");
//printStream.println("winget uninstall \"voidtools.Everything\"");
printStream.flush(); |
I'm relatively new to writing unit tests. I ran into this scenario while writing unit test cases in .NET 8,for azure functions.
Project 1 - ABC.Functions
Project 2 - ABC.Functions.Test
I have added a few nuget packages related to Azure functions in Project1. Should I be replicating these references in Project2 as well? Even if I wanna create mocks while Unit testing the SUT I still need the references to these nuget packages. Are there any design flaws in my test? Is that why I'm having to rely on the nuget package? Or is it completely normal to refer nuget package dependencies of SUT assembly in Test Project.
I haven't tried anything in particular as I wasn't pretty sure where the flaw was or if it is even flawed in the first place. |
Should I add the nupkg dependencies of the Assembly of the SUT to the Test Project as well? |
|unit-testing|testing|tdd|moq|microsoft-unit-testing| |
null |
You could use this regex:
```regex
(?:(?<=^tags::)|\G(?<!^))(\s*\w+)(?= )
```
This matches:
- `(?:(?<=^tags::)|\G(?<!^))` : **either**
- `(?<=^tags::)` : positive lookbehind for start-of-string followed by `tags::`; **or**
- `\G(?<!^)` : end of the previous match (but not at the start of the string)
- `(\s*\S+)` : zero or more of spaces followed by one or more non-space characters, captured in group 1
- `(?=\h)` : positive lookahead for horizontal whitespace
Replace this with `$1,`.
Regex demo on [regex101][1]
[1]: https://regex101.com/r/LxbNQc/1 |
Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding' |
|typescript|svelte|vercel|sveltekit|gun| |
null |
I'm developing an Android app with flutter and Dart, but everytime I try to run the app, or build It, It returns me the same erro:
```console
e: /home/ju-bei/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.8.22/636bf8b320e7627482771bbac9ed7246773c02bd/kotlin-stdlib-1.8.22.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.8.0, expected version is 1.6.0.
e: /home/ju-bei/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib/1.8.22/636bf8b320e7627482771bbac9ed7246773c02bd/kotlin-stdlib-1.8.22.jar!/META-INF/kotlin-stdlib-jdk8.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.8.0, expected version is 1.6.0.
e: /home/ju-bei/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlin/kotlin-stdlib-common/1.8.22/1a8e3601703ae14bb58757ea6b2d8e8e5935a586/kotlin-stdlib-common-1.8.22.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.8.0, expected version is 1.6.0.
```
I'm trying to solve this problem, but anything I try, don't help.
If os needed more information, I update the post here.
OS: Ubuntu Linux
Device: Android 28 API
I've changed the build.gradle, app/build.gradle and settings.gradle, but the erro continues |
The Binary Version Of its metadata is 1.8.0, expected Version is 1.6.0 build error |
|android|flutter|dart|gradle| |
null |
The only thing what was wrong is a direcory:
WRONG directory: https://oss.sonatype.org/content/repositories/snapshots/org/hibernate/orm/
CORRECT directory: https://oss.sonatype.org/content/repositories/snapshots
```
<repositories>
<repository>
<id>hibernate-snapshots</id>
<name>Hibernate snapshots</name>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
</repositories>
``` |
When I set `multiline` to `true`, on each new line, the content get pushed up, and there is a scroll that I can't disable.
[![enter image description here][1]][1]
In the attempt to fix it, I tried to set the height of the TextInput to the contentSize height that I get from `onContentSizeChange`, but there was a flicker on new lines.
[![enter image description here][2]][2]
the issue only happens on Android, `scrollEnabled` set to `false` seems to fix it in iOS
Do you have an idea how can I fix it?
PS: I don't want to set fixed `height` or `maxHeight`, the height should be flexible based on the content of the input
[1]: https://i.stack.imgur.com/t3HtS.gif
[2]: https://i.stack.imgur.com/9yDb1.gif |
I'm building a website using WordPress. I'm trying to set a video as the background, but there are some black areas. I can change the black areas by changing the color in the global settings, but I can't remove them. How can I remove these areas or add a video?"
I'm not familiar with this topic. Could you provide the CSS code you recommended? It could be a setting as well |
merge dataframe but do not sort by merge key |
|python|pandas| |
null |
I'm experimenting with GLFW (compiling with **g++ -o nxtBluePixel nxtBluePixel.cpp -lglfw -lGLEW -lGL** ) to simply draw a blue box and move it up/down/left/right. I want to output a message "out of bounds" when the box touches the edges of the visible area, which should logically be -1 or 1 (in those so-called normalized OpenGL coordinates, so I read). But the box keeps continuing to move in an "invisible" region outside (and is invisible) but no message is displayed until a while (at least 10 hits or so on a key outside the edge boundary ... ChatGPT 4 can't help me, it says:
*"Correct Boundary Check: If you want the "out of bounds" message to appear as soon as the point is about to leave the visible area, your original check without the large epsilon is logically correct. However, if the message appears too late or too early, it might be due to how the point's position is updated or rendered, not the boundary check itself."*
any ideas? I never use OpenGL, so I wanted to try... but this is typically the kind of very annoying problem I hate!
and here my code:
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <string>
#include <cctype>
GLint worldWidth = 400;
GLint worldHeight = 300;
// Starting position of the pixel
float currX = 0.0f;
float currY = 0.0f;
float stepSize = 1.0f / worldWidth;
float speed = 2.0f;
void updateWorld(char keyPressed, float speed){
switch (keyPressed) {
case 'W':
//up
currY += stepSize*speed;
break;
case 'A':
//left
currX -= stepSize*speed;
break;
case 'S':
//down
currY -= stepSize*speed;
break;
case 'D':
//right
currX += stepSize*speed;
break;
}
//using openGL 'normalized' coords i.e. between -1 and 1
if (currX >= 1.0 || currX <= -1.0 || currY >= 1.0 || currY <= -1.0){
printf("OUT OF BOUNDS !!!!");
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
char key_str = '0';
if (action == GLFW_PRESS || action == GLFW_REPEAT) {
switch (key) {
case GLFW_KEY_W:
key_str = 'W';
break;
case GLFW_KEY_A:
key_str = 'A';
break;
case GLFW_KEY_S:
key_str = 'S';
break;
case GLFW_KEY_D:
key_str = 'D';
break;
case GLFW_KEY_Q:
printf("Bye ...");
glfwSetWindowShouldClose(window, GL_TRUE);
break;
default:
printf("unknown key pressed \n");
break;
}
updateWorld(key_str, speed);
}
}
int main(void) {
GLFWwindow* window;
// Initialize the library
if (!glfwInit())
return -1;
//remove win frame
//glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
// Create a windowed mode window and its OpenGL context
window = glfwCreateWindow(worldWidth, worldHeight, "Move Pixel with Keyboard", NULL, NULL);
if (!window) {
glfwTerminate();
return -1;
}
// Make the window's context current
glfwMakeContextCurrent(window);
// Set the keyboard input callback
glfwSetKeyCallback(window, key_callback);
// Initialize GLEW
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK) {
std::cerr << "Failed to initialize GLEW" << std::endl;
return -1;
}
//glfwGetFramebufferSize(window, &worldWidth, &worldHeight);
// Define the viewport dimensions
glViewport(0, 0, worldWidth, worldHeight);
// Set point size
glPointSize(10.0f); // Increase if you want the "pixel" to be bigger
// Loop until the user closes the window
while (!glfwWindowShouldClose(window)) {
// Render here
glClear(GL_COLOR_BUFFER_BIT);
// Set the drawing color to blue
glColor3f(0.0f, 0.0f, 1.0f); // RGB: Blue
// Draw a point at the current position
glBegin(GL_POINTS);
glVertex2f(currX, currY); // Use the updated position
glEnd();
// Swap front and back buffers
glfwSwapBuffers(window);
// Poll for and process events
glfwPollEvents();
}
glfwTerminate();
return 0;
}
In the worst case i can debug step by step with `printf` ... but well it will take a long time and it won't necessarily allow me to understand from where this behavior stems because I see there is an "epsilon" but it changes with resolution so i don't have the formula, it would always be "trial and error" to determined the "epsilon" to use to add or subtract from the theoretical -1 or 1 boundaries.
|
I have a problem with "drop_na" function. I wanted to clean the dataset and erase the "NA" values, but when I entered the code, all datas are disseapperad. I do not understand why it happens. not:Im beginner level.
[You can see clearly what my codes are in this picture](https://i.stack.imgur.com/ORaUW.png)
library(tidyverse)
WDI_GNI<read_csv("C:/Users/sudes/Downloads/P_Data_Extract_From_World_Development_Indicators/a7b778c6-9827-4c45-91b7-8f497087ca17_Data.csv")WDI_GNI <- WDI_GNI %>% mutate(across(contains("[YR"),~na_if(.x, ".."))) %>% mutate(across(contains("[YR"), as.numeric)) WDI_GNI <- drop_na(WDI_GNI)
|
TROUBLING with the "DROP_NA" Function |
|r|rstudio| |
null |
i have being building a telegram bot with nodejs where people can send in a url of a tweet and if it contains a media of type video. it downloads it and sends it to the user. Thats the purpose, which i already completed.
The problem i have is with setting a paywall on this bot account so that after 2 or 3 request, the user interacting with the bot have to make a payment to continue.
so i used the [sendInvoice](https://core.telegram.org/bots/api#sendinvoice) method.
FYI, i'm not using any external librarys, i'm directly interacting with the telegram api endpoints.
I'm using stripe for payments in test mode (my acc is unverified if that helps). the problem i have is as you can see in this picture:
[This is whats happening/showing after some time](https://i.stack.imgur.com/Vm69E.png)
After i send the invoice, then the user clicks the pay button and adds all the necessary card details then after hitting the pay. it keeps buffering and then time outs.
I also tried the [createInvoiceLink](https://core.telegram.org/bots/api#createinvoicelink) method and the same thing happened.
Ofcourse its some mistake in my solution, but i dont know where that is. May be i have to use a webhook or something to catch the checkout initiation/completion. but how can i let the Telegram api know about my payment webhook path (assuming something like that exists).
The only one i found is the method [setWebhook](https://core.telegram.org/bots/api#setwebhook) which is an alternative approach for polling. And that is what i am doing locally with ngrok.
A Part of my code, this is an abstract version of the functionality:
```
const app = express();
const port = 3000;
const botToken = process.env.TELEGRAM_BOT_TOKEN;
app.use(bodyParser.json());
// Webhook endpoint that receives incoming messages (exposed via ngrok)
app.post(`/bot${botToken}`, async (req, res) => {
const { message } = req.body;
console.log({ message });
if (message && message.text) {
const chatId = message.chat.id;
const messageText = message.text;
// after successfull 3 responses from the bot, send an invoice
const invoiceRes = await sendInvoice(
chatId,
"Premium Subscription",
"Unlock premium content with a subscription.",
"premium_subscription",
process.env.PROVIDER_TOKEN,
"subscription",
"USD",
[{ label: "Subscription", amount: 1000 }],
);
console.log(JSON.stringify(invoiceRes, null, 2));
}
res.status(200).end();
});
async function sendInvoice(
chatId,
title,
description,
payload,
providerToken,
startParameter,
currency,
prices,
) {
const apiUrl = `https://api.telegram.org/bot${botToken}/sendInvoice`;
const invoice = {
chat_id: chatId,
title: title,
description: description,
payload: payload,
provider_token: providerToken,
start_parameter: startParameter,
currency: currency,
prices: prices,
};
try {
const response = await fetch(apiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(invoice),
});
const data = await response.json();
// console.log(data);
return data;
} catch (error) {
console.error("There was a problem sending the invoice:", error);
return error.message;
}
}
```
I googled a lot to find some answers, there isnt anything specified in the [payment section of the docs](https://core.telegram.org/bots/payments) either rather than getting the provider token (not anything specifically if i have to do on the stripe account dashboard like adding a webhook endpoint, even if that was the case how would telegram know that is the webhook it should communicate too)
I have been mentioning webhook a lot, because in my mind i am assuming that is my missing solution. if it isnt i'm sorry for doing so. I don't have much experience with stripe or building a telegram bot.
I hope i could get some help with this problem. even a small guidance will be enough if you are busy. just something i can go with that's all i ask. |
I'm currently working on integrating Microsoft Graph APIs into my Java application to retrieve license details for users in my Microsoft 365 tenant. I referred to the official Microsoft documentation [here](https://learn.microsoft.com/en-us/graph/api/user-list-licensedetails?view=graph-rest-1.0&tabs=java) to understand the usage of the Microsoft Graph Java SDK for this purpose. However, despite following the provided guidance, I'm encountering difficulties in implementing the solution within my Java codebase.
**Context:**
- I'm utilizing the Microsoft Graph Java SDK to interact with Microsoft 365 APIs.
- Specifically, I'm referring to the documentation for listing license details for a user [here](https://learn.microsoft.com/en-us/graph/api/user-list-licensedetails?view=graph-rest-1.0&tabs=java).
- My authentication setup and GraphServiceClient instantiation are already in place, following the documentation.
**Issue:** The code snippet provided in the documentation is as follows:
```java
// Code snippets are only available for the latest version. Current version is 6.x
GraphServiceClient graphClient = new GraphServiceClient(requestAdapter);
LicenseDetailsCollectionResponse result = graphClient.users().byUserId("{user-id}").licenseDetails().get();
```
I've attempted to integrate this code into my Java application. While I can successfully query the Microsoft Graph API using tools like Postman, I'm unable to replicate the functionality within my Java codebase.
**Expectation:** I'm seeking assistance in understanding and resolving the following:
1. How can I properly configure the `requestAdapter` required for initializing the `GraphServiceClient` instance in Java?
2. Are there any additional configurations or dependencies required to make the Microsoft Graph Java SDK work seamlessly within a Java application?
I appreciate any insights or guidance on how to resolve this issue and successfully retrieve license details for users using the Microsoft Graph Java SDK within my Java application. |
I had similar problems with webpack 5 and http-proxy-middleware. It was due to webpack DevServer using the `/ws` path, but my proxy and socket server were also using `/ws`.
Before: proxy and socket server using `/ws`.
```js
const setupProxy = [
createProxyMiddleware('/api', options),
createProxyMiddleware('/ws', { ...options, ws: true }),
];
module.exports = (app) => app.use(setupProxy);
```
After: change to use `/wss`, or anything else.
```js
const setupProxy = [
createProxyMiddleware('/api', options),
createProxyMiddleware('/wss', { ...options, ws: true }),
];
module.exports = (app) => app.use(setupProxy);
```
|
Cpp function overloading |
|c++|function|overloading| |
null |
|youtube-api| |
My app is to open one of the application with some parameters in windows.
i was sucessfull by doing that in flask and provided .exe format and it works proper.
now instead of giving .exe i want place the project in server and give the url.
the problem here is if i execute the subprocess.popon it tries to execute in server but now that i want to execute in client side.
I checked with ActiveXObject but got to know that it is just for IE.
now question is what is the best approach to do it?
by node js i thought but that is also server side which same as python.
|
On click of a button open an application in client side |
|javascript|python| |
|javascript|google-cloud-platform| |
|sql|sql-server|t-sql|sql-server-2019| |
|json|nested-json| |
|swift|authentication|swiftui| |
Need a batch script to rename folders that look like this \[MSXEP001\] Dom & Roland - Can't Punish Me EP \[2000\] to looking like MSXEP001-Dom\_&_Roland_-\_Can't_Punish_Me_EP-FLAC-2000.
Need to remove the square brackets, add hypen between cat# and artis(s), add -FLAC- before the year and use underscore. Folders all share the same 'naming formula' and are from [MSXEP001] to [MSXEP043] so would be a bulk renaming.
Any geniuses out there that have the solution to this or can point me into the right direction?
Been decades since I used batch coding so all help is appreciated |
Batch script to rename [MSXEP001] Dom & Roland - Can't Punish Me EP [2000] to MSXEP001-Dom_&_Roland_-_Can't_Punish_Me_EP-FLAC-2000 |
|batch-rename| |
null |
|javascript|html|graphql| |
{"OriginalQuestionIds":[16602175],"Voters":[{"Id":817643,"DisplayName":"StoryTeller - Unslander Monica","BindingReason":{"GoldTagBadge":"c++"}}]} |
Need a batch script to rename folders that look like this [MSXEP001] Dom & Roland - Can't Punish Me EP [2000] to looking like MSXEP001-Dom_&_Roland_-_Can't_Punish_Me_EP-FLAC-2000.
Need to remove the square brackets, add hypen between cat# and artis(s), add -FLAC- before the year and use underscore. Folders all share the same 'naming formula' and are from [MSXEP001] to [MSXEP043] so would be a bulk renaming.
Any geniuses out there that have the solution to this or can point me into the right direction?
Been decades since I used batch coding so all help is appreciated |
How do I test the ohlc series, I cannot see any demo in lightningchart official site.
I tried below code
candle[id] = chart[id].addOHLCSeries().setMouseInteractions(false);
Also previously when I checked ohlcseries of lighning chart ,, candle automatically converting to different candles when i zoom in , how to disable that.I want to preserve the candles of my data.. maybe can reduce width of candles reduce when i zoom in.. but not automatically create. |
Spring security causing 404 with message "No static resource login" |
|spring-boot|spring-mvc|spring-security| |
how to correctly get the value of an element by its index from TypedArray? |
I do know that conditional operators have right associativity, but can't understand how the flow of `condition1` , `condition2` , `expression1` , `expression2` , `expression3` are all happening one after another. Or how the evaluation and flows are changing when we assume that associativity is left to right.
(condition1) ? (expression1) : ((condition2) ? (expression2) : (expression3)) ;
I asked Gemini and Copilot for an explanation, and they keep repeating the same thing: that `condition1` is the rightmost expression, but couldn't understand how. Or how and why `condition1` is the first one to get evaluated, irrespective of right or left associativity. |
Explanation of the associativity of nested conditional operators |
|conditional-operator|operator-precedence| |
null |
I have a opencart 2.3 store and I have downloaded a extension that shows all products on one page, it creates a category called All and displays all products in that category.
It's working all ok but I would like to have the product filter displayed in the left column so it's the same as the other categories.
For example the category here https://www.beechwoodsolutions.co.uk/sites/simply-heavenly-foods/index.php?route=product/category&path=271 has the product filter in the left column.
On the all products category page here https://www.beechwoodsolutions.co.uk/sites/simply-heavenly-foods/index.php?route=product/category&path=-1 I would like to have the product filter displayed.
The extension I downloaded is https://www.opencart.com/index.php?route=marketplace/extension/info&extension_id=29713.
I have contacted the developer but don't think they are active anymore so was seeing if anyone was able to help please. |
|mysql| |
Your algorithm essentially performs a breadth-first search, where you extend all partial matches you found in a previous iteration by one character and keep those that still match. So for a worst case scenario we would want to have as many partial matches as possible for as many iterations as possible.
One such worst case input could be a haystack with an even size, with times the letter "a", and a needle with =/2 characters that are all "a", except the last letter, which would be a "b". So for instance, if is 10:
haystack = "aaaaaaaaaa"
needle = "aaaab"
The `while 1:` loop will make /2−2 iterations (the "minus-2" is the consequence of already having matches with 2 letters before that loop starts).
The inner `for first, start, check in new` loop will make /2+1 iterations
Taking that together, the inner `if` statement will be executed (/2-2)(/2+1) times, i.e. ²/4−/2−2 times, which is O(²), and is therefore the time complexity of your algorithm.
> people were saying that O(n * m) solutions weren't passing at all
You have given proof that their claim is false. Here it is important to realise that time complexity says absolutely *nothing* about how much time an algorithm will need to process *actual* (finite!) inputs. Time complexity is about *asymptotic* behaviour. |
wordpress delete unwanted location |
|wordpress|web|wordpress-theming| |
null |
I'm building a website using WordPress. I'm trying to set a video as the background, but there are some black areas. I can change the black areas by changing the color in the global settings, but I can't remove them. How can I remove these areas or add a video?"
[enter image description here][1]
I'm not familiar with this topic. Could you provide the CSS code you recommended? It could be a setting as well
[1]: https://i.stack.imgur.com/CUOVl.png |
I have a use case:
I have a static website without server side code and I want to send an email whenever someone submits a form on website.
To send an email i am using flask rest api. I have deployed the api seperately and then i am calling the api from the website using javascript.
Now I am wondering how can i protect my api?
I am new to authentication and authorization.
The website is open to all which means its a non user website and any one can submit their queries.
How can i secure my API And call the api using javascript with the required credentials or token. |
Authenticate Flask rest API |
|javascript|authentication|flask|token| |
{"Voters":[{"Id":4621513,"DisplayName":"mkrieger1"},{"Id":243925,"DisplayName":"Tony"},{"Id":3700524,"DisplayName":"Mohsen_Fatemi"}]} |
|c#|arrays|.net|object-pooling| |
I am creating a radar chart via echarts4r package in a shiny app. On small screens, the labels of the radar chart cut off. How do I make sure that the labels are completely visible on any screen? I understand that any solution for this would mean that the radar chart size decreases to accommodate the labels.
### Example code:
library(shiny)
library(echarts4r)
ui <- fluidPage(
tagList(
echarts4rOutput("radar_chart")
)
)
server <- function(input, output, session) {
output$radar_chart <- renderEcharts4r({
df <- data.frame(
x = c("Loooong", "Verrrrry long", "Extreeeeeeeeemely long", "Short", "Min"),
y = runif(5, 1, 5),
z = runif(5, 3, 7)
)
df |>
e_charts(x) |>
e_radar(y, max = 7) |>
e_radar(z) |>
e_tooltip(trigger = "item") |>
e_radar_opts(
axisName = list(
color = "black",
fontFamily = "Libre Franklin",
fontSize = 18
))
})
}
shinyApp(ui, server)
### `bs4Dash` example (radar chart labels are visible on any screen size)
In this example of bs4Dash, when the radar chart is wrapped in `box`, the size is adjusted:
library(shiny)
library(bs4Dash)
library(echarts4r)
library(data.table)
library(dplyr)
df = data.frame(name=c('A','B','C'),
color = c('blue','white','green'),
atr1 = c(34,45,32),
atr2 = c(56,32,21),
atr3 = c(23,45,21))
# UI
ui = dashboardPage(
title = "Example radar plot",
header = dashboardHeader(
title = dashboardBrand(
title = "radarchart test",
color = "primary"
)),
sidebar = dashboardSidebar(
selectizeInput('sel1','name',choices = NULL),
selectizeInput('sel2','color',choices = NULL)
),
body = dashboardBody(
box(echarts4rOutput("radar"))
)
)
# SERVER
server = function(input, output, session) {
#Filter update
updateSelectizeInput(session, 'sel1', choices = sort(unique(df$name)),selected = "A" ,server = TRUE)
observeEvent(input$sel1, {
updateSelectInput(session, inputId = "sel2", label="color",
choices = df[df$name==input$sel1,]$color)
})
#Table creation to use in radarplot
dataradar = reactive({
dataradar = df[df$name==input$sel1 & df$color == input$sel2, c('atr1','atr2','atr3')]
dataradar = data.table(dataradar)
dataradar = melt(dataradar, measure.vars = c(names(dataradar)))
})
#radar plot
output$radar <- renderEcharts4r({
if(!nrow(dataradar()))
return()
dataradar() %>%
e_charts(variable) %>%
e_radar(value) |>
e_radar_opts(
axisName = list(
color = "black",
fontFamily = "Libre Franklin",
fontSize = 18
))
})
}
shinyApp(ui,server)
I tried using `bslib::card` (in place of `box` in the original example code), but that does not adjust the size of radar chart on small screen size as `box` did. Any ideas how can I mimic the same behaviour? |
I am trying to use a drop down menu from a navbar.
I copied the exact code snippets provided at getbootstrap dot com, and bingo, not working. Why?
Are the links to import libraries for popper in the right places?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap demo</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown link
</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><a class="dropdown-item" href="#">Something else here</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<h1>Drop down menu please</h1>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>
</body>
</html> |
Bootstrap v5.3 navbar drop-downs not working. Why? |
|bootstrap-5| |
I'm going through [this](https://www.youtube.com/watch?v=O42LUmJZPx0) tutorial of how to use arrow instead of regular dplyr. Second and subsequent times I run queries on this dataset it's very fast, but the first one is incredibly slow (times below).
### Minimal Reproducible Example
Here's an MRE of what I'm doing. This first bit is to obtain the ~70gb parquet dataset (takes ~6 hours, depending on internet connection).
```r
library(tidyverse)
library(arrow)
# copy_files(
# from = s3_bucket("ursa-labs-taxi-data-v2"),
# to = "~/Datasets/nyc-taxi"
# )
```
then, in preparation:
```r
nyc_taxi <- open_dataset("~/Datasets/nyc-taxi")
# small file to join to later
nyc_taxi_zones <- read.csv(url("https://raw.githubusercontent.com/djnavarro/arrow-user2022/main/data/taxi_zone_lookup.csv")) %>%
janitor::clean_names()
airport_zones <- nyc_taxi_zones %>%
filter(str_detect(zone, "Airport")) %>%
pull(location_id)
# [1] 1 132 138
# Alter schema (otherwise joining int32 and int64 cols won't work)
nyc_taxi_zones2 <- nyc_taxi_zones %>%
transmute(
dropoff_location_id = location_id,
dropoff_borough = borough,
dropoff_zone = zone
) %>%
as_arrow_table(
schema = schema(
dropoff_location_id = int64(),
dropoff_borough = utf8(),
dropoff_zone = utf8()
)
)
```
and finally, the actual operation:
```r
start_time <- Sys.time()
nyc_taxi %>%
filter(
pickup_location_id %in% airport_zones
) %>%
select(
matches("datetime"),
matches("location_id")
) %>%
left_join(
nyc_taxi_zones2
) %>%
count(dropoff_zone) %>%
arrange(desc(n)) %>%
collect()
end_time <- Sys.time()
end_time - start_time
```
- First time running this on a fresh ec2: 17.7 minutes!
- Second time running it in the same R session, 11 seconds!
- Note that after closing and reopening RStudio, it's still 11 seconds.
### What I've tried so far
- Thinking the bottleneck might be an I/O constraint, I switched to an IO optimized ec2, upgraded SSD and a few other things. They didn't make any substantial difference.
- [This](https://stackoverflow.com/a/66340044/5783745) possibly related question/answer looks like some promising leads (it's in python, but perhaps the root cause (not specifying partitioning) seems like a possible explanation for this problem. |
Aliases don't take effect when I use Vim to execute external commands, for example:
:! ll
I want it to support aliases like normal shells do. |
Alias does not take effect when I use Vim to execute external commands |
One counter example to your solution is:
```
[8, 7, 5, 4, 4, 1]
```
Adding as you have done would give the subsets:
```
[8, 4, 4], [7, 5, 1]: difference of sums = 3
```
while the optimal solution is:
```
[8, 5, 4], [7, 4, 1]: difference of sums = 1
```
Thus, to solve this problem, you need to brute force generate all combinations of (n choose floor(n/2)) and find the one with the smallest difference. Here is a sample code:
```python
comb = []
def getcomb(l, ind, k):
if len(comb) == k:
return [comb[:]]
if ind == len(l):
return []
ret = getcomb(l, ind+1, k)
comb.append(l[ind])
ret += getcomb(l, ind+1, k)
comb.pop()
return ret
def get_best_split(l):
lsm = sum(l)
best = lsm
for i in getcomb(l, 0, len(l)//2):
sm = sum(i)
best = min(best, abs(sm - (lsm - sm)))
return best
print(get_best_split([8, 7, 5, 4, 4, 1])) # outputs 1
```
**EDIT:**
If you don't care about the subsets themselves, then you can just generate all possible sums:
```python
def getcomb(l, ind, k, val):
if k == 0:
return [val]
if ind == len(l):
return []
return getcomb(l, ind+1, k, val) + getcomb(l, ind+1, k-1, val + l[ind])
def get_best_split(l):
l = sorted(l, reverse=True)
best = 1000000
for i in getcomb(l, 0, len(l)//2, 0):
best = min(best, abs(i - (sum(l) - i)))
return best
```
|
I am struggling with gtsummary.
Essentially I am trying to make a table with 2 different variables, one is organism one is resistance markers.
Currently both of these variables are character variables. When I made them factor variables it made the table even worse.
I am only trying to include certain organisms which I have already assigned to a vector. As my graph currently looks it is including the correct organisms.
My problem is that there is a column which is labelled ****. This column is essentially counting the organisms without any resistance markers. Those cells in the spreadsheet are just empty.
My questions:
1. Is it possible to delete the column with ****, i think I can show the rest of the data ok without that column
2. Could i rename the column to Nil detected? I have tried to use (modify_header(**** = "**Nil detected**"). But this didnt work. I tried replacing the one entitled CPE in case it was an issue with it being special characters but that didnt help.
```
GNRs_resistance %>%
filter(Organism %in% gramnegativerods) %>%
tbl_summary(include= c(Organism, Resistance.markers),
by = Resistance.markers,
statistic = Organism ~ "{n} ({p}%)") %>%
add_overall() %>%
modify_header(all_stat_cols() ~ "**{level}**<br>n = {n}")
```
[enter image description here]
(https://i.stack.imgur.com/dfbzr.png) |
Why don't you just use await?
try{
let a = await callbackA();
let b = await callbackB(a);
let c = await callbackC(b);
} catch(err){} |
I have a maria-db database docker-compose.yml:
```
version: '3.8'
services:
mariadb:
image: mariadb:latest
container_name: mariadb
restart: always
environment:
MYSQL_ROOT_PASSWORD: admin
MYSQL_DATABASE: "wordpress3,wordpress4"
MYSQL_USER: mohsin
MYSQL_PASSWORD: 12345678
volumes:
- mariadb_data:/var/lib/mysql
networks:
- wordpress_network
networks:
wordpress_network:
external: true
name: wordpress_network
volumes:
mariadb_data:
```
I am running two wordpress docker-compose files (for testing purposes). I want to connect both of them to the mariadb docker-compose. Both files have similar config:
```
version: '3.8'
services:
wordpress:
image: wordpress:latest
container_name: wordpress3
restart: always
environment:
WORDPRESS_DB_HOST: mariadb
WORDPRESS_DB_USER: root
WORDPRESS_DB_PASSWORD: admin
WORDPRESS_DB_NAME: wordpress3
ports:
- "8083:80"
depends_on:
- mariadb
networks:
- wordpress_network
mariadb:
extends:
file: ../mariadb/docker-compose.yml
service: mariadb
networks:
wordpress_network:
name: wordpress_network
external: true
```
When I run the first wordpress docker-compose, it automatically runs mariadb and connects to it. At the same time, the other instance throws an error saying `mariadb already in use`. **I want it to recognize that mariadb is already running, and connect to the shared instance automatically?**
*Two instances access the same db service type of scenario is required (condition: auto runs db service if down)* |
```c#
[QueryProperty("Filename", "Filename_")]
public partial class EditViewModel : ObservableObject
{
[ObservableProperty]
string filename;
partial void OnFilenameChanged(string value)
{
ReadFile();
}
}
```
I think that it is the right way to solve this. there is no any issu |
null |
Try forcing admin access for selected command:
Function Check-RunAsAdministrator()
{
#Get current user context
$CurrentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
#Check user is running the script is member of Administrator Group
if($CurrentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator))
{
Write-host "Script is running with Administrator privileges!"
}
else
{
#Create a new Elevated process to Start PowerShell
$ElevatedProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter
$ElevatedProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
#Set the Process to elevated
$ElevatedProcess.Verb = "runas"
#Start the new elevated process
$process = [System.Diagnostics.Process]::Start($ElevatedProcess)
$process.WaitForExit()
#Exit from the current, unelevated, process
Exit
}
}
#Check Script is running with Elevated Privileges
$process = Check-RunAsAdministrator
Write-Host "Hi, I am admin"
#Your other commands to open a txt, etc
Or try disabling UAC on your VM, maybe it interferes with unintended operations in your tasks when using "AzDevOps" account.
$RegistryUAC="HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
New-ItemProperty -Path $RegistryUAC -Name "EnableLUA" -Value 0 -PropertyType "DWord" -Force |
$this->eventDispatcher->dispatch(new OrderSentEvent($order, $context), 'name.goes.here');
…did the trick. No event subscriber could be found, because if you don't provide one, the full class name will be used. The Flow Builder apparently uses the custom one. |
I want to do marquee animation in Tailwind and next.js and some of it I have done. The only issue I am having is that it is not showing one after the other with the first. The second time it will show after some time.
**I want it to be like this:** [](https://i.stack.imgur.com/5AKUJ.png) but it is showing like this [](https://i.stack.imgur.com/x48lE.png).
**Here is the code of the tailwind CSS:**
```
.animate-marquee {
animation: marquee 10s linear infinite;
float: left;
}
```
**Here is the component code:**
```
import { useRouter } from "next/router";
import pathChecking from "../../utils/pathChecking";
import Image from "next/image";
const testimonial_data = [
{
desc: "Inform, inspire, connect, and collaborate for meaningful action.",
id: "0General Partner at Entrepreneur",
},
{
desc: "Addressing the world’s biggest environmental and social challenges.",
id: "1General Partner at Entrepreneur",
},
{
desc: "Fun, interactive, and immersive technology for real-world positive outcomes. ",
id: "2General Partner at Entrepreneur",
},
];
const HeroSliderComponent = () => {
const route = useRouter();
return (
<>
<div className=" flex animate-marquee space-x-8 w-10000">
{testimonial_data.map((item, index) => {
const { id, img, title, desc, name } = item;
return (
<div className="text-white" key={id}>
<div
className={`relative rounded-2.5xl border border-jacarta-100 bg-white p-12 transition-shadow hover:shadow-xl dark:border-jacarta-700 dark:bg-jacarta-700 `}
>
<p className="block font-display text-xl font-medium group-hover:text-accent dark:text-white text-center">
{desc}
</p>
</div>
</div>
);
})}
</div>
</>
);
};
export default HeroSliderComponent;
```
Infinite marquee with break or delays. |
null |
What if I disable "high performance order storage" in WooCommerce with 500+ daily orders and 5k+ daily traffic? What will be the side effects on the website?
There are some Plugins I am using and it's showing error that these plugins are not supporting HPOS and making issues in the website like rejecting orders and some other UX issues.
What could be the effects of disabling HPOS or any other solution? |
What if I disable "high performance order storage" in WooCommerce? |
|wordpress|woocommerce|orders|woocommerce-theming| |
{"OriginalQuestionIds":[164194],"Voters":[{"Id":584518,"DisplayName":"Lundin","BindingReason":{"GoldTagBadge":"c"}}]} |
I'm trying to set specific column totals in DataFrame dff to certain predetermined values. Currently, I have a DataFrame dff constructed by performing various operations on multiple DataFrames (df, df2, df3, and df1) using multiplication and addition. After calculating the sum of rows and columns, I want to ensure that the column totals of dff are set to specific values, namely 6000, 7000, 8000, and 9000.
```
data = np.random.randint(100, 1000, size=(9, 4))
df = pd.DataFrame(data, columns=['Q1', 'Q2', 'Q3', 'Q4'], index = ['A','B','C','D','E','F','G','H','I'])
# Repeat the above for df1, df2, and df3
# Define weights
weight_df = 0.1
weight_df2 = 0.2
weight_df3 = 0.3
weight_df1 = 0.4
# Calculate weighted sum
dff = df.mul(weight_df).add(df2.mul(weight_df2)).add(df3.mul(weight_df3)).add(df1.mul(weight_df1))
# Calculate sum of rows
dff['row_totals'] = dff.sum(axis=1)
# Calculate sum of columns
column_totals = dff.sum(axis=0)
new_rows = pd.DataFrame({'column_totals': column_totals}).T
dff = dff.append(new_rows)
```
How can I ensure that the column totals of DataFrame dff are set to specific values, such as 6000, 7000, 8000, and 9000, after performing the described operations on multiple DataFrames?
```
# Adjust column_totals to match desired values
desired_column_totals = [616.9, 585.5, 682.4, 456.8]
dff_adjusted = dff.copy()
for col, val in zip(dff_adjusted.columns, desired_column_totals):
dff_adjusted[col] += val - column_totals[col]
```
I've attempted to achieve this by adjusting the values in the column to match the desired total value. The code calculates the difference between the desired total value val and the current total value of the column column_totals[col], and then adds this difference to all the elements in the column. However this is not working. Is there a better way to do it using some inbuilt library. Any insights or alternative approaches would be appreciated. |
To get some code executed just once in this function, you need to tag the order like:
```php
add_action( 'woocommerce_order_status_changed', 'bacs_payment_complete', 10, 4 );
function bacs_payment_complete( $order_id, $old_status, $new_status, $order ) {
// 1. For Bank wire and cheque payments
if ( $order->get_payment_method() === 'bacs'
&& in_array( $new_status, wc_get_is_paid_statuses() )
&& $order->get_meta('confirmed_paid') !== 'yes' )
{
$order->update_meta_data('confirmed_paid', 'yes'); // Tag the order
$order->save(); // Save to database
// Here the code to be executed only once
}
}
```
Code goes in functions.php file of your child theme (or in a plugin). It should work. |
To remove product SKU from email notifications, simply use the following:
```php
add_filter( 'woocommerce_email_order_items_args', 'customize_email_order_items_args', 20 );
function customize_email_order_items_args( $items_args ) {
$items_args['show_sku'] = false;
return $items_args;
}
```
Code goes in functions.php file of your child theme (or in a plugin). Tested and works. |
So when checking for duplicates in an array (that's what I think the algorithm is for; correct me if I'm wrong), you want to check each element against each other element once. Let's have a 2D array of all possible pairs of elements you can check.
For an array with 4 elements, the 2D array would look like this:
```
[(0,0),(0,1),(0,2),(0,3),
(1,0),(1,1),(1,2),(1,3),
(2,0),(2,1),(2,2),(2,3),
(3,0),(3,1),(3,2),(3,3)]
```
We can traverse this 2D array like you said.
```
double[] array = new double[] {1,2,3,4}
for (int i=0;i<array.length;i++){
for (int j=0;j<array.length;j++){
if(array[i]==array[j]){
break;
}
}
}
```
However, this checks both (1,0) and (0,1) which is redundant. All we have to do is check the elements above and including the diagonal from the top left to the bottom right. This makes it so that we have to set j to i+1. |
The simplest solution to find total RAM in a device is to use `NSProcessInfo`:
**Objective C:**
[NSProcessInfo processInfo].physicalMemory
**Swift 3**:
NSProcessInfo.processInfo().physicalMemory
**Swift 5**:
ProcessInfo.processInfo.physicalMemory
Note: `physicalMemory` gives us the information at bytes and can be less than the actual devices memory. To calculate GB, divide by **`1024³`** *(1073741824)* and round up to the closes integer:
Int(round(Double(physicalMemory) / (1024.0 * 1024.0 * 1024.0)))
As documented [here][1].
[1]: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSProcessInfo_Class/Reference/Reference.html#//apple_ref/occ/instm/NSProcessInfo/physicalMemory |