text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Android application, listening to streaming radio. No internet or mobile data bug http://pastebin.com/G4UrTT7Z
What can I do to check for a working internet connection?
Or how do I check if connection is lost?
Can someone help me with this ?
I suppose this is a IOException. I am not sure. When watching logcat and console I don't see any exceptions or forcecloses.
My source code is posted on pastebin.
A: One way is to read a well known site content with URL connection. If you can read it, then it means you have an Internet connection.
Other is to connect to your radio station site: this has double requirement: you have Internet connection AND the radio station site is up.
Maybe both of them will block you, if you read too often!
There is android buggy API to read the network state and suck, but if you connect to WIFI , then you will have the Connected state from API even if your WAN cable pulled out...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15231806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to add more than one image to application using Spring Boot? I have an application which allows to add an image to a product but I don't know how to refactor it that there will be possibility to add many images to one product.
This is model:
@Entity
public class ProductEntity {
@Lob
private byte[] image;
public String getImageBase64() {
return Base64.getEncoder().encodeToString(this.image);
}
This is Controller:
@PostMapping("/add")
@Secured(ROLE_ADMIN)
public String saveProduct(ProductDTO productDTO, @RequestParam("image2") MultipartFile[] files) {
try {
if (files != null && files.length > 0) {
InputStream is = files[0].getInputStream();
byte[] buffer = new byte[is.available()];
is.read(buffer);
productDTO.setImage(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
productService.addProduct(productDTO);
return "redirect:/product/list";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65254415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: FlatList inside FlatList scrolling problem I want to put a FlatList inside another one, but the child flatlist not scrolling.
I tried to convert the child FlatList to ScrollView, put the props scrollEnabled to false to the parent FlatList and both not work.
Here is a code example of what I want to do: https://snack.expo.io/HJ6d97gNH
I expect to scroll inside both flatlist, not only one.
A: use nestedScrollEnabled in inner Flatlist for enabling the scrolling activity
A: You can use the nestedScrollEnabled prop but I would recommend using a <SectionList> since this is somehow buggy!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57477766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to define static folder path in nodejs multer image upload I am setting static path but getting error : "Error: ENOENT: no such file or directory, open 'C:\dashboard new - Copy\uploads\2019-11-28T08:11:09.164Z1564660431900.jpg'"
const storage = multer.diskStorage({ destination: function(req, file, cb) { let dest = path.join(__dirname, '../../uploads'); cb(null, dest); }, filename: function(req, file, cb) { cb(null, new Date().toISOString() + file.originalname); }});
const fileFilter = (req, file, cb) => { if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') { cb(null, true); } else { cb(null, false); }};
const upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 * 5 }, fileFilter: fileFilter});
router.post("/", upload.single('productImage'), async (req, res, next) => {
try {
cosole.log('hi');
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price,
productImage: req.file.path
});
const saveImage = await product.save();
console.log(saveImage)
res.json(saveImage);
} catch (error) {
console.log(error);
res.json(error);
}
});
How to do this?
A: I think you need to provide the destination folder as a key and value, something like this(below)
var upload = multer({ dest: 'uploads/' })
You can check out the full multer documentations here
https://expressjs.com/en/resources/middleware/multer.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59084459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: getting MismatchSenderId with firebase serverside I am trying to send the notification using a php script that is stored in my server and I am getting the MismatchSenderId.
$to="device_id";
$title="MYAPP Push";
$message=" MYAPP Push Notification Message";
sendPush($to,$title,$message);
function sendPush($to,$title,$message){
// API access key from Google API's Console
// replace API
define( "API_ACCESS_KEY", "server_key_provided_by_firebase");
$registrationIds = array($to);
$msg = array(
'message' => $message,
'title' => $title,
'vibrate' => 1,
'sound' => 1
// you can also add images, additionalData
);
$fields = array(
'registration_ids' => $registrationIds,
'data' => $msg
);
$headers = array(
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );
echo $result;
}
Here the error I get when I run the php script:
{"multicast_id":7804476702639319453,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}
I've checked every single question here in stackoverflow and could not solve it.
I am using firebase (spark plan) and developing the app with Phonegap. I believe that has nothing to do with the app
Any Ideas???
A: Copy your google-service.json file to root folder (that contains www, config.xml etc).
Step 1:
Login to your firebase console.
Step 2:
On Project Overview Settings, Copy the Cloud Messaging ServerKey
My key ex:
`AAAAjXzVMKY:APA91bED4d53RX.....bla bla
Step 3:
Replace the key
define( "API_ACCESS_KEY", "My key");
Finally Test the app :D
I sent push notification using node succesfully.
var gcm = require('node-gcm');
// Replace these with your own values.
var apiKey = "MY_SERVER_KEY";
var deviceID = "MY_DEVICE_ID";
var service = new gcm.Sender(apiKey);
var message = new gcm.Message();
message.addData('title', 'Hi');
message.addData('body', 'BLA BLA BLA BLA');
message.addData('actions', [
{ "icon": "accept", "title": "Accept", "callback": "app.accept"},
{ "icon": "reject", "title": "Reject", "callback": "app.reject"},
]);
service.send(message, { registrationTokens: [ deviceID ] }, function (err, response) {
if(err) console.error(err);
else console.log(response);
});
A: The documentation for this error states:
A registration token is tied to a certain group of senders. When a
client app registers for FCM, it must specify which senders are
allowed to send messages. You should use one of those sender IDs when
sending messages to the client app. If you switch to a different
sender, the existing registration tokens won't work.
You should double check that you are using the Server Key from the same project used to generate the google-services.json file the app was built with. The project_number at the top of the google-services.json file must be the same as the Sender ID shown in the project settings Cloud Messaging tab of the Firebase Console.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47431166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problems with TEXTAREA line breaks in ASP.NET MVC 2 I really don't think this has anything to do with ASP.NET MVC 2 itself, but I mention that as it is the environment I am working in and at least one aspect of my problem is connected to the way MVC 2 behaves. My problem is this:
I have a TEXTAREA element on a form that allows multiple lines of data to be entered. When the form is posted back to the server (using IE8), I can see that the data is formatted as "A\n\rB\n\rC\n\rD". I then save this data to a database table where it appears exactly the same way. However, when I come back to the page at a later time, loading the data from the database and setting it as the value of the TEXTAREA element, it displays the "\n\r" as literal characters instead of line breaks!
As a side note, with ASP.NET MVC, if I follow the standard if (!ModelState.IsValid) return View(viewModel); approach, the TEXTAREA displays fine when re-rendering the same form due to a validation error. This tells me that the problem must be related to persisting and retrieving the data to/from the (SQL Server) database.
I have the same display problem in FireFox and Chrome with the notable difference being that the data is formatted as "A\r\nB\r\nC\r\nD" when submitted from those browsers.
With these differences in behavior, how can I handle persisting multi-line data from a TEXTAREA that will render properly in ALL browsers?
A: You should replace \r\n char with tag and create a MvcHtmlString when you want render the text, I use this:
@(MvcHtmlString.Create(Model.Text.Replace("\r\n","<br/>").Replace("\n\r","<br/>)))
Model.Text is a text from an TextArea, I've tested this line of code and it works as well on all five major browsers (IE, FF, Chrome, Opera, Safari).
A: I haven't found an actual solution but have implemented a work around.
When I set the property on my object to the submitted value from the TEXTAREA, I perform a regular expression replacement on the text to convert whatever characters are returned from the browser to '\n' which appears to work as a line break in all browsers I checked (IE8, Chrome & FireFox). Here is the code I'm using (in .NET):
cleanValue = Regex.Replace(value, "(\\n|\\\\n|\\r|\\\\r)+", "\n", RegexOptions.IgnoreCase);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6335655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can anyone give me a little explanatory example about InsertOnSubmit and InsertAllOnSubmit I am trying to understand difference between those two and really need a explanatory simple example for them.
Thanks in advance..
A: Theres a good Q&A about this on the MSDN forums. Most interesting bit:
InsertAllOnSubmit() simply loops over
all the elements in the IEnumerable
collection and calls InsertOnSubmit()
for each element.
A: InsertOnSubmit adds a single record. InsertAllOnSubmit does the same, but for a set (IEnumerable<T>) of records. That's about it.
A: I found this example of InsertAllOnSubmit() at the very bottom of this page. Just remember to add a using statement for System.Collections.Generic
// Create list with new employees
List<Employee> employeesToAdd = new List<Employee>();
employeesToAdd.Add(new Employee() { EmployeeID = 1000, FirstName = "Jan", LastName = "Jansen", Country = "BE" });
employeesToAdd.Add(new Employee() { EmployeeID = 1001, FirstName = "Piet", LastName = "Pieters", Country = "BE" });
employeesToAdd.Add(new Employee() { EmployeeID = 1002, FirstName = "John", LastName = "Johnson", Country = "BE" });
// Add all employees to the Employees entityset
dc.Employees.InsertAllOnSubmit(employeesToAdd);
// Apply changes to database
dc.SubmitChanges();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/372075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Django Rest_Framework strange error can't import name SkippError I just started a project and installed django rest framework, then i have added it in settings.py 's installed apps.
then i run the server, it through me this error:
File
"/home/pyking/.local/lib/python3.6/site-packages/django/template/backends/django.py",
line 125, in get_package_libraries
"trying to load '%s': %s" % (entry[1], e) django.template.library.InvalidTemplateLibrary: Invalid template
library specified. ImportError raised when trying to load
'rest_framework.templatetags.rest_framework': cannot import name
'SkipError'
When removing rest_framework from installed apps, the server works nice, but if add rest_framework in settings.py 's installed apps ,it doesn't work, and throw me above error
Note: The project dont have any models, view, serializers file and anything. i new project with new apps,
Can you please tell me why i facing this error?
A: If there's no missprint - there's some dependencies missing. Create isolated virtualenv and install django and djangorestframework (maybe that's the problem you typed pip install django_rest_framework instead of djangorestframework).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55872645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Trying to test SAML auth with open/free SAML IDP I am trying to test and debug SAML authentication with my app. I currently do not have my own SAML IDP so I am trying to test with free/open SAML IDP providers.
Currently I am testing with SSOCircle: https://www.ssocircle.com/
And when testing after I sign in with that provider I get:
Error occurred
Reason: Unable to do Single Sign On or Federation.
Please enable the additional debug option in "My Debug". Detailed
trace information only available with paid accounts. Check our plans.
Anyone successfully setup SAML auth within their app using SSOCircle. If so can you provide insight into what might be the problem. I signed up for an account and registered my service provider on their site.
I have also looked around for simple free SAML testing IDPs without much luck. If anyone has one they are using that is working that would be helpful as well.
A: using http in SSOCircle address instead of https has worked for me
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57205244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How could i use flags to select which func i want to call Hello this is my first actually stab at writing an actual Go command line program so please forgive the appearance I also pulled some of this code off the Internet. What I am actually trying to do is have the ability to choose when i want to encrypt or decrypt while still being able to choose the src file and dest file. Thanks in advance for any help. I couldn't find anything solid explaining this or at least nothing i could make out.
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"errors"
"io"
"io/ioutil"
"log"
"os"
)
func decrypt(key, ciphertext []byte) (plaintext []byte, err error) {
var block cipher.Block
if block, err = aes.NewCipher(key); err != nil {
return
}
if len(ciphertext) < aes.BlockSize {
err = errors.New("ciphertext too short")
return
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(ciphertext, ciphertext)
plaintext = ciphertext
return
}
func encrypt(key, text []byte) (ciphertext []byte, err error) {
var block cipher.Block
if block, err = aes.NewCipher(key); err != nil {
return nil, err
}
ciphertext = make([]byte, aes.BlockSize+len(string(text)))
iv := ciphertext[:aes.BlockSize]
if _, err = io.ReadFull(rand.Reader, iv); err != nil {
return
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], text)
return
}
func encryptFileData(srcFile, destFile string) {
if len(os.Args) > 1 {
srcFile = os.Args[1]
}
if len(os.Args) > 2 {
destFile = os.Args[2]
}
var cipherText, plainText []byte
var err error
key := []byte("abcdefg123456789")
plainText, _ = ioutil.ReadFile(srcFile)
if cipherText, err = encrypt(key, plainText); err != nil {
log.Fatal(err)
}
ioutil.WriteFile(destFile, cipherText, 0755)
return
}
func decryptFileData(srcFile, destFile string) {
if len(os.Args) > 1 {
srcFile = os.Args[1]
}
if len(os.Args) > 2 {
destFile = os.Args[2]
}
var cipherText, plainText []byte
var err error
key := []byte("abcdefg123456789")
cipherText, _ = ioutil.ReadFile(srcFile)
if plainText, err = decrypt(key, cipherText); err != nil {
log.Fatal(err)
}
ioutil.WriteFile(destFile, plainText, 0755)
return
}
func main() {
encryptFileData(os.Args[1], os.Args[2])
decryptFileData(os.Args[1], os.Args[2])
}
A: Use the flag package. For example:
func main() {
encrypt := flag.Bool("encrypt", false, "encrypt file")
decrypt := flag.Bool("decrypt", false, "decrypt file")
flag.Parse()
srcFile, destFile := flag.Arg(0), flag.Arg(1)
if *encrypt {
encryptFileData(srcFile, destFile)
}
if *decrypt {
decryptFileData(srcFile, destFile)
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35762354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make sure there will be a fixed DB server across multiple deployments in Cloud Foundry? I am a newbie with CF microservices and I am trying to deploy a service multiple times. As far as I understood, each time I deploy into a space the application is getting a different database server and schema. Is there a way to tell the Cloud Foundry to use only a fixed DB server all the times across multiple deployments in one environment?
A: The keyword for your case is 'Service Instance'
You can create a service instance of database server within the environment specific for your application and bind it via application manifest.
e.g.
cf create-service rabbitmq small-plan myapplication-rabbitmq-instance
As long as you have a binding to myapplication-rabbitmq-instance in your application manifest it would be preserved/be the same between application deployments within this space.
e.g. in your application manifest:
---
...
services:
- myapplication-rabbitmq-instance
More on https://docs.cloudfoundry.org/devguide/services/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42969532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how do you convert string into uppercase c++ I am not allowed to use toupper()
these are my functions, one function has to pass the string by reference.
void Uppercase(string x)
{
int y = 0;
while (y < x.length)
{
x[y] = x[y] - 32;
y++;
}
}
void uppercase(string &x)
{
int y = 0;
while (y < x.length)
{
x[y] = x[y] - 32;
y++;
}
Do I at least have the right idea?
I get this error when I build it....
Error 5 error C2446: '<' : no conversion from 'unsigned int (__thiscall std::basic_string,std::allocator>::* )(void) throw() const' to 'int' c:\users\edwingomez\documents\visual studio 2013\projects\homework\homework\homework6.cpp 18 1 Homework
A: Since the restriction from using toupper strikes me as silly and counterproductive, I'd probably respond to such an assignment in a way that followed the letter of the prohibition while side-stepping its obvious intent, something like this:
#include <locale>
#include <iostream>
struct make_upper : private std::ctype < char > {
void operator()(std::string &s){
do_toupper(&s[0], &s[0]+s.size());
}
};
int main() {
std::string input = "this is some input.";
make_upper()(input);
std::cout << input;
}
This, of course, produces the expected result:
THIS IS SOME INPUT.
Unlike the other answers I see posted here, this still gains all the normal advantages of using toupper, such as working on a machine that uses EBCDIC instead of ASCII encoding.
At the same time, I suppose I should admit that (for one example) when I was in fifth grade I was once told to do something like "write 'I will not talk in class', 50 times." so I turned in a paper containing one sentence that read "I will not talk in class 50 times." Sister Mary Ellen (yes, Catholic schools) was not particularly pleased.
A: The std::transform function with a lambda expression is one way to do it:
std::string s = "all uppercase";
std::transform(std::begin(s), std::end(s), std::begin(s),
[](const char& ch)
{ return (ch >= 'a' && ch <= 'z' ? ch - 32 : ch) });
std::cout << s << '\n';
Should output
ALL UPPERCASE
But only if the system is using the ASCII character set (or the ch - 32 expression will give unexpected results).
A: This is correct. But you should take care to add checks on the input. You could check if the characters are lowercase alphabets.
if (x[y] <= 'z') && (x[y] >= 'a')
x[y] = x[y] - 32;
For readability, you should replace 32 by 'a' - 'A'.
Also, your first function does nothing. It creates a copy of the string. Does the required actions on it. And then discards it because you are not returning it, and the function ends.
A: Sample Code:
*
*With correct checks of the range.
*With C++11 version (using range-for-loop).
Note: the production version should be using toupper. But the OP specifically state that can't used.
Code:
#include <iostream>
const char upper_difference = 32;
void uppercaseCpp11(std::string& str) {
for (auto& c : str) {
if (c >= 'a' && c <= 'z')
c -= upper_difference;
}
}
std::string UppercaseCpp11(std::string str) {
uppercaseCpp11(str);
return str;
}
void uppercase(std::string& x) {
for (unsigned int i = 0; i < x.size(); ++i) {
if (x[i] >= 'a' && x[i] <= 'z')
x[i] -= upper_difference;
}
}
std::string Uppercase(std::string x) {
uppercase(x);
return x;
}
int main() {
std::cout << Uppercase("stRing") << std::endl;
std::string s1("StrinG");
uppercase(s1);
std::cout << s1 << std::endl;
std::cout << UppercaseCpp11("stRing") << std::endl;
std::string s2("StrinG");
uppercaseCpp11(s2);
std::cout << s2 << std::endl;
return 0;
}
A: string x = "Hello World";
char test[255];
memset(test, 0, sizeof(test));
memcpy(test, x.c_str(), x.capacity());
for (int i = 0; i < x.capacity(); i++)
{
if (test[i] > 96 && test[i] < 123)
test[i] = test[i] - 32;
}
x.assign(test);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29374002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Docker failing to add repository Universe I'm trying to add universe as a repository in my docker image:
RUN add-apt-repository "deb http://archive.ubuntu.com/ubuntu $(lsb_release -sc) universe"
RUN apt-get update
it errors with this output:
Step 4/24 : RUN add-apt-repository "deb http://archive.ubuntu.com/ubuntu $(lsb_release -sc) universe"
---> Running in 4c924d1455ed
Removing intermediate container 4c924d1455ed
---> b472a493f90c
Step 5/24 : RUN apt-get update
---> Running in d4e292c43bad
Ign:1 http://deb.debian.org/debian stretch InRelease
Hit:2 http://security.debian.org/debian-security stretch/updates InRelease
Hit:3 http://deb.debian.org/debian stretch-updates InRelease
Hit:4 http://deb.debian.org/debian stretch Release
Ign:5 http://archive.ubuntu.com/ubuntu stretch InRelease
Ign:6 http://archive.ubuntu.com/ubuntu stretch Release
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Ign:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Ign:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Ign:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Ign:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Ign:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
Ign:8 http://archive.ubuntu.com/ubuntu stretch/universe all Packages
Err:9 http://archive.ubuntu.com/ubuntu stretch/universe amd64 Packages
404 Not Found [IP: 91.189.88.142 80]
Reading package lists...
W: The repository 'http://archive.ubuntu.com/ubuntu stretch Release' does not have a Release file.
E: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/stretch/universe/binary-amd64/Packages 404 Not Found [IP: 91.189.88.142 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.
ERROR: Service 'api' failed to build: The command '/bin/sh -c apt-get update' returned a non-zero code: 100
My Docker file uses FROM python:2.7-slim as a base.
What am I doing wrong?
Results of cat /etc/os-release:
PRETTY_NAME="Debian GNU/Linux 9 (stretch)"
NAME="Debian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
A: Since you're using debian as base OS image, then you cannot add ubuntu's repository as mentioned by Tarun Lalwani in comments.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66877080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regarding MATLAB slice function
This image represents my 3D array shown by using 'slice' function
My question is:
*
*As you can see from the image, there are 8 images in my 3D array (1mm~8mm)
however, each picture actually represents damage at 0 mm (surface) to 7 mm (z-axis)
So, how do I make z-axis value 0 to 7? instead of 1 to 8?
In the image I attached, you see 0 mm because I set:
zlim([0 8])
However, there are still 8 images corresponding to 1mm to 8mm
Thank you!
A: As shown in the slice documentation:
[x,y,z] = meshgrid(-2:.2:2,-2:.25:2,-2:.16:2);
v = x.*exp(-x.^2-y.^2-z.^2);
xslice = [-1.2,.8,2];
yslice = 2;
zslice = [-2,0];
slice(x,y,z,v,xslice,yslice,zslice)
colormap hsv
You can pass the coordinate system as the first three arguments to slice, then express the slice locations in this coordinate system, so in your case:
[x,y,z] = meshgrid(0:100,0:100,0:7);
slice(x,y,z,xslice,yslice,zslice)
Where you'd express zslice in the range [0,7] when defining your desired slice locations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45904999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use Swashbuckle to generate global parameters in the resulting Swagger file? There are currently ways to add parameters to every path via Swashbuckle. Some such way can be found here.
Let's say I want to add a parameter to every path called 'api-version'. Then this parameter will appear in every path in the Swagger file.
I want Swashbuckle to generate a single global parameter. For example, instead of this
{
"swagger": "2.0",
"paths": {
"/something": {
"post": {
"operationId": "something_do",
"parameters": [
{
"name": "api-version",
"in": "query",
"description": "The API version.",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "Something got done.",
"schema": {
"type": "string"
}
}
}
}
}
}
}
, I want
{
"swagger": "2.0",
"paths": {
"/something": {
"post": {
"operationId": "something_do",
"responses": {
"200": {
"description": "Something got done.",
"schema": {
"type": "string"
}
}
}
}
}
},
"parameters": {
"ApiVersionParameter": {
"name": "api-version",
"in": "query",
"required": true,
"type": "string",
"description": "The API version."
}
}
}
with the parameter set globally, and not under every path. I'm unable to find anything under SwaggerGenOptions that produces this.
A: Thank you Helder. The IDocumentFilter works.
public class GlobalParameterDocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
if (swaggerDoc != null && swaggerDoc.Components != null)
{
swaggerDoc.Components.Parameters.Add(ApiConstants.ApiVersionGlobalParamName, new OpenApiParameter
{
Name = "api-version",
In = ParameterLocation.Query,
Required = true,
Schema = new OpenApiSchema { Type = "string" },
Description = "The API version"
});
}
}
}
The path parameter can then reference this global parameter via an IOperationFilter.
public class OperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
_ = operation ?? throw new ArgumentNullException(nameof(operation));
_ = context ?? throw new ArgumentNullException(nameof(context));
if (operation.Parameters == null)
{
operation.Parameters = new List<OpenApiParameter>();
}
operation.Parameters.Add(
new OpenApiParameter
{
Reference = new OpenApiReference { Id = "parameters/api-version", ExternalResource = "" }
});
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62782119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Making a symbolic function callable -- sympy I'd like to calculate the derivative, then solve for when it is zero.
I am using the sympy module to do this.
r = somefunction(x1,x2)
Using this function, I'd like to be able to call these two matrices.
r_grad = [r.diff(x1), r.diff(x2)]
r_hess = [[r.diff(x1,x1), r.diff(x1,x2)],[r.diff(x2,x1), r.diff(x2,x2)]]
I'd then like to solve for when r_grad[0] and r_grad[1] == 0, and plug that into the hessian.
How can I make these .diff() symbols callable?
A: SymPy has a lambdify module for these purposes:
from sympy.utilities.lambdify import lambdify
func = lambdify((x1, x2), r.diff(x1))
func(1, 2) # evaluate the function efficiently at (1, 2)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25675970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Overwriting lines in text file I want to overwrite lines in a file without losing the data. The program starts by writing data separated by tabs into a "students2.txt" file.
filename = "students2.txt"
file_write = open(filename, "a")
num_of_students = int(input("Enter number of students: "))
for i in range(1, num_of_students + 1):
print("Student", i)
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
matric_no = input("Enter your matric number: ")
print("Input attendance")
mar_4 = int(input())
mar_11 = int(input())
mar_18 = int(input())
mar_25 = int(input())
file_write.write(first_name.title() + "\t")
file_write.write(last_name.title() + "\t")
file_write.write(matric_no.upper() + "\t")
file_write.write(str(mar_4) + "\t")
file_write.write(str(mar_11) + "\t")
file_write.write(str(mar_25) + "\t")
file_write.write(str(mar_18) + "\t" + "\n")
file_write.close()
Then it reads from that file and performs some calculations
file_read = open("students2.txt", "r")
file_write = open("students2.txt", "a")
for i in file_read.readlines():
i = i.strip().split()
std_sum = int(i[3]) + int(i[4]) + int(i[5]) + int(i[6])
std_attd_percent = (std_sum/4) * 100
file_write.write(str(std_attd_percent))
I want to write the std_attd_percent to each line of the "student2.txt" but it just writes it all to the end of the line.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66498744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Efficient tree-based dialogue system? I'm working on a simple tree based dialogue system. its a basic game of click to advance the story, with different choice to choose, leading player to a different story path.
What I did was, I create a plethora of gameObject called Convo. Each Convo contain Text(Component) , and Children to determine which character is on screen, and a tag in those child to display their inflection(ex. sad happy etc.).
Ex
*
*A-0-1 (Text: " John: Hey, what's going on?") (with tag "Choice" if it's the last convo)
*
*John(with tag "Idle")
*Jane(with tag "Irritated")
Story path picture
There's 2 variable: CurrentDialogue(string) and DialogueTracking(int).
On each click, I check if current convo has tag "Choice". If there isn't, I use CurrentDialogue(string) to find gameobject with exact name and display it's text. then increase DialogueTracking by one,
then I modified CurrentDialogue(string) from A-0-1 to A-0-2 and so on using DialogueTracking, and When there's tag "choice" (Ex.A-0-4) , DialogueTracking(int) get reset to one, so it's A-1-1 instead of A-1-5 after player choose a choice.
Here's the problem, after a lot of convo and many story path, I realize my newbie mistake. The code turn into big o' if/else,(the comparing of which choice go which path)
I'm quite new to programming and unity, If anyone could guide me in the right direction on ways to help me learn how to create this system to be clean and efficient , that would be really great!
Thank you!
A: I would suggest making DialogueManager Component that will hold all of your dialogues and each of these should hold reference to other dialogues. Then after displaying dialogue you can check if it has multiple children or just one ( or none ) and display some dialog/popup to choose from keys of these.
In code example it would be like :
[Serializable]
public class Dialogue
{
[SerializeField]
Dictionary<string, Dialogue> _dialogues;
[SerializeField]
string _dialogueText;
public Dialogue(string text)
{
_dialogues = new Dictionary<string, Dialogue>();
_dialogueText = text;
}
public string GetText() { return _dialogueText; }
public bool HasManyPaths() { return _dialogues.Count > 1; }
public string[] GetKeys() { return _dialogues.Keys; }
public Dialogue GetDialogue(string key) { return _dialogues[key]; }
}
Now you should fill this within your Unity inspector and make DialogueManager Component to manage your Dialogues :
public class DialogueManager
: Component
{
[SerializeField]
Dialogue _currentDialogue;
public void InitializeDialogue()
{
string text = _currentDialogue.GetText();
// display the text
if ( _currentDialogue.HasManyPaths() )
{
string[] keys = _currentDialogue.GetKeys();
// display keys;
string selected_key = // user input here
_currentDialogue = _currentDialogue.GetDialogue(selected_key);
}
else
{
string key = _currentDialogue.GetKeys()[0];
_currentDialogue = _currentDialogue.GetDialogue(key);
}
}
}
Using this method you can simply make your dialogues inside Unity editor and add MonoBehaviour script with something like this :
public void Start()
{
GetComponent<DialogueManager>().InitializeDialogue();
}
Simple example of making dialogue tree would be :
{ currentDialogue [ "hello! choose 1 or 2" ]
1.{ dialogue [ "you've chosen 1" ]
. { dialogue [ "this ends dialogue" ] }
}
2. { dialogue [ "you've chosen 2" ]
. { dialogue [ "now choose another number between 3 and 4" ]
3. { dialogue [ "you've chosen 3" ] }
4. { dialogue [ "you've chosen 4" ] }
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42040581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cakephp3 sending mails - no result I'm trying to send email via cakephp3.
This is my app email config:
'EmailTransport' => [
'default' => [
'className' => 'Mail',
// The following keys are used in SMTP transports
'host' => 'localhost',
'port' => 25,
'timeout' => 30,
'username' => 'user',
'password' => 'secret',
'client' => null,
'tls' => null,
],
],
And this is controller :
public function index() {
$this->autoRender = false;
$email = new Email('default');
if (
$email->from(['[email protected]' => 'My Site'])
->to('[email protected]')
->subject('About')
->send('My message')) {
print 'ok';
}
}
And now, if i run this function, result is printed 'ok' on monitor.
But no mail is on my testing email box, even span, nothing.
My question is, why cakephp tells me that sending was done, but no mail is present on my box ?
Thank You.
A: Your configuration is incorrect. cakePHP attempts to send the e-mail via smtp to your localhost.
Most likely you do not have an MTA (ie. exim, dovecot) installed locally and the request gets dropped. This should be visible as an error in you logs (if enabled).
An easy solution is to change the configuration to a working email service for testing, for example Gmail.
Example:
Email::configTransport('gmail', [
'host' => 'smtp.gmail.com',
'port' => 587,
'username' => '[email protected]',
'password' => 'secret',
'className' => 'Smtp',
'tls' => true
]);
Note that the host and port point to Gmail. This example is indicative and was taken from the official documentation.
More information on configuring email transports in cakePHP 3.0 here: http://book.cakephp.org/3.0/en/core-libraries/email.html#configuring-transports
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32583817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rx sliding windows - proper cleanup? I've been trying to build a circuit breaker that can be configured to trip with compound rules like:
*
*2 timeout exceptions within 45 seconds; or
*50 of any other type of exception within 5 minutes
so figured the best way to do this was with sliding windows (or time-buffers whatever you want to call them).
Based on what I could find online and piece together myself I wrote this simple console app:
static IEnumerable<ConsoleKeyInfo> KeyPresses()
{
ConsoleKeyInfo key;
do
{
key = Console.ReadKey();
yield return key;
} while (key.Key != ConsoleKey.Escape);
}
static IObservable<int> TimeLimitedThreshold<T>(IObservable<T> source, TimeSpan timeLimit, int threshold)
{
return source.Window(source, _ => Observable.Timer(timeLimit))
.Select(x => x.Count())
.Merge()
.Where(count => count >= threshold)
.Take(1);
}
static void Main(string[] args)
{
Console.WriteLine("Starting");
var timeLimit = TimeSpan.FromSeconds(5);
const int threshold = 3;
var keys = KeyPresses().ToObservable(Scheduler.Default).Publish().RefCount();
var thresholdHit = TimeLimitedThreshold(keys, timeLimit, threshold);
thresholdHit.Subscribe(count => Console.WriteLine("THRESHOLD BREACHED! Count is: {0}", count));
// block the main thread so we don't terminate
keys.Where(key => key.Key == ConsoleKey.Escape).FirstAsync().Wait();
Console.WriteLine("Finished");
}
(If I should put that in a gist or pastebin instead of in the question please just say so)
Now this seems to do what I want, if I press any key 3 or more times within 5 seconds the "THRESHOLD BREACHED!!!" is printed once and nothing more happens.
My questions are:
*
*Is the TimeLimitedThreshold function at a sensible level of abstraction for when working with Rx.Net?
*Should I be injecting the scheduler to use when creating the Observable.Timer()?
*What cleanup am I missing if any? Memory usage when it comes to Rx.NET really baffles me.
A: I would probably write the threshold function the following way, taking advantage of the Timestamp combinator.
public static IObservable<U> TimeLimitedThreshold
<T,U>
( this IObservable<T> source
, int count
, TimeSpan timeSpan
, Func<IList<T>,U> selector
, IScheduler scheduler = null
)
{
var tmp = scheduler == null
? source.Timestamp()
: source.Timestamp(scheduler);
return tmp
.Buffer(count, 1).Where(b=>b.Count==count)
.Select(b => new { b, span = b.Last().Timestamp - b.First().Timestamp })
.Where(o => o.span <= timeSpan)
.Select(o => selector(o.b.Select(ts=>ts.Value).ToList()));
}
As an added convenience when the trigger is fired the complete buffer that satisfies the trigger is provided to your selector function.
For example
var keys = KeyPresses().ToObservable(Scheduler.Default).Publish().RefCount();
IObservable<string> fastKeySequences = keys.TimeLimitedThreshHold
( 3
, TimeSpan.FromSeconds(5)
, keys => String.Join("", keys)
);
The extra IScheduler parameter is given as the Timestamp method has an extra overload which takes one. This might be useful if you want to have a custom scheduler which doesn't track time according to the internal clock. For testing purposes using an historical scheduler can be useful and then you would need the extra overload.
and here is a fully working test showing the use of a schedular. ( using XUnit and FluentAssertions for the Should().Be(..) )
public class TimeLimitedThresholdSpec : ReactiveTest
{
TestScheduler _Scheduler = new TestScheduler();
[Fact]
public void ShouldWork()
{
var o = _Scheduler.CreateColdObservable
( OnNext(100, "A")
, OnNext(200, "B")
, OnNext(250, "C")
, OnNext(255, "D")
, OnNext(258, "E")
, OnNext(600, "F")
);
var fixture = o
.TimeLimitedThreshold
(3
, TimeSpan.FromTicks(20)
, b => String.Join("", b)
, _Scheduler
);
var actual = _Scheduler
.Start(()=>fixture, created:0, subscribed:1, disposed:1000);
actual.Messages.Count.Should().Be(1);
actual.Messages[0].Value.Value.Should().Be("CDE");
}
}
Subscribing and is the following way
IDisposable subscription = fastKeySequences.Subscribe(s=>Console.WriteLine(s));
and when you want to cancel the subscription ( clean up memory and resources ) you dispose of the subscription. Simply.
subscription.Dispose()
A: Here's an alternative approach that uses a single delay in favour of buffers and timers. It doesn't give you the events - it just signals when there is a violation - but it uses less memory as it doesn't hold on to too much.
public static class ObservableExtensions
{
public static IObservable<Unit> TimeLimitedThreshold<TSource>(
this IObservable<TSource> source,
long threshold,
TimeSpan timeLimit,
IScheduler s)
{
var events = source.Publish().RefCount();
var count = events.Select(_ => 1)
.Merge(events.Select(_ => -1)
.Delay(timeLimit, s));
return count.Scan((x,y) => x + y)
.Where(c => c == threshold)
.Select(_ => Unit.Default);
}
}
The Publish().RefCount() is used to avoid subscribing to the source more than one. The query projects all events to 1, and a delayed stream of events to -1, then produces a running total. If the running total reaches the threshold, we emit a signal (Unit.Default is the Rx type to represent an event without a payload). Here's a test (just runs in LINQPad with nuget rx-testing):
void Main()
{
var s = new TestScheduler();
var source = s.CreateColdObservable(
new Recorded<Notification<int>>(100, Notification.CreateOnNext(1)),
new Recorded<Notification<int>>(200, Notification.CreateOnNext(2)),
new Recorded<Notification<int>>(300, Notification.CreateOnNext(3)),
new Recorded<Notification<int>>(330, Notification.CreateOnNext(4)));
var results = s.CreateObserver<Unit>();
source.TimeLimitedThreshold(
2,
TimeSpan.FromTicks(30),
s).Subscribe(results);
s.Start();
ReactiveAssert.AssertEqual(
results.Messages,
new List<Recorded<Notification<Unit>>> {
new Recorded<Notification<Unit>>(
330, Notification.CreateOnNext(Unit.Default))
});
}
Edit
After Matthew Finlay's observation that the above would also fire as the threshold is passed "on the way down", I added this version that checks only for threshold crossing in the positive direction:
public static class ObservableExtensions
{
public static IObservable<Unit> TimeLimitedThreshold<TSource>(
this IObservable<TSource> source,
long threshold,
TimeSpan timeLimit,
IScheduler s)
{
var events = source.Publish().RefCount();
var count = events.Select(_ => 1)
.Merge(events.Select(_ => -1)
.Delay(timeLimit, s));
return count.Scan((x,y) => x + y)
.Scan(new { Current = 0, Last = 0},
(x,y) => new { Current = y, Last = x.Current })
.Where(c => c.Current == threshold && c.Last < threshold)
.Select(_ => Unit.Default);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22369764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Descending Sorting of an ArrayList of Object I need to sort this ArrayObject :
public ArrayList<WPPost> posts;
on descending :
posts.get(i).getRating()
I have tried with HashMaps, LinkedHashMaps, I haven't found anything. What's the best solution ?
A: I think that one of the best solutions is the use of Collections.sort
Collections.sort(posts, new Comparator<WPPost>() {
@Override
public int compare(WPPost o1, WPPost o2) {
return o2.getRating() - o1.getRating();
}
});
In some implemetations Collectios sort use merge sort algorithm, that will give you a O(log n) complexity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37137348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flex box how to specify the column for item placement I have a software which creates the repeatable blocks. They use flexbox. Currently, they align based on the position of the repeatable block, stacked below each item. Say in the image below if the repeatable blocks are item1, item2, item3, item4. It will render the column with the same order.
But I want to allow the user to have a multi-column option. I can use the grid and considering it is something dynamic I cant use that. Say I can assign the grid-item property to item 1 as firstone and create grid-template-areas:"firstone secondone" but assigning the item2, item3 with grid-item secondone will have content placed one over each other.
grid-template-areas:"firstone secondone" "firstone secondone" "firstone secondone" will do the trick but I don't have a method to generate this CSS there can be more than 4 items.
Any possible solution? Alternatives?
A: Using a grid for these problems is the right choice! What you are trying to achieve is a bit more complex than the use case of flexbox.
By using grid-template-columns instead of grid-template-areas, and the :first-child selector, it it possible to achieve what you describe.
Given this example HTML:
<div>
<article>Item 1</article>
<article>Item 2</article>
<article>Item 3</article>
<article>Item 4</article>
</div>
You can use this CSS:
div {
display: grid;
grid-template-columns: 1fr 1fr;
}
article {
grid-column: 2;
}
article:first-child {
grid-column: 1;
}
Have a look at this fiddle to see an example.
https://jsfiddle.net/h9k5x7uf/
If you want to make this more dynamic or server rendered, replace :first-child with some helper classes instead.
.pull-left { grid-column: 1; }
.pull-right { grid-column: 2; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58637938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In app purchase with hosted content does not work when live Recently I have published application with in-app purchase to App Store. In-app purchase contains hosted content. This purchase item was fully tested with sandbox users and with beta testers as well. But when we go live this item does not work. Payments for this purchase was withdrawn, but content is still locked. I can fetch selected product and his price in App Store build.
Also, I am wondering that all works great using sandbox user, works for all beta and internal testers, but does not work in app downloaded from App Store. This even works after switching back to sandbox.
In-app purchase is approved, content inside is valid, application is ready for sale.
Are there some differences between in-app purchase configuration for App Store build and TestFlight/installed from Xcode one?
Thanks for your time.
A: This appears to be an issue on Apple's servers that started a few days ago. See this forum thread:
https://forums.developer.apple.com/thread/80546
Apple's server team is said to be addressing it now. Here's a quote from an Apple staff member on that thread:
"I've forwarded all of these bug reports to the Apps Ops Engineering QA team for thei review. For everyone else, by all means submit bug reports, but at this point, I'm not going verify that the bug reports are passed on to Apps Ops Engineering QA. The server team's attention is now on this issue."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44722599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to preserve Client IP Address with GKE Ingress controller on Kubernetes? I would like to catch the Client IP Address inside my .NET application running behind GKE Ingress Controller to ensure that the client is permitted.
var requestIpAddress = request.HttpContext.Connection.RemoteIpAddress.MapToIPv4();
Instead of getting Client IP Address I get my GKE Ingress IP Address, due to The Ingress apply some forwarding rule.
The GKE Ingress controller is pointing to the Kubernetes service of type NodePort.
I have tried to add spec to NodePort service to preserve Client IP Address but it doesn't help. It is because the NodePort service is also runng behind the Ingress
externalTrafficPolicy: Local
Is it possible to preserve Client IP Address with GKE Ingress controller on Kubernetes?
NodePort Service for Ingress:
apiVersion: v1
kind: Service
metadata:
name: api-ingress-service
labels:
app/name: ingress.api
spec:
type: NodePort
externalTrafficPolicy: Local
selector:
app/template: api
ports:
- name: http
protocol: TCP
port: 80
targetPort: http
Ingress:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress
namespace: default
labels:
kind: ingress
app: ingress
annotations:
networking.gke.io/v1beta1.FrontendConfig: frontend-config
spec:
tls:
- hosts:
- '*.mydomain.com'
secretName: tls-secret
rules:
- host: mydomain.com
http:
paths:
- path: /*
pathType: ImplementationSpecific
backend:
service:
name: api-ingress-service
port:
number: 80
A: Posted community wiki for better visibility. Feel free to expand it.
Currently the only way to get the client source IP address in GKE Ingress is to use X-Forwarded-For header. It's known limitation for all GCP HTTP(s) Load Balancers (GKE Ingress is using External HTTP(s) LB).
If it does not suit your needs, consider migrating to a third-party Ingress Controller which is using an external TCP/UDP network LoadBalancer, like NGINX Ingress Controller.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70848466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: history.push not working in wait or sync until button click I try to navigate page without refresh using "history.push()" It only work, when it clicked by human via button. It won't work programmatically . It is is only updating url but not navigating in browser.
//Index.js
ReactDOM.render(<Router history={history}><App /></Router>, document.getElementById('root'));
//App.js
<Switch>
<Route path="/" exact strict component={Login}/>
<Route path="/Homepage" exact strict component={Homepage}/>
</Switch>
//History.js
import {createBrowserHistory} from 'history'
export default createBrowserHistory();
Working fine, When clicked directly using button.
//Working
function btnClick(){
history.push('/Homepage');
}
Not working, When it is inside sync or wait function.
//Not Working
const wait=ms=>new Promise(resolve => setTimeout(resolve, ms));
wait(4*1000).then(() => {
history.push('/Homepage');
});
A: You aren't setting the history on your Router correctly
<Router history={history} />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59958319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: pass string array out of function in c I have a function that I'm using to build a string array. Inside the function i can print the array no worries however the program returns from the called function, the array (arr) remains NULL.
How do I get the data out of the array ?
Thanks.
main(){
char **arr = NULL;
funct(arr);
printf("%s\n", arr[2];
}
funct(char **arr){
arr = malloc(10*sizeof(char *));
arr[1...n] = calloc(SIZE, sizeof(char));
// Add data to array
}
A: I can see several problemens in your code:
*
*in the line printf("%s\n", arr[2]; you forgot a closing )
*Your arr variable local to the main function is never initialized. In C, parameters are passed by value meaning that you are passing the NULL pointer to your function and inside this function, the local pointer arr is allocated but not the one of the main function.
The solution is to allocate the array in the main function and pass a pointer to the array and the size to the function that fills it:
main(){
char **arr = malloc(10*sizeof(char *));
funct(arr, 10);
printf("%s\n", arr[2]);
}
funct(char **arr, int size){
// Add data to array
arr[0] = "first data";
....
arr[size -1] = "last data";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22589661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Way to disable count query from PageRequest for getting total pages? We are using Spring Data with the PageRequest and hitting a significantly large set of data. All queries perform optimally except the query being executed to get the total number of pages. Is there a way to disable this feature or would we most likely have to implement our own Pageable?
http://static.springsource.org/spring-data/data-commons/docs/1.3.2.RELEASE/api/org/springframework/data/domain/PageRequest.html
http://static.springsource.org/spring-data/data-commons/docs/1.3.2.RELEASE/api/org/springframework/data/domain/Pageable.html
Edit: After further analysis I believe the only way around this problem is to not use Spring Data and use EntityManager as it allows setting of start row and number of records to return. We only need whether next page is available so we just retrieve one extra record. We also need a dynamic query which doesn't seem possible in Spring Data.
Edit 2: And it would seem I just didn't wait long enough for some responses. Thanks guys!!!
A: The way to achieve this is simply by using List as return value. So for example for a repository defined like this:
interface CustomerRepository extends Repository<Customer, Long> {
List<Customer> findByLastname(String lastname, Pageable pageable);
}
The query execution engine would apply the offset and pagesize as handed in by the Pageable but not trigger the additional count query as we don't need to construct a Page instance. This also documented in the relevant sections of the reference documentation.
Update: If you want the next page / previous page of Page but still skip the count query you may use Slice as the return value.
A: I was able to avoid the count performance degradation in a dynamic query (using Spring Data Specifications) with the base repository solution indicated in several post.
public class ExtendedRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements ExtendedRepository<T, ID> {
private EntityManager entityManager;
public ExtendedRepositoryImpl(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityManager = entityManager;
}
@Override
public List<T> find(Specification<T> specification, int offset, int limit, Sort sort) {
TypedQuery<T> query = getQuery(specification, sort);
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.getResultList();
}
}
A query to retrieve 20 record slices, from a 6M records dataset, takes milliseconds with this approach. A bit over the same filtered queries run in SQL.
A similar implementation using Slice<T> find(Specification<T> specification, Pageable pageable) takes over 10 seconds.
And similar implementation returning Page<T> find(Specification<T> specification, Pageable pageable) takes around 15 seconds.
A: I had recently got such a requirement and the latest spring-boot-starter-data-jpa library has provided the out-of-box solution. Without count feature pagination can be achieved using org.springframework.data.domain.Slice interface.
An excerpt from blog
Depending on the database you are using in your application, it might become expensive as the number of items increased. To avoid this costly count query, you should instead return a Slice. Unlike a Page, a Slice only knows about whether the next slice is available or not. This information is sufficient to walk through a larger result set.
Both Slice and Page are part of Spring Data JPA, where Page is just a sub-interface of Slice with a couple of additional methods. You should use Slice if you don't need the total number of items and pages.
@Repository
public interface UserRepository extends CrudRepository<Employee, String> {
Slice<Employee> getByEmployeeId(String employeeId, Pageable pageable);
}
Sample code-snippet to navigate through larger result sets using Slice#hasNext. Until the hasNext method returns false, there is a possibility of data presence for the requested query criteria.
int page = 0;
int limit = 25;
boolean hasNext;
do {
PageRequest pageRequest = PageRequest.of(page, limit );
Slice<Employee> employeeSlice = employeeRepository.getByEmployeeId(sourceId, pageRequest);
++page;
hasNext = employeeSlice .hasNext();
} while (hasNext);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12644749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Accessing HKEY_CURRENT_USER via Preferences in Java I am trying to write a registry key in the following path in the registry:
HKEY_CURRENT_USER -> Software -> TestApp
I am currently doing:
public static void main(String[] args)
{
Preferences p = Preferences.userRoot().node("/HKEY_CURRENT_USER/Software/TestApp");
p.put("TestKey", "TestValue");
}
But it writes it at HKEY_CURRENT_USER -> Software -> JavaSoft -> Prefs -> /H/K/E/Y_/C/U/R/R/E/N/T/_/U/S/E/R -> Software -> Test/App
How do I get it to follow the absolute path, and why is it putting extra slashes in?
A: You may take a look to this beautiful blog post about Read/Write the registry
I may draw your attention to this passage of the code:
/**
* Write a value in a given key/value name
* @param hkey
* @param key
* @param valueName
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void writeStringValue
(int hkey, String key, String valueName, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
writeStringValue(systemRoot, hkey, key, valueName, value);
}
else if (hkey == HKEY_CURRENT_USER) {
writeStringValue(userRoot, hkey, key, valueName, value);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
I think this solution is very elegant in onder to manage read/write operations against the registry.
A:
How do I get it to follow the absolute path
You can use reflection to access the private methods in the java.util.prefs.Preferences class. See this answer for details: https://stackoverflow.com/a/6163701/6256127
However, I don't recommend using this approach as it may break at any time.
why is it putting extra slashes in?
Have a look at this answer: https://stackoverflow.com/a/23632932/6256127
Registry-Keys are case-preserving, but case-insensitive. For example if you have a key "Rbi" you cant make another key named "RBi". The case is saved but ignored. Sun's solution for case-sensitivity was to add slashes to the key.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29368967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java FX-2 Timer count increasing heap size I am showing timer on user interface in a Java FX 2.0 application. Problem is that when i start a timer on the screen(showing it on label) it starts to increase HEAP size and that is increasing no of Survivors in GC, i checked all its behavior in NetBeans profiler. But when i stopped(i.e. comment) the timer code every thing was working perfectly. I am sharing my timer code if any one can suggest memory leak or any other timer showing procedure to save me from increasing Heap size. Here is my ShowTime code.
public void startTimer(){
timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.getKeyFrames().add(
new KeyFrame(Duration.seconds(1),
new EventHandler() {
// KeyFrame event handler
@Override
public void handle(Event event) {
// System.out.println("Entring time event");
if (timeSeconds % 60 == 0) {
mm++;
}
pagingTimeLbl.setText(String.format("%02d", mm) + " : " + String.format("%02d", timeSeconds % 60));
if(paging.getPriority()){
pagingPanelGrid.setStyle(timeSeconds%2==0?"-fx-border: 2px solid; -fx-border-color: red;":"-fx-border: 2px solid; -fx-border-color: black;");
}
if (timeSeconds <= 0) {
timeline.stop();
}
timeSeconds++;
}
}));
timeline.playFromStart();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18609304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to copy specific columns and filtered rows into another worksheet Please, I need some help with my code. I filtered some rows using VBA and would like to copy only two columns instead of all columns.
Public Sub CheckPrKey()
lastRow = Worksheets("ETM_ACS2").Range("A" & Rows.Count).End(xlUp).Row
For r = 2 To lastRow
If Worksheets("ETM_ACS2").Range("I" & r).Value = "Y" And Worksheets("ETM_ACS2").Range("N" & r).Value < "100" Then
Worksheets("ETM_ACS2").Range("D, N" & r).Copy
**Worksheets("ETM_ACS2").Rows(r).Copy**
Worksheets("dashboard").Activate
lastRowdashboard = Worksheets("dashboard").Range("B" & Rows.Count).End(xlUp).Row
Worksheets("dashboard").Range("A" & lastRowdashboard + 1).Select
ActiveSheet.Paste
End If
Next r
ActiveCell.Offset(1, 0).Select
End Sub
A: I'm not sure that got the point, but try.
Public Sub CheckPrKey()
lastRow = Worksheets("ETM_ACS2").Range("A" & Rows.Count).End(xlUp).Row
lastRowdashboard = Worksheets("dashboard").Range("B" & Rows.Count).End(xlUp).Row
With Worksheets("ETM_ACS2")
For r = 2 To lastRow
If .Range("I" & r).Value = "Y"
If .Range("N" & r).Value < "100" Then
Worksheets("dashboard").Range("A" & lastRowdashboard + 1)=.Range("D" & r)
Worksheets("dashboard").Range("B" & lastRowdashboard + 1)=.Range("N" & r)
lastRowdashboard = lastRowdashboard +1
End if
End If
Next r
End With
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72593072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: On Checkbox click show hide div having same class dynamically I want click on the check box and hide the respective content.
Now in my code all the content with same class gets hidden when I click any one of the checkbox.
Since my front end tags are in apex I do not want to use id, attr, name,value. I want to use class and fix this issue, exactly in the way I have written in this fiddle.
Fiddle link for reference
$('input[type="checkbox"]').click(function() {
if ($(this).is(":checked")) {
$('.div1').hide();
} else {
$('.div1').show();
}
});
<h3 align="center"> This JavaScript shows how to hide divisions </h3>
<form>
<input type="checkbox">Exam1
<div class="div1">I am content1!
</div>
<br>
<input type="checkbox">Exam2
<div class="div1">I am content2!
</div>
<br>
<input type="checkbox">Exam3
<div class="div1">I am content3!
</div>
<br>
<input type="checkbox">Exam4
<div class="div1">I am content4!
</div>
<br>
</form>
https://jsfiddle.net/6ybp2tL6/
Is this possible??
Thanks in advance
A: Try this instead DEMO
$('input[type="checkbox"]').click(function() {
($(this).is(":checked")) ? $(this).next().hide() : $(this).next().show();
});
A: Try to hide all the divs with class div1 initially,
$(".div1").hide();
$('input[type="checkbox"]').click(function() {
$(this).next('.div1').toggle(!this.checked); //toggle(false) will hide the element
});
And toggle the visibility of the relevant div element with class div1 by using next() and toggle()
DEMO
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36954050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JSON Login Authentification Zend Framework I am creating a form login with ExtJS, and sending JSON data to do authentification within Zend Framework. The problem is, no matter what username and password I fill, login always succeed. Here's the related code :
Submit Function for Ext JS Form, where we send JSON data contained username and password.
var doLogin = function () {
if (formPanel.getForm().isValid()) {
formPanel.getForm().submit({
method: 'POST',
url: '/zend/public/auth/valid',
waitMsg: 'Processing Request',
success: function (form, action) {
document.location = '/zend/public/guestbook';
},
failure: function (form, action) {
if (action.failureType = 'server') {
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Login Failed', obj.errors.reason);
} else {
Ext.Msg.alert('Warning!', 'Authentification server is uneachable : ' + action.response.responseText);
}
formPanel.getForm().reset
}
})
}
}
The Controller, we have ValidAction function to receive and send JSON data, and process to do the authentification.
public function validAction()
{
if(!isset($this->session->isLogin)){
$username = mysql_escape_string($_POST['username']);
$password = mysql_escape_string($_POST['password']);
$formdata = array('username'=>$username, 'password'=>$password);
if ($this->_process($formdata)) {
$this->session->setExpirationSeconds(3600);
$msg = '{success:true, result:{message:\'Welcome, '.$username.'!\'}}';
} else {
$msg = '{success:false, errors:{reason:\'Login failed, try again.\'}}';
}
}
protected function _process($values) {
// Get our authentication adapter and check credentials
$adapter = $this->_getAuthAdapter();
$adapter->setIdentity($values['username']);
$adapter->setCredential($values['password']);
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$user = $adapter->getResultRowObject();
$auth->getStorage()->write($user);
return true;
}
return false;
}
The problem lies in validAction, and weirdly I do var_dump to $this->process($formdata) and returns false, yet it always go to if function, message Success. Any ideas? Appreciated fellas.
UPDATE :
The var_dump :
Uncaught Error: You're trying to decode an invalid JSON String:
array(2) {
["username"]=>
string(2) "ad"
["password"]=>
string(4) "pass"
}
bool(false)
string(59) "{success:false, errors:{reason:'Login failed, try again.'}}"
A: Backend problem
You are outputting invalid JSON.
PHP provides json_encode to save you having to manually create json:
$response=array();
$response['success']=false;
$response['result']=array();
$response['message']='Welcome '.$username;
$msg = json_encode($response);
If you really don't want to use this you should add double quotes to your keys, and change to double quotes for your string properties too:
$msg = '{"success":true, "result":{"message":"Welcome, '.$username.'!"}}';
Front end problem
You are using success and failure methods, but I can't see anything in your back end code to send status headers.
The failure method will only get called when a response returns with a non 200 status code. So you may need to either add this to your back end code, and/or also decode the response inside your success method to make sure that you have sent success:true as part of your json before redirecting.
To send the header in PHP 5.4 or newer:
http_response_code(401);
in 5.3 or older you have to use header method instead - but if you are running this version you should upgrade immediately so I wont include an example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42406616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Data Control call from Javascript page How to call Existing Oracle ADF Data Control(DataBase Call) from Javascript in JDeveloper?
A: You can expose your ADF Business Components as REST webservice
(https://blogs.oracle.com/shay/entry/rest_based_crud_with_oracle)
and consume them from javascript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43320573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DurandalJS Routing Behavior What I Have
Trying to understand what's going on and how to control it. I have a "public" view for users that have not yet been authenticated, and a "home" view for users that are authenticated. Here's my route config:
app.start().then(function() {
//Replace 'viewmodels' in the moduleId with 'views' to locate the view.
//Look for partial views in a 'views' folder in the root.
viewLocator.useConvention();
//configure routing
router.useConvention();
router.mapRoute('home', 'viewmodels/home', 'Test App', true);
router.mapRoute('public', 'viewmodels/public', 'Test App', true);
router.mapRoute('set/:id', 'viewmodels/set', 'Set');
router.mapRoute('folder/:id', 'viewmodels/folder', 'Folder');
router.mapRoute('api', 'viewmodels/api', 'API Reference');
router.mapRoute('error', 'viewmodels/error', 'Error', false);
app.adaptToDevice();
//Show the app by setting the root view model for our application with a transition.
if (dataservice.isAuthenticated() === true) {
app.setRoot('viewmodels/shell', 'entrance');
router.navigateTo('home');
} else {
app.setRoot('viewmodels/public');
router.navigateTo('#/public');
}
router.handleInvalidRoute = function (route, params) {
logger.logError('No route found', route, 'main', true);
router.navigateTo('#/error');
};
});
The Problems
When I run the app for the first time, I'm not authenticated, and I get an error:
Uncaught TypeError: Cannot call method 'lookupRoute' of undefined
Originating from the 'router.navigateTo('#/public');' line.
Then when I try to click the login button, I get the same error from this:
define(['durandal/app', 'durandal/plugins/router', 'services/dataservice'], function (app, router, dataservice) {
var publicViewModel = function () {
self.logIn = function () {
app.setRoot('viewmodels/shell');
router.navigateTo('#/home');
};
But the content loads correctly. When I navigate to a particular page by clicking, say to /folder/2, and then change the url to /folders/2 (invalid), I get "route not found" in my log, as expected, but I run into a few other issues:
*
*I don't get the error page, or any errors (as I think I should, per my handleInvalidRoute)
*If I click on something else, the url doesn't change, and new content isn't loaded, again with no errors.
I think I'm breaking routing somehow, but I'm not sure how. How can I correct the above issues?
Screen:
A: I suspect calling navigateTo where you are might be too soon for some reason. To test this theory try move this code.
if (dataservice.isAuthenticated() === true) {
app.setRoot('viewmodels/shell', 'entrance');
router.navigateTo('home');
} else {
app.setRoot('viewmodels/public');
router.navigateTo('#/public');
}
into an "activate" method on your publicviewmodel, and in the main.js just leave this:
app.setRoot('viewmodels/public');
EDIT: Old suggestion
I believe on your viewmodel for the root you need a router property. So modify your public viewmodel to add one:
define(['durandal/app', 'durandal/plugins/router', 'services/dataservice'], function (app, router, dataservice) {
var publicViewModel = function () {
self.router = router;
self.logIn = function () {
app.setRoot('viewmodels/shell');
router.navigateTo('#/home');
};
(where do you define self though?)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16006405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: change property using map but for nested array of object I have above array of object within an array of object like below
{
"data": [
{
"id": "1a",
"isChecked": false
},
{
"id": "2b",
"isChecked": false
}
]
},
{
"data": [
{
"id": "2a",
"isChecked": false
},
{
"id": "2b",
"isChecked": false
}
]
}
]
How can I make arr[1].data[0].id['2a'] check property to true?
I know it's possible to use multiple map if I've index and 2a but I don't, what if I only have single "2a" as id?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73108173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Kotlin extensions/synthetic properties: same object in multiple invocations of Fragment.onViewCreated() I am using kotlin-android-extensions to import synthetic view properties from my layout to my Fragment. In my onViewCreated() Fragment method I am calling addTextChangedListener() on an EditText view that is a synthetic import. This is working fine the first time the Fragment is instantiated, but the next time it comes along, my new listener is being added to the same view object as the last invocation. So now both TextChangedListener objects are being triggered on text changes, with predictably poor results. The view from the first appearance of the Fragment is never dereferenced as far as I can tell.
Here's my output from logging the view object which shows it's the same thing.
First appearance:
AmountTextWatcher (com.redacted.util.AmountTextWatcher@36d1ccc) added to amount_edit_text: android.support.v7.widget.AppCompatEditText{79e2a VFED..CL. ......I. 0,0-0,0 #7f0f013a app:id/amount_edit_text}
Second appearance:
AmountTextWatcher (com.redacted.util.AmountTextWatcher@5812584) added to amount_edit_text: android.support.v7.widget.AppCompatEditText{79e2a VFED..CL. ......ID 0,0-434,200 #7f0f013a app:id/amount_edit_text}
Of course, I can work around this issue by using findViewById() to access my view instead of the synthetic reference, but I'm wondering if anyone else is running in to this issue and if there is a better way to handle it (other than not using the synthetic view reference.)
FYI: Using Kotlin version 1.0.6.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42499387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get Specific Field array
0 =>
object(stdClass)[284]
public 'option_id' => string '243' (length=3)
public 'option_name' => string 'upme_profile_fields' (length=19)
public 'option_value' => string 'a:17:{i:50;a:7:{s:8:"position";s:2:"50";s:4:"type";s:9:"separator";s:4:"meta";s:22:"profile_info_separator";s:4:"name";s:12:"Profile Info";s:7:"private";i:0;s:7:"deleted";i:0;s:17:"show_to_user_role";i:0;}i:60;a:14:{s:8:"position";s:2:"60";s:4:"icon";s:6:"camera";s:5:"field";s:10:"fileupload";s:4:"type";s:8:"usermeta";s:4:"meta";s:8:"user_pic";s:4:"name";s:15:"Profile Picture";s:8:"can_hide";i:0;s:8:"can_edit";i:1;s:7:"private";i:0;s:6:"social";i:0;s:7:"deleted";i:0;s:17:"show_to_user_role";i:0;s:17:"edit_b'... (length=5301)
public 'autoload' => string 'yes' (length=3)
how do i get field 'option_value' from the above output.
A: I dont know what your variable name is but you could do something like this:
$option_value = $array[0]->option_value;
Since its an object inside, use the -> (arrow operator), and point the desired property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24380018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Bind to property of object I am currently developing a little musicplayer just for fun.
I was wondering if I can bind to a class named Track and access its propertys in XAML.
public class Track
{
public string TitleName { get; set; }
public BitmapImage Cover { get; set; }
}
Code can explain better than I can so here's my pseudo code:
<Grid>
<Image Source="{Binding BindingName="CurrentTrack" PropertyName="Cover"}"/>
<TextBlock Text="{Binding BindingName="CurrentTrack" PropertyName="Title"}"/>
</Grid>
Can I get something like this without using a Converter or sth like that ?
A: You can access a child property like this:
<TextBox Text="{Binding CurrentTrack.TitleName}"/>
You must have bound your View to your ViewModel
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33959875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Python- turn values in a dictionary into a list i have a question:
I have a dictionary like this
{1: [4, 2, 1, 3], 2: [4, 3, 1, 2], 3: [4, 3, 1, 2]}
and I want to get each of the values into their own list within a loop
eg.
for each key in myDict
myList = [4,2,1,3]
do something in my list/ clear my list then loop around so...
myList = [4,3,1,2]
I have no idea how to attempt this, does anybody have any suggestions?
A: Dictionaries have a.values() method, and you can use it like so:
for myList in myDict.values():
print(myList) # Do stuff
Keep in mind camelCase isn't a convention in Python.
A: solution of you problem
a={1: [4, 2, 1, 3], 2: [4, 3, 1, 2], 3: [4, 3, 1, 2]}
mylist=a[1]
print(mylist)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70421706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: difference between encoding/gob and encoding/json I am writing an application in Go which uses encoding/gob to send structures and slices over UDP between nodes. It works fine but I notice that encoding/json also has the similar API. Searched and found this information(https://golang.org/pkg/encoding/):
gob Package gob manages streams of gobs - binary values exchanged
between an Encoder (transmitter) and a Decoder (receiver).
json Package json implements encoding and decoding of JSON as defined in
RFC 4627.
Can someone explain to me whether one is more efficient than the other and in general compare when to choose what? Also if I need to interface with a non-Go application, I guess json would be preferred?
A: Gob is much more preferred when communicating between Go programs. However, gob is currently supported only in Go and, well, C, so only ever use that when you're sure no program written in any other programming language will try to decode the values.
When it comes to performance, at least on my machine, Gob outperforms JSON by a long shot. Test file (put in a folder on its own under your GOPATH)
$ go test -bench=.
testing: warning: no tests to run
BenchmarkGobEncoding-4 1000000 1172 ns/op
BenchmarkJSONEncoding-4 500000 2322 ns/op
BenchmarkGobDecoding-4 5000000 486 ns/op
BenchmarkJSONDecoding-4 500000 3228 ns/op
PASS
ok testencoding 6.814s
A: Package encoding/gob is basically Go specific and unusable with other languages but it is very efficient (fast and generates small data) and can properly marshal and unmarshal more data structures. Interfacing with other tools is often easier via JSON.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41179453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: SAS while reading varbinary data from Amazon RDS is appending spaces at the end of the data. Can we avoid it? SAS while reading varbinary data from Amazon RDS is appending spaces at the end of the data.
proc sql;
select emailaddr from tablename1;
quit;
The column emailaddr is varbinary(20)
For example:
I inserted "[email protected] ", but while reading from db, it is appending spaces equal to the length of the column.
Since the column length is 20 it is returning "[email protected] " ( note the spaces appended. I cannot use the trim() function since this also removes spaces that might genuinely be part of the original inserted data.
How can i stop sas from appending these spaces?
For my program i need to get the exact data as present in database without any extra spaces attached.
A: That's how SAS works; SAS has only CHAR equivalent datatype (in base SAS, anyway, DS2 is different), no VARCHAR concept. Whatever the length of the column is (20 here) it will have 20 total characters with spaces at the end to pad to 20.
Most of the time, it doesn't matter; when SAS inserts into another RDBMS for example it will typically treat trailing spaces as nonexistent (so they won't be inserted). You can use TRIM and similar to deal with the spaces if you're using regular expressions or concatenation to work with these values; CATS and similar functions perform concatenation-with-trimming.
If trailing spaces are part of your data, you are mostly out of luck in SAS. SAS considers trailing spaces irrelevant (equivalent to null characters). You can append a non-space character in SQL, or translate the spaces to NBSPs ('A0'x) or something else, while still in SQL, or use quotes or something around your actual values - but whatever you do will be complicated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38533053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Storing NSMutableArray I am currently storing an instance of a class in an NSMutableArray by using NSValue with "valueWithPointer". The problem is within this class I have another NSMutableArray, whenever I convert the instance of the class back from NSValue the NSMutableArray contained within it is of length 0, all of its elements have been removed. Does anyone know why this happens and how to solve it?
Any help would be much appreciated.
A: Unless there's a very good reason that you specifically need NSValue, you should not add a class instance to an NSMutableArray that way. Just do:
[myMutableArray addObject:myClassInstance];
This does all the right things with regards to memory management (and avoids ugly pointer value stuff), and should let you get at your class instance's array objects after retrieving the object. See the NSMutableArray docs for a quick starter on how to use the class properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12925491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the case for using html-codes when any Unicode character can be encoded in UTF-8? I read Joel Spolsky's article on characters and encoding (twice), and I am enlightened.
I don't get why people on the Internet use HTML code encoded in UTF-8 in their HTML documents, such as
'
for making the browser display an apostrophe?
Citing Joel:
"UTF-8 was another system for storing your string of Unicode code points, those magic U+ numbers, in memory using 8 bit bytes."
Now: Let's say I am writing a blog (that is: I create a string), I decide to use Unicode characters, select one that I want to have printed on the screen, decide that it is a good idea to represent it as an HTML code rather than "the letter itself", encode it in UTF-8, send the bytes over the Internet to someone, let this person's browser decode the bytes, and let said browser decode the characters (again) to display an apostrophe.
Why would anyone want to do that?
A: There are three scenarios where it is useful to use a character reference:
*
*When you aren't encoding the document in a Unicode encoding (hopefully you won't be this century)
*When you are using a character with special meaning in HTML (such as a ' inside an attribute value delimited by ' characters)
*When you don't have a keyboard layout with which you can type the character you want to use
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43591461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Limitations of assertEqual The docs for assertEqual in Python unittest say
assertEqual(first, second, msg=None)
Test that first and second are equal. If the values do not compare equal, the test will fail
If my inputs, first & second are deep nested objects (e.g. dict of list of dict and list etc.), are there any limitation to what cannot be compared with the above assert statement? So far, I know that if at any depth, there's a list, its order has to match on both sides (because that's how I would normally compare a list).
There's no specific mention of nested objects in the docs and I couldn't find a clear answer to it.
A: assertEqual calls the appropriate type equality function (if available). e.g. assertEqual on lists actually calls assertListEqual. If no type equality function is specified, assertEqual simply uses the == operator to determine equality.
Note that you can make and register your own type equality functions if you wish.
If you want to look at the actual implementation, assertListEqual simply delegates to assertSequenceEqual which ultimately uses != to compare items. If the sub-items are nested, it gets compared however python compares those items. For example, lists are considered equal if:
Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see Comparisons in the language reference.)
See the docs on python sequences.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28199240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How does Chai JS make function parentheses optional? I'm referring to the testing assertion library : http://chaijs.com/api/bdd/#false
You can write language chain assertions like the following:
expect(false).to.be.false;
expect() is obviously a global function, "to.be" looks like two properties, but how does the last part "false" work. I'm expecting that it would have to be a function call:
expect(false).to.be.false();
Is this 2015 ES syntax? I can't seem to find a reference to it in https://github.com/lukehoban/es6features
Stack Overflow says its not possible: How to implement optional parentheses during function call? (function overloading)
Can anyone shed some light on how something like this is implemented ?
Source Code: https://github.com/chaijs/chai/blob/master/lib/chai/core/assertions.js#L281
A: You can do this (and a lot of other stuff) with Object.defineProperty. Here's a basic example:
// our "constructor" takes some value we want to test
var Test = function (value) {
// create our object
var testObj = {};
// give it a property called "false"
Object.defineProperty(testObj, 'false', {
// the "get" function decides what is returned
// when the `false` property is retrieved
get: function () {
return !value;
}
});
// return our object
return testObj;
};
var f1 = Test(false);
console.log(f1.false); // true
var f2 = Test("other");
console.log(f2.false); // false
There's a lot more you can do with Object.defineProperty. You should check out the MDN docs for Object.defineProperty for detail.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37149599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How do I make a Bootstrap sass variable visible to another imported sass file? I am using bootstrap-sass in a Rails application. So far, everything has worked fine, but I have just tried to import another third-party sass file that uses bootstrap variables and it cannot see them.
In my application.css.scss
*= require bootstrap_local
In bootstrap_local.css.scss
@import "bootstrap";
@import "bootstrap-social";
When I do a page access, I get a Rails error
Undefined variable: "$line-height-computed".
(in .../app/assets/stylesheets/bootstrap-social.scss:11)
The variable needed by bootstrap-social.scss is defined in the previously imported bootstrap file (in fact it's defined in a partial bootstrap/variables that it includes).
As far as I understand, this should work because bootstrap_local is required, which means that everything in it is compiled together in one scope, so everything imported into bootstrap_local is treated as being one large file. Perhaps I have this wrong?
If I throw an @import "bootstrap"; into bootstrap-social.scs then it works fine. But I should not need to do this, so I either doing something wrong or I there is some misconfiguration with my setup.
What do I need to do to fix this?
Gems:
*
*bootstrap-sass-3.1.1.1
*sass-rails-4.0.3
System:
*
*Rails 4.0.1
*ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux]
(Bootstrap Social is a set of social sign-in buttons made in pure CSS based on Bootstrap and Font Awesome.)
A: The problem described in the question can be resolved by changing the application.css.scss manifest to use import instead of require:
@import "bootstrap_local";
It is also necessary to remove any require_tree . from the manifest because it would otherwise require the same bootstrap_local file because it lies in its path.
On reflection, not having require tree . in the manifest is probably wise because it prevents unwanted files from being included. I only had it there because it's there by default in a new Rails project (the same goes for require_self; it's cleaner not to put that in the manifest).
In reference to the suggestion about prefixing the file with an underscore, this is a good thing to do when the you don't need file, like bootstrap-social in the question, to be a compiled into a separate CSS file. So, I did end up renaming it to _bootstrap-social.scss.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24780646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to extend browser script timeout I have some JQuery that takes a while to run and after a few second I get the error:
Stop running this script?
A script on this page is causing internet explorer to run slowley. If it continues to run, your computer may become unresponsive
Is there a way to extend the timeout? I guess that would mean extending the timeout on the persons machine who browses to the URL
A: If you're running your script under Google Chrome, you can disable the hang monitor with the flag: --disable-hang-monitor at the command line.
Under Mozilla based browsers (e.g., Firefox, Camino, SeaMonkey, Iceweasel), go to about:config and change the value of dom.max_script_run_time key.
A: If you're asking about programmatically changing it, you can't since it is an unsecured action and no browser will allow you to do it.
PS. As suggested above, try to understand the problem and refactor your code to reduce the execution time.
A: Under Internet Explorer the maximum instruction allowed to run in a script before seeing timeout dialog is controlled by a registry key :
HKEY_CURRENT_USER\Software\Microsoft\InternetExplorer\Styles\MaxScriptStatements
This is a maximum statements so it shouldn't be related to how fast the computer run. There might be others values that I'm not aware of.
The default value is 5 000 000. Are you doing too much ?
See http://support.microsoft.com/kb/175500.
A: jQuery has its own timeout property. See: http://www.mail-archive.com/[email protected]/msg15274.html
However the message you're getting is not a jQuery issue but a server or architecture issue.
Try to see if you're loading too many Ajax calls at the same time. See if you can change it to handle less calls at a time.
Also, check the server to see how long it takes to get a response. In long running XHR requests the server may take too long to respond. In this case the server-side application or service needs modification.
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/948906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Run Time Error 2147467259(80004005) while uploading excel data into access table I am using Office 2016 and trying to upload data from excel to an Access Database. I am attaching the code below. However while running the code, getting the error message @ Newconn.open line.
I am using windows 10 64 bit system and have activated Access 16.0 object library and ActiveX data object 2.5 library as well.
following code for your reference:
Sub test()
Dim Newconn As ADODB.Connection
Set Newconn = New ADODB.Connection
Dim RecordSet As ADODB.RecordSet
Set RecordSet = New ADODB.RecordSet
Dim Wb As Workbook, Ws As Worksheet
Set Wb = ThisWorkbook
Set Ws = Wb.Sheets("Sheet1")
Newconn.Open "Microsoft.ace.oledb.16.0;File Source:=C:\Users\Shazra\Desktop\Test\test.accdb"
RecordSet.Open "Table1", Newconn, adOpenDynamic, adLockOptimistic
RecordSet.Fields(0).Value = Ws.Range("A2").Value
RecordSet.Fields(1).Value = Ws.Range("B2").Value
RecordSet.Fields(2).Value = Ws.Range("C2").Value
RecordSet.Fields(3).Value = Ws.Range("D2").Value
RecordSet.Update
RecordSet.Close
Newconn.Close
End Sub
Thanks in advance for any suggestion.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58171831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django: Using current user as a foreign key to projects model I am building a web-app where people can write projects. The projects are stored in a model and I want to use the user as the foreign key so I can show the user their projects on a webpage. Instances are entered through a form.
The code always assigns the default value (1) and and not the user. Can any of you see what's causing this bug?
Here is the code for the creation of the model in models.py:
class PersonalProject(models.Model):
user = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField()
code = models.TextField()
def __str__(self):
return self.title
Heres the code for the form view to create the project in views.py:
def newproject(request):
if User is None:
messages.error(request, "Must be signed in")
return redirect('main:dashboard')
if request.method == "POST":
form = NewProjectForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('main:dashboard')
else:
messages.error(request, "Error")
else:
form = NewProjectForm()
return render(request,
"main/newproject.html",
{"form":form})
Heres the code for the homepage view in views.py:
def dashboard(request):
messages.info(request, request.user.username)
return render(request=request,
template_name="main/dashboard.html",
context={"structuredprojects": StructuredProject.objects.all(), "personalprojects": PersonalProject.objects.filter(user__username=request.user.username)})
I really hope you can help - I've been stuck on this for a while
A: You can set the user of the instance wrapped in the form to request.user:
from django.contrib.auth.decorators import login_required
@login_required
def newproject(request):
if request.method == "POST":
form = NewProjectForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('main:dashboard')
else:
messages.error(request, "Error")
else:
form = NewProjectForm()
return render(request,
"main/newproject.html",
{"form":form})
Note: You can limit views to a view to authenticated users with the
@login_required decorator [Django-doc].
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60873504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to convert a List into a number in python using recursion only def listIntoNumber(list,base):
//Enter code Here
Print(listIntoNumber([1,2,3,2,9],1) # It should return 12329
This above method listIntoNumber needs to be completed in rescursivly
A: Simple enough, if the list has one element, return it, else, multiply the first element by the base to the power of the list length minus 1 and add the output of the recursive call on the rest of the list.
NB. I imagine you meant base 10, base 1 doesn't really make sense ;)
def listIntoNumber(lst, base):
assert len(lst) > 0
if len(lst) == 1:
return lst[0]
return lst[0]*base**(len(lst)-1) + listIntoNumber(lst[1:], base)
print(listIntoNumber([1,2,3,2,9], 10))
# 12329
print(listIntoNumber([1,0,0,1,0], 2))
# 18
A: I assume base is the current number
def listIntoNumber(lst,base):
if len(lst)==0:
return base
base=base+lst[0]*(10**(len(lst)-1))
print(base)
lst.pop(0)
return listIntoNumber(lst,base)
print(listIntoNumber([1,2,3,2,9],0))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69940935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: why the Oracle support Concatenation Operator "||" write as "| |"? The Oracle SQL support Concatenation Operator || write as | |,
which means there is a blank space between two solid vertical bars.
Dose it may confused the tokenizer?
SELECT col1||col2||col3||col4 "Concatenation" FROM tab1; is working.
so dose SELECT col1| |col2| |col3| |col4 "Concatenation" FROM tab1;.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61095175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Plotting data from two different dataframes to a single Dash graph I'm trying to generate a Dash app which displays historical and forecasted housing prices. I've got the forecasted data stored in a different dataframe from the historical prices, and I'd like to plot them both on the same graph in Dash, and have the graph get updated via callback when the user picks a different city from a dropdown menu. I would like both traces of the graph to update when a value is selected in the dropdown. I've tried various things but can only get one trace from one dataframe plotted for the graph in my callback:
# --- import libraries ---
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from dash.dependencies import Output, Input
# --- load data ---
df_h = pd.read_csv('df_h.csv')
df_arima = pd.read_csv('df_arima.csv')
options = [] #each column in the df_h dataframe is an option for the dropdown menu
for column in df_h.columns:
options.append({'label': '{}'.format(column, column), 'value': column})
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# --- initialize the app ---
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# --- layout the dashboard ---
app.layout = html.Div(
children = [
html.Div([
html.Label('Select a feature from drop-down to plot'),
dcc.Dropdown(
id = 'city-dropdown',
options = options,
value = 'Denver, CO',
multi = False,
clearable = True,
searchable = True,
placeholder = 'Choose a City...'),
html.Div(id = 'forecast-container',
style = {'padding': '50px'}),
]),
],
)
# --- dropdown callback ---
@app.callback(
Output('forecast-container', 'children'),
Input('city-dropdown', 'value'))
def forecast_graph(value):
dff = df_h[['Date', value]] #'value' is identical between the two dataframes. references
dfa = df_arima[df_arima['City'] == value] # a col in dff and row values in dfa
return [
dcc.Graph(
id = 'forecast-graph',
figure = px.line(
data_frame = dff,
x = 'Date',
y = value).update_layout(
showlegend = False,
template = 'xgridoff',
yaxis = {'title': 'Median Home Price ($USD)'},
xaxis = {'title': 'Year'},
title = {'text': 'Median Home Price vs. Year for {}'.format(value),
'font': {'size': 24}, 'x': 0.5, 'xanchor': 'center'}
),
)
]
I was able to accomplish this in Plotly but can't figure out how to do it in Dash. This is what I want in Dash:
Plotly graph I am trying to reproduce in callback, that is linked to a dropdown menu
This is all I can get to work in Dash:
Only one dataframe plots in Dash
This is the code that works in plotly graph objects:
from statsmodels.tsa.arima_model import ARIMA
df_ml = pd.read_csv('df_ml.csv')
# --- data cleaning ---
df_pred = df_ml[df_ml['RegionName'] == city]
df_pred = df_pred.transpose().reset_index().drop([0])
df_pred.columns = ['Date', 'MedianHomePrice_USD']
df_pred['MedianHomePrice_USD'] = df_pred['MedianHomePrice_USD'].astype('int')
df_pred['Date'] = pd.to_datetime(df_pred['Date'])
df_pred['Date'] = df_pred['Date'].dt.strftime('%Y-%m')
df_model = df_pred.set_index('Date')
model_data = df_model['MedianHomePrice_USD']
def house_price_forecast(model_data, forecast_steps, city):
#--- ARIMA Model (autoregressive integrated moving average) ---
model = ARIMA(model_data, order = (2,1,2), freq = 'MS')
res = model.fit()
forecast = res.forecast(forecast_steps)
forecast_mean = forecast[0]
forecast_se = forecast[1]
forecast_ci = forecast[2]
df_forecast = pd.DataFrame()
df_forecast['Mean'] = forecast_mean.T
df_forecast['Lower_ci'], df_forecast['Upper_ci'] = forecast_ci.T
df_forecast['Date'] = pd.date_range(start = '2021-02', periods = forecast_steps, freq = 'MS')
df_forecast['Date'] = df_forecast['Date'].dt.strftime('%Y-%m')
df_forecast.index = df_forecast['Date']
fig = go.Figure()
fig.add_trace(go.Scatter(x = df_pred['Date'], y = df_pred['MedianHomePrice_USD'],
mode = 'lines', name = 'Median Home Price ($USD)',
line_color = 'rgba(49, 131, 189, 0.75)', line_width = 2))
fig.add_trace(go.Scatter(x = df_forecast.index, y = df_forecast['Mean'],
mode = 'lines', line_color = '#e6550d',
name = 'Forecast mean'))
fig.add_trace(go.Scatter(x = df_forecast.index, y = df_forecast['Upper_ci'],
mode = 'lines', line_color = '#e0e0e0', fill = 'tonexty',
fillcolor = 'rgba(225,225,225, 0.3)',
name = 'Upper 95% confidence interval'))
fig.add_trace(go.Scatter(x = df_forecast.index, y = df_forecast['Lower_ci'],
mode = 'lines', line_color = '#e0e0e0', fill = 'tonexty',
fillcolor = 'rgba(225,225,225, 0.3)',
name = 'Lower 95% confidence interval'))
fig.update_layout(title = 'Median Home Price in {}, {} - {} (Predicted)'.format(
city, model_data.idxmin()[:-3], df_forecast_mean.idxmax()[:-3]),
xaxis_title = 'Year', yaxis_title = 'Median Home Price ($USD)',
template = 'xgridoff')
fig.show()
house_price_forecast(model_data, 24, 'Denver, CO') #24 month prediction
Perhaps a more succinct way of asking this question: How do I add a trace to an existing Dash graph, with data from a different dataframe, and both traces get updated when the user selects a value from a single dropdown?
A: Figured it out...
Don't use the syntax I used above in your callback. Put the px.line call inside a variable(fig, in this case), and then use fig.add_scatter to add data from a different dataframe to the graph. Both parts of the graph will update from the callback.
Also, fig.add_scatter doesn't have a dataframe argument, so use df.column or df[column] (ex. 'dfa.Date' below)
# --- import libraries ---
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.express as px
from dash.dependencies import Output, Input
# --- load data ---
df_h = pd.read_csv('df_h.csv')
df_h['Date'] = pd.to_datetime(df_h['Date'])
df_arima = pd.read_csv('df_arima.csv')
df_arima['Date'] = pd.to_datetime(df_arima['Date'])
df_arima['Date'] = df_arima['Date'].dt.strftime('%Y-%m')
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
# --- initialize the app ---
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
dcc.Graph(id = 'forecast-container')
]
)
# --- dropdown callback ---
@app.callback(
Output('forecast-container', 'figure'),
Input('city-dropdown', 'value'))
def update_figure(selected_city):
dff = df_h[['Date', selected_city]]
# dff[selected_city] = dff[selected_city].round(0)
dfa = df_arima[df_arima['City'] == selected_city]
fig = px.line(dff, x = 'Date', y = selected_city,
hover_data = {selected_city: ':$,f'})
fig.add_scatter(x = dfa.Date, y = dfa.Mean,
line_color = 'orange', name = 'Forecast Mean')
fig.add_scatter(x = dfa.Date, y = dfa.Lower_ci,
fill = 'tonexty', fillcolor = 'rgba(225,225,225, 0.3)',
marker = {'color': 'rgba(225,225,225, 0.9)'},
name = 'Lower 95% Confidence Interval')
fig.add_scatter(x = dfa.Date, y = dfa.Upper_ci,
fill = 'tonexty', fillcolor = 'rgba(225,225,225, 0.3)',
marker = {'color': 'rgba(225,225,225, 0.9)'},
name = 'Upper 95% Confidence Interval')
fig.update_layout(template = 'xgridoff',
yaxis = {'title': 'Median Home Price ($USD)'},
xaxis = {'title': 'Year'},
title = {'text': 'Median Home Price vs. Year for {}'.format(selected_city),
'font': {'size': 24}, 'x': 0.5, 'xanchor': 'center'})
return fig
if __name__ == '__main__':
app.run_server(debug = True)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66678955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Field authenticationManager in *** required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found I have following class:
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("SampleClientId")
.secret("secret")
.authorizedGrantTypes("authorization_code")
.scopes("user_info")
.autoApprove(true) ;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
and following dependencies:
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
compile 'org.springframework.security.oauth:spring-security-oauth2:2.3.2.RELEASE'
}
When I start application I see following log:
"C:\Program Files\Java\jdk1.8.0_111\bin\java" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=50479 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.1\lib\idea_rt.jar=50480:C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_111\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\rt.jar;D:\work\sso\server\out\production\classes;D:\work\sso\server\out\production\resources;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-starter-web\2.0.1.RELEASE\88751ed76791d12425ce5a80476baf1749a44cf4\spring-boot-starter-web-2.0.1.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework.security.oauth\spring-security-oauth2\2.3.2.RELEASE\cf6e03591f593139f1d1d44278d962090aa226c9\spring-security-oauth2-2.3.2.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-starter-json\2.0.1.RELEASE\f2e1aeeb1ac02bfa1b4f7254633484af1866fc65\spring-boot-starter-json-2.0.1.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-starter\2.0.1.RELEASE\33abc1286b0aabea4f08ff4285d09e587835a716\spring-boot-starter-2.0.1.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-starter-tomcat\2.0.1.RELEASE\4b46f4aaff6c8a5a1c8184996d5e9e8a9354db8d\spring-boot-starter-tomcat-2.0.1.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.hibernate.validator\hibernate-validator\6.0.9.Final\b149e4cce82379f11f6129eb3187ca8ae5404005\hibernate-validator-6.0.9.Final.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework\spring-webmvc\5.0.5.RELEASE\a7fd53c7ad06b0fa7dd4ff347de1b2dc508739e\spring-webmvc-5.0.5.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework.security\spring-security-web\5.0.4.RELEASE\bd2592c928d043f70742fd8ae409f751a63132dd\spring-security-web-5.0.4.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework\spring-web\5.0.5.RELEASE\d51dbb5cabe72ae02e400577bac48f7fc94088de\spring-web-5.0.5.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework.security\spring-security-config\5.0.4.RELEASE\355fc8c3d1c61fe85915082587946ad346250d85\spring-security-config-5.0.4.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework.security\spring-security-core\5.0.4.RELEASE\f2924cd62fa8b14546b2b3c31dcd9e55abf9a5e\spring-security-core-5.0.4.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-autoconfigure\2.0.1.RELEASE\b0bf9d34ed70c6987a86cd58a009065e5fa02545\spring-boot-autoconfigure-2.0.1.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot\2.0.1.RELEASE\b8c5b14cbb0e52fdded8f98a8c1493cc74c7cf59\spring-boot-2.0.1.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework\spring-context\5.0.5.RELEASE\9cca4bf5acb693249a01c218f471c677b951d6e2\spring-context-5.0.5.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework\spring-aop\5.0.5.RELEASE\b11b61b94d7fb752a1c9bf3461d655c3084fae47\spring-aop-5.0.5.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework\spring-beans\5.0.5.RELEASE\984445863c0bbdaaf860615762d998b471a6bf92\spring-beans-5.0.5.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework\spring-expression\5.0.5.RELEASE\fc6c7a95aeb7d00f4c65c338b08d97767eb0dd99\spring-expression-5.0.5.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework\spring-core\5.0.5.RELEASE\1bd9feb1d9dac6accd27f5244b6c47cfcb55045c\spring-core-5.0.5.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\commons-codec\commons-codec\1.11\3acb4705652e16236558f0f4f2192cc33c3bd189\commons-codec-1.11.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.codehaus.jackson\jackson-mapper-asl\1.9.13\1ee2f2bed0e5dd29d1cb155a166e6f8d50bbddb7\jackson-mapper-asl-1.9.13.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework.boot\spring-boot-starter-logging\2.0.1.RELEASE\10681a28c95e9f9c0159327a1ed0c860517c7ad7\spring-boot-starter-logging-2.0.1.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\javax.annotation\javax.annotation-api\1.3.2\934c04d3cfef185a8008e7bf34331b79730a9d43\javax.annotation-api-1.3.2.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.yaml\snakeyaml\1.19\2d998d3d674b172a588e54ab619854d073f555b5\snakeyaml-1.19.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.datatype\jackson-datatype-jdk8\2.9.5\23e37f085279ba316c0df923513b81609e1d1f6\jackson-datatype-jdk8-2.9.5.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.datatype\jackson-datatype-jsr310\2.9.5\d1f0d11e816bc04e222a261106ca138801841c2d\jackson-datatype-jsr310-2.9.5.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.module\jackson-module-parameter-names\2.9.5\f824c60751ffb7bfc3a0d30dfe0e42317d8e67f5\jackson-module-parameter-names-2.9.5.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-databind\2.9.5\3490508379d065fe3fcb80042b62f630f7588606\jackson-databind-2.9.5.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.apache.tomcat.embed\tomcat-embed-websocket\8.5.29\37786f4ca8a1597a91a0f437e659a76d1fcc5bf1\tomcat-embed-websocket-8.5.29.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.apache.tomcat.embed\tomcat-embed-core\8.5.29\51eac5adde4bc019261b787cb99e5548206908e6\tomcat-embed-core-8.5.29.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.apache.tomcat.embed\tomcat-embed-el\8.5.29\893fb2c87ec1aa248a7911d76c0c06b3fca6bc9b\tomcat-embed-el-8.5.29.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\javax.validation\validation-api\2.0.1.Final\cb855558e6271b1b32e716d24cb85c7f583ce09e\validation-api-2.0.1.Final.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.jboss.logging\jboss-logging\3.3.2.Final\3789d00e859632e6c6206adc0c71625559e6e3b0\jboss-logging-3.3.2.Final.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\com.fasterxml\classmate\1.3.4\3d5f48f10bbe4eb7bd862f10c0583be2e0053c6\classmate-1.3.4.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.springframework\spring-jcl\5.0.5.RELEASE\f4a2854b9d865e8b86717595aec16f877f8c6489\spring-jcl-5.0.5.RELEASE.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.codehaus.jackson\jackson-core-asl\1.9.13\3c304d70f42f832e0a86d45bd437f692129299a4\jackson-core-asl-1.9.13.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\ch.qos.logback\logback-classic\1.2.3\7c4f3c474fb2c041d8028740440937705ebb473a\logback-classic-1.2.3.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.apache.logging.log4j\log4j-to-slf4j\2.10.0\f7e631ccf49cfc0aefa4a2a728da7d374c05bd3c\log4j-to-slf4j-2.10.0.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.slf4j\jul-to-slf4j\1.7.25\af5364cd6679bfffb114f0dec8a157aaa283b76\jul-to-slf4j-1.7.25.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-annotations\2.9.0\7c10d545325e3a6e72e06381afe469fd40eb701\jackson-annotations-2.9.0.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-core\2.9.5\a22ac51016944b06fd9ffbc9541c6e7ce5eea117\jackson-core-2.9.5.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\ch.qos.logback\logback-core\1.2.3\864344400c3d4d92dfeb0a305dc87d953677c03c\logback-core-1.2.3.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.slf4j\slf4j-api\1.7.25\da76ca59f6a57ee3102f8f9bd9cee742973efa8a\slf4j-api-1.7.25.jar;C:\Users\ntkachev\.gradle\caches\modules-2\files-2.1\org.apache.logging.log4j\log4j-api\2.10.0\fec5797a55b786184a537abd39c3fa1449d752d6\log4j-api-2.10.0.jar" com.my.sso.server.AuthorizationServerApplication
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.1.RELEASE)
2018-04-12 18:07:40.163 INFO 1252 --- [ main] c.m.s.s.AuthorizationServerApplication : Starting AuthorizationServerApplication on ntkachev with PID 1252 (D:\work\sso\server\out\production\classes started by ntkachev in D:\work\sso\server)
2018-04-12 18:07:40.166 INFO 1252 --- [ main] c.m.s.s.AuthorizationServerApplication : No active profile set, falling back to default profiles: default
2018-04-12 18:07:40.204 INFO 1252 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@8e0379d: startup date [Thu Apr 12 18:07:40 MSK 2018]; root of context hierarchy
2018-04-12 18:07:41.040 INFO 1252 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2018-04-12 18:07:41.060 INFO 1252 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-04-12 18:07:41.061 INFO 1252 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.29
2018-04-12 18:07:41.064 INFO 1252 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_111\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86)\Bitvise SSH Client;C:\Program Files\nodejs\;C:\Program Files (x86)\Skype\Phone\;C:\Windows\System32\;C:\Program Files\Java\jdk1.8.0_111\bin;C:\Program Files (x86)\apache\apache-maven-3.0.5\bin;C:\Program Files (x86)\gradle-2.3-all\gradle-2.3\bin;C:\Program Files\7-Zip;C:\Users\ntkachev\AppData\Local\Microsoft\WindowsApps;C:\Users\ntkachev\AppData\Roaming\npm;C:\Python27;D:\work\fiddler;.]
2018-04-12 18:07:41.138 INFO 1252 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-04-12 18:07:41.138 INFO 1252 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 936 ms
2018-04-12 18:07:41.237 INFO 1252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-04-12 18:07:41.237 INFO 1252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-04-12 18:07:41.237 INFO 1252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-04-12 18:07:41.237 INFO 1252 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-04-12 18:07:41.237 INFO 1252 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-04-12 18:07:41.237 INFO 1252 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-04-12 18:07:41.268 WARN 1252 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authServerConfig': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.authentication.AuthenticationManager' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2018-04-12 18:07:41.285 INFO 1252 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2018-04-12 18:07:41.292 INFO 1252 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-04-12 18:07:41.355 ERROR 1252 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field authenticationManager in com.my.sso.server.AuthServerConfig required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.
Process finished with exit code 1
What wrong with my configuration?
Actually I try to repeat ecxample from http://www.baeldung.com/sso-spring-security-oauth2 and I don't see explicit declaration of this bean
A: Need to add
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
@Configuration
public class UserSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public AuthenticationManager getAuthenticationManager() throws Exception {
return super.authenticationManagerBean();
}
}
A: Seems that I've found the solution to the issue, besides that we need add spring-boot-starter-security dependency, starting from spring-security 5.x bean of type AuthenticationManager is not autoconfigured for you, you need to define one by yourself
see: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide#authenticationmanager-bean
A: Alright, so in recent versions of Spring it is not enough to simply add the bean in your configurer class, you actually need to do something else.
Whatever dependency missing to autowire or to tcreate a bean, has to be specified in the main class of your application. For your case, let's say your WebSecurityConfigurerAdapter is under the package "configure", do the folowing:
@SpringBootApplication
@ComponentScan({"controller", "services", "configure"}) // This is what you need
@EntityScan("com.my.sso.server.models")
public class YourApplicationMainClass { ...
Also, when adding and overriding the bean, make sure @Override is above @bean:
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
A: The missing class is in spring-security-core. Try adding this dependency:
compile ('org.springframework.boot:spring-boot-starter-security')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49800117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: What does it mean when owner is None on an AWS S3 object? When viewing an object through the AWS S3 console, under owner I see no value. Viewing the object owner attribute on a query of objects indicates the value of owner for these objects is None.
An example query that would return this information:
[o.owner for o in s3.Bucket(bkt_name).objects.filter(Prefix=filter_pattern)]
In the above case, I would see a list returning w/ None values, eg:
[None, None, ...]
These objects were uploaded with ACL set to bucket owner controlled:
{"ACL": "bucket-owner-full-control"}
My expectation would be that the bucket owner would show up here, not a None. What I'd like to understand is what would cause a None to appear. Is this a permissions issue in that I am not allowed to see the owner name? I presume all objects must have an owner and thus None is not an "actual" option but merely rendered if I am in fact no allowed to see the actual string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70450325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Does not name a type error on constructor and destructor I'm trying to understand why this class is asking for a type on constructor and destructor, from what I've seen it seems that it would be something wrong with my class declaration but, it seems like I wrote it right. Also overloading operator<< seems to just return an error because it is also not recognized.
Board.h
#ifndef BOARD_H_
#define BOARD_H_
#include <string>
#include <iostream>
#include "Board.cpp"
class Board{
public:
Board(std::string p1_token, std::string p2_token, std::string blank_token);
~Board();
void clear();
//Accessors
int numRows();
int numColumns();
int numTokensInColumn(int colNum);
// bool is true if player 1 turn, false if player 2
// Returns blank if no one wins, winner token if some wins
std::string insert(int column, bool turn);
//ostream& operator<<(ostream& os, const Board& bd);
private:
std::string p1_token;
std::string p2_token;
std::string blank_token;
std::string ** ptr_columns;
int amt_cols;
int amt_rows;
};
#endif
Board.cpp
#include "Board.h"
#include <iostream>
#include <string>
Board::Board(std::string p1, std::string p2, std::string blank){
p1_token = p1;
p2_token = p2;
blank_token = blank;
amt_cols = 4;
amt_rows = 5;
ptr_columns = new std::string*[amt_cols];
//Right now all these are uniform
//Definition of order
//left-right first order of columns 0-end(4-1)
//Then
//down-up for each index of column ^, 0-end(5-1)
for(int I=0; I<amt_cols-1; ++I){
ptr_columns[I] = new std::string[5];
for(int V=0; V<amt_rows-1; ++V){
ptr_columns[I][V] = blank_token;
}
}
}
Board::~Board(){
delete [] ptr_columns;
}
ostream& Board::operator<<(ostream& os, const Board& bd){
for(int V = amt_rows-1; V>=0; --V){
for(int I = 0; I<amt_cols-1;++I){
os << bd.ptr_columns[I][V] << " ";
}
os << "\n";
}
return os;
}
Errors
Board.cpp:5:1: error: ‘Board’ does not name a type
Board::Board(std::string p1, std::string p2, std::string blank){
^~~~~
Board.cpp:25:1: error: ‘Board’ does not name a type
Board::~Board(){
^~~~~
Board.cpp:29:1: error: ‘ostream’ does not name a type
ostream& Board::operator<<(ostream& os, const Board& bd){
^~~~~~~
In file included from Board.cpp:1:0:
Board.h:19:2: error: ‘ostream’ does not name a type
ostream& operator<<(ostream& os, const Board& bd);
^~~~~~~
Board.cpp:29:1: error: ‘ostream’ does not name a type
ostream& Board::operator<<(ostream& os, const Board& bd){
^~~~~~~
In file included from Board.h:5:0,
from connect_four_main.cpp:3:
Board.cpp:5:1: error: ‘Board’ does not name a type
Board::Board(std::string p1, std::string p2, std::string blank){
^~~~~
Board.cpp:25:1: error: ‘Board’ does not name a type
Board::~Board(){
^~~~~
Board.cpp:29:1: error: ‘ostream’ does not name a type
ostream& Board::operator<<(ostream& os, const Board& bd){
^~~~~~~
In file included from connect_four_main.cpp:3:0:
Board.h:19:2: error: ‘ostream’ does not name a type
ostream& operator<<(ostream& os, const Board& bd);
A: You have a number of issues.
Don't #include .cpp files.
Your << operator should be declared as a free function not a member function, declare it as a friend instead:
class Board{
...
friend std::ostream& operator<<(std::ostream& os, const Board& bd);
...
}
Your operator uses some member variables from this rather than bd, the correct implementation is:
std::ostream& operator<<(std::ostream& os, const Board& bd){
for(int V = bd.amt_rows-1; V>=0; --V){
for(int I = 0; I<bd.amt_cols-1;++I){
os << bd.ptr_columns[I][V] << " ";
}
os << "\n";
}
return os;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60140562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Buttons don't have uniform padding I am using a headless UI tab component and when I add padding to the buttons as in below code, I expect all the buttons to have uniform padding but there seems to be some issues here.
Headless UI tabs component:
<Tab.List className="flex sm:flex-col">
<Tab>
{({ selected }) => (
<button
className={`px-6 py-4 ${selected ? 'bg-white text-black' : 'bg-red-600 text-white'}`}
>
Frontend
</button>
)}
</Tab>
<Tab>
{({ selected }) => (
<button
className={`px-6 py-4 ${selected ? 'bg-white text-black' : 'bg-red-600 text-white'}`}
>
Backend
</button>
)}
</Tab>
<Tab>
{({ selected }) => (
<button
className={`px-6 py-4 ${selected ? 'bg-white text-black' : 'bg-red-600 text-white'}`}
>
Multimedia
</button>
)}
</Tab>
</Tab.List>
Result:
Possible Cause:
Button padding seems to be rendering twice by headless UI otherwise button itself has the required padding.
Also if it is of any help, I have added the .babelrc.js and updated the _document.js for making twin macro work:
.babelrc.js
module.exports = {
presets: [['next/babel', { 'preset-react': { runtime: 'automatic' } }]],
plugins: ['babel-plugin-macros', ['styled-components', { ssr: true }]],
}
_document.js
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
Any help or suggestion is greatly appreciated
EDIT:
Changing the button to a div solved the issue. I am still not quite sure how it solved though
A: Tab itself renders a button. So, to prevent nesting a button element inside another, you need to use the as prop on the Tab component:
<Tab.List className="flex sm:flex-col">
<Tab as={Fragment}>
{({ selected }) => (
<button
className={`px-6 py-4 ${
selected ? 'bg-white text-black' : 'bg-red-600 text-white'
}`}
>
Frontend
</button>
)}
</Tab>
{/*...*/}
</Tab.List>
You can also do:
<Tab.List className="flex sm:flex-col">
<Tab
className={({ selected }) =>
`px-6 py-4 ${selected ? 'bg-white text-black' : 'bg-red-600 text-white'}`
}
>
Frontend
</Tab>
{/*...*/}
</Tab.List>
Reference: https://headlessui.dev/react/tabs#styling-the-selected-tab
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69568807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Return const reference to local variable correctly Additionally to the answers 1, 2, 3 and GotW88, assume the following methods
QString createString()
{
return QString("foobar");
}
const QString& getString()
{
return createString();
}
This will yield the famous "warning C4172: returning address of local variable or temporary" with VS2013.
Now if i changed the second method to
const QString& getString()
{
const QString& binder = createString();
return binder;
}
Which does not report an error anymore. Is this a safe way to fix the warning without changing the signature of the API? Why does this work?
A: It doesn't work. That way you simply suppress the warning by making the situation harder to analyze. The behavior is still undefined.
A: Your "fix" doesn't.
To preserve the signature, you must make some tradeoffs. At the minimum, getString is not reentrant, and that can't be fixed other than returning a copy of the string. It is also not thread-safe, although that's fixable without changing the signature.
At a minimum, to preserve the signature you must retain the string yourself. A simple solution might look as follows:
const QString & getString() {
static QString string = createString();
return string;
}
Another approach would be to make the string a class member, if your function is really a method:
class Foo {
QString m_getString_result;
public:
const QString & getString() {
m_getString_result = createString();
return m_getString_result;
}
};
For thread safety, you'd need to keep the result in thread local storage. That still wouldn't fix the reentrancy issue - as such, it's not fixable given the signature that you have.
A: This behavior is undefined.
const QString& getString()
{
const QString& binder = createString();
return binder;
}
Once binder goes out of scope. It is not defined any more.
You can make it defined by keeping the binder alive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31006807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: malloc(): invalid size (unsorted) on new unsigned char[] There are enormous amounts of memory-error related posts here on SO but none addresses my problem.
Consider this class (definition and declaration merged for an easy read):
#define SIZEMACRO(mem) *reinterpret_cast<uint32_t *>(mem)
class StoredRecord {
uint64_t idx;
unsigned char* mem;
public:
~StoredRecord() {
delete[] mem;
}
StoredRecord() : idx(0), mem(nullptr) {}
StoredRecord(uint64_t _idx, unsigned char* _mem) : idx(_idx), mem(new unsigned char[SIZEMACRO(_mem)]) {
memcpy(mem, _mem, SIZEMACRO(_mem));
}
static std::shared_ptr<StoredRecord> createShared(uint64_t _idx, unsigned char* _mem) {
return std::make_shared<StoredRecord>(_idx, _mem);
}
// Some getter for idx and mem
};
It doesnt do much, takes the memory and uses SIZEMACRO() (which evaluates the first bytes as uint32_t and uses this as the size, works well) to determinate the size of the memory chunk, allocates the same size and copies it.
These StoredRecord are kept in an std::vector<std::shared_ptr<StoredRecord>> m_records in another class.
No problem here whats-o-ever.
However, the code crashes when used as follows:
const uint32_t a = 1800;
const uint32_t b = 1900;
const uint32_t c = 2000;
unsigned char data1[a];
unsigned char data2[b];
unsigned char data3[c];
memset(data1, 0, a);
memset(data2, 0, b);
memset(data3, 0, c);
memcpy(data1, &a, sizeof(uint32_t));
memcpy(data2, &b, sizeof(uint32_t));
memcpy(data3, &c, sizeof(uint32_t));
m_records.push_back(StoredRecord::createShared(0, data1)); // fine
m_records.push_back(StoredRecord::createShared(1, data2)); // fine
// crashes with "malloc(): invalid size (unsorted)"
// at mem(new unsigned char[SIZEMACRO(_mem)])
m_records.push_back(StoredRecord::createShared(2, data3));
However, if I decrease c = 1900 everything is fine. With a, b or c above ~1950, it crashes with the malloc invalid size when run with GDB or run normaly.
I've also run my code with valgrind, there no crash happens and it dosn't even complain about that new unsigned char. I already double-checked the SIZEMACRO() and it evaluates fine to 1800, 1900 and 2000.
What puzzles me is the error-message "invalid size". Why can't I malloc more then ~1950 bytes here?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58199753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Excel - Sumproduct two arrays from the same column I'm looking for a way to produce a sumproduct between two arrays derived from the same column of values. For example:
A B C
1 FC 100
1 ST 5
2 FC 120
2 ST 3
3 FC 26
3 ST 7
In this scenario, I need a formula that calculates (100*5)+(120*3)+(26*7), or in other words performs a sumproduct of values in column C when column B is "FC" and values in column C when column B is "ST".
I've searched for quite a while and have been unable to find a suitable answer. Any help would be appreciated. Thank you
A: As Scott Craner commented (please accept his answer, if he writes one):
SUMPRODUCT((B1:B5="FC")*(C1:C5*C2:C6))
This approach uses array references, multiplies them together, and then takes the SUMPRODUCT of the results. Working out from the second set of nested terms:
*
*C1:C5 returns the array [100,5,120,3,26]
*C2:C6 (offset by one row) returns [5,120,3,26,7]
Multiplying these arrays gives the intermediate array:
*
*[500,600,360,78,182]
Which is each number in column C multiplied by the one after it. However only every other result (indicated by the value "FC" in column B) is to be included in the final sum. This is accomplished using the other nested term, which tests the value of each cell of the specified range in order:
*
*B1:B5="FC" returns the array [TRUE,FALSE,TRUE,FALSE,TRUE]
Excel treats TRUE/FALSE values as 1/0 when multiplying (though not for addition/subtraction), so the SUMPRODUCT function sees:
*
*[1,0,1,0,1]*[500,600,360,78,182] => [500,0,360,0,182]
and then adds the values of the resulting products:
*
*500 + 0 + 360 + 0 + 182 = 1042
A: For this specific example.
{=SUM((IF(B1:B6="FC",C1:C6,0)*IF(B2:B7="ST",C2:C7,0)))}
This will only work if FC and ST alternate just like in the example. If it does not, you could quickly change it to fit this format by sorting column A primarily and column B secondarily.
Notice the array in the second if statement is offset by one cell. This allows the arrays to multiply in the manner desired. Also, since it is an array formula, make sure you use CTRL+SHIFT+Enter when you put it in its cell.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38339749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add MapView in an Activity who already had an "extends"? I'am developping an android application including swipe view with tab.
All page had his own layout, all of that is working great :D.
But I want add to one of this view a MapView ( from Google API ), so i need to extends my MainActivity ( the only one I have ) to MapActivity, but I can't ( nothing wrong here ):
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener{
so is there a way to manage my MapView from MainActivity ?
thanks a lot :)
( sorry for my poor english syntax )
A: Often when you stumble across a problem like this, you need to look at encapsulation rather than extension. Can't you use the MapView as a member variable?
If you check out the MapView API, it states that we must implement the Android life cycle for the MapView in order for it to function properly. So, if you use a MapView as a member variable, you need to override the following methods in your main activity to call the matching methods in the MapView:
onCreate(Bundle)
onResume()
onPause()
onDestroy()
onSaveInstanceState(Bundle)
onLowMemory()
As an example, your Activity would look like the following:
public final class MainActivity extends Activity {
private MapView mMapView;
@Override
public final void onCreate(final Bundle pSavedInstanceState) {
super(pSavedInstanceState);
this.mMapView = new MapView(this);
/* Now delegate the event to the MapView. */
this.mMapView.onCreate(pSavedInstanceState);
}
@Override
public final void onResume() {
super.onResume();
this.getMapView().onResume();
}
@Override
public final void onPause() {
super.onPause();
this.getMapView().onPause();
}
@Override
public final void onDestroy() {
super.onDestroy();
this.getMapView().onDestroy();
}
@Override
public final void onSaveInstanceState(final Bundle pSavedInstanceState) {
super.onSaveInstanceState(pSavedInstanceState);
this.getMapView().onSaveInstanceState(pSavedInstanceState);
}
@Override
public final void onLowMemory() {
super.onLowMemory();
this.getMapView().onLowMemory();
}
private final MapView getMapView() {
return this.mMapView;
}
}
A: The answer is no. It is not possible to utilize a MapView without extending MapActivity. As gulbrandr pointed out there is a similar question here, this may be of use for anyone attempting the same thing that I was.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21812402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make a dynamic circle clock in HTML5 Canvas I would like to make a circular clock with HTML and JS, using the <canvas>.
I wrote this code:
function updateClock ()
{
// Variables for the time
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
// Convert time variable in RADs
var RADcurrentTime = {
hours : currentHours * Math.PI * 2 / 24,
minutes : currentMinutes * Math.PI * 2 / 60,
seconds : currentSeconds * Math.PI * 2 / 60
};
// Compose the circle clock
var clock_canvas = document.getElementById("clock");
var context = clock_canvas.getContext("2d");
var hours_radius = 70;
context.beginPath();
context.arc(screen.availWidth/2, screen.availHeight/2, hours_radius, 0, RADcurrentTime.hours);
context.closePath();
context.lineWidth = 3;
context.stroke();
var minutes_radius = 50;
context.beginPath();
context.arc(screen.availWidth/2, screen.availHeight/2, minutes_radius, 0, RADcurrentTime.minutes);
context.closePath();
context.lineWidth = 3;
context.stroke();
var seconds_radius = 30;
context.beginPath();
context.arc(screen.availWidth/2, screen.availHeight/2, seconds_radius, 0, RADcurrentTime.seconds);
context.closePath();
context.lineWidth = 3;
context.stroke();
`
but it doesn't work. I put in the body tag onload="updateClock(); setInterval('updateClock()', 1000 )" and it still doesn't work. The only thing I get is a white screen...
Anyone can help me suggesting the cause?
A: You are not drawing your content relative to canvas but to screen which could result in a very different offset.
If your canvas is lets say 200 pixels wide and high and your screen is 1920x1080 then half of that would draw the clock from center point 960, 540, ie. way outside the limits of the canvas of (here) 200x200.
Instead of this:
context.arc(screen.availWidth/2,screen.availHeight/2, hours_radius, 0, RADcurrentTime.hours);
use something like this (assuming canvas is square size):
context.arc(canvas.width/2, canvas.height/2,hours_radius,0,RADcurrentTime.hours);
^^^^^^^^^^^^ ^^^^^^^^^^^^^
You may also get some useful input from this answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23658563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Python Optimized Comparison Between List of Dict I'm trying to see whether nodes reside within the volume of a sphere, and add the node id to a list. However, the efficiency of the algorithm is incredibly slow and I'm not sure how to improve it.
I have two lists. List A has the format [{'num': ID, 'x': VALUE, 'y': VALUE, 'z': VALUE] while List B has the format [{'x': VALUE, 'y': VALUE, 'z': VALUE, 'rad': VALUE}].
The size of both lists can run upwards of 100,000 items each.
My current code is posted below, but it's very inefficient.
filteredList = []
for i in range(len(sList)):
minx = (sList[i]['x']) - (sList[i]['radius'])
maxx = (sList[i]['x']) + (sList[i]['radius'])
miny = (sList[i]['y']) - (sList[i]['radius'])
maxy = (sList[i]['y']) + (sList[i]['radius'])
minz = (sList[i]['z']) - (sList[i]['radius'])
maxz = (sList[i]['z']) + (sList[i]['radius'])
for j in range(len(nList)):
if minx <= nList[j]['x'] <= maxx:
if miny <= nList[j]['y'] <= maxy:
if minz <= nList[j]['z'] <= maxz:
tmpRad = findRadius(sList[i],nList[j])
if tmpRad <= sList[i]['radius']:
filteredList.append(int(nList[j]['num']))
I'm at a loss and appreciate any ideas.
Edit: Adding extra information about the data format.
List A (nList) -- defines nodes, with locations x,y,z, and identifier num
[{'y': 0.0, 'x': 0.0, 'num': 1.0, 'z': 0.0},
{'y': 0.0, 'x': 1.0, 'num': 2.0, 'z': 0.0},
{'y': 0.0, 'x': 2.0, 'num': 3.0, 'z': 0.0},
{'y': 0.0, 'x': 3.0, 'num': 4.0, 'z': 0.0},
{'y': 0.0, 'x': 4.0, 'num': 5.0, 'z': 0.0},
{'y': 0.0, 'x': 5.0, 'num': 6.0, 'z': 0.0},
{'y': 0.0, 'x': 6.0, 'num': 7.0, 'z': 0.0},
{'y': 0.0, 'x': 7.0, 'num': 8.0, 'z': 0.0},
{'y': 0.0, 'x': 8.0, 'num': 9.0, 'z': 0.0},
{'y': 0.0, 'x': 9.0, 'num': 10.0, 'z': 0.0}]
List B (sList) -- defines spheres using x,y,z, radius
[{'y': 18.0, 'x': 25.0, 'z': 26.0, 'radius': 0.0056470000000000001},
{'y': 29.0, 'x': 23.0, 'z': 45.0, 'radius': 0.0066280000000000002},
{'y': 46.0, 'x': 29.0, 'z': 13.0, 'radius': 0.014350999999999999},
{'y': 0.0, 'x': 20.0, 'z': 25.0, 'radius': 0.014866000000000001},
{'y': 27.0, 'x': 31.0, 'z': 18.0, 'radius': 0.018311999999999998},
{'y': 10.0, 'x': 36.0, 'z': 46.0, 'radius': 0.024702000000000002},
{'y': 27.0, 'x': 13.0, 'z': 48.0, 'radius': 0.027300999999999999},
{'y': 14.0, 'x': 1.0, 'z': 13.0, 'radius': 0.033889000000000002},
{'y': 31.0, 'x': 20.0, 'z': 11.0, 'radius': 0.034118999999999997},
{'y': 23.0, 'x': 28.0, 'z': 8.0, 'radius': 0.036683}]
A: (This answer deals with simple optimisations and Python style; it works with the existing algorithm, teaching some points of optimisation, rather than replacing it with a more efficient one.)
Here are some points to start with to make the code easier to read and understand:
*
*Iterate over sList, not over range(len(sList)). for i in range(len(sList)) becomes for i in sList and sList[i] becomes i.
*No need for that tmpRad; put it inline.
*Instead of if a: if b: if c: use if a and b and c.
Now we're at this:
filteredList = []
for i in sList:
minx = i['x'] - i['radius']
maxx = i['x'] + i['radius']
miny = i['y'] - i['radius']
maxy = i['y'] + i['radius']
minz = i['z'] - i['radius']
maxz = i['z'] + i['radius']
for j in nList:
if minx <= j['x'] <= maxx and miny <= j['y'] <= maxy and minz <= j['z'] <= maxz and findRadius(i,j) <= i['radius']:
filteredList.append(int(j['num']))
(PEP 8 would recommend splitting that long line to lines of no more than 80 characters; PEP 8 would also recommend filtered_list and s_list and n_list rather than filteredList, sList and nList.)
I've put the findRadius(i, j) <= i['radius'] first for style and because it looks like it might be more likely to evaluate to false, speeding up calculations. Then I've also inlined the minx etc. variables:
filteredList = []
for i in sList:
for j in nList:
if findRadius(i, j) <= i['radius'] \
and i['x'] - i['radius'] <= j['x'] <= i['x'] + i['radius'] \
and i['y'] - i['radius'] <= j['y'] <= i['y'] + i['radius'] \
and i['z'] - i['radius'] <= j['z'] <= i['z'] + i['radius']:
filteredList.append(int(j['num']))
One thing to think about is that i['x'] - i['radius'] <= j['x'] <= i['x'] + i['radius'] could be simplified; try things like subtracting i['x'] from all three parts.
You can shorten this even more with a list comprehension.
filteredList = [int(j['num']) for j in nList for i in sList
if findRadius(i, j) <= i['radius']
and i['x'] - i['radius'] <= j['x'] <= i['x'] + i['radius']
and i['y'] - i['radius'] <= j['y'] <= i['y'] + i['radius']
and i['z'] - i['radius'] <= j['z'] <= i['z'] + i['radius']]
And finally, named tuples (this has the side-effect of making them immutable, too, which is probably desired? Also note it's Python 2.6 only, read the page for how you could do it with older versions of Python):
from collections import namedtuple
node = namedtuple('node', 'x y z num')
sphere = namedtuple('sphere', 'x y z radius')
nList = [
node(x=0.0, y=0.0, z=0.0, num=1.0),
node(x=1.0, y=0.0, z=0.0, num=2.0),
node(x=2.0, y=0.0, z=0.0, num=3.0),
node(x=3.0, y=0.0, z=0.0, num=4.0),
node(x=4.0, y=0.0, z=0.0, num=5.0),
node(x=5.0, y=0.0, z=0.0, num=6.0),
node(x=6.0, y=0.0, z=0.0, num=7.0),
node(x=7.0, y=0.0, z=0.0, num=8.0),
node(x=8.0, y=0.0, z=0.0, num=9.0),
node(x=9.0, y=0.0, z=0.0, num=10.0)]
sList = [
sphere(x=25.0, y=18.0, z=26.0, radius=0.0056470000000000001),
sphere(x=23.0, y=29.0, z=45.0, radius=0.0066280000000000002),
sphere(x=29.0, y=46.0, z=13.0, radius=0.014350999999999999),
sphere(x=20.0, y=0.0, z=25.0, radius=0.014866000000000001),
sphere(x=31.0, y=27.0, z=18.0, radius=0.018311999999999998),
sphere(x=36.0, y=10.0, z=46.0, radius=0.024702000000000002),
sphere(x=13.0, y=27.0, z=48.0, radius=0.027300999999999999),
sphere(x=1.0, y=14.0, z=13.0, radius=0.033889000000000002),
sphere(x=20.0, y=31.0, z=11.0, radius=0.034118999999999997),
sphere(x=28.0, y=23.0, z=8.0, radius=0.036683)]
Then, instead of sphere['radius'] you can do sphere.radius. This makes the code neater:
filteredList = [int(j.num) for j in nList for i in sList
if findRadius(i, j) <= i.radius
and i.x - i.radius <= j.x <= i.x + i.radius
and i.y - i.radius <= j.y <= i.y + i.radius
and i.z - i.radius <= j.z <= i.z + i.radius]
Or, without the list comprehension,
filteredList = []
for i in sList:
for j in nList:
if findRadius(i, j) <= i.radius \
and i.x - i.radius <= j.x <= i.x + i.radius \
and i.y - i.radius <= j.y <= i.y + i.radius \
and i.z - i.radius <= j.z <= i.z + i.radius:
filteredList.append(int(j.num))
Finally, choose nicer names; [style changed slightly as per comments, putting findRadius at the end as it's more likely to be computationally expensive - you're the best judge of that, though]
filteredList = [int(n.num) for n in nodes for s in spheres
if s.x - s.radius <= n.x <= s.x + s.radius and
s.y - s.radius <= n.y <= s.y + s.radius and
s.z - s.radius <= n.z <= s.z + s.radius and
findRadius(s, n) <= s.radius]
Or,
filteredList = []
for s in spheres:
for n in nodes:
if (s.x - s.radius <= n.x <= s.x + s.radius and
s.y - s.radius <= n.y <= s.y + s.radius and
s.z - s.radius <= n.z <= s.z + s.radius and
findRadius(s, n) <= s.radius):
filteredList.append(int(n.num))
(You could put srad = s.radius in the outer loop for a probable slight performance gain if desired.)
A: one we can remove from the sample
unless you need to iterate over a list by index, one shouldn't, also avoid using range, and merge ifs together
filteredList = []
for a in sList:
minx = (a['x']) - (a['radius'])
maxx = (a['x']) + (a['radius'])
miny = (a['y']) - (a['radius'])
maxy = (a['y']) + (a['radius'])
minz = (a['z']) - (a['radius'])
maxz = (a['z']) + (a['radius'])
for b in nList:
if minx <= b['x'] <= maxx and miny <= b['y'] <= maxy and minz <= b['z'] <= maxz:
tmpRad = findRadius(a,b)
if tmpRad <= a['radius']:
filteredList.append(int(b['num']))
A: First off, Python isn't built for that kind of iteration. Using indices to get at each element of a list is backwards, a kind of brain-damage that's taught by low-level languages where it's faster. In Python it's actually slower. range(len(whatever)) actually creates a new list of numbers, and then you work with the numbers that are handed to you from that list. What you really want to do is just work with objects that are handed to you from whatever.
While we're at it, we can pull out the common s['radius'] bit that is checked several times, and put all the if-checks for the bounding box on one line. Oh, and we don't need a separate 'tmpRad', and I assume the 'num's are already ints and don't need to be converted (if they do, why? Why not just have them converted ahead of time?)
None of this will make a huge difference, but it at least makes it easier to read, and definitely doesn't hurt.
filteredList = []
for s in sList:
radius = s['radius']
minx = s['x'] - radius
maxx = s['x'] + radius
miny = s['y'] - radius
maxy = s['y'] + radius
minz = s['z'] - radius
maxz = s['z'] + radius
for n in nList:
if (minx <= n['x'] <= maxx) and (miny <= n['y'] <= maxy) and \
(minz <= n['z'] <= maxz) and (findRadius(s, n) <= radius):
filteredList.append(n['num'])
Now it's at least clear what's going on.
However, for the scale of the problem we're working with, it sounds like we're going to need algorithmic improvements. What you probably want to do here is use some kind of BSP (binary space partitioning) technique. The way this works is:
*
*First, we rearrange the nList into a tree. We cut it up into 8 smaller lists, based on whether x > 0, whether y > 0 and whether z > 0 for each point (8 combinations of the 3 boolean results). Then each of those gets cut into 8 again, using the same sort of criteria - e.g. if the possible range for x/y/z is -10..10, then we cut the "x > 0, y > 0, z > 0" list up according to whether x > 5, y > 5, z > 5, etc. You get the idea.
*For each point in the sList, we check whether minx > 0, etc. The beautiful part: if minx > 0, we don't have to check any of the 'x < 0' lists, and if maxx < 0, we don't have to check any of the 'x > 0' lists. And so forth. We figure out which of the 8 "octants" of the space the bounding box intersects with; and for each of those, we recursively check the appropriate octants of those octants, etc. until we get to the leaves of the tree, and then we do the normal point-in-bounding-box, then point-in-sphere tests.
A: Actually, you could save all that by:
filteredList = [int(node['num']) for sphere in sList \
for node in nList if findRadius(sphere,node)<=sphere['radius']]
If the distance from a point to a sphere's globe is less than the sphere's radius, then I guess we can say it is in the sphere, right?
I assume findRadius is defined like:
def findRadius(sphere,node):
return ((node['x']-sphere['x'])**2 + \
(node['y']-sphere['y'])**2 + \
(node['z']-sphere['z'])**2)**.5
A: (AFAICT, the following solution is algorithmically faster than any other answer posted so far: approximately O(N log N) vs O(N²). Caveat: this assumes that you don't have massive amounts of overlap between bounding boxes.)
If you are allowed to pre-compute an index structure:
*
*Push all the min/max x values into a set and sort them, thus creating a list of vertical regions spanning the x-axis. Associate each region with the set of bounding boxes that contain it.
*Repeat this procedure for min/max y values, to create a list of horizontal regions, and associate each region with the set of bounding boxes it contains.
*For each point being tested:
*
*Use a binary chop to find the horizontal region that contains the point's x coordinate. What you really want, though, is the set of bounding boxes associated with the region.
*Likewise, find the set of bounding boxes associated with the y coordinate.
*Find the intersection of these two sets.
*Test the bounding boxes in this residue set using Pythagoras.
A: Taking in all this advice, I managed to come up with a solution that was about 50x faster than the original.
I realized that the bottleneck was in the datatype (list of dicts) I was using. Looping over multiple lists was incredibly slow in my cast and using sets was much more efficient.
First thing I did was to implement named tuples. I knew how my list of nodes was numbered which provided the hash I needed for efficiency.
def findNodesInSpheres(sList,nList,nx,ny,nz):
print "Running findNodesInSpheres"
filteredList = []
for a in sList:
rad = a.radius
minx = (a.x) - (rad) if (a.x - rad > 0) else 0
maxx = (a.x) + (rad) if (a.x + rad < nx ) else nx
miny = (a.y) - (rad) if (a.y - rad > 0) else 0
maxy = (a.y) + (rad) if (a.y + rad < ny ) else ny
minz = (a.z) - (rad) if (a.z - rad > 0) else 0
maxz = (a.z) + (rad) if (a.z + rad < nz ) else nz
boundingBox = set([ (i + j * (nx + 1) + k * (nx + 1) * (ny + 1)) for i in range (int(minx),int(maxx)+1)
for j in range (int(miny),int(maxy)+1) for k in range(int(minz),int(maxz)+1) ])
for b in sorted(boundingBox):
if findRadius(a,nList[b]) <= rad:
filteredList.append(nList[b].num)
return filteredList
Using set() instead of list provided massive speedups. The larger the data set (nx, ny, nz), the more the speedup.
It could still be improved using tree implementation and domain decomposition as has been suggested, but for the moment it works.
Thanks to everyone for the advice!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4311082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c++ std regexp why not matched? i wannna get keyword matching length
but, always match count is zero
why..?
string text = "sp_call('%1','%2','%a');";
std::regex regexp("%[0-9]");
std::smatch m;
std::regex_match(text, m, regexp);
int length = m.size();
cout << text.c_str() << " matched " << length << endl; // always 0
A: regex_match
Determines if the regular expression e matches the entire target character sequence, which may be specified as std::string, a C-string, or an iterator pair.
You need to use regex_search
Determines if there is a match between the regular expression e and some subsequence in the target character sequence.
Also you can use regex_iterator, example from here:
string text = "sp_call('%1','%2','%a');";
std::regex regexp("%[0-9]");
auto words_begin =
std::sregex_iterator(text.begin(), text.end(), regexp);
auto words_end = std::sregex_iterator();
std::cout << "Found "
<< std::distance(words_begin, words_end)
<< " words:\n";
for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
std::smatch match = *i;
std::string match_str = match.str();
std::cout << match_str << '\n';
}
Found 2 words:
%1
%2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49605813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pyspark partitionBy: How do I partition my data and then select columns I have the following data:
import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4], 'col3': [5, 6]}
df = pd.DataFrame(data=d)
I want to partition the data by 'col1', but I don't want the 'col1' variable to be in the final data. Is this possible?
The below code would partition by col1, but how do I ensure 'col1' doesn't appear in the final data?
from pyspark.sql.functions import *
df.write.partitionBy("col1").mode("overwrite").csv("file_path/example.csv",
header=True)
Final data would be two files that look like:
d1 = {'col2': [3], 'col3': [5]}
df1 = pd.DataFrame(data=d1)
d2 = {'col2': [4], 'col3': [6]}
df2 = pd.DataFrame(data=d2)
Seems simple, but i can't figure out how I can partition the data, but leave the variable used to partition out of the final csv?
Thanks
A: ONce you partition the data using
df.write.partitionBy("col1").mode("overwrite").csv("file_path/example.csv", header=True)
There will be partitions based on your col1.
Now while reading the dataframe you can specify which columns you want to use like:
df=spark.read.csv('path').select('col2','col3')
A: Below is the code for spark 2.4.0 using scala api-
val df = sqlContext.createDataFrame(sc.parallelize(Seq(Row(1,3,5),Row(2,4,6))),
StructType(Seq.range(1,4).map(f => StructField("col" + f, DataTypes.IntegerType))))
df.write.partitionBy("col1")
.option("header", true)
.mode(SaveMode.Overwrite)
.csv("/<path>/test")
It creates 2 files as below-
*
*col1=1 with actual partition file as below-
col2,col3
3,5
*col2=2 with actual partition file as below-
col2,col3
4,6
same for col2=2
I'm not seeing col1 in the file.
in python-
from pyspark.sql import Row
df = spark.createDataFrame([Row(col1=[1, 2], col1=[3, 4], col3=[5, 6])])
df.write.partitionBy('col1').mode('overwrite').csv(os.path.join(tempfile.mkdtemp(), 'data'))
api doc - https://spark.apache.org/docs/latest/api/python/pyspark.sql.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61761679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I use Sass variables with data attributes in HTML5 I am trying to achieve a background color change when scrolling, so I need to use a data-bg attribute like this in my HTML markup:
<div class="section" data-bg="#ccff00">
How can I use a SCSS/Sass variable instead of the Hex code? For example:
<div class="section" data-bg="$background-color">
So when I change the variables this color also changes without having to change the HTML markup.
A: You can add your variable into the :root selector (like Bootstrap do),
and use it with the css function var().
:root {
--bg-color: $background-color;
--text-color: $text-color;
}
If you want to get the value using jQuery :
jQuery(':root').css('--bg-color');
:root {
--bg-color: #f00;
--text-color: #0f0;
}
section {
height: 100px;
color: var(--text-color);
background-color: var(--bg-color);
}
<section>
Lorem ipsum ...
</section>
A: No, you cannot use sass Variables in Data Attribute directly but there is an indirect way of doing this.
In this way also you can change Variable from dark to light, and it will change the color from red to green.
But those both should be declared in your data-bg as i did. See this example.
[data-bg='dark']{
--text-color: red;
}
[data-bg='light']{
--text-color: green;
}
div {
color: var(--text-color);
}
<div data-bg="light"> testing green</div>
<div data-bg="dark"> testing red</div>
A: An instance of data-bg attribute you can use style attribute to store the variable.
In html:
<div class="section" style="--data-bg:#ccff00">
and in scss:
.section{
$bg: var(--data-bg);
width: 200px;
height: 200px;
background: $bg;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63846704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting `ld: directory not found for option` build error after installing cocoa pod I installed a new cocoa pod (LaunchDarkly) for my Xcode project, but I'm getting the following error in my CI server when trying to build the project:
⚠️ ld: directory not found for option '-F/Users/runner/Library/Developer/Xcode/DerivedData/ProjectName-hlaqakonueydmsgzoxgekwjpjyds/Build/Products/Debug-iphonesimulator/LDSwiftEventSource'
⚠️ ld: directory not found for option '-F/Users/runner/Library/Developer/Xcode/DerivedData/ProjectName-hlaqakonueydmsgzoxgekwjpjyds/Build/Products/Debug-iphonesimulator/LaunchDarkly'
❌ ld: framework not found LDSwiftEventSource
❌ clang: error: linker command failed with exit code 1 (use -v to see invocation)
How do I fix this?
A: I realized the issue was that I was still building the .xcodeproj file as shown below:
xcodebuild build-for-testing
-project ProjectName.xcodeproj
-scheme ProjectName
-destination 'platform=iOS Simulator,name=iPhone 12,OS=latest'
-testPlan UnitTests
| xcpretty
But since I was now using cocoa pods in my project, I needed to use the .xcworkspace file to build it:
xcodebuild build-for-testing
-workspace ProjectName.xcworkspace
-scheme ProjectName
-destination 'platform=iOS Simulator,name=iPhone 12,OS=latest'
-testPlan UnitTests
| xcpretty
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69110271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: edit text in android hi
i want to restrict the special characters (!,@,#,$ etc.) from entering in to Edit Text field in android. how to do this please any body help..
thnx.
A: You need to use input filter and set it on Edit Text with setFilters method
A: You need to look at the reference. EditTest inherits from TextView:
http://developer.android.com/reference/android/widget/TextView.html
There you can add an TextChangedListener:
addTextChangedListener(TextWatcher watcher)
Then you test for your special characters and remove them if they are found
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4498307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to persist OffsetTime and OffsetDateTime with JPA and Hibernate? How can I persist Java 8 OffsetTime and OffsetDateTime with Hibernate as proper SQL types (TIME_WITH_TIMEZONE and TIMESTAMP_WITH_TIMEZONE)?
I found a solution for LocalTime and LocalDateTime using EnhancedUserTypes in a blog.
How would the user types be for offset data?
A: Hibernate ORM 5.3 implements the JPA 2.2 standard.
Supported types from the Java 8 Date and Time API
The JPA 2.2 specification says that the following Java 8 types are supported:
*
*java.time.LocalDate
*java.time.LocalTime
*java.time.LocalDateTime
*java.time.OffsetTime
*java.time.OffsetDateTime
Hibernate ORM supports all these types, and even more:
*
*java.time.ZonedDateTime
*java.time.Duration
Entity mapping
Assuming you have the following entity:
@Entity(name = "DateTimeEntity")
public static class DateTimeEntity {
@Id
private Integer id;
@Column(name = "duration_value")
private Duration duration = Duration.of( 20, ChronoUnit.DAYS );
@Column(name = "instant_value")
private Instant instant = Instant.now();
@Column(name = "local_date")
private LocalDate localDate = LocalDate.now();
@Column(name = "local_date_time")
private LocalDateTime localDateTime = LocalDateTime.now();
@Column(name = "local_time")
private LocalTime localTime = LocalTime.now();
@Column(name = "offset_date_time")
private OffsetDateTime offsetDateTime = OffsetDateTime.now();
@Column(name = "offset_time")
private OffsetTime offsetTime = OffsetTime.now();
@Column(name = "zoned_date_time")
private ZonedDateTime zonedDateTime = ZonedDateTime.now();
//Getters and setters omitted for brevity
}
The DateTimeEntity will have an associated database table that looks as follows:
CREATE TABLE DateTimeEntity (
id INTEGER NOT NULL,
duration_value BIGINT,
instant_value TIMESTAMP,
local_date DATE,
local_date_time TIMESTAMP,
local_time TIME,
offset_date_time TIMESTAMP,
offset_time TIME,
zoned_date_time TIMESTAMP,
PRIMARY KEY (id)
)
Source: Mapping Java 8 Date/Time entity attributes with Hibernate
A: Since version 2.2, JPA offers support for mapping Java 8 Date/Time API, like LocalDateTime, LocalTime, LocalDateTimeTime, OffsetDateTime or OffsetTime.
Also, even with JPA 2.1, Hibernate 5.2 supports all Java 8 Date/Time API by default.
In Hibernate 5.1 and 5.0, you have to add the hibernate-java8 Maven dependency.
So, let's assume we have the following Notification entity:
@Entity(name = "Notification")
@Table(name = "notification")
public class Notification {
@Id
private Long id;
@Column(name = "created_on")
private OffsetDateTime createdOn;
@Column(name = "notify_on")
private OffsetTime clockAlarm;
//Getters and setters omitted for brevity
}
Notice that the createdOn attribute is a OffsetDateTime Java object and the clockAlarm is of the OffsetTime type.
When persisting the Notification:
ZoneOffset zoneOffset = ZoneOffset.systemDefault().getRules()
.getOffset(LocalDateTime.now());
Notification notification = new Notification()
.setId(1L)
.setCreatedOn(
LocalDateTime.of(
2020, 5, 1,
12, 30, 0
).atOffset(zoneOffset)
).setClockAlarm(
OffsetTime.of(7, 30, 0, 0, zoneOffset)
);
entityManager.persist(notification);
Hibernate generates the proper SQL INSERT statement:
INSERT INTO notification (
notify_on,
created_on,
id
)
VALUES (
'07:30:00',
'2020-05-01 12:30:00.0',
1
)
When fetching the Notification entity, we can see that the OffsetDateTime and OffsetTime
are properly fetched from the database:
Notification notification = entityManager.find(
Notification.class, 1L
);
assertEquals(
LocalDateTime.of(
2020, 5, 1,
12, 30, 0
).atOffset(zoneOffset),
notification.getCreatedOn()
);
assertEquals(
OffsetTime.of(7, 30, 0, 0, zoneOffset),
notification.getClockAlarm()
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29211210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Errors in code during the the creation downloader of search page in python The scope of the project is to download the results of a search page locally with the names page 1,page 3 etc. First, was made a code which just downloads the results of one page locally. The code is in follow lines and its written to compare the modification evolution and the problems which are appeared:
import urllib.request as urr
from urllib.parse import quote
from urllib.request import urlopen
response=urr.urlopen('http://archive.data.gov.gr/dataset?q=%CE%A0%CE%B5%CF%81%CE%B9%CE%B2%CE%B1%CE%BB%CE%BB%CE%BF%CE%BD'+quote('περιβαλλον') )
page=response.read()
print(page)
f=open('C:\page.html',"wb")
f.write(page)
f.close()
So the evolution of this set of code must be find in the result of search for example the Greek word "υγεια" if you type in the address bar http://archive.data.gov.gr/dataset?q=υγεία&page=3
the third page of the health results will appear (numbering starts at 1). So the parameter q = ALPHABETICAL indicates the question while page = INTEGRAL indicates the results page. The follow block of code try when we want to research a word-for example the word "περιβαλλον" to:a)The start page, even if we type 2 b) the final page, even if we type 4
The program, in this example -as written previously will create 3 files with names page2.html,page3.html,page4.html The code is :
import os, sys
import re
import urllib.request as urr
from urllib.parse import quote
from urllib.request import urlopen
#-*- coding: UTF-8 -*-
#coding: UTF-8
response=urr.urlopen('http://archive.data.gov.gr/dataset?q=%CF%85%CE%B3%CE%B5%CE%B9%CE%B1'+quote('υγεια') )
#response=urr.urlopen('http://archive.data.gov.gr/dataset?q=υγεία&page=3'+quote('υγεια') )
#page=response.read()
#page=findall"(?!\")http://archive.data.gov.gr/dataset?q=περιβάλλον&page=*(?=\")", response
pagea=print(re.findall("(?!\")http://archive.data.gov.gr/dataset?q=περιβάλλον&page=*(?=\")", str(response)))
pagea=response.read()#.decode('UTF-8')#
print(pagea)
f=open('C:\pagea.html',"wb")
for i in pagea:
f.write(pagea)
f.close()
In the comments is part of code which try to resolve the issues without any result. Any idea to sort and save result is welcome
The main problem is that it not appeared a way to create all the pages(page1,page2 etc)
A: Try to add the following line at the begin of your code :
# -*- coding: utf-8 -*-
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70145737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why html sections didn't open I have an html file on my desktop , it has some images and when I click on them I got a section of another page and the url of this page is like : "mysite.html/#section-name " but the problem is when I host this html file the first page is hosted with no problem but when i click on images nothing happened and also when I put mysite.com/#section-name I got just the first page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48776746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to assign value to mat-button? <button type="submit" mat-button value="PC_Job005" (click)="clickCard($event)">View Details</button>
I'm trying to assign value to this button on angular. On click I can't find the value anywhere in the MouseEvent object. How could I give mat-button a value and then access it in an on click or (click)?
A: you can
<button mat-button (click)="clickCard('PC_Job005')">..</button>
clickCard(value:any)
{
console.log(value)
}
//or
<button mat-button value="PC_Job005" (click)="clickCard($event)">..</button>
clickCard(event:any)
{
//see that you need use currentTarget
console.log(event.currentTarget.getAttribute('value'))
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64552862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I create a windows service in Delphi? I have been assigned an assignment to create such a service in delphi which will track the logged in user activity on the computer. For this i have to
*
*I want my service to be run in the background and should store the name of every ACTIVE window in particular time events.
*Learn how to create windows service in delphi
How should I get started?
A: Create a Windows service in Delphi:
http://www.devarticles.com/c/a/Delphi-Kylix/Creating-a-Windows-Service-in-Delphi/
A: You will want to do some research in the CBT hooks provided by the Microsoft SDK. They include the ability to be notified each time a window is created, among other things.
A: The Service code from Aldyn is able to track logged in users. Not sure if it is what you want, but it must surely be a good start. The vendor goes through fits of activity and sleep, so be sure it does what you want as-is.
Aldyn SvCOM
| {
"language": "en",
"url": "https://stackoverflow.com/questions/406181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there any way to rearrange excel data without copy paste? I have an excel file that contain country name and dates as column name.
+---------+------------+------------+------------+
| country | 20/01/2020 | 21/01/2020 | 22/01/2020 |
+--------- ------------+------------+------------+
| us | 0 | 5 | 6 |
+---------+------------+------------+------------+
| Italy | 20 | 23 | 33 |
+--------- ------------+------------+------------+
| India | 0 | 0 | 6 |
+---------+------------+------------+------------+
But i need to arrange column names country, date, and count. Is there any way to rearrange excel data without copy paste.
final excel sheet need to look like this
+---------+------------+------------+
| country | date | count |
+--------- ------------+------------+
| us | 20/01/2020 | 0 |
+---------+------------+------------+
| us | 21/01/2020 | 5 |
+---------+------------+------------+
| us | 22/01/2020 | 6 |
+---------+------------+------------+
| Italy | 20/01/2020 | 20 |
+--------- ------------+------------+
| Italy | 21/01/2020 | 23 |
+--------- ------------+------------+
| Italy | 22/01/2020 | 33 |
+--------- ------------+------------+
| India | 20/01/2020 | 0 |
+---------+------------+------------+
A: Unpivot using Power Query:
*
*Data --> Get & Transform --> From Table/Range
*Select the country column
*
*Unpivot Other columns
*Rename the resulting Attribute and Value columns to date and count
*Because the Dates which are in the header are turned into Text, you may need to change the date column type to date, or, as I did, to date using locale
M-Code
Source = Excel.CurrentWorkbook(){[Name="Table2"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"country", type text}, {"20/01/2020", Int64.Type}, {"21/01/2020", Int64.Type}, {"22/01/2020", Int64.Type}}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"country"}, "date", "count"),
#"Changed Type with Locale" = Table.TransformColumnTypes(#"Unpivoted Other Columns", {{"date", type date}}, "en-150")
in
#"Changed Type with Locale"
A: Power Pivot is the best way, but if you want to use formulas:
In F1 enter:
=INDEX($A$2:$A$4,ROUNDUP(ROWS($1:1)/3,0))
and copy downward. In G1 enter:
=INDEX($B$1:$D$1,MOD(ROWS($1:1)-1,3)+1)
and copy downward. H1 enter:
=INDEX($B$2:$D$4,ROUNDUP(ROWS($1:1)/3,0),MOD(ROWS($1:1)-1,3)+1)
and copy downward
The 3 in these formulas is because we have 3 dates in the original table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60905766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access to module config in Zend Framework 2 How I can get access to my module config from the controller?
A: I am really surprised at how obscure this is, because I had exactly the same problem and could not find a definitive answer. One would think the ZF2 documentation would say something about this. Anyhow, using trial and error, I came across this extremely simple answer:
Inside controller functions:
$config = $this->getServiceLocator()->get('Config');
Inside Module class functions (the Module.php file):
$config = $e->getApplication()->getServiceManager()->get('Config');
whereas $e is an instance of Zend\Mvc\MvcEvent
In general, the config is accessible from anywhere you have access to the global service manager since the config array is registered as a service named Config. (Note the uppercase C.)
This returns an array of the union of application.config.php (global and local) and your module.config.php. You can then access the array elements as you need to.
Even though the OP is quite old now, I hope this saves someone the hour or more it took me to get to this answer.
A: What exactly do you want to do in your controller with the module configuration? Is it something that can't be done by having the DI container inject a fully configured object into your controller instead?
For example, Rob Allen's Getting Started with Zend Framework 2 gives this example of injecting a configured Zend\Db\Table instance into a controller:
return array(
'di' => array(
'instance' => array(
'alias' => array(
'album' => 'Album\Controller\AlbumController',
),
'Album\Controller\AlbumController' => array(
'parameters' => array(
'albumTable' => 'Album\Model\AlbumTable',
),
),
'Album\Model\AlbumTable' => array(
'parameters' => array(
'config' => 'Zend\Db\Adapter\Mysqli',
)),
'Zend\Db\Adapter\Mysqli' => array(
'parameters' => array(
'config' => array(
'host' => 'localhost',
'username' => 'rob',
'password' => '123456',
'dbname' => 'zf2tutorial',
),
),
),
...
If you need to do additional initialization after the application has been fully bootstrapped, you could attach an init method to the bootstrap event, in your Module class. A blog post by Matthew Weier O'Phinney gives this example:
use Zend\EventManager\StaticEventManager,
Zend\Module\Manager as ModuleManager
class Module
{
public function init(ModuleManager $manager)
{
$events = StaticEventManager::getInstance();
$events->attach('bootstrap', 'bootstrap', array($this, 'doMoarInit'));
}
public function doMoarInit($e)
{
$application = $e->getParam('application');
$modules = $e->getParam('modules');
$locator = $application->getLocator();
$router = $application->getRouter();
$config = $modules->getMergedConfig();
// do something with the above!
}
}
Would either of these approaches do the trick?
A: for Beta5, you can add function like this in Module.php
public function init(ModuleManager $moduleManager)
{
$sharedEvents = $moduleManager->getEventManager()->getSharedManager();
$sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
$config = $e->getApplication()->getConfiguration();
$controller = $e->getTarget();
$controller->config = $config;
});
}
in controller, you can get config :
print_r($this->config);
A: To read module-only config your module should just implement LocatorRegisteredInterface
Before:
namespace Application;
class Module
{
// ...
}
After:
namespace Application;
use Zend\ModuleManager\Feature\LocatorRegisteredInterface;
class Module implements LocatorRegisteredInterface
{
// ...
}
That implementation says LocatorRegistrationListener to save module intance in service locator as namespace\Module
Then anywhere you can get access to your module:
class IndexController extends AbstractActionController
{
public function indexAction()
{
/** @var \Application\Module $module */
$module = $this->getServiceLocator()->get('Application\Module');
$moduleOnlyConfig = $module->getConfig();
// ...
}
}
A: There is a pull request ready now which pulls the module class (so the modules/foo/Module.php Foo\Module class) from the DI container. This gives several advantages, but you are also able to grab that module instance another time if you have access to the Zend\Di\Locator.
If your action controller extends the Zend\Mvc\Controller\ActionController, then your controller is LocatorAware. Meaning, upon instantiation your controller is injected with the locator knowing about modules. So, you can pull the module class from the DIC in your controller. Now, when your module consumes a config file and stores this inside the module class instance, you can create a getter to access that config data from any class with a locator. You probably have already an accessor with your module Foo\Module::getConfig()
While ZF2 is heavily under development and perhaps this code will change later on, this feature is currently covered by this test, with this the most relevant part:
$sharedInstance = $locator->instanceManager()->getSharedInstance('ListenerTestModule\Module');
$this->assertInstanceOf('ListenerTestModule\Module', $sharedInstance);
So with $sharedInstance your module class, you can access the config from there. I expect a shorthand for this feature soon, but this can only be done after PR #786 has been merged in ZF2 master.
A: You need to implements ServiceLocatorAwareInterface from your model. And then you can set setServiceLocator() and getServiceLocator() which give you direct access to the service manager. Take a look at this code sample https://gist.github.com/ppeiris/7308289
A: I created the module with controller plugin and view helper for reading a config in controllers and views. GitHub link __ Composer link
Install it via composer
composer require tasmaniski/zf2-config-helper
Register new module "ConfigHelper" in your config/application.config.php file
'modules' => array(
'...',
'ConfigHelper'
),
Use it in controller and view files
echo $this->configHelp('key_from_config'); // read specific key from config
$config = $this->configHelp(); // return config object Zend\Config\Config
echo $config->key_from_config;
A: you can also access any config value anywhere by this hack/tricks
$configReader = new ConfigReader();
$configData = $configReader->fromFile('./config.ini');
$config = new Config($configData, true);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8957274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: What is a good way to indicate a field is mandatory? I would like to indicate to the user that a particular textbox or combobox is mandatory. What is a neat way to do this?
Currently, I have a gradient red border around the textbox when the text is null or empty, but it seems a bit much when you show a form and a number of the fields are red. I'm looking for something that is clear, but is not so overwhelming to the user. Something subtle.
I would prefer to make the textbox indicate that the field is mandatory rather than say make the label bold or have an asterisk. What are my options or any ideas you might have.
A: A recent usability study suggests taking the opposite approach and indicating which fields are optional rather than required. Furthermore, try to ask for only what you really need in order to reduce the number of optional fields.
The reason is that users tend to assume all fields are required anyway. They may not understand or pay attention to the asterisk, whereas they readily understand clearly labeled optional fields.
Link to the study (see Guideline 5):
https://www.cxpartners.co.uk/our-thinking/web_forms_design_guidelines_an_eyetracking_study/
A: Just put a * in front on the mandatory fields. It's simple, yet effective. I think most people will know what this means. Also, when they try to submit and it fails, because some mandatory field was not filled in correctly, then you let the user know which field they need to change (by using those red borders, for instance). I think this is what most people are accustomed to.
Edit: I saw that you didn't want to use an asterisk by the way. I still think this is the best option, simply because I think most people will recognize it right away and know what to do :)
A: I do it this way. Mark the left-border of the element with 2px Red color.
A: you can also change background color of textbox..
A: It depends on your design, of course, but I prefer something simpler like the labels of the input being bold. The red outline, while clear, does have an "error" connotation associated with it, which might be misleading to the user. Bolding the labels is subtle, but easy to understand without being an eyesore.
A: I like the jquery 'example' plugin for text input fields. A subtle grey inlay for instructions or sample input.
See demo page here for an, ahem, example. http://mucur.name/system/jquery_example/
Depending on how many fields you have, it might be too cluttered, but light-colored, italicized text like:
first name (required)
last name (required)
might work for your app.
HTH
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1956655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: scatterplot() formatting in car package I want to differs the component of the scatterplot.
*
*the points
*the regression line (in green)
*the smoothed conditional spread (in red dashed line)
*the non-parametric regression smooth (solid line, red)
The output should be like this
But my code is:
scatterplot(wt ~ mpg, data = mtcars)
and the output is like this
anybody knows how to change the formatting color like the picture 1
A: You should be able to specify the colors:
scatterplot(wt ~ mpg, data = mtcars, col=c("green3", "red", "black"))
(These are the default colors; see ?scatterplot.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53904223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Meteor, Blaze: create a simple loop with each? A simple problem, but I can`t find the simple solution. Did I have to write a helper for that?
I want to create a specific amount of li items in a template. The concrete number is given through a parameter called max.
{{> rating max=10 value=rating }}
<template name="rating">
<ul class="rating">
{{#each ?}}
<li class="star">\u2605</li>
{{/each }}
</ul>
</template>
A: Im fine with:
Template.registerHelper('repeat', function(max) {
return _.range(max); // undescore.js but every range impl would work
});
and
{#each (repeat 10)}}
<span>{{this}}</span>
{{/each}}
A: From http://docs.meteor.com/#/full/blaze_each:
Constructs a View that renders contentFunc for each item in a
sequence.
So each must be used with a sequence (array,cursor), so you have to create a helper that create a sequence to use #each.
Usually view is customized by item value, but in your case an array with max size will do the job.
Or you can create a custom template helper where you can pass html to repeat and number of repetition and concat html in helper.
Something like(code not tested):
// Register helper
htmlRepeater = function (html,n) {
var out = '';
for(var i=0 ; i<n;i++)
out.contat(html);
return Spacebars.SafeString(out);
};
Template.registerHelper('repeat', htmlRepeater);
------------------------
// in template.html
{{{repeat '<li class="star">\u2605</li>' max}}}
A: Simply return the required number of items from the underlying helper:
html:
{{> rating max=10 value=rating }}
<template name="rating">
<ul class="rating">
{{#each myThings max}}
<li class="star">\u2605</li>
{{/each }}
</ul>
</template>
Note that max needs to be passed through the html template to the {{#each}}
js:
Template.rating.helpers({
myThings: function(max){
// return an array 0...max-1 (as convenient as any other set of values for this example)
return Array.apply(null, Array(max)).map(function (x, i) { return i; });
}
});
Of course if you were iterating over a collection then you could just limit your .find() to max.
I also notice your rating template isn't using the parameter value anywhere. Did you mean to do:
<ul class = "{{value}}">
or was the value supposed to be substituted elsewhere?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34225697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: javascript eval issue (let = new Array) Why does this work?
eval('let = new Array')
Please help me im confused
Tried to run it on: firefox, chrome.
Excepted result: error
A: It's because let is only restricted keyword when in strict mode MDN source:
let = new Array();
console.log(let);
VS
"use strict";
let = new Array();
console.log(let);
A: Let is the name of variable.
Example here:
let = new Array
foo = new Array
bar = new Array
console.log(let, foo, bar)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75529396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: angular 4 - http response from service to component without direct function return My http request has some layer to get the data needed for its request -
UPDATE - I added a observable variable as transportation - I didn't get it to work. It's under the //suggestion 's
component.ts
//make a post
service.getUserId(formData)
//suggestion - this.service.response.subscribe(x=>x)
Service.ts
//suggestion - response: Observable;
getUserId (formData){
http.get().subscribe( x => getSubmissionId(x))
}
getSubmissionId(x, formData){
http.get(...x).subscribe( y =>
{post(y, formData)}
)
}
post(y, formData){
options: formData - append to post
http.request('POST', ...y).subscribe(
x => console.log('response', x)
//suggestion: x => {
this.response = new Observable(
observer => {
() => observer.next(res)
}
)
}
)
}
There is no way to get the request up the chain returned.
How can I send the data to the component?
I tried a response:Observable at the top of my service and a this.service.response.subscribe(x=>x), but that seemed to be wrong.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48627853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP system() keeps giving input to console I'm a coder of a server, and when I crash the server I have no way to start it back up unless the host is here. I've been trying to execute the file via PHP, and so far so good. However, with this method, the server is spammed with "Usage: /say " (consolelikechat plugin). From what it seems, when I use the following:
chdir('C:/SERVERS/BUKKIT/');
system('"C:\\Program Files\\Java\\jre7\\bin\\java.exe" -server -Xincgc -Xmx8192M -jar craftbukkit.jar'); ?>
the input of '' is being sent to the server at a very high speed. I have tried using popen and shell_exec, however these do not even start the server. Running it from the .bat file just returns the command.
Sorry if this is not clear enough, it is the best I can do to explain the problem.
A: Try escaping your slashes maybe?
system('"C:\\Program Files\\Java\\jre7\\bin\\java.exe" -server -Xincgc -Xmx8192M -jar craftbukkit.jar 2>&1');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21064204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to implement flow for this query Create below three User Lookup fields Account-
Assigned Attorney
Assigned Paralegal
Managing Attorney
When an event is created, automatically add each of the users in these specific “fields” on an account as an attendee to each event at the point the event is created;
Assigned Attorney
Assigned Paralegal
Managing Attorney
For all future events on an Account calendar, when an assignment in one of the three fields below changes, automatically update the attendees on the event, removing any removed attendees and adding any added attendees.
Assigned Attorney
Assigned Paralegal
Managing Attorney
actually i am trying in this screen flow and I make 3 lookup field relation with user object. After i make the event but this sends error
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75238931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add dynamically functions into html I am sending html from server side to client side, and in the the client side i am catching the html and trying to insert JS/JQ function to it.
this is the html:
<div align=center style=background-image:url(/srv/admin/img/announcement/error_dynamic_icon.gif);height:70px;background-repeat:no-repeat;background-position:50% 50%;background-position:50% 50%>. </div>
<li id=announcement4 class=announcement>
<table class=tg>
<tr>
<th class=tg-031e rowspan=3 style=background-image:url(/srv/admin/img/announcement/maintenance_icon.png);background-position:50% 50%></th>
<th rowspan=3 class=border_separator></th>
<th class=title_style colspan=2>Title - 3 test</th>
</tr>
<tr>
<td class=tg_text colspan=2>Unfeeling so rapturous discovery he exquisite. Reasonably so middletons or impression by terminated. Old pleasure required removing elegance him had. Down she bore sing saw calm high. Of an or game gate west face shed. ?no great but music too old found arose. </td>
</tr>
<tr class=r2>
<td class=tg-031e></td>
<td class=tg-031e><input id=button4 type=button class=ajax_btn_right value=Confirm ></input><input id=checkbox4 type=checkbox class=ajax_checkbox ></input></td>
</tr>
</table>
</li>
<li id=announcement6 class=announcement>
<table class=tg>
<tr>
<th class=tg-031e rowspan=3 style=background-image:url(/srv/admin/img/announcement/general_message_icon.png);background-position:50% 50%></th>
<th rowspan=3 class=border_separator></th>
<th class=title_style colspan=2>Title - 5 test</th>
</tr>
<tr>
<td class=tg_text colspan=2>Now led tedious shy lasting females off. Dashwood marianne in of entrance be on wondered possible building. Wondered sociable he carriage in speedily margaret. Up devonshire of he thoroughly insensible alteration. An mr settling occasion insisted distance ladyship so. Not attention say frankness intention out dashwoods now curiosity. Stronger ecstatic as no judgment daughter speedily thoughts. Worse downs nor might she court did nay forth these. </td>
</tr>
<tr class=r2>
<td class=tg-031e></td>
<td class=tg-031e><input id=button6 type=button class=ajax_btn_right value=Confirm ></input><input id=checkbox6 type=checkbox class=ajax_checkbox ></input></td>
</tr>
</table>
</li>
<li id=announcement7 class=announcement>
<table class=tg>
<tr>
<th class=tg-031e rowspan=3 style=background-image:url(/srv/admin/img/announcement/external_link_icon.png);background-position:50% 50%></th>
<th rowspan=3 class=border_separator></th>
<th class=title_style colspan=2>Title - 6 test</th>
</tr>
<tr>
<td class=tg_text colspan=2>Increasing impression interested expression he my at. Respect invited request charmed me warrant to. Expect no pretty as do though so genius afraid cousin. Girl when of ye snug poor draw. Mistake totally of in chiefly. Justice visitor him entered for. Continue delicate as unlocked entirely mr relation diverted in. Known not end fully being style house. An whom down kept lain name so at easy. </td>
</tr>
<tr class=r2>
<td class=tg-031e></td>
<td class=tg-031e><input id=button7 type=button class=ajax_btn_right value=Confirm ></input><input id=checkbox7 type=checkbox class=ajax_checkbox ></input></td>
</tr>
</table>
</li>
<div class=footer align=center>Please confirm you have read and acted upon this message</div>
using jquery or javascript i want to add to each button a function, base on their class or id.
to on click event.
for eaxample:
jQuery.each( all buttons with the class/id name, function(add function to the button ) {
alert( 'hello world' );
});
A: You need to use a delegated event handler. Try this:
$(document).on('click', '#myElement', function() {
alert('hello world');
});
I used document as the primary selector as an example. You should use the closest element to those dynamically appended.
A: Demo
You can use ;
$( ".class_name" ).bind( "click", function() {
// your code here
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23539120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Two GetEnumerator methods? I really can't understand why, in this example, this class defines two GetEnumerator methods: one explicitly implementing the interface and the other one implicitly as I got it. So why?
class FormattedAddresses : IEnumerable<string>
{
private List<string> internalList = new List<string>();
public IEnumerator<string> GetEnumerator()
{
return internalList.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return internalList.GetEnumerator();
}
public void Add(string firstname, string lastname,
string street, string city,
string state, string zipcode)
{
internalList.Add($@"{firstname} {lastname} {street} {city}, {state} {zipcode}");
}
}
A:
why [...] this class defines two GetEnumerator methods:
Well, one is generic, the other is not.
The non-generic version is a relic from .NET v1, before generics.
You have class FormattedAddresses : IEnumerable<string> but IEnumerable<T> derives from the old interface IEnumerable.
So it effectively is class FormattedAddresses : IEnumerable<string>, IEnumerable and your class has to implement both. The two methods differ in their return Type so overloading or overriding are not applicable.
Note that the legacy version is implemented 'explicitly', hiding it as much as possible and it is often acceptable to not implement it:
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplemented();
}
Only in a full blown library class (as opposed to an application class) would you bother to make it actually work.
A: The second method implements the non-generic version of the method. Its an explicit interface implementation to avoid a name conflict (overloads cannot differ only by return type).
The whole class should be deleted anyway. Hold a list of FormattedAddress, don't make a custom List class for it!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54409072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do you word wrap a RichTextField for Blackberry I've been trying to modify a rich text field to display correctly in its half of the horizontal field.
The goal is this:
---------------------------
| address is | ***********|
| very long | ** IMAGE **|
| state, zip | ***********|
---------------------------
Where address is a single string separate from the city and zip.
I am modifying the address field like this:
RichTextField addrField = new RichTextField(address) {
public int getPreferredWidth() {
return 200;
}
protected void layout(int maxWidth,int maxHeight) {
super.layout(getPreferredWidth(),maxHeight);
setExtent(getPreferredWidth(), getHeight());
}
};
The results look like this:
-----------------------------
| address is ve| ***********|
| state, zip | ** IMAGE **|
| | ***********|
-----------------------------
where clearly the address is just going under the image. Both horizontal fields are static 200 pixels wide. It's not like the system wouldn't know where to wrap the address.
However, I have heard it is not easy to do this and is not done automatically.
I have had no success finding a direct answer online. I have found people saying you need to do it in a custom layout manager, some refer to the RichTextField API, which is of no use. But nobody actually mentions how to do it.
I understand that I may need to read character by character and set where the line breaks should happen. What I don't know is how exactly to do any of this. You can't just count characters and assume each is worth 5 pixels, and you shouldn't have to.
Surely there must be some way to achieve this in a way that makes sense.
Any suggestions?
A: I don't have an exact solution to your problem but in terms of measuring the width of text, if you have a reference to the Font object for the font being used in your field, you can call Font.getAdvance() to get the width of the specified text in pixels. This might help if you have to insert manual breaks in your text.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2716708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Background Seeding/Loading iOS Core Data Store My iOS 8.0 + app is essentially a dictionary app, presenting a read-only data set to the user in an indexed, easily navigable format. I have explored several strategies for loading the static data, and I have decided to ship the app with several JSON data files that are serialized and loaded into a Core Data store once when the app is first opened. The call to managedObjectContext.save(), therefore, will happen only once in the lifetime of the app, on first use.
From reading Apple's Core Data Programming Guide in the Mac Developer Library (updated Sept. 2015), I understand that Apple's recommended practice is to 1) separate the Core Data stack from the AppDelegate into a dedicated DataController object (which makes it seem odd that even in Xcode 7.2 the Core Data stack is still put in the AppDelegate by default, but anyway...); and
2) open (and, I assume, seed/load) the persistent store in a background thread with a dispatch_async block, like so :
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
//(get URL to persistent store here)
do {
try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
//presumably load the store from serialized JSON files here?
} catch { fatalError("Error migrating store: \(error)") }
}
I'm just getting started learning about concurrency and GCD, so my questions are basic:
1) If the data set is being loaded in a background thread, which could take some non-trivial time to complete, how does the initial view controller know when the data is finished loading so that it can fetch data from the ManagedObjectContext to display in a UITableView ?
2) Along similar lines, if I would like to test the completely loaded data set by running some fetches and printing debug text to the console, how will I know when the background process is finished and it's safe to start querying?
Thanks!
p.s. I am developing in swift, so any swift-specific tips would be tremendous.
A: Instead of trying to make your app import the read-only data on first launch (forcing the user to wait while the data is imported), you can import the data yourself, then add the read-only .sqlite file and data model to your app target, to be copied to the app bundle.
For the import, specify that the persistent store should use the rollback journaling option, since write-ahead logging is not recommended for read-only stores:
let importStoreOptions: [NSObject: AnyObject] = [
NSSQLitePragmasOption: ["journal_mode": "DELETE"],]
In the actual app, also specify that the bundled persistent store should use the read-only option:
let readOnlyStoreOptions: [NSObject: AnyObject] = [
NSReadOnlyPersistentStoreOption: true,
NSSQLitePragmasOption: ["journal_mode": "DELETE"],]
Since the bundled persistent store is read-only, it can be accessed directly from the app bundle, and would not even need to be copied from the bundle to a user directory.
A: Leaving aside whether loading a JSON at the first startup is the best option and that this question is four years old, the solution to your two questions is probably using notifications. They work from all threads and every listening class instance will be notified. Plus, you only need to add two lines:
*
*The listener (your view controller or test class for question 2) needs to listen for notifications of a specific notification name:
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.handleMySeedNotification(_:)), name: "com.yourwebsite.MyCustomSeedNotificationName", object: nil)
where @objc func handleMySeedNotification(_ notification: Notification) is the function where you are going to implement whatever should happen when a notification is received.
*The caller (your database logic) the sends the notification on successful data import. This looks like this:
NotificationCenter.default.post(name: "com.yourwebsite.MyCustomSeedNotificationName", object: nil)
This is enough. I personally like to use an extension to Notification.Name in order to access the names faster and to prevent typos. This is optional, but works like this:
extension Notification.Name {
static let MyCustomName1 = Notification.Name("com.yourwebsite.MyCustomSeedNotificationName1")
static let MyCustomName2 = Notification.Name("CustomNotificationName2")
}
Using them now becomes as easy as this: NotificationCenter.default.post(name: .MyCustomSeedNotificationName1, object: nil) and even has code-completion after typing the dot!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34566501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: keep only the images in tensorflow dataset? I am trying to create a AutoEncoder using tensorflow datasets as inputs and the outputs.
I loaded the tf_flowers dataset using tensorflow dataset.
splits = ["train[:80%]", "train[80%:90%]", "train[90%:100%]"]`
(ds_train, ds_validation, ds_test), info = tfds.load(name="tf_flowers", with_info=True, split=splits, as_supervised=False)
The data has loaded perfectly as expected.
Now what i want do is modify my datasets so that i have only the images i.e, my files and my labels should both be my images.
How can I modify my code to achieve this ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62491118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating an index by group Simple question, but can't seem to find the answer.
I am trying to divide all cells in a column with the first cell.
V1=c(4,5,6,3,2,7)
V2= c(2,4,5,8,7,9)
group=c(1,1,1,2,2,2)
D= data.frame(V1=V1, V2=V2, group=group)
D
V1 V2 group
1 4 2 1
2 5 4 1
3 6 5 1
4 3 8 2
5 2 7 2
6 7 9 2
This is what I would like to get:
V1 V2 group
1 1.0 1.0 1
2 1.3 2.0 1
3 1.5 2.5 1
4 1.0 1.0 2
5 0.7 0.9 2
6 2.3 1.1 2
A: A dplyr option:
D %>%
group_by(group) %>%
mutate_at(c("V1", "V2"), ~./first(.))
# A tibble: 6 x 3
# Groups: group [2]
V1 V2 group
<dbl> <dbl> <dbl>
1 1 1 1
2 1.25 2 1
3 1.5 2.5 1
4 1 1 2
5 0.667 0.875 2
6 2.33 1.12 2
A: Here is a one-liner base R solution,
D[-3] <- sapply(D[-3], function(i) ave(i, D$group, FUN = function(i)i / i[1]))
D
# V1 V2 group
#1 1.0000000 1.000 1
#2 1.2500000 2.000 1
#3 1.5000000 2.500 1
#4 1.0000000 1.000 2
#5 0.6666667 0.875 2
#6 2.3333333 1.125 2
A: A dplyr way:
library(dplyr)
D %>%
group_by(group) %>%
mutate_all(~ round(. / first(.), 1))
A data.table approach:
library(data.table)
setDT(D)[, lapply(.SD, function(x) round(x / x[1], 1)), by = group]
A: A base R solution:
split(D, D$group) <- lapply(split(D, D$group),
function(.) {
.[,1:2] <- as.data.frame(t(t(.[, 1:2]) / unlist(.[1,1:2])))
.
})
D
# V1 V2 group
# 1 1.0000000 1.000 1
# 2 1.2500000 2.000 1
# 3 1.5000000 2.500 1
# 4 1.0000000 1.000 2
# 5 0.6666667 0.875 2
# 6 2.3333333 1.125 2
A: An option with base R
by(D[-3], D[3], FUN = function(x) x/unlist(x[1,])[col(x)])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57411470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Varnish Cache invalidation after POST request I was not able answer on my question. But does Varnish invalidate cache of page after post request? For example I have page, where user can put his comment, after posting his comment, does Varnish purge cache, or not?
A: After little chat, on official IRC:
By default, meaning in builtin.vcl, cache lookup is bypassed for POST requests -- return(pass) from vcl_recv so it doesn't change anything in the cache, it just doesn't look in the cache, and the backend response is marked as uncacheable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55573253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Choose smallest value from lists given same coordinates in 2d list I have two lists:
a = [[9, 5], [9, 10000], [9, 10000], [5, 10000], [5, 10000], [10001, 10], [10001, 10]]
b = [19144.85, 8824.73, 26243.88, 23348.02, 40767.17, 55613.43, 40188.8]
I am trying to remove the repeated coordinates in a and remove the adjacent value in b but by leaving the smallest value. So for example coordinate [9,10000] is repeated twice with values in b of 8824.73 and 26243.88 the result should be two lists where there is only one [9,10000] with the smaller of b which is 8824.73.
So overall the result should look like:
aa = [[9,5],[9,10000],[5,10000],[10001,10]]
bb = [19144.85, 8824.73, 23348.02, 40188.8]
I am finding it difficult to formulate the problem and iterate through the lists and I am not sure how I can use the zip function. Any help is appreciated!
A: Here is an O(n) solution using collections.defaultdict:
from collections import defaultdict
dd = defaultdict(list)
for (key1, key2), value in zip(a, b):
dd[(key1, key2)].append(value)
aa = list(map(list, dd))
bb = list(map(min, dd.values()))
print(aa, bb, sep='\n'*2)
[[9, 5], [9, 10000], [5, 10000], [10001, 10]]
[19144.85, 8824.73, 23348.02, 40188.8]
Explanation
There are 3 steps:
*
*Create a dictionary mapping each pair of keys to a list of values. Be careful to use tuple as keys, which must be hashable.
*For unique keys, just extract your defaultdict keys, mapping to list so that you have a list of lists instead of list of tuples.
*For minimum values, use map with min.
Note on ordering
Dictionaries are insertion ordered in Python 3.6+, and this can be relied upon in 3.7+. In earlier versions, you can rely on consistency of ordering between dd.keys and dd.values provided no operations have taken place in between access of keys and values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53047889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: In TFS API, how do I get the full class name for a given test? I have an ITestCaseResult object in hand and I can't figure out how to extract the Test Class information from it. The object contains the test method's name in the TestCaseTitle property but there are a lot of duplicate titles across our code base and I would like more information.
Assuming I have Foo.Bar assembly with class Baz and method ThisIsATestMethod, I currently only have access to the ThisIsATestMethod information from the title, but I would like to obtain Foo.Bar.Baz.ThisIsATestMethod.
How can I do that using the TFS API?
Here's some stripped down code:
var def = buildServer.CreateBuildDetailSpec(teamProject.Name);
def.MaxBuildsPerDefinition = 1;
def.QueryOrder = BuildQueryOrder.FinishTimeDescending;
def.DefinitionSpec.Name = buildDefinition.Name;
def.Status = BuildStatus.Failed | BuildStatus.PartiallySucceeded | BuildStatus.Succeeded;
var build = buildServer.QueryBuilds(def).Builds.SingleOrDefault();
if (build == null)
return;
var testRun = tms.GetTeamProject(teamProject.Name).TestRuns.ByBuild(build.Uri).SingleOrDefault();
if (testRun == null)
return;
foreach (var outcome in new[] { TestOutcome.Error, TestOutcome.Failed, TestOutcome.Inconclusive, TestOutcome.Timeout, TestOutcome.Warning })
ProcessTestResults(bd, testRun, outcome);
...
private void ProcessTestResults(ADBM.BuildDefinition bd, ITestRun testRun, TestOutcome outcome)
{
var results = testRun.QueryResultsByOutcome(outcome);
if (results.Count == 0)
return;
var testResults = from r in results // The "r" in here is an ITestCaseResult. r.GetTestCase() is always null.
select new ADBM.Test() { Title = r.TestCaseTitle, Outcome = outcome.ToString(), ErrorMessage = r.ErrorMessage };
}
A: You can do this by downloading the TRX file from TFS and parsing it manually. To download the TRX file for a test run, do this:
TfsTeamProjectCollection tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://my-tfs:8080/tfs/DefaultCollection"));
ITestManagementService tms = tpc.GetService<ITestManagementService>();
ITestManagementTeamProject tmtp = tms.GetTeamProject("My Project");
ITestRunHelper testRunHelper = tmtp.TestRuns;
IEnumerable<ITestRun> testRuns = testRunHelper.ByBuild(new Uri("vstfs:///Build/Build/123456"));
var failedRuns = testRuns.Where(run => run.QueryResultsByOutcome(TestOutcome.Failed).Any()).ToList();
failedRuns.First().Attachments[0].DownloadToFile(@"D:\temp\myfile.trx");
Then parse the TRX file (which is XML), looking for the <TestMethod> element, which contains the fully-qualified class name in the "className" attribute:
<TestMethod codeBase="C:/Builds/My.Test.AssemblyName.DLL" adapterTypeName="Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.Adapter, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" className="My.Test.ClassName, My.Test.AssemblyName, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" name="Test_Method" />
A: Here you have a way to get the Assembly name:
foreach (ITestCaseResult testCaseResult in failures)
{
string testName = testCaseResult.TestCaseTitle;
ITmiTestImplementation testImplementation = testCaseResult.Implementation as ITmiTestImplementation;
string assembly = testImplementation.Storage;
}
Unfortunately, ITestCaseResult and ITmiTestImplementation don’t seem to contain the namespace of the test case.
Check the last response in this link, that might help.
Good Luck!
EDIT:
This is based on Charles Crain's answer, but getting the class name without having to download to file:
var className = GetTestClassName(testResult.Attachments);
And the method itself:
private static string GetTestClassName(IAttachmentCollection attachmentCol)
{
if (attachmentCol == null || attachmentCol.Count == 0)
{
return string.Empty;
}
var attachment = attachmentCol.First(att => att.AttachmentType == "TmiTestResultDetail");
var content = new byte[attachment.Length];
attachment.DownloadToArray(content, 0);
var strContent = Encoding.UTF8.GetString(content);
var reader = XmlReader.Create(new StringReader(RemoveTroublesomeCharacters(strContent)));
var root = XElement.Load(reader);
var nameTable = reader.NameTable;
if (nameTable != null)
{
var namespaceManager = new XmlNamespaceManager(nameTable);
namespaceManager.AddNamespace("ns", "http://microsoft.com/schemas/VisualStudio/TeamTest/2010");
var classNameAtt = root.XPathSelectElement("./ns:TestDefinitions/ns:UnitTest[1]/ns:TestMethod[1]", namespaceManager).Attribute("className");
if (classNameAtt != null) return classNameAtt.Value.Split(',')[1].Trim();
}
return string.Empty;
}
internal static string RemoveTroublesomeCharacters(string inString)
{
if (inString == null) return null;
var newString = new StringBuilder();
foreach (var ch in inString)
{
// remove any characters outside the valid UTF-8 range as well as all control characters
// except tabs and new lines
if ((ch < 0x00FD && ch > 0x001F) || ch == '\t' || ch == '\n' || ch == '\r')
{
newString.Append(ch);
}
}
return newString.ToString();
}
A: Since the details of the testcase are stored in the work item you can fetch the data by accessing the work item for the test case
ITestCaseResult result;
var testCase = result.GetTestCase();
testCase.WorkItem["Automated Test Name"]; // fqdn of method
testCase.WorkItem["Automated Test Storage"]; // dll
A: public string GetFullyQualifiedName()
{
var collection = new TfsTeamProjectCollection("http://tfstest:8080/tfs/DefaultCollection");
var service = collection.GetService<ITestManagementService>();
var tmProject = service.GetTeamProject(project.TeamProjectName);
var testRuns = tmProject.TestRuns.Query("select * From TestRun").OrderByDescending(x => x.DateCompleted);
var run = testRuns.First();
var client = collection.GetClient<TestResultsHttpClient>();
var Tests = client.GetTestResultsAsync(run.ProjectName, run.Id).Result;
var FullyQualifiedName = Tests.First().AutomatedTestName;
return FullyQualifiedName;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20356033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: While loop in R giving "argument is of length zero" error I've been doing some topic modelling (LDA), and I've created a matrix of the posterior probabilities that each document (in this case, a day's worth of tweets). I'd like to measure how focused each day's discussion is, so I'd like to see how many topics are needed to "explain" some percentage of that day's discussion. I'm able to do it for a small number of topics:
thresh<-.98
distribution98 <- function(x){
if (x[k]>thresh){x<-1}
else if(x[k]+x[k-1]>thresh){x<-2}
else if(x[k]+x[k-1]+x[k-2]>thresh){x<-3}
else {x<-4}}
apply(ndx, 2, short)
Where ndx is my matrix of posteriors (each column is a day, each row is a topic and I've sorted each column from lowest to higherst) and this particular function is looking for how many topics are needed to explain 98% of the discussion.
I'm trying to write a function that can do this for any number of topics, and I'm getting an error message that I don't understand:
k<-100
results<-vector(mode="numeric", length=324)
short<- function(x){ for (j in 1:ncol(ndx)) {
i<-0
total<-0
while(total < thresh){
total<-(total+x[k-i])
i<-(1+i)
results[j]<-i
}
}
}
apply(ndx, 2, short)
Error in while (total < thresh) { : argument is of length zero
My thought was that this would leave me with a vector (result) that was just a record of how large i had to get in order to push total above thresh. But I don't understand the error--total and thresh are both numeric, so total < thresh either has to be true or false?
A: I guess you are looking for something like this :
## giving a vector x and a threshold .thresh
## returns the min index, where the cumulative sum of x > .thresh
get_min_threshold <-
function(x,.thresh)
max(which(cumsum(x[order(x)]) < .thresh))+1
## apply the function to each column of the data.frame
lapply(ndx,get_min_threshold,.thresh=.98)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24086228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Hibernate and Postgres large objects - freeing Blob resources in entity finalize() method I have an application using EJB 3.0 and Hibernate running on JBoss 4.2.3 AS and the transactions controlled by the EJB.
I was facing a problem that there was several messages on Postgres log about large objects like "ERROR: invalid large-object descriptor: 0" and sometimes "ERROR: large object 488450 does not exist". The result was that everything worked fine in the application but sometimes (not always) Postgres couldn't commit the transaction after the hibernate commit (after all the code in the main EJB called method being executed).
I investigated the legacy code and found a superclass of all the entities that represents file storage in the database. In this class the file is represented by a Blob attribute and it is used by getBinaryStream() method. What i found weird is what is in the finalize() method of this class as bellow:
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "BIN_CONTENT", nullable = true, updatable = true)
protected Blob content;
@Override
protected void finalize() throws Throwable {
if (this.content != null) {
try {
IOUtils.closeQuietly(this.content.getBinaryStream());
} catch (Exception e) {
logger.severe("Error finalizing Blob stream");
}
try {
this.content.free();
} catch (AbstractMethodError e) {
} catch (SQLFeatureNotSupportedException e) {
} catch (UnsupportedOperationException e) {
} catch (Throwable e) {
logger.severe("Error finalizing Blob stream");
}
this.content = null;
}
super.finalize();
}
After i commented this code everything seemed to work fine. The question is:
Is that necessary? I want to understand what is going internally due the execution of this code that is causing the errors on the database side.
A: There are several problems with the code you've provided.
The first problem is finalize() timing.
java.sql.Blob implementation depends on the jdbc driver and usually the implementing class stores only identifier of the blob and when content is accessed (using getBinaryStream() for example) another call(s) to database is performed. This implies that at the moment when getBinaryStream() is invoked connection which was used to get blob should be still opened.
But JVM doesn't provide any guaranties when finalize will be invoked so accessing Blob in finalize is incorrect.
I don't know for sure if PostgreSQL jdbc driver uses this logic for blobs but I know for sure that java.sql.Array implementation has this limitation (that is you cannot invoke methods of array after connection is closed).
The second problem is that though blob mapping is defined as lazy even if client didn't use it blob field will always be loaded by finalize().
In general it is responsibility of the client to perform clean up when using blobs. The pattern for usage the blob is:
try {
blob = entity.getContent();
// ... use blob
} finally {
// ... do blob cleanup
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19452614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I conditionally add with boost MPL? I am trying to evaluate a bitset's value based on the type arguments provided. The function I have right now is this:
template <class Set, class PartialSet>
constexpr auto tupleBitset() {
using type =
typename mpl::fold<
PartialSet,
mpl::integral_c<unsigned long long, 0>,
mpl::eval_if<
mpl::has_key<Set, mpl::_2>,
mpl::plus<
mpl::_1,
mpl::integral_c<unsigned long long, 1ull << getIndex<Set, mpl::_2>()>
>,
mpl::_1
>
>::type;
return std::bitset<mpl::size<Set>::value>(type::value);
}
Basically the gist of the function's intent is to be able to create a bitset whose bits are created based off the intersection of Set and PartialSet, both of which are mpl::sets. The function getIndex is also provided:
template <class Set, class Index>
constexpr auto getIndex() {
return mpl::distance<
typename mpl::begin<Set>::type,
typename mpl::find<Set, Index>::type
>::type::value;
}
This approach doesn't seem to work, with the compile errors evaluating down to the following:
'value' is not a member of 'boost::mpl::same_as<U1> in 'not.hpp'
'C_': invalid template argument for 'boost::mpl::aux::not_impl', expected compile-time constant expression in not.hpp
Is it possible that the left shift is not a compile time constant?
It seems that the problem is with the call to getIndex, as the mpl::_2 is not being substituted. Unfortunately, I cannot figure out how to force the substitution.
A: Problem is that you pass the place_holder to the function getIndex.
You may transform your function in struct like that
template< typename Set, typename Index > struct getIndex
: mpl::integral_c<unsigned long long, ( mpl::distance<
typename mpl::begin<Set>::type,
typename mpl::find<Set, Index>::type
>::type::value )>
{
};
template <class Set, class PartialSet>
constexpr auto tupleBitset() {
using type =
typename mpl::fold<
PartialSet,
mpl::integral_c<unsigned long long, 0>,
mpl::eval_if<
mpl::has_key<Set, mpl::_2>,
mpl::plus<
mpl::_1,
mpl::shift_left<mpl::integral_c<unsigned long long, 1ull>,
getIndex<Set, mpl::_2>>
>,
mpl::_1
>
>::type;
return std::bitset<mpl::size<Set>::value>(type::value);
}
Demo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35659426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Write a String Message to Remote Server Using Socket in Android I am trying to write a simple message to a remote Server using Socket in Android, The remote server was provided to me, here is my attempt, it stops at out.write
@Override
protected String doInBackground(String... params) {
String comment = params[0];
Log.i(TAG_STRING, "Comment is " + comment);
String response = null;
Socket socket = null;
try {
socket = new Socket("www.regisscis.net", 8080);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
DataInputStream in = new DataInputStream(socket.getInputStream());
Log.i(TAG_STRING, "Calling Write");
out.writeBytes(comment);
out.flush();
String resposeFromServer = in.readUTF();
out.close();
in.close();
response = resposeFromServer;
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
Would anyone know what I am doing wrong,
A: Turns out that I to use out.println("message") instead of out.write("message") when I post to this server. So I have updated my method like so
@Override
protected String doInBackground(String... params) {
String comment = params[0];
String response = null;
Socket socket = null;
try {
socket = new Socket("www.regisscis.net", 8080);
if (socket.isConnected()) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
Log.i(TAG_STRING, "Calling Write");
out.println(comment);
String resposeFromServer = in.readLine();
out.close();
in.close();
response = resposeFromServer;
socket.close();
} else {
Log.i(TAG_STRING, "Socket is not connected");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25341563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails API + MongoDB passing parameters to the url i have simple API example with simple GET routing.
I have MongoDB and my document from collection look's like this:
{
"_id" : ObjectId("51411cf11b4cb1b19a7115c0"),
"name" : "some_name",
"type" : "some_type",
"services" : [
"service_one",
"service_two"
],
"location" : {
"type" : "some_type",
"description" : "Some description",
},
"address" : {
"street" : "some_street",
"building" : "building",
"post_code" : "some_post_code",
"city" : "some_city",
"province" : "some_province"
}
}
My controller:
class V1::DataController < V1::ApplicationController
def index
@data = Data.all
render 'v1/data/index'
end
def show
@data = Data.find_by(name: params[:id])
render json: @data
end
end
I use jbuilder to render my output.
Now, my question is, how to make that parameter passed in the url, was reflected in the json result ? For example, my Mongo document have "name", so i wanna sort result by name.
http://api.loc:3000/data?name=some_name
Can you write a simple example?
Thanks.
A: Some of the naming conventions used in your example are a little weird. If all you want to do is sort I would consider changing the "name" parameter to something more descriptive. Keeping with your example the following might help.
class V1::DataController < V1::ApplicationController
...
def index
#ASC
if data_params[:order].eql?('asc')
@data = Data.asc(data_params[:name])
else
#DESC
@data = Data.desc(data_params[:name])
end
render 'v1/data/index'
end
def data_params
params.permit(:name, :order)
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30007794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WCF Large SOAP Request Exception 400 Bad Request I am looking for solution to my WCF Error 400 Bad Request with SOAP request longer than 64K. I know there are a lot of solutions out there when I google it. However, I am still not successful in fixing my site to work. Hence, I am seeking for professional advice here.
Client Side Code:
Private Sub Calculate()
Dim svc As New XXXService.XXXServiceClient
Dim i As Integer
Dim attributes As List(Of XXXService.AttributesStruct)
Dim calculateSingleResponse As XXXService.SingleXXXResponseStruct
Try
attributes = New List(Of XXXService.AttributesStruct)
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_One", .AttributesValue = "1"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Two", .AttributesValue = "XXX"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Three", .AttributesValue = "1"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Four", .AttributesValue = "0"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Five", .AttributesValue = "1"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Six", .AttributesValue = "70"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Seven", .AttributesValue = "80"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Eight", .AttributesValue = "09.12.2012"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Nine", .AttributesValue = "12.12.2012"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Ten", .AttributesValue = "15.11.2012"})
i = 0
While i < 80
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Eleven[" & i.ToString & "]", .AttributesValue = "2"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Twelve[" & i.ToString & "]", .AttributesValue = "5"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Thirteen[" & i.ToString & "]", .AttributesValue = "1"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Fourteen[" & i.ToString & "]", .AttributesValue = "NA"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Fifteen[" & i.ToString & "]", .AttributesValue = "0"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Sixteen[" & i.ToString & "]", .AttributesValue = "0"})
i = i + 1
End While
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Seventeen", .AttributesValue = "0"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Eighteen", .AttributesValue = "0"})
attributes.Add(New XXXService.AttributesStruct With {.AttributesKey = "A_Nineteen", .AttributesValue = "0"})
calculateSingleResponse = _
svc.Calculate("Test", True, "XXX", attributes.ToArray(),{"P_XXX"})
svc.Close()
Response.Write("********************************************<br/>")
Response.Write("[ErrorCode: " & calculateSingleResponse.ErrorCode & "]<br/>")
Response.Write("[ErrorDescription: " & calculateSingleResponse.ErrorDescription & "]<br/>")
Catch ex As Exception
Response.Write("EXCEPTION:" & "<br/>" & ex.Message & "<br/>" & ex.StackTrace & "<br/>")
If Not ex.InnerException Is Nothing Then
Response.Write("INNER EXCEPTION:" & "<br/>" & ex.InnerException.Message & "<br/>" & ex.InnerException.StackTrace)
End If
End Try
End Sub
Client Side Config:
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147483647" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IXXXService" closeTimeout="10:01:00"
openTimeout="10:01:00" receiveTimeout="10:10:00" sendTimeout="10:01:00"
allowCookies="false" bypassProxyOnLocal="true" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="BasicHttpBehaviour_IXXXService">
<dataContractSerializer maxItemsInObjectGraph="2147483646" />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://127.0.0.1:999/XXXService.svc"
behaviorConfiguration="BasicHttpBehaviour_IXXXService" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IXXXService" contract="XXXService.IXXXService"
name="BasicHttpBinding_IXXXService" />
</client>
</system.serviceModel>
Server Side Config:
<system.serviceModel>
<services>
<service name="WcfClient.XXXService">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="BasicHttpBinding_IXXXService"
contract="WcfClient.IXXXService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<timeouts closeTimeout="00:01:10" openTimeout="00:01:00" />
</host>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="BasicHttpBinding_IXXXService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="true" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- For wcf caller to receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
<dataContractSerializer maxItemsInObjectGraph="2147483646"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
A: I have found the issue myself:
*
*Binding between server side and client side must be the same, hence I change both to basicHttpBinding
*Service name is case sensitive, I changed "WcfClient.XXXService" to "wcfClient.XXXService" and it works now.
Hope this can help others with the same difficulties =)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13761111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any online .plist editor? I'm interested in an online application like the tool that comes with XCode, that shows the keys and values as rows, in an editable manner and handles xml plists (I don't care if it handles binary ones as well).
A: So, I was wondering the exact same thing, and when I saw this question and its answer, I said "Screw it, I'm making one!" And so I did. Two days later, here's my answer to you:
http://tustin2121.github.io/jsPlistor/
jsPListor (version 1 as of Aug 8th, 2013) will allow you to paste in the contents of an xml plist into it (via the Import button) and edit it with drag and drop and the like. When you're done, hit Export and it will package it all up into a valid plist for you to copy and paste back into the file.
There's still some bugs and glaring vacancies (like the Data Editing Dialog), but it functions. Future versions will attempt to allow saving via html5 download, and loading of files into data rows.
Feel free to examine, contribute, and submit bugs at the github repo: https://github.com/tustin2121/jsPlistor
A: I have resigned myself to the fact that there probably isn't one I will ever find. What I have found, however, is that JSON format and text PList format are very similar, and there are plenty of JSON editors available online and for windows and mac both. It may not be suitable for your needs, but it suited my needs just fine. By using nothing more than a couple of find & replaces in Notepad you can get 90% of the way to a plist file. The only big issue is semicolons vs. commas.
If you're working on a small enough file, that could be done manually. With larger files, a simple utility app to convert JSON to PList files would probably be pretty simple to whip up if you've got the urge.
Again, this all applies only to text formatted plist files. Most plist editors on mac at least can save a plist in text format.
A: There's Plistinator - its a native C++/Qt app for Mac, Windows and Linux desktop. So not an online tool, but it is at least portable and runs cross-platform (in case that is what the request for a web-based editor was about).
I'm not sure if the JS version handles binary files (Plistinator does). If you have a Mac you could edit them via the JS editor if you convert binary to XML via
plutil -convert xml myfile.plist
Note that will over-write myfile.plist with the XML version, which may not represent all the same information that the binary version can.
Full-disclosure: I am the author of Plistinator and the $12.99 goes to pay for my ramen & rent.
A: I don't think there are any plist editors online, at least not as functional as Plist Editor with Xcode.
You could use an online XML-editor, like Xmlia2.0, and code it yourself.
Why would you ever want an online tool for editing XML-files when you've got Plist Editor from xcode?
A: I wrote one once back in the day (for the old non-XML plist files). The structure is very regular, so it's not hard to create something that looks and acts more or less like the XCode plist editor.
I don't know off-hand of any online XML editors, but they must exist. Given a DTD-savvy XML editor, you ought to be able to edit plist files pretty easily.
A: Any web app that accepts .txt documents will edit plists just fine. Likewise for .xml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1492497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: How to display Arraylist of type String in a dialogue I have a Arraylist of String type. How can i display it on a dialogue to a user and him select the one.also the need is to highlight the earlier selection in the made by the user.
Some code example will be helpful.
thanks
A: Try this code in ur onCreate
protected CharSequence[] Months = { "January", "February", "March", "April", "May","June", "July", "August", "September","October","November","December" };
Button selected_month = ( Button ) findViewById( R.id.button );
selected_month.setOnClickListener(new View.OnClickListener(){
new AlertDialog.Builder( <Classname>.this )
.setTitle( "Months" )
.setSingleChoiceItems( Months, 0, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(<Classname>.this, Months[which], Toast.LENGTH_SHORT).show();
}
})
.setPositiveButton( "OK", new DialogButtonClickHandler() )
.setNegativeButton("No", new DialogButtonClickHandler() )
.create();
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6028066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the most idiomatic way of working with an Iterator of Results? I have code like this:
let things = vec![/* ...*/]; // e.g. Vec<String>
things
.map(|thing| {
let a = try!(do_stuff(thing));
Ok(other_stuff(a))
})
.filter(|thing_result| match *thing_result {
Err(e) => true,
Ok(a) => check(a),
})
.map(|thing_result| {
let a = try!(thing_result);
// do stuff
b
})
.collect::<Result<Vec<_>, _>>()
In terms of semantics, I want to stop processing after the first error.
The above code works, but it feels quite cumbersome. Is there a better way? I've looked through the docs for something like filter_if_ok, but I haven't found anything.
I am aware of collect::<Result<Vec<_>, _>>, and it works great. I'm specifically trying to eliminate the following boilerplate:
*
*In the filter's closure, I have to use match on thing_result. I feel like this should just be a one-liner, e.g. .filter_if_ok(|thing| check(a)).
*Every time I use map, I have to include an extra statement let a = try!(thing_result); in order to deal with the possibility of an Err. Again, I feel like this could be abstracted away into .map_if_ok(|thing| ...).
Is there another approach I can use to get this level of conciseness, or do I just need to tough it out?
A: There are lots of ways you could mean this.
If you just want to panic, use .map(|x| x.unwrap()).
If you want all results or a single error, collect into a Result<X<T>>:
let results: Result<Vec<i32>, _> = result_i32_iter.collect();
If you want everything except the errors, use .filter_map(|x| x.ok()) or .flat_map(|x| x).
If you want everything up to the first error, use .scan((), |_, x| x.ok()).
let results: Vec<i32> = result_i32_iter.scan((), |_, x| x.ok());
Note that these operations can be combined with earlier operations in many cases.
A: filter_map can be used to reduce simple cases of mapping then filtering. In your example there is some logic to the filter so I don't think it simplifies things. I don't see any useful functions in the documentation for Result either unfortunately. I think your example is as idiomatic as it could get, but here are some small improvements:
let things = vec![...]; // e.g. Vec<String>
things.iter().map(|thing| {
// The ? operator can be used in place of try! in the nightly version of Rust
let a = do_stuff(thing)?;
Ok(other_stuff(a))
// The closure braces can be removed if the code is a single expression
}).filter(|thing_result| match *thing_result {
Err(e) => true,
Ok(a) => check(a),
}
).map(|thing_result| {
let a = thing_result?;
// do stuff
b
})
The ? operator can be less readable in some cases, so you might not want to use it.
If you are able to change the check function to return Some(x) instead of true, and None instead of false, you can use filter_map:
let bar = things.iter().filter_map(|thing| {
match do_stuff(thing) {
Err(e) => Some(Err(e)),
Ok(a) => {
let x = other_stuff(a);
if check_2(x) {
Some(Ok(x))
} else {
None
}
}
}
}).map(|thing_result| {
let a = try!(thing_result);
// do stuff
b
}).collect::<Result<Vec<_>, _>>();
You can get rid of the let a = try!(thing); by using a match in some cases as well. However, using filter_map here doesn't seem to help.
A: Since Rust 1.27, Iterator::try_for_each could be of interest:
An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error.
This can also be thought of as the fallible form of for_each() or as the stateless version of try_fold().
A: You can implement these iterators yourself. See how filter and map are implemented in the standard library.
map_ok implementation:
#[derive(Clone)]
pub struct MapOkIterator<I, F> {
iter: I,
f: F,
}
impl<A, B, E, I, F> Iterator for MapOkIterator<I, F>
where
F: FnMut(A) -> B,
I: Iterator<Item = Result<A, E>>,
{
type Item = Result<B, E>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|x| x.map(&mut self.f))
}
}
pub trait MapOkTrait {
fn map_ok<F, A, B, E>(self, func: F) -> MapOkIterator<Self, F>
where
Self: Sized + Iterator<Item = Result<A, E>>,
F: FnMut(A) -> B,
{
MapOkIterator {
iter: self,
f: func,
}
}
}
impl<I, T, E> MapOkTrait for I
where
I: Sized + Iterator<Item = Result<T, E>>,
{
}
filter_ok is almost the same:
#[derive(Clone)]
pub struct FilterOkIterator<I, P> {
iter: I,
predicate: P,
}
impl<I, P, A, E> Iterator for FilterOkIterator<I, P>
where
P: FnMut(&A) -> bool,
I: Iterator<Item = Result<A, E>>,
{
type Item = Result<A, E>;
#[inline]
fn next(&mut self) -> Option<Result<A, E>> {
for x in self.iter.by_ref() {
match x {
Ok(xx) => if (self.predicate)(&xx) {
return Some(Ok(xx));
},
Err(_) => return Some(x),
}
}
None
}
}
pub trait FilterOkTrait {
fn filter_ok<P, A, E>(self, predicate: P) -> FilterOkIterator<Self, P>
where
Self: Sized + Iterator<Item = Result<A, E>>,
P: FnMut(&A) -> bool,
{
FilterOkIterator {
iter: self,
predicate: predicate,
}
}
}
impl<I, T, E> FilterOkTrait for I
where
I: Sized + Iterator<Item = Result<T, E>>,
{
}
Your code may look like this:
["1", "2", "3", "4"]
.iter()
.map(|x| x.parse::<u16>().map(|a| a + 10))
.filter_ok(|x| x % 2 == 0)
.map_ok(|x| x + 100)
.collect::<Result<Vec<_>, std::num::ParseIntError>>()
playground
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36368843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
} |
Q: escape characters in Swift I specifically am wondering how you could escape a newline in Swift, but generic escape characters would be great too.
In Python you can do this:
print("Dear grandma, \nHow are you?")
How can you do this in Swift?
A: Newlines as \n work in Swift string literals too.
Check out the docs: Special Unicode Characters in String Literals
A: Here is an example replacing a unicode character in a string with a comma (to give you a sense of using escaped unicodes).
address = address.stringByReplacingOccurrencesOfString("\u{0000200e}", withString: ",", options: nil, range: nil)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29312733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.