text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
Django, request.user is always Anonymous User
I am using a custom authentication backend for Django (which runs off couchdb). I have a custom user model.
As part of the login, I am doing a request.user = user and saving the user id in session.
However, on subsequent requests, I am not able to retrieve the request.user. It is always an AnonymousUser. I can, however, retrieve the user id from the session and can confirm that the session cookie is being set correctly.
What am I missing?
I do not want to use a relational db as I want to maintain all my user data in couchdb.
Edit: I have written a class which does not inherit from Django's auth User. It, however, has the username and email attributes. For this reason, my backend does not return a class which derives from auth User.
Please elaborate. If you are using a custom user model (which is different from a custom user PROFILE model), then you are basically on your own and the django.contrib.auth framework can not help you with authentication. If you are writing your own authentication system and are not using django.contrib.auth, then you need to turn that off because it seem to be interfering with your system.
The request.user is set by the django.contrib.auth.middleware.AuthenticationMiddleware.
Check django/contrib/auth/middleware.py:
class LazyUser(object):
def __get__(self, request, obj_type=None):
if not hasattr(request, '_cached_user'):
from django.contrib.auth import get_user
request._cached_user = get_user(request)
return request._cached_user
class AuthenticationMiddleware(object):
def process_request(self, request):
request.__class__.user = LazyUser()
return None
Then look at the get_user function in django/contrib/auth/__init__.py:
def get_user(request):
from django.contrib.auth.models import AnonymousUser
try:
user_id = request.session[SESSION_KEY]
backend_path = request.session[BACKEND_SESSION_KEY]
backend = load_backend(backend_path)
user = backend.get_user(user_id) or AnonymousUser()
except KeyError:
user = AnonymousUser()
return user
Your backend will need to implement the get_user function.
I too have custom authentication backend and always got AnonymousUser after successful authentication and login. I had the get_user method in my backend. What I was missing was that get_user must get the user by pk only, not by email or whatever your credentials in authenticate are:
class AccountAuthBackend(object):
@staticmethod
def authenticate(email=None, password=None):
try:
user = User.objects.get(email=email)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
@staticmethod
def get_user(id_):
try:
return User.objects.get(pk=id_) # <-- tried to get by email here
except User.DoesNotExist:
return None
Its easy to miss this line in the docs:
The get_user method takes a user_id – which could be a username,
database ID or whatever, but has to be the primary key of your User
object – and returns a User object.
It so happened that email is not primary key in my schema. Hope this saves somebody some time.
You say you've written a custom authentication backend, but in fact what you seem to have written is a complete custom authentication app, which doesn't interface with Django's contrib.auth.
If you want to use a non-relational database for your authentication data, all you need to do is create a class that provides two methods: get_user(user_id) and authenticate(**credentials). See the documentation. Once you have authenticated a user, you simply call Django's normal login methods. There should be no reason to manually set request.user or put anything into the session.
Update after edit That has nothing to do with it. There's no requirement that the user class derives from auth.models.User. You still just need to define a get_user method that will return an instance of your user class.
In case you are using an API (Django-rest-framework) and accessing a view using a get, post, etc. methods.
You can get a user by sending the Bearer/JWT token corresponding to that user.
Wrong
# prints Anonymous User
def printUser(request):
print(request.user)
Correct
# using decorators
# prints username of the user
@api_view(['GET']) # or ['POST'] .... according to the requirement
def printUser()
print(request.user)
That's not working for me. I'm sending the token and i'm still getting an anonymous user in my APIView
ahh.. i'm always falling into this silly mistake
@AlxVallejo were you able to resolve the issue? I am getting AnonymousUser as well.
I had similar problem when I used custom authentication backend. I used field different than the primary key in the method get_user.
It directly solved after using primary key which must be number (not str)
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id) # <-- must be primary key and number
except User.DoesNotExist:
return None
After sending Token using Authorization header, the token will be gotten in dispatch function as bellow:
'''
def dispatch(self, request, *args, **kwargs):
self.args = args
self.kwargs = kwargs
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
self.initial(request, *args, **kwargs)
# Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
response = handler(request, *args, **kwargs)
except Exception as exc:
response = self.handle_exception(exc)
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
So you are using django_role_permission's HasRoleMixin, the dispatch method of this mixin will hide dispatch of the view.
I think that the solution is to redefine the mixin of roles-permissions
any chance you could elaborate on how to fix this? This is happening to me!
user = authenticate(username=username, password=password)
if user is not None:
return render(request, 'home.html',{'user_id':user.id})
This would be a better answer if you explained how the code you provided answers the question.
Added these in my view
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
and started getting original user
| common-pile/stackexchange_filtered |
RJ11 pinout (serial) for Amplus AM03128-H11 LED display
I've got an Amplus AM03128-H11 LED display, without the documentation and serial cable.
I found the programming manual online, but I have no idea what the pinout on the serial RJ11 connector is supposed to be.
Anyone out there who knows ?
Or who has one of these devices and is willing to check the wiring for me?
Nope, nothing. Either find a datasheet or reverse engineer it by tracing out the connections. If you're lucky the pinout is marked on the PCB.
@Bimpelrekkie Give me some credit :-) I already checked the PCB. Tick layer of black glue/paste covers everything. My Google-fu is failing me on the datasheet. Have no trouble finding sample-code to control that display, but everyone seems to assume that you will have the supplied serial cable that came with the thing. And manufacturer doesn't respond to emails.
Email to Amplus...?
Guessing this is some obscure de facto standard: http://www.asayo.com/images/products/led-sign-cable/cable-spec.jpg 2,3,4 are RX, TX, GND
Quick test with a meter may help to see if that's correct.
@Finbarr Tried to email them. 4 weeks ago. No answer yet.
@τεκ I found that image myself already and it is possible these Asayo LED signs are a rebrand of the original Amplus ones. The pictures on the site look very similar and one of them shows a multi-color sign that Asayo dind't actually sell but the picture looks very much like the Amplus AM03128-H13 model (which also uses that same cable). Barring any other info I'm going to just try it.
| common-pile/stackexchange_filtered |
Add a newline after each closing html tag in web2py
Original
I want to parse a string of html code and add newlines after closing tags + after the initial form tag. Here's the code so far. It's giving me an error in the "re.sub" line. I don't understand why the regex fails.
def user():
tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
result = re.sub("(</.*?>)", "\1\n", tags)
return dict(form_code=result)
PS. I have a feeling this might not be the best way... but I still want to learn how to do this.
EDIT
I was missing "import re" from my default.py. Thanks ruakh for this.
import re
Now my page source code shows up like this (inspected in client browser). The actual page shows the form code as text, not as UI elements.
<form><label for="email_field">Email:</label>
<input type="email" name="email_field"/><label
for="password_field">Password:</label>
<input type="password" name="password_field"/><input
type="submit" value="Login"/></form>
EDIT 2
The form code is rendered as UI elements after adding XML() helper into default.py. Thanks Anthony for helping. Corrected line below:
return dict(form_code=XML(result))
FINAL EDIT
Fixing the regex I figured myself. This is not optimal solution but at least it works. The final code:
import re
def user():
tags = "<form><label for=\"email_field\">Email:</label><input type=\"email\" name=\"email_field\"/><label for=\"password_field\">Password:</label><input type=\"password\" name=\"password_field\"/><input type=\"submit\" value=\"Login\"/></form>"
tags = re.sub(r"(<form>)", r"<form>\n ", tags)
tags = re.sub(r"(</.*?>)", r"\1\n ", tags)
tags = re.sub(r"(/>)", r"/>\n ", tags)
tags = re.sub(r"( </form>)", r"</form>\n", tags)
return dict(form_code=XML(tags))
The only issue I see is that you need to change "\1\n" to r"\1\n" (using the "raw" string notation); otherwise \1 is interpreted as an octal escape (meaning the character U+0001). But that shouldn't give you an error, per se. What error-message are you getting?
It gives: <type 'exceptions.NameError'>(global name 're' is not defined)
The same result with r applied, btw
I assume that just means you need to import re. (Disclaimer: that's what you would need in regular Python. I've never used web2py, and I have a vague sense that imports might work a bit differently there. See e.g. http://stackoverflow.com/questions/6557000/problem-in-function-call-using-import-in-web2py. But as a first step, I'd try just putting import re above your function-definition and seeing if it fixes the issue.)
Zillion thanks! Now the page shows up. However, the output is still not correctly formatted. I'll update the original question with my findings.
No, imports work as usual in web2py. In the past, there was an issue specifically with modules in the application's "modules" folder that required a special import method, but that is no longer the case. Imports of modules in sys.path (such as the standard library) have always worked as usual in web2py.
By default, web2py escapes all text inserted in the view for security reasons. To avoid that, simply use the XML() helper, either in the controller:
return dict(form_code=XML(result))
or in the view:
{{=XML(form_code)}}
Don't do this unless the code is coming from a trusted source -- otherwise it could contain malicious Javascript.
Thanks! My form is now correctly displayed. XML() did the magic. Last issue: the regex pattern is only partially ok.
| common-pile/stackexchange_filtered |
How to know if a fridge would be able to maintain its temperature
I would like to understand the thermodynamic relation that exist on a big fridge. If you have any links to help me to more understand the physics relation, it would be nice :)
So here is my problem:
There is an electric charge into a big fridge which dissipates X watts into the fridge. The fridge is said to maintained the temperature at T. with T inferior to the ambient temperature.
I also know the electric power consumed by the fridge, which is equal to E. I do not know the transfer ratio between electric power and "calorific power". If you need to add some value, do not hesitate but the less would be the better :)
And finally, I know what is the input (T_input_liquid) and output liquid temperature T_output_liquid , the throughput F of the calorific liquid.
At the end, we may know what would be the COP needed for stabilizing the temperature T into the fridge for X watts.
There is an electric charge into a big fridge which dissipates X watts into the fridge.
We'd normally say "electrical energy" into the fridge. It doesn't dissipate heat into the fridge (which would raise the temperature - it uses the energy to run a compressor which is located outside the cold compartment.
I also know the electric power consumed by the fridge, which is equal to E. I do not know the transfer ratio between electric power and "calorific power". If you need to add some value, do not hesitate but the less would be the better :)
I would expect a CoP (coefficient of performance) of about 3. For every 1 watt into the compressor up to 3 watts of cooling (or heat pumping) could be achieved.
And finally, I know what is the input (T_input_liquid) and output liquid temperature T_output_liquid , the throughput F of the calorific liquid.
It's not important for the calculations we are doing.
At the end, we may know what would be the COP needed for stabilizing the temperature T into the fridge for X watts.
Temperature will stabilise when cooling power matches the rate of heat leakage into the fridge. In refrigeration systems the compressor is oversized and a thermostat is used to switch off the compressor when adequate cooling has been achieved. For your calculations you would need to measure the duty cycle (% on time) of the compressor.
| common-pile/stackexchange_filtered |
Can this be reworked with a hot air gun?
I posted before about the Microchip RN4020 (Bluetooth Low Energy) PicTail failing. I have some spare RN4020 modules and access to a heat gun. If I can take this RN4020 off and put a new one on, how would you suggest I do it? Or is it too large or difficult because of the package?
The pads at the bottom are going to be the hard ones.
Those are the same pads - they are plated through holes cut in half. What will probably happen if not very careful is the shield can and internal components will come off first - but not a big deal if you've already decided the existing module is bad. Try to clean up and put the new one on with an iron.
Just checked the datasheet. They are all castellations and not in fact plain pads as they appear in the photo.
Also lots of flux will help and sometimes you can heat up stubborn pads with a soldering iron while under the heat gun. You can also put a bunch of solder on there first, just bridge everything. That'll help transfer and retain some heat.
Heat guns aren't ideal for soldering -- they tend to spew heat all over the board indiscriminantly, causing unwanted secondary damage, delamination, etc. A Hot Air Rework Station is a better instrument because its nozzle focuses the hot air just on the pins.. But for a small board like this, with not much else on the board, the plain heat gun might work well enough. If the switch and the SOT-223 fall off during rework, those should be easy to remount.
I was able to rework it. I got access to a hot air gun. It took a lot of work to get the part off. I had to re-solder the pins of the new one with a soldering iron. There wasn't enough solder after getting the part off, plus the connections weren't good enough with the hot air gun.
| common-pile/stackexchange_filtered |
One AntiForgery token for all requests
I have Web API 2 web service with methods:
// Makes and returns Token by login/password.
string GetToken(string login, string password);
// Returns orders of current account.
Order[] GetMyOrders();
I want to authenticate user in GetMyOrders() by him Request to this method.
Request has to contain Token which will be mapped to accountId on the web-service side.
Client will use this Token for each Requests.
Can I implement GetToken() method using ASP.NET Identity?
And what is right way to authenticate using this Token and ASP.NET Identity? Can I use ValidateAntiForgeryTokenAttribute or something else?
GetToken() will work only through https, but GetMyOrders() will work through http.
Is your API part of an ASP.NET MVC site or stand-alone?
It is stand-alone web-service. It does not have any web-views.
ValidateAntiForgeryTokenAttribute is used to prevent CSRF, not usually required for an API.
Yes you can implement OAuth Bearer Tokens in webapi.
Example below:
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
The best way to authenticate the token is built-in, which means that you will only need to put the [Authorize] data annotation.
So basically you should use Owin middleware which will allow you to use OAuth Bearer token authentication.
| common-pile/stackexchange_filtered |
How can I collect order delivery date/time in Store?
Any ideas on how I could collect order delivery date/time in Store.
Best wishes
Lee
You just need to create a custom order field and then output that in the checkout process.
Store > Settings > Order Fields. Pick an available field and give it a name ('Delivery Date' for instance).
Then output this as normal in the checkout. You can use it in combination with jQuery UI Datepicker to provide a date selection widget and set the correct formatting automatically. Or if you need the time included in the same field as well then I look to use jQuery DateTimePicker. You have lots of control here when it comes to date and time selection.
That combination works very well and can be pulled through into the Store order confirmation emails too.
| common-pile/stackexchange_filtered |
Firebase functions fails to deploy with same error in all functions
I'm trying to deploy my firebase functions but all the functions return me error, I had already deployed before without any error.
I did not install anything new since the last time that a deploy was correct.
Every functions return almost the same error, the only thing that changes is the "errorId"
I have tried to logout from firebase-cli and login again, i have updated firebase-tools, firebase-admin, firebase-functions from npm.
I'm deploying with firebase deploy --only functions
Deployment error.
Build failed:
{
"error": {
"canonicalCode": "INVALID_ARGUMENT",
"errorMessage": "`npm_install` had stderr output:\nnpm WARN tar ENOENT: no such file or directory, open<EMAIL_ADDRESS>WARN tar ENOENT: no such file or directory, open<EMAIL_ADDRESS>WARN tar ENOENT: no such file or directory, open<EMAIL_ADDRESS>WARN tar ENOENT: no such file or directory, open<EMAIL_ADDRESS>WARN tar ENOENT: no such file or directory, open<EMAIL_ADDRESS>ERR! code E404\nnpm ERR! 404 Not Found<EMAIL_ADDRESS>ERR! A complete log of this run can be found in:\nnpm ERR! /builder/home/.npm/_logs/2019-06-08T18_16_17_266Z-debug.log\n\nerror: `npm_install` returned code: 1",
"errorType": "InternalError",
"errorId": "FD2536C1"
}
}
Package.json :
{
"name": "functions",
"engines": {
"node": "8"
},
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"@firebase/storage": "^0.2.16",
"@google-cloud/vision": "^0.24.0",
"@sendgrid/mail": "^6.4.0",
"cors": "^2.8.5",
"dateformat": "^3.0.3",
"firebase": "^5.11.1",
"firebase-admin": "^7.4.0",
"firebase-functions": "^2.3.1",
"json2csv": "^4.5.1",
"mailchimp-api-v3": "^1.13.0",
"moment-timezone": "^0.5.25",
"openpay": "^1.0.3",
"paypal-rest-sdk": "^1.8.1",
"request": "^2.88.0"
},
"devDependencies": {
"eslint": "^4.12.0",
"eslint-plugin-promise": "^3.6.0",
"firebase-functions-test": "^0.1.6"
},
"private": true
}
Correct deploy of the functions.
Update***
I have tried to delete everything and uninstall every package except for the ones required for firebase-functions and start over with one test function in node 8 i'm having the same issue, with node 6 it was deployed, but i need to use node 8 because i need to use await/async
Could you expand a lutter more about tour setup? We need more information to help you
Its complairont about missing package, havé u triés installing thèm? Most of them are types, maybe uses but libraries you are using
Yes, i have installed them all...
I have a similar setup. However, it fails when I use a private github dependency: e.g. "dependency": "github:org/repo#v1.0.0"
I had a similar deployment failure. I think it was caused by me running firebase deploy from the app directory rather the the app\functions directory. In any case, I ran the following commands from the terminal (using VSCode in my case) having changed into the app\functions directory. Deployment then worked perfectly.
npm install --save @google-cloud/storage
npm install --save firebase-admin@latest
npm install --save firebase-functions@latest
firebase deploy
Hope that helps.
Checking the log
You can examine the actual logs by using this command to open the log
firebase functions:log
Doing this is really helpful since specific issue will usually be visible there. I sometimes even had error as simple as a missing package name in package.json
It would have been much helpful if firebase could show better info on the errors directly. but at least we can find them here.
I hope it helps
I had similar issue and it ended up being a missing module in my package.json
You can view more detailed / useful logs here: https://console.cloud.google.com/logs
Firebase functions:log really helps! In my case I had not enabled signin method in the firebase project (:
| common-pile/stackexchange_filtered |
Thumb position when driving/rallying
I am not a rally driver or anything...but out of curiosity, is it safer and more technical to lock my thumbs into the steering wheel when rallying?
If so, then does that apply to normal track racing too?
If not then why shouldn't I lock my thumbs?
(when I'm holding the steering wheel 9 and 3)
Thank you!
Get into the habit of not having your thumbs inside the wheel rim ever (racing, off-road, on-road) - a pot-hole or accident can rip the wheel round and break your thumb...
Seen it happen to drivers - off to hospital with a broken thumb for a simple accident, no other injury though...
But this may cause others to say " I was fine"... but do you really want to test?
Agreed - always keep all your digits on the outside of the wheel!
Thumbs up for safety! Or non-broken thumbs, whichever...
so it still would be 9 and 3 but thumbs not locked in the steering right
| common-pile/stackexchange_filtered |
How to find the path of properties file dynamically from the code?
I have maven project in Java in which I have a property file (quartz.properties) under this directory:
/src/main/resources
Now I can use this property file in two ways from this class as shown below:
/**
* Create a StdSchedulerFactory that has been initialized via
* <code>{@link #initialize(Properties)}</code>.
*
* @see #initialize(Properties)
*/
public StdSchedulerFactory(Properties props) throws SchedulerException {
initialize(props);
}
/**
* Create a StdSchedulerFactory that has been initialized via
* <code>{@link #initialize(String)}</code>.
*
* @see #initialize(String)
*/
public StdSchedulerFactory(String fileName) throws SchedulerException {
initialize(fileName);
}
I am not sure how can I use StdSchedulerFactory class to provide the path of my quartz.properties file.
As of now I am providing hardcoded path like this but this is not the right way to provide the path since if anyone else is running this code in their desktop or laptop then it will not work. I will be running this application from my desktop and also I will be making a runnable jar as well so I want that my program should load my properties file dynamically without any hardcoded path.
public class TestingQuartz {
public static void main(String[] args) throws SchedulerException {
SchedulerFactory factory = new StdSchedulerFactory(
"C:\\workspace\\tester_quartz\\quartzmain\\src\\main\\resources\\quartz.properties");
Scheduler scheduler = factory.getScheduler();
scheduler.start();
}
}
As your configuration file is in src/main/resources of a mavenized project, it will be embedded in the resulting artifact (jar, war...) you build with maven. Thus you should load the file "from the classpath" like this :
StdSchedulerFactory factory = new StdSchedulerFactory();
factory.initialize(this.getClass().getClassLoader().getResourceAsStream("quartz.properties"));
StdSchedulerFactory doesn't take InputStream as an input.
Oops yes actually I meant using the initialize(InputStream) method; I changed it in my answer
I tried using your way - SchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(TestingQuartz .class.getClassLoader().getResourceAsStream("quartz.properties")); but somehow it is giving compilation error as The method initialize(InputStream) is undefined for the type SchedulerFactory.
I have updated the code in my question to add more details of how I am using it.
which version of quartz do you use ? At least 2.2 provides such a method : http://quartz-scheduler.org/api/2.2.0/org/quartz/impl/StdSchedulerFactory.html#initialize(java.io.InputStream)
I am using 2.2.1 and I do see that method is there in StdSchedulerFactory() class but whenever I try to use it the way you told me, I always see compilation error somehow. Problem is SchedulerFactory is an interface and I don't see that method over there and may be that's why it is not working for me.
Mmmh yes the initialize(...) method is declared by StdSchedulerFactory but not in the SchedulerFactory interface. Fixed in my answer
Since it appears to be on your class path you could do this:
getClass().getClassLoader().getResource("quartz.properties").toExternalForm()
If the maven project generates a war or ear then deployed on a JavaEE container such as JBoss, it may not work as the URL returned by getResource(...) will refer to a kind of virtual storage area, which won't open properly with File. I suggest using getResourceAsStream in my answer (that arrived a bit later than yours; i'm a slow typer :)
Thanks - been working a lot in JavaFX for a desktop client and that didn't occur to me... Good catch.
| common-pile/stackexchange_filtered |
Can I retrieve a spreadsheet with just a title name for google sheets api v4 .net?
I know that there is a way to get a spreadsheet using a sheetID. I was wondering if it's possible to get a sheet using a spreadsheet's title rather than sheetID without using a map. I know that it's possible to retrieve a sheet using its name in a spreadsheet using linq. Any help would be appreciated.
I meant to say if there is a way to get a spreadsheet using its title.
Not with the Sheets API - with Drive, yes
| common-pile/stackexchange_filtered |
"no such sysroot directory" while building qt project
MacOS Mojave Version 10.14 (18A389).
Today I updated Xcode to version 10.0 (10A255). End when I try to build my Qt project I get an error:
clang: warning: no such sysroot directory: '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk' [-Wmissing-sysroot]
In file included from ../greed/timediagram.cpp:1:
In file included from ../../../Qt/5.9.1/clang_64/lib/QtGui.framework/Headers/QtGui:3:
In file included from /Users/arsenyspiridonov/Qt/5.9.1/clang_64/lib/QtGui.framework/Headers/QtGuiDepends:3:
In file included from /Users/arsenyspiridonov/Qt/5.9.1/clang_64/lib/QtCore.framework/Headers/QtCore:4:
In file included from ../../../Qt/5.9.1/clang_64/lib/QtCore.framework/Headers/qglobal.h:47:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/utility:202:
In file included from /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/cstring:61:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/string.h:61:15: fatal error: 'string.h' file not found
#include_next <string.h>
^~~~~~~~~~
1 error generated.
make: *** [timediagram.o] Error 1
16:13:47: Процесс «/usr/bin/make» завершился с кодом 2.
Ошибка при сборке/установке проекта greed (комплект: Desktop Qt 5.9.1 clang 64bit)
Во время выполнения этапа «Сборка»
What's the problem? How to fix it?
add 'QMAKE_MAC_SDK = macosx10.14' to your .pro file, and manually delete .qmake.stash from your build directory (or directories).
*.pro file — Qt project file? Where I have to write it?
There are no .qmake.stash in directories under MacOS
.pro file is created by QtCreator ... .qmake.stash is created in the target build folder of the application.
Simply deleting the .qmake.stash from my debug and release build directories solved the problem with no .pro editing, after upgrading from Sierra->Mojave, for me.
Simply deleting the .qmake.stash from my build directories solved the problem with no .pro editing.
In my case I updated xcode to the last version, so instead of have on the folder the version 10.13, I had MacOSX10.14.sdk ( that is a symbolic link to the folder MacOSX.sdk)
so, you can solve the problem with this code on terminal:
sudo ln -s MacOSX.sdk/ MacOSX10.13.sdk
positioned on the current folder.
I hope it helps.
I just reinstalled Qt. All is Ok now
This helped me:
Close the project in Qt Creator.
Delete the .pro.user file in your code directory.
Add QMAKE_MAC_SDK = macosx10.14 and QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.14 to your .pro file in a text editor (not in Qt Creator). Replace 10.14 with whatever MacOS version you want to build for.
Re-open the project in Qt Creator. It will reconfigure.
Build.
Adding to sellen's Answer: If you have trouble locating your .qmake.stash file, or if you don't have a .qmake.stash file in your build folder, try locating it using the terminal:
find /path/to/base/folder -name ".qmake.stash"
In my case I had a .qmake.stash file in my build parent folder, but not in my build folder. Not sure how it got there but somehow QMake picked it up and as soon as I deleted it and restarted Qt Creator things started to work again.
the fast solution is to create new shotcut in /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs folder, you can copy the exist shortcut, them change the name you need.
I had the same issue (but use CMake to build project). It appears after Xcode tools update.
My solution:
Go inside build directory (looks like "build/Desktop..." in you project folder)
Delete or rename "CMakeCache.txt"
The solution for me was just to perform a clean build.
rm -rf build
mkdir build
cd build
cmake ..
This happen to me recently and my Xcode needed to update. So I would recommend quitting xcode and trying to update your current version to see if that fixes your problem.
The question states that Xcode had been updated, so recommending updating it is not useful.
| common-pile/stackexchange_filtered |
Dependency Injection error: Unable to resolve service for type while attempting to activate, while class is registered
I created an .NET Core MVC application and use Dependency Injection and Repository Pattern to inject a repository to my controller. However, I am getting an error:
InvalidOperationException: Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.
Repository:
public interface IBloggerRepository { ... }
public class BloggerRepository : IBloggerRepository { ... }
Controller:
public class BlogController : Controller
{
private readonly IBloggerRepository _repository;
public BlogController(BloggerRepository repository)
{
_repository = repository;
}
public IActionResult Index() { ... }
}
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddScoped<IBloggerRepository, BloggerRepository>();
}
I'm not sure what I'm doing wrong. Any ideas?
I know this is an old question, but... You should not dispose the db context inside a service. The db context is automatically disposed by the scope resolver. If you dispose it inside a service, it might be disposed when calling a next service within the same request/scope.
Make sure the service(missing class) is added using ´services.AddTransient();´
This is a common error of Injecting the Wrong Service in the Constructor. Sometimes, we register the service correctly in the DI container but still get the same error. This might be caused by mistakenly injecting the wrong service into the constructor of the dependant. To solve this issue and others related to this, see https://code-maze.com/dotnet-how-to-solve-unable-to-resolve-service-for-a-type
@ecemcy How does that link help more than the accepted answer below?
To break down the error message:
Unable to resolve service for type 'WebApplication1.Data.BloggerRepository' while attempting to activate 'WebApplication1.Controllers.BlogController'.
That is saying that your application is trying to create an instance of BlogController but it doesn't know how to create an instance of BloggerRepository to pass into the constructor.
Now look at your startup:
services.AddScoped<IBloggerRepository, BloggerRepository>();
That is saying whenever a IBloggerRepository is required, create a BloggerRepository and pass that in.
However, your controller class is asking for the concrete class BloggerRepository and the dependency injection container doesn't know what to do when asked for that directly.
I'm guessing you just made a typo, but a fairly common one. So the simple fix is to change your controller to accept something that the DI container does know how to process, in this case, the interface:
public BlogController(IBloggerRepository repository)
// ^
// Add this!
{
_repository = repository;
}
Note that some objects have their own custom ways to be registered, this is more common when you use external Nuget packages, so it pays to read the documentation for them. For example if you got a message saying:
Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor' ...
Then you would fix that using the custom extension method provided by that library which would be:
services.AddHttpContextAccessor();
For other packages - always read the docs.
Similarly, I was inadvertently activating the wrong object in Startup.cs. I had services.AddTransient<FooService, FooService>(); instead of services.AddTransient<IFooService, FooService>();. Those pesky letters LOL. Thanks for pointing me in the right direction!
My issue was that I needed to look at the arguments of the constructors for the classes that I was injecting. Once I added the types for the arguments the error disappeared!
The catchy phrase from the answer above... "That is saying whenever a IBloggerRepository is required, create a BloggerRepository and pass that in"
I made the exact typo, I love this site.
I ran into this issue because in the dependency injection setup I was missing a dependency of a repository that is a dependency of a controller:
services.AddScoped<IDependencyOne, DependencyOne>(); //I was missing this line!
services.AddScoped<IDependencyTwoThatIsDependentOnDependencyOne, DependencyTwoThatIsDependentOnDependencyOne>();
Solved my problem, because I recognized my services were not in the correct "namespace".
In my case I was trying to do dependency injection for an object which required constructor arguments. In this case, during Startup I just provided the arguments from the configuration file, for example:
var config = Configuration.GetSection("subservice").Get<SubServiceConfig>();
services.AddScoped<ISubService>(provider => new SubService(config.value1, config.value2));
I was having a different problem, and yeah the parameterized constructor for my controller was already added with the correct interface. What I did was something straightforward. I just go to my startup.cs file, where I could see a call to register method.
public void ConfigureServices(IServiceCollection services)
{
services.Register();
}
In my case, this Register method was in a separate class Injector. So I had to add my newly introduced Interfaces there.
public static class Injector
{
public static void Register(this IServiceCollection services)
{
services.AddTransient<IUserService, UserService>();
services.AddTransient<IUserDataService, UserDataService>();
}
}
If you see, the parameter to this function is this IServiceCollection.
Only if anyone have the same situation like me, I am doing a tutorial of EntityFramework with existing database, but when the new database context is created on the models folders, we need to update the context in the startup, but not only in services.AddDbContext but AddIdentity too if you have users authentication
services.AddDbContext<NewDBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<NewDBContext>()
.AddDefaultTokenProviders();
You need to add a new service for DBcontext in the startup
Default
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
Add this
services.AddDbContext<NewDBContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("NewConnection")));
https://learn.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db#register-and-configure-your-context-in-startupcs
Public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IEventRepository, EventRepository>();
}
You forgot to add "services.AddScoped" in startup ConfigureServices method.
I got this issue because of a rather silly mistake. I had forgotten to hook my service configuration procedure to discover controllers automatically in the ASP.NET Core application.
Adding this method solved it:
// Add framework services.
services.AddMvc()
.AddControllersAsServices(); // <---- Super important
I had to add this line in the ConfigureServices in order to work.
services.AddSingleton<IOrderService, OrderService>();
I was getting below exception
System.InvalidOperationException: Unable to resolve service for type 'System.Func`1[IBlogContext]'
while attempting to activate 'BlogContextFactory'.\r\n at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type serviceType, Type implementationType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type serviceType, Type implementationType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType, ServiceProvider serviceProvider)\r\n at System.Collections.Concurrent.ConcurrentDictionaryExtensions.GetOrAdd[TKey, TValue, TArg] (ConcurrentDictionary`2 dictionary, TKey key, Func`3 valueFactory, TArg arg)\r\n at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)\r\n at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)\r\n at lambda_method(Closure , IServiceProvider , Object[] )\r\n at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync()
Because I wanted register Factory to create instances of DbContext Derived class IBlogContextFactory and use Create method to instantiate instance of Blog Context so that I can use below pattern along with dependency Injection and can also use mocking for unit testing.
the pattern I wanted to use is
public async Task<List<Blog>> GetBlogsAsync()
{
using (var context = new BloggingContext())
{
return await context.Blogs.ToListAsync();
}
}
But Instead of new BloggingContext() I want to Inject factory via constructor as in below BlogController class
[Route("blogs/api/v1")]
public class BlogController : ControllerBase
{
IBloggingContextFactory _bloggingContextFactory;
public BlogController(IBloggingContextFactory bloggingContextFactory)
{
_bloggingContextFactory = bloggingContextFactory;
}
[HttpGet("blog/{id}")]
public async Task<Blog> Get(int id)
{
//validation goes here
Blog blog = null;
// Instantiage context only if needed and dispose immediately
using (IBloggingContext context = _bloggingContextFactory.CreateContext())
{
blog = await context.Blogs.FindAsync(id);
}
//Do further processing without need of context.
return blog;
}
}
here is my service registration code
services
.AddDbContext<BloggingContext>()
.AddTransient<IBloggingContext, BloggingContext>()
.AddTransient<IBloggingContextFactory, BloggingContextFactory>();
and below are my models and factory classes
public interface IBloggingContext : IDisposable
{
DbSet<Blog> Blogs { get; set; }
DbSet<Post> Posts { get; set; }
}
public class BloggingContext : DbContext, IBloggingContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("blogging.db");
//optionsBuilder.UseSqlite("Data Source=blogging.db");
}
}
public interface IBloggingContextFactory
{
IBloggingContext CreateContext();
}
public class BloggingContextFactory : IBloggingContextFactory
{
private Func<IBloggingContext> _contextCreator;
public BloggingContextFactory(Func<IBloggingContext> contextCreator)// This is fine with .net and unity, this is treated as factory function, but creating problem in .netcore service provider
{
_contextCreator = contextCreator;
}
public IBloggingContext CreateContext()
{
return _contextCreator();
}
}
public class Blog
{
public Blog()
{
CreatedAt = DateTime.Now;
}
public Blog(int id, string url, string deletedBy) : this()
{
BlogId = id;
Url = url;
DeletedBy = deletedBy;
if (!string.IsNullOrWhiteSpace(deletedBy))
{
DeletedAt = DateTime.Now;
}
}
public int BlogId { get; set; }
public string Url { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? DeletedAt { get; set; }
public string DeletedBy { get; set; }
public ICollection<Post> Posts { get; set; }
public override string ToString()
{
return $"id:{BlogId} , Url:{Url} , CreatedAt : {CreatedAt}, DeletedBy : {DeletedBy}, DeletedAt: {DeletedAt}";
}
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
----- To Fix this in .net Core MVC project -- I did below changes on dependency registration
services
.AddDbContext<BloggingContext>()
.AddTransient<IBloggingContext, BloggingContext>()
.AddTransient<IBloggingContextFactory, BloggingContextFactory>(
sp => new BloggingContextFactory( () => sp.GetService<IBloggingContext>())
);
In short in .net core developer is responsible to inject factory function, which in case of Unity and .Net Framework was taken care of.
Adding yet another answer to the fix, because I've been bitten by this one multiple times now. If you create an "Options" class that you're binding to configuration, you might be registering it like this:
// Your options class
public record MyOptions(string SomeSetting);
// ----- 8< -----
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyOptions>(configuration.GetSection(configPath));
}
}
If you now have a consumer of those options, you'll find that the following code will throw the exception above:
public class OptionsConsumer
{
public OptionsConsumer(MyOptions options)
{
}
}
You have to ask for the "wrapped" version of your options instead:
public class OptionsConsumer
{
public OptionsConsumer(IOptions<MyOptions> options)
{
}
}
For .NET 6.0
I just add this line on Program.cs
builder.Services.AddDbContext<DatabaseContext>();
For me it worked to add the DB context in the ConfigureServices as follows:
services.AddDBContext<DBContextVariable>();
If you are using AutoFac and getting this error, you should add an "As" statement to specify the service that the concrete implementation implements.
Ie. you should write:
containerBuilder.RegisterType<DataService>().As<DataService>();
instead of
containerBuilder.RegisterType<DataService>();
I received this error message with ILogger being injected into a .NET 5 class. I needed to add the class type to fix it.
ILogger logger --> ILogger <MyClass> logger
Not sure if this will help anyone else, but I was correctly dependency injecting and got this error when trying to access my API controllers.
I had to shut down the project and rebuild after already adding them to my startup.cs class - for some reason a rebuild got Visual Studio to recognize the service class was properly registered when before it was getting an error.
I had the same issue and found out that my code was using the injection before it was initialized.
services.AddControllers(); // Will cause a problem if you use your IBloggerRepository in there since it's defined after this line.
services.AddScoped<IBloggerRepository, BloggerRepository>();
I know it has nothing to do with the question, but since I was sent to this page, I figure out it my be useful to someone else.
Had the same issue all I did was to register my DBContext in Startup.cs.
The problem is that you are calling a DBContext that the application has not registered with so it does not know what to do when your view tries to reference it.
Key part of the error message, "while attempting to activate"
private readonly SmartPayDBContext _context;
Solution that worked for me
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<SmartPayDBContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
}
How does this add to the existing answers?
I replaced
services.Add(new ServiceDescriptor(typeof(IMyLogger), typeof(MyLogger)));
With
services.AddTransient<IMyLogger, MyLogger>();
And it worked for me.
I had problems trying to inject from my Program.cs file, by using the CreateDefaultBuilder like below, but ended up solving it by skipping the default binder. (see below).
var host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureServices(servicesCollection => { servicesCollection.AddSingleton<ITest>(x => new Test()); });
webBuilder.UseStartup<Startup>();
}).Build();
It seems like the Build should have been done inside of ConfigureWebHostDefaults to get it work, since otherwise the configuration will be skipped, but correct me if I am wrong.
This approach worked fine:
var host = new WebHostBuilder()
.ConfigureServices(servicesCollection =>
{
var serviceProvider = servicesCollection.BuildServiceProvider();
IConfiguration configuration = (IConfiguration)serviceProvider.GetService(typeof(IConfiguration));
servicesCollection.AddSingleton<ISendEmailHandler>(new SendEmailHandler(configuration));
})
.UseStartup<Startup>()
.Build();
This also shows how to inject an already predefined dependency in .net core (IConfiguration) from
I was getting this issue when I was working with a 3rd party service - (MassTransit) using the IPublishEndpoint interface in a repo pattern.
End up being that I was calling my services before I was starting MassTransit.
Hope this helps someone...
Posting this response because the title doesn't specifically state how the code is deployed.
In an Azure Function, this error will occur if you forget to decorate the startup class with [assembly: FunctionsStartup(typeof(My.Functions.Startup))]
Startup.cs
[assembly: FunctionsStartup(typeof(My.Functions.Startup))]
namespace My.Functions
{
public class Startup : FunctionsStartup
{
......
The title isn’t the question. It isn’t intended to be. It’s just a summary. The body of the question should include clarifying details. Please don’t just respond to the title, but also acknowledge and respond to the specifics of the question as detailed in the question body.
My error was more like this: System.InvalidOperationException: Unable to resolve service for type access class while attempting to activate controller class
It turns out that I was unnecessarily referencing my access class in the constructor of the controller. The controller really just needs a basic initialization of the access instance.
I got the same error because of I was added the line of code below in program.cs file
builder.Services.AddScoped<IInvoiceService, InvoiceService>();
var app = builder.Build();
so I replaced the code like below.then issue fixed
builder.Services.AddScoped<IInvoiceService, InvoiceService>();
var app = builder.Build();
You do not explain why the second code is better. But mainly, those two blocks are identical.
| common-pile/stackexchange_filtered |
Remove xfce without terminal access or default root account
I purged any packages related to xfce on Debian, and when I rebooted the login screen was still there. Upon login, there was only the wallpaper and a right click context menu available. Launching terminal emulator or Zutty closes them instantly. Tried booting into safe mode as well, makes no difference. How do I boot into a terminal or wipe xfce? Default root is disabled.
(sudo still works on one account)
How do I boot into a terminal
Start with the kernel command-line option rescue (also known as single – the "single-user" mode). Debian uses GRUB, so press e at the boot menu to edit the kernel command line; add the option at the end of the 'linux' line.
If that doesn't work in some way, use the option systemd.unit=multi-user.target to perform a normal boot but without the graphical login.
Other options: emergency (similar to 'rescue' but even smaller); systemd.debug-shell (normal boot but with a root terminal on CtrlAltF9).
or wipe xfce?
Look through dpkg -l for the package corresponding to "login screen" service (the display manager), which is probably LightDM but could also be GDM or SDDM – doing systemctl list-dependencies graphical.target should show the service name.
Once you've found the package, uninstall it with sudo apt purge --autoremove.
Default root is disabled. (sudo still works on one account)
Anything you do as root, you can also do through 'sudo' (which literally lets you run things "as root").
| common-pile/stackexchange_filtered |
Can Panic Spellbomb be returned to the library in response to its ability?
When activating the ability on Panic Spellbomb (tap, Sacrifice Panic Spellbomb: Target creature can't block this turn.), can the opponent then use an Instant such as Banishing Stroke to put Panic Spellbomb on the bottom of it's owner's library? Both are happening at instant speed, so do they stack like typical instants?
Your opponent can't do that. Sacrificing the Spellbomb is part of the cost, and you pay costs as part of activating the ability and putting it on the stack, and only once you're done with all that does anyone get priority. So by the time your opponent gets the chance to do anything, it's already in your graveyard. (This is just like how your opponent couldn't do something in response to you paying mana for a spell or ability.)
If the Spellbomb weren't being sacrificed, your opponent could cast Banishing Stroke on it, but it wouldn't really accomplish anything. Once an ability is activated, it exists on the stack independently of its source. (Yes, activated abilities use the stack.) You'd activate the ability, and your opponent could cast Banishing Stroke in response. The Banishing Stroke would then be on top of the stack, and resolve first. It'd put the Spellbomb on the bottom of your library, then the Spellbomb's ability would resolve as usual.
Side note: all spells and activated abilities use the stack, regardless of whether they're instants (or at "instant speed"). The important thing about instants and activated abilities is that they can be cast/activated any time you have priority, e.g. while something's already on the stack. That is, the bottom thing on the stack definitely doesn't have to be at "instant speed", just the things added on top of it (usually) - and the stack resolves top-down the same way no matter what's on it.
All spells, activated abilities, and triggered abilities use the stack. Panic Spellbomb's ability is no exception. Although it does happen at instant speed, Panic Spellbomb's ability is not actually an instant spell, it is an activated ability. From the comprehensive MTG rules:
602.1. Activated abilities have a cost and an effect. They are written as "[Cost]: [Effect.] [Activation instructions (if any).]"
Panic Spellbomb's ability reads: "Tap, Sacrifice Panic Spellbomb: Target creature can't block this turn." Sacrificing Panic Spellbomb is part of the cost of activating it's ability because it comes before the colon.
602.2. To activate an ability is to put it onto the stack and pay its costs, so that it will eventually resolve and have its effect.
This means that in order to put Panic Spellbomb's ability on the stack, you must pay its costs (tap it and sacrifice it) first, meaning that it would be in your graveyard before it even went on the stack in the first place. Panic Spellbomb would then be an illegal target for Banishing Stroke as Panic Spellbomb would be in the graveyard.
| common-pile/stackexchange_filtered |
RSA to DER anomaly
I have a private key in PEM format and when i run a openssl asn1parse on it i get the following:
0:d=0 hl=3 l= 159 cons: SEQUENCE
3:d=1 hl=2 l= 13 cons: SEQUENCE
5:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
16:d=2 hl=2 l= 0 prim: NULL
18:d=1 hl=3 l= 141 prim: BIT STRING
However if i convert this PEM to DER, and do a openssl asn1parse again, I lose that wrapper and the resulting file size is a bit smaller.
How can i convert the RSA PEM to DER, while keeping the above wrapper?
How are you converting it now?
openssl rsa -inform pem -in key.pem -outform der -out key.der
Can you show us the PEM header for the input file?
Do you mean in hex? Because if not isnt the above post the header?
No. The PEM file is a text file that contains a header, base64 encoded DER data, and a footer. The asn1parse command is just decoding the base64. I'm interested in the PEM header. It's a line that starts with "-----BEGIN " followed by some more text. Depending on what exactly the DER data contains that text will vary.
grrr i dont have the file at hand but i remember there being a few extra bytes at the start at the file that get stripped when the file is converted to der.
I'm trying to figure out what format your input file is in. There is more than one way to store a private key in a PEM file.
block 0-9f snippet....-----BEGIN PRIVATE KEY-----
MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBANVDkSjrm8V5MnKk
FjWgSZy4bHHnHTVy3EdxrkR/NjD1mBgw9y+h
-----END PRIVATE KEY-----
The -----BEGIN PRIVATE KEY----- header you mention in your comment, indicates that you have a private key in PKCS8 format. Although it seems slightly strange to me. I would have expected the asn1parse output to look more like this:
0:d=0 hl=4 l=1213 cons: SEQUENCE
4:d=1 hl=2 l= 1 prim: INTEGER :00
7:d=1 hl=2 l= 13 cons: SEQUENCE
9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
20:d=2 hl=2 l= 0 prim: NULL
22:d=1 hl=4 l=1191 prim: OCTET STRING
Note that you have no INTEGER field in your output.
You can use the openssl pkcs8 utility to convert a PKCS8 file from PEM to DER
openssl pkcs8 -topk8 -in rsakey.pem -out rsakey.der -outform DER -nocrypt
| common-pile/stackexchange_filtered |
How can I reference other servers in the same inventory by group name?
I have a static inventory that contains groups and servers inside these groups. Group names can change and so the server names. I'm passing group names as a variable during runtime to the playbook. I'm trying to check a bunch of ports between different servers in the inventory.
So if this is the inventory
group1
server1
group2
server2
server3
And I have group1 and group2 as variables.
I'm trying to do something like this
hosts: group1_var
tasks:
- name: test connection
ansible.windows.win_wait_for:
host: **{{groups[group2_var]}}** ##How do I implement this correctly????
port: 443
delay: 3
Also a second part to this question, but I cannot for some reason return the value of the magic variable if groupX is a variable. When it's a simple string it returns the server names ok.
debug : msg="{{groups['{{groupX}}']))"
To the one who voted as off-topic because not a programming question: this is a typical loop/control structure problem hence definitely a programming question. And even thought it is a basic question, it is absolutely on-topic Testing connection between machines is only the task ran inside the loop(s) and is not the actual problem here.
What I understand from your question.
You have a source group and target group of server(s)
You want to pass those dynamically to your playbook at run time
You want to run a task on each server in the source group for each server in the target group.
You actually need two loops. The first one is the natural play loop (i.e. hosts parameter in your play). The second loop: will be on your task. I used a debug task for the example. You just have to report the loop on your own task.
Given the inventory inventories/default/main.yml
---
group1:
hosts:
server1:
group2:
hosts:
server2:
server3:
And the following playbook.yml
---
- hosts: "{{ source_group }}"
gather_facts: false
tasks:
- name: test connection
debug:
msg: "testing connection from {{ inventory_hostname }} to {{ item }}"
loop: "{{ groups[target_group] }}"
You can check connections from group1 to group2
$ ansible-playbook -i inventories/default/ playbook.yml \
-e source_group=group1 -e target_group=group2
PLAY [group1] ********************************************************
TASK [test connection] ***********************************************
ok: [server1] => (item=server2) => {
"msg": "testing connection from server1 to server2"
}
ok: [server1] => (item=server3) => {
"msg": "testing connection from server1 to server3"
}
PLAY RECAP ***********************************************************
server1: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Or from group2 to group1
$ ansible-playbook -i inventories/default/ playbook.yml \
-e source_group=group2 -e target_group=group1
PLAY [group2] ********************************************************
TASK [test connection] ***********************************************
ok: [server2] => (item=server1) => {
"msg": "testing connection from server2 to server1"
}
ok: [server3] => (item=server1) => {
"msg": "testing connection from server3 to server1"
}
PLAY RECAP ***********************************************************
server2: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
server3: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
Or even from group2 to group2 itself
$ ansible-playbook -i inventories/default/ playbook.yml \
-e source_group=group2 -e target_group=group2
PLAY [group2] ********************************************************
TASK [test connection] ***********************************************
ok: [server2] => (item=server2) => {
"msg": "testing connection from server2 to server2"
}
ok: [server2] => (item=server3) => {
"msg": "testing connection from server2 to server3"
}
ok: [server3] => (item=server2) => {
"msg": "testing connection from server3 to server2"
}
ok: [server3] => (item=server3) => {
"msg": "testing connection from server3 to server3"
}
PLAY RECAP ***********************************************************
server2: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
server3: ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
From your description
... check ... ports between different servers in the inventory
I understand that you like to do connection test from servers in group1 to servers in group2
group1 --------> group2
---> server2
server1 ---|
---> server3
and whereby servers in group1 (server1) are not the Ansible Control Node.
To do so you could use an approach like
---
- hosts: all
become: false
gather_facts: false
tasks:
- name: Show connection test
delegate_to: group1
debug:
msg: "Connect from 'group1' node to {{ inventory_hostname }}"
when: "'group2' in group_names"
resulting into
TASK [Show connection test] ****************
ok: [server2 -> server1] =>
msg: Connect from 'group1' node to server2
ok: [server3 -> server1] =>
msg: Connect from 'group1' node to server3
Documentation
Controlling where tasks run: delegation and local actions
Sepcial variables
Conditionals
Regarding
I cannot for some reason return the value of the magic variable if groupX is a variable.
you may have a look into the following example
---
- hosts: "{{ target_group }}" # aka group_var
become: false
gather_facts: false
vars:
group_x: "group1"
tasks:
- debug:
msg: "{{ groups[group_x] }}"
and
FAQ
When should I use {{ }}? Also, how to interpolate variables or dynamic variable names?
| common-pile/stackexchange_filtered |
Javascript: Form submits after first validation and after applying styles
Am trying to prevent certain user ids from emails to submit form, like a blacklist, for example<EMAIL_ADDRESS>and take denieduser1 and when the user submits the form then appears a bootstrap alert saying something is wrong, the problem is that if you click on the button again the form is submitted without doing validation again, if I remove the part where styles are applied and use an alert then it works so here is the code am using:
For the form:
<form id="contact" method="post" class="form" role="form" onsubmit="return validate()" action="m41lS3nd.php">
The validation code:
function validate(){
e.preventDefault;
var rejectList = [ "denied1" , "denied2" ]; //List of Blacklisted emails or domains
var emailValue = $('#email').val(); // To Get Value (can use getElementById)
var splitArray = emailValue.split('@'); // To Get Array
if(rejectList.indexOf(splitArray[0]) >= 0) //Check if contains any unwanted emails
{
// Means it has the rejected domains
document.getElementById("notification").style.display = "block"; //If unwanted emails are detected will show an alert
document.getElementById("notification").style.marginTop = "5px";
return false;
}else
var contactform = document.getElementById("contact"); //If good email is entered then get the form name and submits the form
contactform.submit();
return true;
}
The bootstrap alert:
<!--Notification for invalid emails such as spam or unsolicited emails-->
<div id="notification" class="alert alert-warning alert-dismissible fade in" role="alert" style="display: none;">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>Oops!</strong>There is something wrong with your email, your reference code is: BL1SE.
</div>
The Submit Button:
<button class="btn btn btn-md" type="submit">Send Message <i class="fa fa-paper-plane fa-1x" style="color: white;"></i></button>
I took the code and adapted from this post but cannot comment or contact author and don't know what am doing wrong: Code for validation
I tried doing so but then it skips validation and submit the form directly without doing validation I added e.preventDefault; like this: function validate(){ e.preventDefault; var rejectList = [ "denied1" , "denied2" ]; ...}
Please never rely on client-side validation alone. (i.e. javascript..). http form submissions can be faked and will bypass any js validation you do. it's good for UX, but that's it.
In the case when validation is good, it is enough to just return true, cause that will trigger the form submit, otherwise you are doing it sort of twice. And yes, remove the e.preventDefault() & add the right else brace.
It looks like your Javascript syntax is incorrect because e.preventDefault(); is referring to a nonexistent variable. I suspect your Javascript console is reporting the error.
I would also strongly recommend adding {} as appropriate after the else. I'd guess that's not going to behave exactly the way you think. Formatted to show the difference:
} else
var contactform = document.getElementById("contact");
contactform.submit();
return true;
compared with:
} else {
var contactform = document.getElementById("contact");
contactform.submit();
}
return true;
If you added another else/if condition that does not return then you will hit contactform.submit(); without having declaring and initializing contactform.
| common-pile/stackexchange_filtered |
Channel Bleeding with ADG732
I'm building a circuit that uses a 32:1 mux (ADG732) to feed the selected channel into an amplifying stage so I only need one amplifying circuit. The input signals are from pressure sensors which have a capacitive nature and produce ~10mV of amplitude. The problem is that when I try to feed the channels through the multiplexer the sensors connected to the off channels are still affecting the output of the multiplexer; essentially bleeding across the channels in low-frequency operation. I think it might have something to do with the high impedance of the sensor. Is there any way to deal with it or is there a better mux for this purpose? I've tried to separate the input and multiplexer from the rest of the circuits (amplifiers, filter) but there is still crosstalk.
Edit 1:
I'm not switching channels at the moment so I doubt the settling time would be an issue. Also, the original plan is to do the amplifying after mux so I don't need to install 32 amps. The schematic is quite messy but it is basically sensor inputs through header are fed straight into mux then to the amp/filter stages.
This is the circuit with mux
Amplifying/filtering circuit only
Edit 2:
All sensors are on separated sheets of PVDF. The electrodes are attached to copper tape contacts on both sides of the PVDF with a little bit of solder. I do not have sufficient knowledge with ground design so I just tie all the things I want to ground to the GND pin on my microcontroller. Let me also note that when the system is tested with a function generator (20mV sine wave of 5Hz) everything works just fine. The multiplexer has no problem switching and the amplifying and filtering stages also perform as expected.
For example, say channel 1 and 2 are PVDF inputs and channel 3 is the 20mV sine wave at 5Hz. If ch1 is selected and no pressure is applied to ch1 sensor, the output of the multiplexer would just be flat as expected. However, if pressure is applied to ch2 sensor while ch1 is on and ch2 is off, we can observe variation in output caused by ch2 as if ch2 is also on. The same effect applies vise versa. The exception being channel 3 (sine wave) which does not create interference or get interfered by the first to channels.
How quickly are you changing the multiplexer from one channel to the next?
Need a schematic for this question. You should pre amplify the 10mV signal before sending it through the mux.
Can you post a link to pressure sensors you are using? Also, can you quantify the effect of "bleeding" you see?
Where is the reference ground to your sensors?
It's some generic PVDF film with electrode attached for testing so there isn't a spec sheet for it. The whole circuit is powered by Teensy 3.6 which offers a 5V output. One of the electrodes of the PVDF film is connected to the header that leads into the mux while the other electrode is connected to the ground of Teensy. The effect of the bleed is quite significant since almost all voltage from any off channel appears at the output with little or no attenuation.
Nothing is clear. You are saying that applying pressure to one piezoelectric sensor causes voltage change on all sensors. You probably need to draw the sketch of your sensor array, how "electrodes" are attached to the film, whether all are on the same PVDF sheet, and again, now grounds are distributed/connected.
Tell us about your GND system. Or attach a photo.
Sorry about the lack of clarity. I've added some further explanation of the design setup and figure. Really do appreciate the help.
Between each multiplexer input line (whether on or off) and the common drain (output) there is a capacitance of around 150 pF. This is round-about stated on page 4 of the data sheet - it talks about On Switch Drain, Source Capacitance of 350 pF and it will be similar when the switch is off because internally it's a JFET or MOSFET. It might be as low as 100 pF when off but, for a ball-park figure I'd go for 150 pF.
So you have 31 unused channels all injecting a bit of charge through these 150 pF capacitors and, on the common drain pin you have a virtual earth amplifier responding accordingly. I understand it's this way because you are trying to amplify charge and convert it to voltage.
Do you start to see the problem you have? All 31 together can be regarded as a single input with a capacitance directly to the D pin of nearly 5 nF and this will potentially be a significant noise source and cross-interference source.
Also, on your schematic I don't see where your 0 volts comes from.
I can see that Cs and Cd would be problematic due to charge injection, but I am not switching channels at all and my input signals are at best 50Hz. So I guess even if the 31 off pins are combined, due to the low-frequency signals the impedance of the capacitor should be massive. (I'm referencing the figure on the left at 5:41 by Texas Instrument)
I’m not talking about switching channels. Your feedback capacitor is 3.3 nF and that is the same order as the combined capacitance of the multiplexers.
Where does the 3.3nF come from?
C1 is 3n3 I presume - it has 332 in the part number and this usually means 3300 pF = 3.3 nF.
It's actually 300pF which would only make it worse I suppose. Regardless, I tried the multiplexer without the rest of the circuit but it still does not work. I'm guessing it's due to the high source impedance.
With or without your op-amp charge amplifier you will still have similar issues. It's capacitive coupling. To prove this, get a heap of 100 pF capacitors and replace the multiplexer with just capacitors and see what happens.
What would be a good way to decouple these capacitors or reduce such noise?
I hate to say it but putting an amplifier on each input appears the only likely solution. I hate to say it because not using an amplifier per channel (and hence having a low driving impedance for the selected channel) appears the only fix. I have tried to think of an alternative but failed in that respect.
@Andyaka I hate to say it but putting an amplifier on each input appears the only likely solution. Sometimes op-amps are way cheaper than extra engineering time, too :)
| common-pile/stackexchange_filtered |
Linux error creating temporary file /var/tmp/
I'm using centos 6 - recently I am getting this error anything I want to install anything on server for example with varnish - var/tmp is empty and has root:root as owner i have checked with 777 permission on var/tmp directory but still same error -
Also checked if it was related to systemd using below command -- but results showing other
pidof systemd && echo "systemd" || echo "other"
error is below
Total download size: 2.2 M
Installed size: 8.1 M
Is this ok [y/N]: y
Downloading Packages:
varnish-5.2.1-1.el6.x86_64.rpm
| 2.2 MB 00:00
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
error: error creating temporary file /var/tmp/rpm-tmp.cNUXgY: No such file or directory
error: Couldn't create temporary file for %pre(varnish-5.2.1-1.el6.x86_64): No such file or directory
Error in PREIN scriptlet in rpm package varnish-5.2.1-1.el6.x86_64
error: install: %pre scriptlet failed (2), skipping varnish-5.2.1-1.el6
Verifying : varnish-5.2.1-1.el6.x86_64
1/1
Failed:
varnish.x86_64 0:5.2.1-1.el6
Never chmod 777 anything for any reason. There is no good reason to ever use this command. This is much too destructive. In the case of a temporary directory, it will just stop working properly.
/var/tmp should be mode 1777 (with the sticky bit set). What does ls -ld /var/tmp show? Also, please show us the preinstall script being run by the package: rpm -qp --scripts varnish-5.2.1-1.el6.x86_64.rpm.
The correct permissions for /var/tmp would be "1777". Only "777" does not set the sticky bit which could be part of the issue.
Could you check if "mktemp -d --tmpdir=/var/tmp rpm-tmp.XXXXXX" is working? This is to test if creating a temp directory is working at all.
Secondly you could try to disable SELinux temporarily. Maybe RPM is changing some context internally and therefore is not allowed to created directories.
If that doesn't help we would need more information:
how do you install the package?
does it work for other packages?
system setup
recent changes, did it work before those changes?
have tried with 1777 permission aswell for both tmp and var/tmp 2. mktemp -d --tmpdir=/var/tmp rpm-tmp.XXXXXX is giving output /tmp/ci-REI2MPBNPl - SELinux is enabled i have set to disable - running sudo setenforce 0 - but after checking it still showing as enabled - in permissive mode.
Installing packages via command line bitvise as root user - it doesnt work for other packages - system has centos 6 + apache and nginx 16gb ram -- i have only realised this issue today maybe it happened before - but i have been able to install previously just that i havent had to install anything for long time - only issue was with a server power outage and it was fixed by hosting and rebooted
You can disable SELinux from the configuration. This way it's disabled for everything.
Could you also check if /var/lib is a separate file system and if yes how it's mounted? Maybe it's mounted readonly. Just a wild guess.
tried disabling from configuration file as mentioned - but doesnt fix issue - [Home]/var/lib/ and has 0755 please can you clarify what you mean by how its mounted
D'oh, I meant /var/tmp in my last answer, not /var/lib. Sorry for that.
Check with "df" if /var/tmp appears as a separate filesystem. If yes then run "mount" (without options) and find the line which represents the mount point. There you find the mount options.
thanks i checked using findmnt got output like this
├─/home /dev/mapper/vg_is74154-lv_home
└─/var/tmp (deleted) /dev/mapper/vg_is74154-lv_root[/tmp//deleted]
running df doesn't show it being separate file system
This "(deleted)" hint from findmnt is weird. Especially as it is also noted for lv_root. This points to some problem with your LVM. Unfortunately I don't have a machine with LVM at hand to reproduce this. You should check your LVM setup, especially if the LV root_fs is ok. Did you add/remove/modify volumes lastly?
LV is looking ok - can this be permission or configuration issue tried lots of different things but nothing is fixing this issue
To be honest it's hard to tell without seeing the system. Try adding all information about your LVM setup, everything we found in the last hours and all changes you tried to fix it into your question. Maybe some other people have ideas then.
i just tried install of some .rmp and it got completed so it must be some issue it has with installing varnish using epel - i have done it in past without issue but dont understand why it doesnt install now
it wont let me uninstall epel aswell showing same error couldnt create a temporary file for error
| common-pile/stackexchange_filtered |
PRISM Navigation - Xamarin Forms - MasterDetail/FlyoutPage page setup, previous page nav links disabled when back button pressed?
So I built an app using Prism Library and Xamarin Forms and the Navigation flow starts with a MasterDetail page, like so.
NavigationService.NavigateAsync($"/{nameof(MainMenuPage)}/{nameof(NavigationPage)}/{nameof(DashboardPage)}");
MainMenuPage
My MainMenuPage contains the Flyout page with a ListView of the MenuItems
<FlyoutPage.Flyout>
<NavigationPage
NavigationPage.HasNavigationBar="false"
Icon="{ StaticResource HamburgerIcon }"
Style="{ StaticResource MainMenuStyle }"
Title="{ grial:Translate PageTitleMainMenu }">
<x:Arguments>
<ContentPage>
<Grid>
<BoxView
Style="{ StaticResource MainMenuOrModalBackgroundStyle }"
Opacity="1" />
<Image
Style="{ StaticResource MainMenuBackgroundImageStyle }" />
<Grid
grial:Effects.ApplyIOSSafeAreaAsPadding="Left,Right"
RowSpacing="0"
VerticalOptions="FillAndExpand">
<Grid.RowDefinitions>
<RowDefinition
Height="Auto" />
<RowDefinition
Height="*" />
<RowDefinition
Height="Auto"/>
</Grid.RowDefinitions>
<local:BrandBlock
Grid.Row="0"
Grid.Column="0"
Margin="20,60,20,30"
VerticalOptions="Start"
HorizontalOptions="Start" />
<ListView
Margin="0,0,0,10"
Grid.Row="1"
SelectedItem="{ Binding SelectedMainMenuItem, Mode=TwoWay}"
ItemsSource="{ Binding MainMenuItems }"
VerticalOptions="FillAndExpand"
Style="{ StaticResource MainMenuListViewStyle }">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<views:MainMenuItemTemplate />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.Behaviors>
<behavior:EventToCommandBehavior EventName="ItemTapped"
Command="{Binding NavigateCommand}"
EventArgsParameterPath="Item">
</behavior:EventToCommandBehavior>
</ListView.Behaviors>
</ListView>
<views:ApplicationVersionTemplate Grid.Row="2" Margin="35,0,0,20" HorizontalOptions="Start" VerticalOptions="Start" />
</Grid>
</Grid>
</ContentPage>
</x:Arguments>
</NavigationPage>
</FlyoutPage.Flyout>
<FlyoutPage.Detail>
<NavigationPage>
<x:Arguments>
<ContentPage>
<Grid></Grid>
</ContentPage>
</x:Arguments>
</NavigationPage>
</FlyoutPage.Detail>
I'm navigating to the detail pages using the following format:
await NavigationService.NavigateAsync($"{nameof(NavigationPage)}/{SelectedMainMenuItem.PageName}", null, SelectedMainMenuItem.IsModal, SelectedMainMenuItem.IsAnimated);
I noticed in a lot of the samples, the MasterDetailPage.Master node is in a ContentPage not a NavigationPage node like I'm doing. Is that what I'm doing wrong? It looks to me like NavigationPage is a child of Master here. Is that correct? Just trying to figure out why when I go back to a previous page (by pressing the back button in the navbar) the page is disabled, meaning the navigation links no longer work. My initial root page navigation is absolute, all the rest of the Navigate commands are relative.
Note - I changed the MasterDetailPage to FlyoutPage since the naming changed in Xamarin.Forms v5. This bug was happening before I changed the name to FlyoutPage.
I don't know about FlyoutPage.Detail, but MasterDetailPage.Content should be left empty in xaml, it's filled automatically when navigating.
Also, with MasterDetailPage, I navigate to ../SomeOtherPage to add it to the stack (enable back button). Navigate to /MainPage/NavigationPage/AnotherPage to replace the stack (no back button).
So, I rolled back my code to a previous version and then, one at a time, added back in the packages and code changes, smoke testing each iteration along the way. My best guess is there was a conflict between Telerik UI for Xamarin package and the latest Xamarin Forms version but I can't be sure. I updated Xamarin Forms and Prism to latest update and it's all working fine.
| common-pile/stackexchange_filtered |
How to build a C++ make project using specific LDFLAGS (Mac OSX)
I have a project that needs to be built using cmake and make. However, I want the project to use libc++ (since its written in C++11) so I need to set the right linker flags. Is there a way I can pass the following flags via command line?
LDFLAGS="-L/usr/local/opt/llvm/lib -Wl,-rpath,/usr/local/opt/llvm/lib"
Or do I need to edit my CMakeLists.txt file? If so how can I add this to the file?
For the more complex linker flags use
set (CMAKE_SHARED_LINKER_FLAGS -Wl,-rpath,/usr/local/opt/llvm/lib)
To add a library search directory (-L) simply add
link_directories(/usr/local/opt/llvm/lib)
See also this and that answer
| common-pile/stackexchange_filtered |
C++ analog to array of records in Pascal
I'm learning C++. My main language is Free Pascal. In FP I can do this:
type
TSomeType = (Foo1, Foo2, Foo3);
TSomeRecord = record
Field1: String;
Field2: String;
end;
var
MyArray: array[TSomeType] of TSomeRecord;
So array has length=3. Then I can use it for example: MyArray[Foo2].Field1 := 'Some string' Can I do something similar in C++? Can't find solution in C++ array tutorials
Regards
I don't know FP, but that looks like an associative array to me. If so, look at std::map.
in C you can use struct for a record and regular array. You can use it in C++ too but in C++ you should use objects instead (FP has ocjects too).
@ImreL: The only difference between a struct and a class in C++ is the default visibility of members and inheritance.
Can you explain exactly what that code for?
@EdS. actually the only difference is default visibility, a struct can inherit just like a class
@aaronman: You misread my comment. I said "the default visibility of members and inheritance.". Inheritance is public by default with structs, private with classes. There are two differences, the latter often forgotten and not as widely known. I can see how the comment came off that way though.
You are correct interesting
I know C++ structures, but I didn't know how to do array where length is some enum. Problem solved by VoidStar. Thanks
Equivalent code in C++ would look something like this :
enum { Foo1, Foo2, Foo3, N };
struct SomeRecord
{
string Field1;
string Field2;
}
SomeRecord array[N];
array[Foo2].Field1 = "Some String";
This is the most direct equivalent, but in C++ it's more normal to use vector<SomeRecord> rather than a C-style array. A vector behaves mostly like an array, but can grow/shrink to hold more/fewer items. Combined with C++11 move semantics, it can be surprisingly efficient to "copy" around too - where possible, operations that look as if they require the array to be copied are implemented by messing with pointers behind the scenes. This makes life easier for passing/returning vector values to/from functions, among other things.
| common-pile/stackexchange_filtered |
Did I get a lemon, or does the ipod touch g4 come with a crappy usb cable?
Really, I mean you shell out $300 for this thing you'd think the usb cable would be able to sync after two months of use.
I ended up buying one from China that works just fine (as opposed to the one that came with it!)
I noticed the new USB cable that came with my iPhone 4 was different than the older one with iPhone 3G, and even different than the one that came with my iPad. It was made with that new "rubberized" white plastic like the new ear buds, that seems springier.
Anyway, if the cable stops functioning under normal use after only two months, I'm quite certain it would be covered under Apple's iPod one year warranty. You should go to your friendly neighbourhood Apple Store or inquire about a replacement.
Yeah that sounds like a good idea.
I believe that all current generation Apple devices some with the same sync cable. From my experience (almost everyone I know is an apple fan) some people wear through them pretty quickly (usually girls who wind them up and put them in hand bags etc) and some last forever (such as mine which just sits on the desk and only gets used every few days. its the original cable that came with my first iPhone a few years back and still works fine).
I've had mine for 2 months, throwing it in the bottom of my bag every day, and I've had no problems with it yet.
It's the same thickness as the previous iPod USB cable I have, though softer. That one is several years old and still working fine, though I haven't abused it nearly as much.
One nice thing is that, despite being Apple-proprietary, the cable itself is fairly standard across their products these days, so if you have a friend who upgrades iPods/iPhones a lot, they might have a spare (or three) they'd be willing to give you.
Also, FWIW, Apple's cable was almost certainly from China, as well. :-)
| common-pile/stackexchange_filtered |
can't retrieve image id from build stream when trying to debug with a remote interpreter defined with docker
I get "java.util.concurrent.completionexception: com.intellij.docker.agent.apitaskexception: can't retrieve image id from build stream" when trying to debug a certain python script with a remote python interpreter defined either using a docker or docker-compose.
I can run the image and can launch my app using docker-compose up from terminal without issues. Docker is well defined within pycharm as I see it in the services.
pycharm profession 2024.3.1
Windows environment with docker 4.20.1 with wsl
My computer isn't connected to the internet.
I read previous similar topics but they all mentioned the obvious things of verifying the docker image and docker plugin to pycharm.
what I'm missing?
| common-pile/stackexchange_filtered |
How to determine if a GitHub project has a POM file or not?
I'm a member of an organization on GitHub, which has varieties of different projects in it. I'm looking for a way to check the type a project, without actually opening it.
For example, if it is a Maven project, I want my program to return pom.xml, if it is a Python project, return a requirements.txt, and if it is a Ruby project, return Gemfile and so on.
Is there any way I can determine the type of the project? I tried searching online, but wasn't able to find this functionality available in any API.
Any help is appreciated.
I don't have an answer, unfortunately, but for a second I thought you were searching GitHub for pornography, not "pom" files...
The following works with curl, jq and XMLStarlet. See also GitHub API Overview. There's also a Ruby library to access the API.
Organization's repositories
$ curl -s https://api.github.com/orgs/apache/repos?per_page=4 | \
jq ".[] | {project: .full_name}"
{
"project": "apache/tapestry3"
}
{
"project": "apache/apr-iconv"
}
{
"project": "apache/tapestry4"
}
{
"project": "apache/tapestry5"
}
File existence and content (POM)
$ curl -s https://raw.githubusercontent.com/apache/maven/master/pom.xml_does_not_exist
404: Not Found
$ curl -s https://raw.githubusercontent.com/apache/maven/master/pom.xml | \
xml sel -t -o "[" -v "//_:project/_:parent/_:groupId" -o "|" \
-v "//_:project/_:groupId" -o "]:" -v "//_:project/_:artifactId" -o ":" \
-v "//_:project/_:version" -n -t -v "//_:project/_:name" -n -v "//_:project/_:description"
[org.apache.maven|]:maven:3.5.0-SNAPSHOT
Apache Maven
Maven is a software build management and
comprehension tool. Based on the concept of a project object model:
builds, dependency management, documentation creation, site
publication, and distribution publication are all controlled from
the declarative file. Maven can be extended by plugins to utilise a
number of other development tools for reporting or the build
process.
Thanks for your answer! I was looking to do something quite similar to this. This helped me get an idea of what I was missing with the GitHub API! :)
| common-pile/stackexchange_filtered |
( "SELECT password FROM peerlist WHERE username=?",username1)
I created a login window and there was a table "peerlist" that contains name, username, password. I want to verify the username and password from the table.
username1 contains name of user that I get from login window. I tried to retrieve password using username1.
cursor.execute( "SELECT password FROM peerlist WHERE username=?",username1)
But there was an error
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current
statement uses 1, and there are 3 supplied.
cursor.execute("SELECT password FROM peerlist WHERE username=?",[username1]) should do it.
Use a tuple for the parameters:
cursor.execute( "SELECT password FROM peerlist WHERE username=?", (username1,))
The parameters are supposed to be a tuple or a list (a sequence); but a string is a sequence too (it has a length and you can address the individual characters), so you gave the .execute() call a sequence of len(username1) characters instead of one parameter. Apparenty the username is 3 characters long, hence the error message.
This is bad idea, will cause SQL-injection. Details refer to http://docs.python.org/2/library/sqlite3.html
cursor.execute( "SELECT password FROM peerlist WHERE username=%s"%(username1))
No, no, no, no, no. Don't replace strings on your own. sqlite3 can do that for you in an SQL-injection safe way.
You just opened a SQL injection attack. Can I come hack your web apps?
I try it,
here username1 contain value alan
but there is an error.
sqlite3.OperationalError: no such column: alan
| common-pile/stackexchange_filtered |
Single Supply OpAmp AC Analysis in LTspice
I'm trying to build a non-inverting amplifier with a gain of two, with a little bit of filtering. I need to amplifier a signal from 0Vdc-to-1.65Vdc to 0Vdc-to-3.3Vdc, and ideally have a low-pass cut-off around 1.3kHz
Looking through the net I can't really understand how to do an AC analysis on a single supply opamp circuit, there are a million-and-one examples of dual-supply OpAmp filters, but I've not seen any demonstrating a single supply OpAmp filter AC analysis for frequency response - can anybody help?
I think I found the solution - and that is to correct (for the AC Analysis only) the bias points, so this means the AC source is offset by mid-rail (in this case 1.65) as is the bottom side of R1
However - I would still love to make sure this approach is correct
Cheers!
There isn't really much difference for AC analysis for a single-supply op-amp. The input needs to be offset to accommodate the op-amp's input range limits.
In your example, add a 833mV DC supply between the AC1 generator (-) pin and GND. This will provide an offset for the signal. The DC offset will be amplified by 2 to yield 1.66V at the output with AC = 0.
Once you've done that, make sure your offset AC swing is still within the range of the op-amp common-mode range. This can be quite a bit smaller than you expect. The AD8605 supports rail-to-rail input. You'll need to reduce the AC component so that the output isn't going to clip. Suggest maybe 100mV.
Thanks! Think I've got it. Cheers!
In general, opamps don't "know or care" if they have a single or dual supply. It's just a question of what you call the 0V reference. There are techniques to generate an artificial mid rail "0V" (it's called a "virtual ground") if you are constrained to a single supply, and even specialist chips to do this, but the op amp operation is unaffected, so long as it works works well.
There are op amps like this one, billed as "single supply" opamps, but in this case the description really means that the output can operate all the way to 0V (the "negative" supply). This is not the general case.
In short, and op amp can be "single supply" if you ensure that it is biassed somewhere sensible between its supply pins. In a "split supply" situation, we call that point "0V", but it could just as well be +2.5V in an app with 5V supply only. What we need to take care of is that the op amp output will get close enough to the supply pins for our intended application.
From this, it is clear that SPICE analysis of the opamp circuit itself does not differ at all between the two cases. It's just a question of what we label as 0V.
You need to DC-bias the input so your amplifier is not saturated. Normally you'd put it in the middle of the output range. Simulate that first (.op). You can stack a DC supply on the AC input.
You should also ensure that with your desired signal level the amplifier does not clip or unduly distort. You'll need a transient simulation for that, with appropriate bias and input signal. This is not necessary for the AC analysis but the AC analysis is not useful if the amplifier is going to be clipping.
Don't bother changing the input level for the AC analysis, it only scales the output results and adds potential confusion. AC analysis replaces the nonlinear components with linearized equivalents about the operating point, so nonlinear effects are ignored.
| common-pile/stackexchange_filtered |
Where is the obb(expansion) file location on a nexus 5 running Android 6.0.1 for development?
I have a nexus 5 device running Android 6.0.1 and I'm developing an app that needs to use expansion files. I am having trouble with where to put the obb file on the device for testing!
I'm using android studio for development and the app installs on the device, however, it fails because the obb file is not present.
I'm sure there is a simple explanation, but I have failed so far!
In android 5 on the same device, it was in the /mnt/shell/emulated folder, however that folder does not appear to exist any more in android6
Thanks in advance for any help
| common-pile/stackexchange_filtered |
Which class needs to implement INotifyDataErrorInfo?
In the case of a binding such as
<TextBox Text={Binding Path=SomeItem.AnotherItem.Property} />
Which class(es) need to implement INotifyDataErrorInfo:
The DataContext
SomeItem
AnotherItem
Some combination of these
AnotherItem
INotifyDataErrorInfo must be implemented by object who own's the property to which is bound.
If you're using an MVVM pattern , the INotifyDataErrorInfo is usually implemented by the view-model. This view-model, usually, is then your view's datacontext.
| common-pile/stackexchange_filtered |
Getting an error 'Unknown column' in 'order clause' using TypeORM
I'm trying to create a query with TypeORM and MySQL.
I keep getting the following error:
[Nest] 44806 - 12/09/2021, 2:37:03 PM ERROR [ExceptionsHandler]
ER_BAD_FIELD_ERROR: Unknown column 'sort_order' in 'order clause'
QueryFailedError: ER_BAD_FIELD_ERROR: Unknown column 'sort_order' in
'order clause'
My query is:
const { limit, page: skip, userLat, userLng, searchQuery, weekday, startHour, endHour } = options;
let stores;
// get only stores that open in the start and end hours range
const openHoursQuery = `
'${startHour}' BETWEEN \`from\` AND \`to\` AND
'${endHour}' BETWEEN \`from\` AND \`to\`
AND weekday = ${weekday}
`;
// get the distance from user's location to each store
const getDistanceQuery = `
SQRT(
POW(69.1 * (lat - ${userLat}), 2) +
POW(69.1 * (${userLng} - \`long\`) * COS(lat / 57.3), 2)
) AS distance
`;
stores = this.storeRepository
.createQueryBuilder('store')
.leftJoinAndSelect('store.hours', 'store_hours')
.addSelect(userLat && userLng ? getDistanceQuery : '')
.where(searchQuery ? `name LIKE '%${searchQuery}%'` : '')
.andWhere(weekday && startHour && endHour ? openHoursQuery : '')
.orderBy(userLat && userLng ? 'distance' : 'sort_order') //sort_order
.take(limit)
.skip(skip)
.getManyAndCount();
return stores;
The problem is caused by the "leftJoinAndSelect" method, when I comment the join the query executes without any problems.
My DB tables look like this:
TABLE: stores
COLUMNS: id, uuid, name, status, address, URL, email, lat, long, sort_order
Table: store_hours
COLUMNS: id, store_id, weekday, from, to, type
EDIT:
I managed to understand the issue, I had to use store.sortOrder which is the name corresponding field in the 'store' Entity.
I have now a follow-up issue that sort by distance is not working when I use the 'join' method.
'distance' is an additional field I created in the select to sort the stores by the distance from the user.
Thank you
Found the answer.
I should of use the Alise argument and not create alise myself.
Solution:
.addSelect(userLat && userLng ? getDistanceQuery : '', 'distance')
.orderBy(userLat && userLng ? 'distance' : 'store.sortOrder')
| common-pile/stackexchange_filtered |
Strong /strɔːŋ/ → stronger /strɔːŋɡər/ - Why do we have to put an extra /g/ in front of /ər/? Is it a rule?
Ok, see this in the dictionary:
Strong → /strɔːŋ/
Stronger → /strɔːŋɡər/
Why do we have to put an extra /g/ in front of /ər/?
But sing → /sɪŋ/ & singer → /ˈsɪŋər/ do not adhere to that rule. But "sing" is not an adjective.
Is it a rule that whenever we see /ŋ/ at the end of an adjective & if we want to put -er at the end of that word, then we will pronounce it like /ŋɡər/?
I'd say it's not so much a rule as just a reflection of the most common pronunciations. In some parts of England (think Beetle territory), singer might be pronounced as /sɪŋɡər/.
"Sing" doesn't end with a hard g.
"Sing" and "Strong" end with exactly the same sound for me. And I do know people who say //ˈstrɔːŋər/ (And it always sounds weird to me.)
There aren't many adjectives that end with /ŋ/ and that take the endings -er -est, so it's debatable if this is a rule. However, it does also apply to the adjectives long and young. I'm uncomfortable adding -er -est to the adjective wrong, but if I did I would not insert a /g/.
@ralph.m Yes, in the midlands and in Norfolk too!
@sumelic The Longman's pronunciation dictionary backs you up on that point about comp and sup forms of wrong although I personally have a /g/ in wronger but not in wrongest. However, in general the observation about /ng/ in adjectives seems to hold as described by Roach, for example, in my post below.
@Araucaria: Well, it's not a very large sample size... as I said, I can only think of the three words long, strong, and young. I guess as an experiment, it might be possible to try to elicit comparative and superlative forms of monosyllabic pseudo-words ending in eng and see what native speakers tend to do.
@sumelic Yes, that would be an interesting experiment.
In both Southern Standard British English and General American, there is indeed a phonological generalisation that can be made such that adjectives ending in /ŋ/ have comparative forms ending in /gə/ (or /gər/ in Gen Am).
The phoneme /ŋ/ in English is phonologically interesting in its own right. For a start in English there are no words that begin with this morpheme. There are lots of words beginning with the other nasals /m/ and /n/, but none with /ŋ/. This makes /ŋ/ the only consonant in English which doesn't occur at the beginning of English words. Even /ʒ/ occurs at the beginning of one relatively frequent English word, the word genre.
Secondly the distribution of /ŋ/ within words is very interesting too. Here is an excerpt from Peter Roach's English Phonetics and Phonology: A Practical Course (2009, pp 46-48), which explains why and also addresses the adjective question:
Medially, ŋ occurs quite frequently, but there is in the BBC accent a rather complex and quite interesting rule concerning the question of when ŋ may be pronounced without a following plosive. When we find the letters 'nk' in the middle of a word in its orthographic form, a k will always be pronounced; however, some words with orthographic 'ng' in the middle will have a pronunciation containing ŋg and others will have ŋ without g. For example, in BBC pronunciation we find the following:
A: 'finger' fɪŋgə, 'anger' æŋgə
B: 'singer' sɪŋə, 'hanger' hæŋə
In the words of [...] A the ŋ is followed by g, while the words of [...] B have no g. What is the difference between A and B? The important difference is in the way the words are constructed - their morphology. The words of column B can be divided into two grammatical pieces: 'sing' + '-er', 'hang' + '-
er'. These pieces are called morphemes, and we say that column B words are morphologically different from column A words, since these cannot be divided into two morphemes. 'Finger' and 'anger' consist of
just one morpheme each.
We can summarise the position so far by saying that (within a word containing the letters 'ng' in the spelling) ŋ occurs without a following g if it occurs at the end of a morpheme; if it occurs in the middle of a morpheme it has a
following g.
Let us now look at the ends of words ending orthographically with 'ng'. We find that these always end with ŋ; this ŋ is never followed by a g. Thus we find that the words 'sing' and 'hang' are pronounced as sɪŋ and hæŋ; to
give a few more examples, 'song' is sɒŋ, 'bang' is bæŋ and 'long' is lɒŋ. We do not need a separate explanation for this: the rule given above, that no g is pronounced after ŋ at the end of a morpheme, works in these cases too, since
the end of a word must also be the end of a morpheme. (If this point seems difficult, think of the comparable case of sentences and words: a sound or letter that comes at the end of a sentence must necessarily also come at the end
of a word, so that the final k of the sentence 'This is a book' is also the final k of the word 'book'.)
Unfortunately, rules often have exceptions. The main exception to the above morpheme-based rule concerns the comparative and superlative suffixes '-er' and '-est'. According to the rule given above, the adjective 'long' will be pronounced lɒŋ, which is correct. It would also predict correctly that if we add another morpheme to 'long', such as the suffix '-ish', the pronunciation of ŋ would again be without a following g. However, it would additionally predict that the comparative and superlative forms 'longer' and 'longest' would be pronounced with no g following the ŋ, while in fact the correct pronunciation of the words is:
'longer' lɒŋgə 'longest' lɒŋgɪst
As a result of this, the rule must be modified: it must state that comparative and superlative forms of adjectives are to be treated as single-morpheme words for the purposes of this rule. It is important to remember that English speakers in general (apart from those trained in phonetics) are quite ignorant of this rule, and yet if a foreigner uses the wrong pronunciation (i.e. pronounces ŋg where ŋ should occur, or ŋ where ŋg should be used), they notice that a mispronunciation has occurred.
[...]
The velar nasal consonant ŋ is, in summary, phonetically simple (it is no more difficult to produce than m or n) but phonologically complex (it is, as we have seen, not easy to describe the contexts in which it occurs).
(pp. 46-48)
Richard Venezky summarises the situation in relation to adjectives in The American Way of Spelling (1999):
However, the pronunciation of any form ending in < nger > or < ngest > cannot be predicted unless the morphemic identities or and are known. If these are the comparative and superlative endings, then < ng > is pronounced /ŋɡ/, as in stronger, in most other cases the /ŋɡ/ cluster is leveled to /ŋ/, just as it is in word-final position. (p. 139)
We can demonstrate that this is because of the fact that these words are adjectives and not for another reason by comparing homophonous noun and adjective pairs.
Imagine that a cruise liner sinks in the middle of the ocean. All the inhabitants survive and end up on a desert island. After a couple of years they have built a new rudimentary society. The island however, is divided into two camps. There are those who are very happy to be away from their old lives and who don't want to be discovered or rescued. Then there are those that long to go back home and join their families who think the islanders should try and make contact with the outside world. The ones that long to go home are dubbed the longers. Notice that this word has no /g/ sound in it. The base of this word longer, is the verb long. The noun is made from adding the ER suffix (or, more strictly speaking the -ə(r) suffix) to this base. We can contrast this /g/-less word with the adjective longer meaning more long. This is made similarly by adding an -ə(r) to the base long. However, because this is an adjective form adding the suffix requires a /g/ to be inserted at the end of the root.
So, if the Longers were to have a change of heart, we could have the following sentence:
The Longers were longers no longer.
Note that this will not be true for all varieties of English. Some varieties always have a /g/ following an /ŋ/, regardless of the part of speech. Others may have no /g/ in the comparative adjective forms. Some may have other complicating factors determining whether or not a /g/ is present.
Hi, very interesting but I could not find "Longer" with the meaning of "The ones that long to go home" in the dictionary. Where do you get that word?
@Tom Thank you :) It's a freely productive affix. You can add -er to any base verb to give you a well-formed noun meaning a person or thing that does that thing. See -er noun suffix definition 2 here at Merriam Webster : )
+1 @Araucaria, thoroughly put. Could I add that, as afar as I can tell, /ŋ/ in English is always preceded by a short single vowel, never a long vowel or diphthong? If that's true, I guess it's a consequence of the fact that /ŋ/ is always derived from /n/ + /g/ or /n/ + /k/.
Also, could it be that the comparatives like 'stronger' are treated differently because (e.g.) the OE form was 'strengra' - no vowel between the /g' and the /r/ - which presumably reduced later to *strengr, with syllabic 'r'. This would have been easier to pronounce with the /g/ in place.
@DavidGarner Yes, in fact the last elipsis in the Roach text is a paragraph from the book which says exactly that! Re the OE, I'd never heard that before but it sounds eminently plausible to me. (I'm not good on OE though, so your guess is better than mine!)
My OE is limited to 'An Old English Grammar' by Randolph Quirk!
@DavidGarner with one exception being the onomatopoeic word boing!
"Stronger" results from a morphological process which adds an ending to the stem "strong". "Singer results from a syntactic process which adds an ending to the word "sing". "G" is lost at the end of a word after velar nasal, but this does not happen at the end of a stem which is not also the end of a word.
In standard generative phonology (e.g., SPE), the difference is annotated by putting the # boundary before and after every word, so that "sing" is preceded and followed by #, but the "-er" agent suffix is not a word, so the combination is written "#sing#er#". However "strong+er" has only the weaker + morpheme boundary at the end of the stem "strong".
Aside from its effect in causing the deletion of preceding "g" after engma, the # boundary also determines the end of a stress word. The addition of "#er" to a verb never affects the position of the stresses in the verb.
Greg Lee, are you really telling us that when the average English-speaker says [or said, when this difference was established] "She's a stronger singer", he's aware of a two different processes, and decides whether to pronounce the G accordingly? To me, and to most English-speakers, both '-er's are just endings.
@DavidGarner, no, I can't see into people's heads. I gather that you can.
I really don't see how you might infer that from my last comment. I think I posed a reasonable question.
@DavidGarner, I said nothing about what people are aware of or about processes of affixation. You are saying something about that, for "most English speakers". How could you possibly know? You give no evidence at all. It seems reasonable to me to infer that your vision into English speakers' heads is much superior to mine.
you're quite right that I made an unwarranted assumption, because it seemed self-evident to me that the two processes - morphological and syntactic - that you describe would be indistinguishable to a lay speaker. However, you're a linguist and I'm an old coder who's read a few books on language, so I'm going to back down here!
| common-pile/stackexchange_filtered |
C#: Class/Method That Builds Connection
Completely new to C#.
In my app, several buttons will connection to MySql and pass information to and from it. Each button has it's own connection string, which I find redundant and was curious if there was a way in C# to build a Class or Method, holding the connection string, and call the connection in each button, instead of establishing the connection, then calling it.
I tried building a Public Method which used MySqlConnection mycon parameter and had it return mycon, however, in the other buttons, it saw mycon as a method, not an object. From there I tried a Class (using syntax from dotnetperls and other sites), which have yielded other errors about type. Clearly, being new to this, I am approaching the wrong syntax to build a Class and Method, though I'm assuming that since a Method will be an action, I am actually seeking a class that will hold the objects and allow other parts of the program to access it.
See below pseudo-code as an example:
Current
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection mycon = new MySqlConnection();
mycon.ConnectionString = "Connection";
mycon.Open();
// Code
mycon.Close();
}
private void button2_Click(object sender, EventArgs e)
{
MySqlConnection mycon = new MySqlConnection();
mycon.ConnectionString = "Connection";
mycon.Open();
// Code
mycon.Close();
}
private void button3_Click(object sender, EventArgs e)
{
MySqlConnection mycon = new MySqlConnection();
con.ConnectionString = "Connection";
mycon.Open();
// Code
mycon.Close();
}
Goal:
Some Class
{
//MySqlConnection parameters establish mycon
}
private void button1_Click(object sender, EventArgs e)
{
mycon.Open();
// Code
mycon.Close();
}
private void button2_Click(object sender, EventArgs e)
{
mycon.Open();
// Code
mycon.Close();
}
private void button3_Click(object sender, EventArgs e)
{
mycon.Open();
// Code
mycon.Close();
}
Note: I am aware of the XML approach (and have used it in another one of my programs), but am trying to see if there's a Class/Method approach.
You should be wrapping all your connections in using's.
And also probably not doing directly it in your UI's event
I'd suggest having a method (can probably be static, and exist in a place accessible from anywhere in your code) that deals with all the details of getting a connection, and returns it. Then anywhere you need a connection, call that method.
class SomeClass
{
private void button1_Click(object sender, EventArgs e)
{
using (var conn = Utilities.GetConnection())
{
conn.Open();
// Code
}
}
}
public static class Utilities
{
public static MySqlConnection GetConnection()
{
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Connection";
return conn;
}
}
And use using to ensure that the connection is always closed. It's usually good practice to do this with any IDisposable that you use.
For some info/duscussion on whether Open() should be in GetConnection() or not, see using statement with connection.open
Absolutely beautiful; saved a ton of code and gives me some ideas on how to leverage this. Also, good point on the OPEN, it's kind of redundant itself since, when I call this method, I'll be opening a connection!
Use a static method to create connection, and using shorthand to close/dispose it:
SomeClass
{
public static MySqlConnection CreateConnection()
{
MySqlConnection mycon = new MySqlConnection();
mycon.ConnectionString = "Connection";
mycon.Open();
return mycon;
}
}
private void button1_Click(object sender, EventArgs e)
{
using (MySqlConnection conn = SomeClass.CreateConnection())
{
}
}
If Open() throws, I think there might be resources that aren't properly disposed.
@TimS. - hm, need to look at it.
http://stackoverflow.com/questions/9316981/using-statement-with-connection-open has more info - the accepted answer there is that you shouldn't open a connection before returning it. Kind of a pointless, subjective thing, though.
class SomeClass : IDisposable
{
SqlConnection conn;
public SomeClass
{
conn = new SqlConnection("some connectionstring");
}
public void Open()
{
conn.Open()
}
public void Close()
{
conn.Close()
}
public void Dispose()
{
conn.Dispose()
}
}
Would this class use conn, or how would another class use this one?
Well, by calling this class, you use the SqlConnection indirectly.
conn is private; if I have an instance of SomeClass, I can't do anything with the connection except open, close, and dispose.
You can add methods to the class that uses that connection. If you want to use the connection directly, you can either make it a public property, or just create instances of it wherever you need it. As a public property, you could declare it: public SqlConnection Connection {get; set;}
I would do something like this:
public class DataBase
{
private static string DEFAULT_CONNECTION_STRING = "*your connection string*";
private string connectionString;
private DbProviderFactory factory;
public DataBase()
{
connectionString = DEFAULT_CONNECTION_STRING;
factory = DbProviderFactories.GetFactory("MySql.Data.MySql");
}
public IDataReader GetData(string sql)
{
using(var conn = factory.CreateConnection())
using(var command = factory.CreateCommand())
{
command.CommandText = sql;
command.CommandType = CommandType.Text;
conn.ConnectionString = this.connectionString;
conn.Open();
command.Connection = conn;
return cmd.ExecuteReader();
}
}
}
| common-pile/stackexchange_filtered |
Which ML algorithms can be used to optimize a weighted quadratic loss function?
I want to solve the following optimization problem:
$$ L = n^{-1} \sum^n_{i=1} w_i ( y_i - \tau(x_i))^2 $$
where $w_i \in \mathbb{R}^+$ weights, $y_i \in \mathbb{R}$ outcome data, $x_i$ features/covariates, and $\tau$ an unknown function to be specified or approximated by a machine learning (ML) algorithm.
For example if we specify a linear model $\tau(x_i)=x_i' \beta$ with parameters $\beta$ the problem above reduces to weighted least squares estimation of a linear model. If we then add a regularization
$$L + \lambda ||\beta||_q$$
we obtain the Lasso model for $q=1$ and the Ridge regression models for $q=2$. Consequently the R function glmnet for example, allows for weights.
Now, we could extend our model for $\tau$ by including splines, for exmaple, to learn non-linear continuous functions and increase the flexibility of the model.
My question: are there any models / ML methods outside this class to minimize $L$?
For example, random forests can be used to approximate $\tau$ if there are no weights, I believe. However, a weighted random forest I have not seen yet and the standard functions e.g. randomforest does not allow for weights. I suppose the regression type models for $\tau$ (Ridge, Lasso, Spline, etc.) are the only ones that apply here but I am very curious if anybody can point to ML methods that work with weights.
$L$ can be expressed as an unweighted model merely by multiplying all $y_i$ and $\tau(x_i)$ by $\sqrt{w_i}.$
@whuber Yes, but $\tau$ is unknown (unless specified as in a regression model) and the function approximator would still need to take the weights into account in the term $(\sqrt{w_i} \tau(x_i))$
Right: once you estimate $\tau,$ divide it by the roots of the weights.
@whuber I am not certain if I understand. Do you suggest to estimate a ML model with outcomes $\sqrt{w_i} y_i$ and obtain $\tau'(x_i)$ and then obtain $\tau$ by dividing $\tau'(x_i)$ through $\sqrt{w_i}$
The most popular solution algorithm for nonlinear least squares problems is arguably the Gauss Newton method https://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm
Your question is about optimizing $L.$ If you have an unweighted optimizer, it will find the solution I describe. Whether that's useful might depend on how $\tau$ is described in the solution. It will work for regression models.
| common-pile/stackexchange_filtered |
Adding pins/points to Choropleth Map D3JS
I would like to add pins or points or some circle to choropleth Map in D3JS. I am not sure how to do it. Can you please help?
Thanks,
Madhu
I just got it working by var projection=d3.geo.albersUsa();
var coords=projection(['-77.679863', '43.088015']);
var sample=states.append('svg:circle')
.attr('cx',coords[0])
.attr('cy',coords[1])
.attr('r',1)
.style('fill','red');
Please help me use some other pin with tool tip attached to it. Do we have any svg component for the same?
| common-pile/stackexchange_filtered |
jqplot Yaxis rescale
I'm using jqplot for represent several parameters in series across the time. So I have one Xaxis represent the time and several Yaxes(yaxis, y2axis, y3axis, y4axis, etc.). Each parameter is in different units(temperature, voltage, current, pressure, etc.), so all the Yaxes set to auto for min and max because I dont know what values will come from the server. I'm using ajax request to fill the data and next for real time updating the series with new points.
So now I want for the user to be able to set manual min and max for any Y-axe. So I set by this way:
var axis_name="y2axis";
console.log(plot.axes[axis_name].max);
var new_max=prompt("Please enter max value?");
console.log(new_max);
var plotOptionsEval = "plotOptions = { axes: { "+axis_name+": { max: \""+new_max+"\" } } };";
eval(plotOptionsEval);
console.log(plotOptions);
plot.replot(plotOptions);
console.log(plot.axes[axis_name].max);
So , when I set new max for the first axis(yaxis) everythins is fine.
But when I try to set the max parameter of any other axis - y4axis for example something gone wrong and that max value has a some different value from this the user is entered.
This is a debug from console.log output
50
12
axes: y4axis: {max: "12"}
350
Any ideas?
So I have found a solution if someone asking the same.
The trick is you need to set min and max parameters for all Yaxis in your plot. So I have prepared the min/max axes object with its original values:
var plotOptions = {
axes: {
yaxis: {min: 11.568, max: 11.582}
y2axis: {min: 11.688, max: 11.702}
y3axis: {min: 6.390000000000001, max: 6.53}
y4axis: {min: -300, max: 50}
}
}
Next set the desired Yaxis min/max parameter in the plotOptions object:
var new_max=prompt("Please enter max value?");
plotOptions.axes.y2axis.max=parseFloat(new_max);
and finally replot it:
plot.replot(plotOptions);
| common-pile/stackexchange_filtered |
cassandra possible node loss
I am fairly new to Cassandra and found this website
https://www.ecyrd.com/cassandracalculator/
Not sure how accurate it is, but i have one misunderstanding.
Consider following example:
cluster size 8
replication factor 5
read concern ONE
write concern ONE
As a result i get that I can lose 4 nodes without impacting the application. Does anyone know what calculation leads us to this result? Thanks in advance.
P.S. I would like to remark that I am not interested in any other aspect, except "how many nodes I can loose without impacting application". The answer I am looking for is not how consistency works, or anything else, but exclusively what equation stands behind described result for "how many nodes I can loose without impacting application" and why.
A CL.ONE can always lead to the possibility of data loss. As an example: A replica as the coordinator gets requests, writes locally and sends ack to client. If that system is then hit by a meteor before the data to the other replicas has been sent theres data loss.
If you use local_quorum or quorum then with a RF=5 you can have 2 nodes of the replica set fail without any data loss (excluding cases like not following expected operational practices around repairs). However with CL.ONE your application can still run even if 4 of the 5 replicas died, in some cases availability is more important than the durability and consistency. I would recommend always start with quorum and then only change your consistency if theres an unmet availability of performance requirement.
Thank you for the response. I understand part with data loss using write consistency ONE. What I fail to understand is the criteria that is used while calculating amount of nodes i can loose and not impact application. Do you know how it works?
data loss limit is the number of replicas ack'd on a request. If your request is acknowledged to the client, then all the nodes that acknowledged it die then your application will think a write succeeded but the data is gone.
You can tune consistency at query level also based on requirements.
SELECT * FROM users WHERE state='ABC' USING CONSISTENCY QUORUM; Yes, CL ONE provides good availability than quorum but quorum will give you more consistent data.
| common-pile/stackexchange_filtered |
librdkafka producer's Internal queues - how do they work?
I had a few questions about GoLang Kafka producer using librdkafka -
These are based on the logs I am seeing in the producer log when I set debug: all.
The producer spends some time in building message sets once the batch threshold is recached or linger.ms is passed. However, what happens almost all the time is - messages are moved from partition queue to xmit queue. I was trying to get some documentation on it, but could not find much, so wanted to check if I can get some help on the stack. My questions are following -
a) Does the application produce calls write to a partition specific queue(s)?
b) Are there one xmit queue and one partition queue per partition?
c) What triggers a transfer from partition queue to xmit queue? and why do we need two queues?
d) When the Kafka producer is creating messagesets for a partition - does it block all operations for the partition? (Like moving messages from partition queue to xmit queue)? In short, when message sets are being built for a partition, can new messages sneak in the xmit queue? Is it blocked?
e) How many threads work for creating message sets? Is it one per producer or one per partition?
| common-pile/stackexchange_filtered |
Malament theorem in curved spacetime?
Malament's theorem roughly assert that given a very general theory of a point particle, characterized by some operator $P_D$ such that for a region of space $D$ at a given time $t$, $P_D | \Psi \rangle$ corresponds to the certainty that the particle is localized within $D$, which obeys the following rules
Translation covariance: For a translation $a$, we have a unitary operator $U(a)$ such that $U(a) P_D U(-a) = P_{D+a}$.
Localizability: For two disjoint subsets of the same spacelike hyperplane $D_1$, $D_2$, $P_{D_1} P_{D_2} = P_{D_2} P_{D_1} = 0$.
Lower bound on energy : For a timelike vector $\xi$, $U(\lambda \xi)$ has a spectrum bounded from below.
Microcausality: For any two spatial regions in two spacelike hypersurfaces $D_1$, $D_2$, we have $P_{D_1} P_{D_2} = P_{D_2} P_{D_1}$.
The Localizability just says that a particle can't be at two places at once (fairly important for a point particle), and microcausality is just the usual relativistic causality.
With this, we have that any quantum theory obeying those rules has $P_D = 0$ for all $D$ : the only theory is the theory of $0$ particles.
Does this theorem generalizes well to curved spacetime? Quantum theories on curved spacetime lack unitary operators, both in space and time, which seems like the biggest issue (localizability can probably be adapted well enough using achronal slices and microcausality the lack of causal curves from $D_1$ to $D_2$), as we know that asking for unitary transformations for spacetimes without Killing vectors is not reasonable.
| common-pile/stackexchange_filtered |
cpython-35m-x86_64-linux-gnu.so is generated from which base file type
I am trying to find my way around some inherited code. I have found a complied file called:
filename.cpython-35m-x86_64-linux-gnu.so
From what file type (.py, .cpp, .pdx) this file was complied from? Is there also any documentation around the meaning of each part of cpython-35m-x86_64-linux-gnu.so?
This file is a cpython extension (from the conventional name). Depending on the technologies at play it could be generated from nearly any type of file with the correct tooling, though it most commonly is a .c extension. Common others are .cpp (for c++ code) and .pyx (for cython modules). As an example of an uncommon file type that could produce a c extensions, I've written setuptools-golang which produces such files from .go source.
The second part of your question is what each of those portions of the extension mean. This is outlined in PEP 3149 though I'll explain each part here. Each is separated by dashes (-), I'll explain each of them separately:
cpython: this is the "implementation". in this case it means you're using the most popular implementation of python that is implemented in C python/cpython. Another example "implementation" you might see here is pypy3 (for the 3.x flavor of pypy)
35m: this is the first part of the "application binary interface" marker, in this case it is saying this is python3.5 and the m is indicating that python was compiled using pymalloc
x86_64: this part of the abi is indicating it was compiled for a 64 bit architecture, also known as amd64
linux-gnu: this indicates that the shared object targets linux
| common-pile/stackexchange_filtered |
Error In Deploying LWC
I'm trying to deploy my code but when It's not updated in custom components
Kindly advice what's the issue and can you advice also the difference between working on scratch orgs and non-scratch orgs with lightning web component
Its says to enable my domain? have you done that?
Thanks this worked for me :)
@PranayJaiswal You should add your comment as an answer.
probably it's already irrelevant, but still. App Builder points out that you don't have My Domain deployed and it's required in order to use Custom Lightning Components. So please deploy it in Setup -> My Domain and then you'll be able to see your component
There's no errors, so presumably, you just need to update your metadata.
Locate the file helloWebComponent.js-meta.xml, and alter it to the following:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>45.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
You'll want to check the documentation, including the "See Also" sections.
As for your final question, there is no difference with LWC in regards to using scratch orgs versus not. The only general difference is that you can't use force:source:push on a non-scratch org, nor force:source:pull.
It's already updated
but still same issue
| common-pile/stackexchange_filtered |
Merging the content of an Ajax called form using WebTestCase
I'm using the SonataAdminBundle plus DoctrineORMBundle and let's say I have a Post/Tags relationship where Tags are many-to-many to Posts.
I'm trying to run a functional test on the Post form. Tags are shown in the Post form throw an widget where the Tag form fields comes from another request (Ajax call) and merged in the Post form by Javascript.
It's easy to rely on Javascript to do this but when it comes to the functional testing
scenario, using the WebTestCase class, I found a difficulty to simulate such functionality.
Let's say I'm testing the Create action of the Post and using this code on my test case.
public function testCreate() {
$client = static::createClient();
$client2 = static::createClient();
//main request. The Post form
$crawler = $client->request('GET','/route/to/posts/create');
//second request (The Tag form) simulating the request made via Ajax
$crawler2 = $client2->request('GET','/admin/core/append-form-field-element?code=my.bundle.admin.tags);
}
The problem with the code above it's that from thereon I don't know how to merge the Tag form into the Post form so this way they are submitted together.
Any ideas?
Have a look at mink: http://mink.behat.org/
Thank you. I wasn't aware of Mink's existence. It's really a powerful tool but I didn't get it to work properly in my case (not because of Mink itself).
Finally I found how to merge those 2 request contents together. Here is code that I used:
public function testCreate() {
$client = static::createClient();
$client2 = static::createClient();
//main request. The Post form
$crawler = $client->request('GET','/route/to/posts/create');
//second request (The Tag form) simulating the request made via Ajax
$crawler2 = $client2->request('GET','/admin/core/append-form-field-element?code=my.bundle.admin.tags);
//first request's form. This is where we'll merge the content.
$form = $crawler->selectButton('submitButton')->form();
//let's say we want to merge each input fields from the second request
foreach ($crawler2->filter('input') as $node) {
//we use the Crawler\Form::set method with a new InputFormField instance
//that uses a DOMNode as parameter
$form->set(new InputFormField($node));
}
//now we can test if the form has our merged input field from the ajax call
$this->assertTrue($form->has('tagName'));
}
| common-pile/stackexchange_filtered |
Delete s3 bucket object
I'm facing problems when deleting objects from an S3 bucket, my policies are these:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": "*",
"Action": [
"s3:GetObject",
"s3:DeleteObject"
],
"Resource": "arn:aws:s3:::frienlinkfotos/*"
},
{
"Effect": "Allow",
"Principal": "*",
"Action": "s3:ListBucket",
"Resource": "arn:aws:s3:::frienlinkfotos"
}
]
}
My permissions allow me to see and delete objects, so based on that, I made this function in Golang to delete objects in a bucket:
func DeletePost(c *gin.Context) {
// iniciando aws
service := utils.UtilAWS()
svc := s3.New(service)
//pegando id_usuario a partir do contexto
IDUser := utils.GetUserJWT(c)
uuidPost := c.PostForm("uuid_post")
IDPost, err := strconv.Atoi(c.PostForm("id_post"))
if err != nil {
log.Println("Erro ao converter id", err)
c.Status(400)
return
}
_, err = DB.Exec(`DELETE FROM post WHERE id_post = ? AND id_usuario_pt = ? AND uuid_post = ?`, IDPost, IDUser, uuidPost)
if err != nil {
log.Println("Erro ao deletar post", err)
c.Status(400)
} else {
c.Status(200)
}
// deletando tambem do bucket:
Bucket := os.Getenv("Bucket")
log.Println(Bucket)
_, err = svc.DeleteObject(&s3.DeleteObjectInput{Bucket: aws.String(Bucket), Key: aws.String(uuidPost)})
if err != nil {
log.Println("Erro ao deletar post do S3 bucket", err)
c.JSON(400, err)
}
err = svc.WaitUntilObjectNotExists(&s3.HeadObjectInput{
Bucket: aws.String(Bucket),
Key: aws.String(uuidPost),
})
}
but this function gives me this error:
Error when deleting post from S3 bucket AccessDenied: Access Denied
status code: 403, request id: HMMCQN87, host id: GFtkmaI4hBft5Sh9U78/HIAljTcTYzW29J8hG6JavZxBMjubBvDaf5ia57e9PAd/q5I=
Why even releasing permissions for deletion, I cannot delete any object?
Listing my objects is going smoothly.
For more information, my service only has this function:
package utils
import (
"log"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
)
var s3Session = session.New()
func UtilAWS() *session.Session {
//Variaveis de login para o aws
region := os.Getenv("REGION")
key := os.Getenv("KEY")
secretpass := os.Getenv("SECRETPASS")
if region == "" || key == "" || secretpass == "" {
log.Println("informações de login da AWS não pode ser nulas")
}
s3Config := &aws.Config{
Region: aws.String(region),
Credentials: credentials.NewStaticCredentials(key, secretpass, ""),
}
s3Session = session.New(s3Config)
return session.New(s3Config.WithRegion(region))
}
In general, don't use S3 bucket policies to supply permissions to IAM principals (user and roles) that are in the same AWS account. Instead, attach IAM policies to those IAM principals. In your specific case, you've given everyone access and this is a dangerous policy so you should remove the bucket policy asap.
Your Bucket Policy means that everyone in the world (including me) can now upload objects to your bucket, delete object and list objects (eg I just found post/2465d4d5-85fd-4f11-b975-92cb59928705). You should delete this bucket policy immediately!
In my case, the project I'm doing is a portfolio, it's a social network, the images can be seen by anyone who logs into the social network
But I want that when a user deletes a post, the image/video is also deleted from my s3, what would be the most recommended practice? @JohnRotenstein
This would be the responsibility of your app, since only the app 'understands' what it means to delete a post. The app should keep track of which files are associated with a post and then delete the object when it isn't needed anymore.
Bucket policy is fine, but lambda(or other aws service) execution role is missing s3 access, for lambda go to
IAM > roles > find your lambda execution role > permissions > add s3 full access permission
Remember to block public access if there is valueable data, I could delete the objects from your bucket
instead of giving full access you(which is not recommended) you should suggest to give specific access rights. i.e. AllowDeleteObjects
In all likelihood, the OP's S3 bucket policy is not fine (it allows anyone to get and delete objects, as you indicated). Regardless of Block Public Access (BPA) settings, this is not a good bucket policy.
In my case, the project I'm doing is a portfolio, it's a social network, the images can be seen by anyone who logs into the social network
But I want that when a user deletes a post, the image/video is also deleted from my s3, what would be the most recommended practice? @jarmod
Track the S3 assets associated with a given post so that your back-end application can delete them when it is asked to delete a post. You can do that with key/value lookup in DynamoDB or you could simply structure your S3 assets to always be under a prefix such as <post-id>/. But please remove the bucket policy and apply the permissions needed to the IAM role that your back-end service assumes.
| common-pile/stackexchange_filtered |
Probability of sampling with and without replacement
In sampling without replacement the probability of any fixed element in the population to be included in a random sample of size $r$ is $\frac{r}{n}$. In sampling with replacement the corresponding probability is $\left[1- \left(\frac{1}{1-n}\right)^r\right]$.
Please help me show how this is proved.
Hello, if you can, please explain what it is about this question which makes it so you can't prove it. Do you understand what it's saying, and just don't have any idea where to start, or do you not understand completely what it's saying? Giving more context in your question will help you get more relevant answers and hints. Cheers
I have closed this older question as a duplicate of a newer question. This question asks about the probability of drawing a single special element out of a set of size $n$ when taking a sample of size $r$. The linked question is about drawing $k$ special elements out of a set of size $N$ when taking a sample of size $m$. This question is special case of the latter with $n = k = 1$.
Sampling without replacement
Just a note in terms of nomenclature:
$$
{n \choose r} = {_n}C_r = \frac{n!}{r!(n-r)!}
$$
There are ${n \choose r}$ ways to select the sample of $r$ elements from the pool of $n$ items. That is our denominator—the universe of possible results. To count the number of samples which include our special fixed element (call it $x^*$) we can just realize that we must pick $x^*$, and there is only one way to do that (${1 \choose 1}$, and that leaves us a pool of $n-1$ item from which we need to select $r-1$ to fill out the sample. There are:
$$
{1 \choose 1}{n-1 \choose r-1}
$$
ways to create our desired samples. So the probability of having $x^*$ in our mix is:
$$
\frac{{n-1 \choose r-1}}{{n \choose r}} = \frac{(n-1)!}{(r-1)!(n-r)!}\div\frac{n!}{r!(n-r)!}= \frac{(n-1)!}{(r-1)!(n-r)!}\cdot\frac{r!(n-r)!}{n!} = \mathbf{\frac{r}{n}}
$$
Sampling with replacement
First a clarification. When sampling without replacement, the maximum number of times $x^*$ can appear is, of course, $1$. When sampling with replacement, it can appear between $0$ and $r$ times. Judging by the answer you gave, the question you want to answer is the number of ways the fixed element $x^*$ appears at least once. That is most easily addressed by realizing it is all possible ways except for the times that it does not appear at all. In other words:
$$
P(\textrm{at least once}) = 1 - P(\textrm{never})
$$
In order for $x^*$ to never appear, it cannot appear in any of the $r$ slots, which means that we can only pick from the remaining $n-1$ items. The probability that in slot $1$ we select something other than $x^*$ is $\frac{n-1}{n} = 1 - \frac{1}{n}$. This has to happen in every one of the $r$ slots, so the probability of having no manifestations of the fixed element in a sample of size $r$ is:
$$
\left(\frac{n-1}{n}\right)^r = \left(1 - \frac{1}{n}\right)^r
$$
So the probability of at least one showing is everything else, or:
$$
\mathbf{1- \left(1 - \frac{1}{n}\right)^r}
$$
Unfortunately, this is not the same as the value you posted in the question. Is it at all possible that the value in the innermost parentheses was supposed to be $1-\frac{1}{n}$ and not $\frac{1}{1-n}$?
for without replacement :-
total no. of possible ways of selecting $r$ elements from $n$ elements = $_nC_r$
total no. of ways where element $x$ is always selected would be equal to selecting $(r-1)$ element from $(n-1)$ elements [as we would consider $x$ to be already selected] ,
which would be = $_{(n-1)}C_{(r-1)}$
probability =
$$
\frac{{_{(n-1)}}C_{(r-1)}}{_nC_r} = \frac{r}{n}
$$
:-> $C$ is the combination
for with replacement :-
total possible no. of selections would be = C(n+r-1,r) [bars and star logic]
total cases where element x is never selected are = C(n+r-2,r) [n reduces to n-1]
probability of at least one selection of element x = [1 - {C(n+r-2,r)}/{C(n+r-1,r)}]
which comes out to be = (n-1)/(n+r-1)
| common-pile/stackexchange_filtered |
Unify lines that contains same patterns
I have a database with this structure:
word1#element1.1#element1.2#element1.3#...
word2#element2.1#element2.2#element2.3#...
...
...
I would like to unify the elements of 2 or more lines every time the word at the beginning is the same.
Example:
...
word8#element8.1#element8.2#element8.3#...
word9#element9.1#element9.2#element9.3#...
...
Now, lets suppose word8=word9, this is the result:
...
word8#element8.1#element8.2#element8.3#...#element9.1#element9.2#element9.3#...
...
I tried with the command sed:
I match 2 lines at time with N
Memorize the first word of the first line: ^\([^#]*\) (all the elements exept '#')
Memorize all the other elements of the first line: \([^\n]*\)
Check if in the second line (after \n) is present the same word: \1
If it's like that I just take out the newline char and the first word of the second line: \1#\2
This is the complete code:
sed 'N;s/^\([^#]*\)#\([^\n]*\)\n\1/\1#\2/' database
I would like to understand why it's not working and how I can solve that problem.
Thank you very much in advance.
not [#]* it's [^#]*
sorry, error typing...
you should tell if your file was sorted by 1st field (word 1,2....), if not sorted, what do you want to do the "join"?
yes, the file is sorted by 1st field.
This might work for you (GNU sed):
sed 'N;s/^\(\([^#]*#\).*\)\n\2/\1#/;P;D' file
Read 2 lines at all times and remove the line feed and the matching portion of the second line (reinstating the #) if the words at the beginning of those 2 lines match.
the solution is beautiful but I thing it fails if we have 3 or more lines with a common key.
@JJoao To handle more than 2 lines use. sed ':a;N;s/^\(\([^#]*#\).*\)\n\2/\1#/;ta;P;D' file
sed '#n
H
$ { x
:cycle
s/\(\n\)\([^#]*#\)\([^[:cntrl:]]*\)\1\2/\1\2\3#/g
t cycle
s/.//
p
}' YourFile
Assuming word are sorted
load the whole file in buffer (code could be adapted if file is to big to use only several lines in buffer)
at the end, load holding buffer content to working buffer
remove the new line and first word of any line where previous line start with same word (and add a # as seprator)
if occur, retry once again
if not, remove first char (a new line due to loading process)
print
You can try with perl. It reads input file line by line, splits in first # character and uses a hash of arrays to save the first word as key and append the rest of the line as value. At the END block it sorts by the first word and joins the lines:
perl -lne '
($key, $line) = split /#/, $_, 2;
push @{$hash{$key}}, $line;
END {
for $k ( sort keys %hash ) {
printf qq|%s#%s\n|, $k, join q|#|, @{$hash{$k}};
}
}
' infile
Using text replacements:
perl -p0E 'while( s/(^|\n)(.+?#)(.*)\n\2(.*)/$1$2$3 $4/ ){}' yourfile
or indented:
perl -p0E 'while( # while we can
s/(^|\n) # substitute \n
(.+?\#) (.*) \n # id elems1
\2 (.*) # id elems2
/$1$2$3 $4/x # \n id elems1 elems2
){}'
thanks: @birei
I would mark first newline character optional, because otherwise it wouldn't match same pattern between first and second lines. Although it will leave a blank one at the beginning, but it does not seem critical.
@Birei, thank you for the bug report and suggestion. I edited in similar way: s/(^|\n) ... /$1../ in order to remove the blank.
$ cat file
word1#element1.1#element1.2#element1.3
word2#element2.1#element2.2#element2.3
word8#element8.1#element8.2#element8.3
word8#element9.1#element9.2#element9.3
word9#element9.1#element9.2#element9.3
.
$ awk 'BEGIN{FS=OFS="#"}
NR>1 && $1!=prev { print "" }
$1==prev { sub(/^[^#]+/,"") }
{ printf "%s",$0; prev=$1 }
END { print "" }
' file
word1#element1.1#element1.2#element1.3
word2#element2.1#element2.2#element2.3
word8#element8.1#element8.2#element8.3#element9.1#element9.2#element9.3
word9#element9.1#element9.2#element9.3
| common-pile/stackexchange_filtered |
Backface Visibility not working on children
This solutions (Webkit backface visibility not working) didn't work, as I'd like to have other transformed objects inside container that should show the backface.
.container {
position: relative;
transform-origin: 50% 50% 0;
transition: transform 1s ease 0s;
width: -moz-min-content;
width: -webkit-min-content;
}
.container img {
backface-visibility: hidden;
}
input:checked + .container {
transform: rotateY(180deg);
}
<input type="checkbox" name="" id="" />
<div class="container">
<img src="http://jsequeiros.com/sites/default/files/imagen-cachorro-comprimir.jpg" alt="" />
</div>
The backface of that cat shouldn't be visible. Any solution for this problem?
What is your problem exactly ?
The title says it: when the image turns, both faces are visible, but the backface should be invisible
I finally discovered how to solve this!
The problem was the the 3d was not affecting the image. Just by adding the property: transform-style: preserve-3d; includes the image as part of the "3d world". Before, the backface property wasn't working, because it really wasn't 3d! It was like a texture painted on the parent's surface. Now it is a 3d entity with all its components and it can be transformed in 3d without collapsing to the surface of the parent.
.container {
position: relative;
transform-origin: 50% 50% 0;
transition: transform 1s ease 0s;
width: -moz-min-content;
width: -webkit-min-content;
transform-style: preserve-3d;
}
.container img {
backface-visibility: hidden;
}
input:checked + .container {
transform: rotateY(180deg);
}
<input type="checkbox" name="" id="" />
<div class="container">
<img src="http://jsequeiros.com/sites/default/files/imagen-cachorro-comprimir.jpg" alt="" />
</div>
Be aware of the "-webkit-transform-style: preserve-3d;" for Chrome, Safari & Opera. I forgot this and started to do all sorts of manipulation until I found that this answer and understood I had forgotten the -webkit-version since I was testing in Safari. Thanks for saving me a lot of time!!! :D
EDIT
setting backface-visibility: hidden; on the elem you're transforming solve the issue
.container {
position: relative;
transform-origin: 50% 50% 0;
transition: transform 1s ease 0s;
width: -moz-min-content;
width: -webkit-min-content;
}
.container{
backface-visibility: hidden;
}
input:checked + .container {
transform: rotateY(180deg);
}
<input type="checkbox" name="" id="" />
<div class="container">
<img src="http://todofondosdeamor.com/wp-content/uploads/images/48/gatitos-1__400x300.jpg" alt="" />
</div>
I'm afraid that container can't have backface-visibility hidden. If it could, the answer would be just transforming it. That is why I said that the solution I linked to isn't usefull in this case.
you're rotating .container
yeah, but I don't want to hide every objects backface inside the container, only that image
| common-pile/stackexchange_filtered |
Express-session returns 'undefined', even though I declared the session
I've been working on this website for a while and didn't really have a problem, 'till now.
When the user logs in, a session cookie is initialized this cookie is called user and stores the users email. When I console log the cookie on the login post request, just after I declared it, it shows data, but, when I change of route (to any other) ex. the home route, the cookie is not persistent and my user cookie changes to 'undefined'.
Post Request, I'm using the firebase API for authentification:
// Login POST Route
router.post('/login', (req, res) => {
// Firebase authentication service
firebase_user.auth().signInWithEmailAndPassword(req.body.email, req.body.password).then(data => {
// Cookie Init
req.session.user = req.body.email;
console.log(req.session.user); // In here, cookie shows desired value
}).catch(err => {
res.send({"error": err.message});
});
});
Home route:
router.get('/home', (req, res) => {
// Check if Session Cookie Exists
if (req.session.user) {
res.render('home.ejs');
} else {
res.redirect('/login');
console.log(req.session.user); // This console log shows 'undefined' even tho there the cookie was initialized correctly
}
});
Middlewares:
app.use(bodyParser.json());
app.use(morgan('combined'));
app.set('view engine', 'ejs');
app.use(express.static('./public'))
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({secret:"Testasl",resave:false,saveUninitialized:true,cookie:{secure:!true}}));
// Routes
app.use(routes);
And here is how I send the data to the login method. I use Axios and Vue:
var urlLog = 'http://localhost:3000/login';
new Vue({
el: '#main',
data: {
email: '',
password: '',
showForm: true,
showPreloader: false,
errorMessage: '',
errorShow: false
},
methods: {
submitForm: function() {
// Validates forms
if (this.email!='' && this.password!=''){
// Show Preloader
this.showForm=false;
this.showPreloader=true;
// Ajax Post Request
axios.post(urlLog, {
email: this.email,
password: this.password
}).then(res => {
if (res.error){
// Shows form
this.showForm=true;
this.showPreloader=false;
// Shows Error
this.errorShow = true;
this.errorMessage = res.error;
} else {
// do nothing
}
// Server Side error
}).catch(err => {
console.log(err);
});
} else {
this.errorShow = true;
this.errorMessage = 'All fields are necessary...';
}
}
}
});
Any idea why this is happening???
**** EDITED ****
UPDATE: So I was playing around with cookies, to be precise, with the cookie-parser module, and I decided to initialize a cookie with it. And returned this error message:
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:491:11)
at ServerResponse.setHeader (_http_outgoing.js:498:3)
at ServerResponse.header (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\response.js:767:10)
at ServerResponse.append (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\response.js:728:15)
at ServerResponse.res.cookie (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\response.js:853:8)
at router.get (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\bin\routes.js:74:9)
at Layer.handle [as handle_request] (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Thirsty-Robot\Desktop\Projects\Important\Robotics\Dashboard\node_modules\express\lib\router\layer.js:95:5)
The cookie was set in this way:
// Login GET Route
router.get('/login', (req, res) => {
res.render('log_in.ejs');
res.cookie('idk', 'idksj');
console.log(req.cookies);
});
What does "change of route, cookie disappears" mean? We need to see both the code where you initialize the session and the route where you don't find the session. Show us both and document exactly what you do and don't see that you are expecting.
Edited just now
What order are the three app.get() and app.use() executed in (session middleware vs. /home route definition vs. /login route definition). White route registration goes first, second and third?
When you make the Axios requests from the browser, are you making a request to the exact same domain and port and protocol that the web page the Javascript is running from was loaded from? Same origin or cross origin? I'm looking for ways that a cookie gets lost. May need to set withCredentials: true in axios requests.
Edited just now, I got an error from the cookie-parser module.
You can't set a header after already sending the headers, as your error states.
In your case, you're setting the cookie header after ending the response:
// Login GET Route
router.get('/login', (req, res) => {
res.render('log_in.ejs'); // completes the response
res.cookie('idk', 'idksj'); // tries to set a cookie header
console.log(req.cookies);
});
For this case, you would be well served to just swap those two lines:
// Login GET Route
router.get('/login', (req, res) => {
res.cookie('idk', 'idksj');
res.render('log_in.ejs');
console.log(req.cookies);
});
Though you probably want to do that only after validating the login (which you're not really doing in this code block)
| common-pile/stackexchange_filtered |
Is HMAC necessary if all API calls are made through https?
If all api calls are sent through https, does HMAC add any extra security? For example, in oauth 2, the client sends its secret key to the provider without any hashing whatsoever. Is this considered secure because it's over https? While not strictly oauth, would using HMAC on this call make oauth 2 more secure? If so, why isn't that a standard part of oauth 2?
The OAuth 2 standard requires that the authorization server MUST use HTTPS on all of its endpoints and the client SHOULD use a callback protected with HTTPS. Since message contents (headers, query parameters and fragments considering OAuth) are known only by the server and the client, usage of an HTTPS connection is considered to be safe. Thus there's no gain using a separate signature for authorization request, that's why such signatures are not even mentioned in the standard.
This not necessarily hold for the response though. If the client receives the authorization response to an unprotected callback, then it cannot verify its validity. In such cases, an attacker can send arbitrary authorization results to the client. Adding a signature with the callback parameters, you may avoid this. However, it seems to be a better solution to use mutual client/server authentication with a HTTPS callback instead.
While there's no real gain using signatures during authorization, they may be useful to access protected resources to avoid stealing access tokens. This is why the MAC token type is in the standard, see section 7.1.
HMAC is for authentication that determining who you are, https is for security of transport that ensure on one in the middle can see the content of your transport.
Oauth 2 authorization server use secret key or password determining who you are. Oauth2 resource server use token from authorization server determining who you are. Using https or not depends on whether you want to protect your secret key and tokens.
| common-pile/stackexchange_filtered |
Fn keys can't adjust brightness MATE desktop
I just installed Ubuntu 14.04 and removed Unity and installed MATE. Now, the Fn keys on my keyboard can't adjust brightness. Here's the thing that makes it extra extr confusing: my brightness worked under Unity. Even more confusing, there is a bug in MATE that makes a small white square appear. I don't see it. It's like when I press my brightness keys, nothing happens like I'm not even pressing them. This worked under Unity.
Also, I'm not using a version of Ubuntu MATE or anything, I installed the packages myself from official PPAs and the Ubuntu repos.
Is there a package that is responsible for the brightness? maybe I need to install it.
Okay. If no one wants to give me an answer, at least tell me of a program I can use to adjust my brightness. A command would do nicely.
The problem is MATE does not come with a program to manage brightness. In a terminal, type sudo apt-get install mate-power-manager and let it install. Restart, and brightness should now work because there is a program to handle brightness key presses.
| common-pile/stackexchange_filtered |
Windows batch/cmd file to extract network drives (strings between delimiters)?
I have backed up the network drive to an xml file in the format below.
<drive>
<drive letter>X</drive letter>
<drive path>\\DANIEL-HP\Users\Public\Documents\Downloaded Data Sheets</drive path>
</drive>
<drive>
<drive letter>Y</drive letter>
<drive path>\\DANIEL-HP\Users\Public</drive path>
</drive>
I want to run a batch or cmd file to extract the drive letter and path from between the delimiters and then map them.
For simplicity sake let's ignore whether other drives are mapped or not.
Delimiters for drive letter are <drive letter> and </drive letter> .
Delimiters for drive path are <drive path> and </drive path>
I am not sure on how to parse the / <> symbols.
I meant to post this on super user, is it okay to leave it here?
You could try powershell "([xml]((gc test.xml) -replace 'drive')).selectNodes('//drive') | %{ net use \"$($_['letter'].innerText):\" $_['path'].innerText }" from the cmd prompt (replacing test.xml with the name of your xml file). That'll only work if your XML has a proper <?xml version="1.0"?> declaration and a proper root node though.
That's quite straight with a simple for loop:
for /f "tokens=3 delims=<>" %%a in ('find "<drive letter>" test.xml') do echo %%a
No need to escape > and <, because they are safe within the quotes.
edit
build up two "arrays" (1) for letter and path, then join them to get the desired result:
@ECHO off
setlocal enabledelayedexpansion
REM get drives:
set c=0
for /f "tokens=3 delims=<>" %%a in ('find "<drive letter>" t.xml') do (
set /a c+=1
set drv-!c!=%%a
)
REM set paths:
set c=0
for /f "tokens=3 delims=<>" %%a in ('find "<drive path>" t.xml') do (
set /a c+=1
set pth-!c!=%%a
)
for /l %%x in (1,1,%c%) do echo !drv-%%x! !pth-%%x!
(1) quoted because of the comments on this answer
test.xml is causing problems so renamed it to test.txt
Thanks, that puts me in the right direction.
for /f "tokens=3 delims=<>" %%a in ('find "<drive letter>" test.txt' ) do echo %%a for /f "tokens=3 delims=<>" %%b in ('find "<drive path>" test.txt') do echo %%b
gives me a result
X Y \\DANIEL-HP\Users\Public\Documents\Downloaded Data Sheets \\DANIEL-HP\Users\Public
I am working on getting the result as
X \\DANIEL-HP\Users\Public\Documents\Downloaded Data Sheets Y \\DANIEL-HP\Users\Public and then dynamically assign to variables.
+1 Thanks @Stephan Perfect answer.
Gather the data first then display it ....nice !!!!
Finally, concluded my code with net use !drv-%%x! "!pth-%%x!" /p:yes
brilliant :) Cleared some of my doubts with arrays too.
the file extension shouldn't make any difference (a textfile is a textfile, no matter how you name it). Please check for a possible typo.
Simple using JREPL.BAT - a regular expression find/replace utility. It is pure script (hybrid batch/JScript) that runs natively on any Windows machine from XP onward, without the need of any 3rd party exe files.
Disclaimer - Ideally, you should be using an xml parser to read the file. But assuming the file always has an xml layout as you show, then the following should work from the command line.
jrepl "<(drive letter)>(.*?)</\1>\s*<(drive path)>(.*?)</\3>" "$2+': = '+$4" /m /jmatch /f test.xml
Here is the output if I put your sample xml in "test.xml"
X: = \\DANIEL-HP\Users\Public\Documents\Downloaded Data Sheets
Y: = \\DANIEL-HP\Users\Public
I assume you want the values as variables within a batch script. You can use a FOR /F loop to process the paired values:
@echo off
for /f "delims=| tokens=1*" %%A in (
'jrepl "<(drive letter)>(.*?)</\1>\s*<(drive path)>(.*?)</\3>" "$2+'|'+$4" /m /jmatch /f test.xml'
) do (
echo Drive letter = %%A
echo Drive path = %%B
echo(
)
And the outptut:
Drive letter = X
Drive path = \\DANIEL-HP\Users\Public\Documents\Downloaded Data Sheets
Drive letter = Y
Drive path = \\DANIEL-HP\Users\Public
| common-pile/stackexchange_filtered |
How does the abstraction of AC make sense when flat-footed?
I am looking for a rule-wise explanation of the logic as to why your deflection bonus (e.g. a shield) is counted in your flat-footed AC.
From what I understand, being flat-footed means you didn't see the attack coming, and are unable to react to it, so only your passive armor counts (meaning the opponent still has to hit 'hard enough' to actually pierce your protections).
In that context, how would you be able to parry? You can't dodge, you should not be able to parry as well.
I realize a shield can be useful if you can't dodge because you 'just have to raise it'; The problem is not every flat-footed situation should allow for a shield to be used.
Pushing things to the extreme: consider an invisible character sneaking to a guard. The combat is not started, the guard is unaware of any danger. The character is behind the guard, unseen, unheard, and ready to hit. Why would that guard's shield be taken into accout? Why would his armor even be? The character should be able to stick its dagger in the guard's neck (or any other not-armor-covered part) and deal a good amout of damage without having much armor to go through.
If I'm not mistaken, according to the rules that guard should be flat-footed. This means if the character attacks the guard, the rules consider he is able to: sense the attack, turn around, deflect the attack with his shield.
From the logic of that context, I'd say that guard should be considered defenseless, shouldn't he?
My table had trouble with a player recently contesting the logic of that rule (and honestly I can't blame him), and we had trouble making him accept that yes, his paladin's shield was useful against that ogre's enormous club.
This seems to be asking a lot of questions, to be honest. Shields give a Shield bonus, not a Deflection bonus and the part about flat-footed vs defenseless seems unrelated.
I do see a single question here, along the lines of “How does the abstraction of AC make sense when flat-footed?”, plus the complication of misreading shield bonuses. This should be answerable.
@Erik Indeed, sorry for the mis-categorizing. The question remains the same though. How does that make sense?
Are you asking for a rules-based explanation ("the rules say X, so that's what happens"), or for a logic-based explanation ("the rules say X, which makes sense when you consider real-world concepts Y & Z")?
As an aside, even the heavy-duty simulationist system GURPS (third edition, anyway) has what's called Passive Defense (PD) that's gained from heavy armor and carrying a shield. PD adds to shield block attempts, weapon parry attempts, and even speed-based dodge attempts (armor and shield weight makes success rare, though); PD also allows an outside chance of an attack just glancing off even if no defense is attempted. After all, when someone tries to stab you--even if you're unaware of the attempt--there's an advantage to being even half-covered by a big metal sheet.
It's a valid question, and since there are feats that grant shield bonuses that don't apply when flat-footed, he clearly isn't the first.
First, shields don’t give deflection bonuses. They give shield bonuses. The difference is not so important for discussing flat-footed targets, but touch attacks ignore shield bonuses (and don’t ignore deflection bonuses), so the difference is pretty important when someone is trying to touch someone else.
Second, abstraction is a major part of the game. Both shields themselves and the flat-footed status are heavily abstracted, and cover myriad different things with singular mechanics. Abstraction is necessary for any game, to simplify the rules and keep the game moving, but by definition they must come at the loss of verisimilitude. By covering many different things with one rule, you accept that some of those things don’t really quite “fit” the rule precisely.
So, for shields: there is no concept of “active” shields and “passive” shields, so a giant tower shield, which is effectively a wall that you carry around, grants the same type of bonus as a simple light wooden shield. Also, note that the “buckler” appears to be used more like what the real world called a “targe,” strapped to the arm, rather than actively in the hand as true bucklers were. True bucklers do not appear in the game.
And flat-footed or losing Dexterity to AC (which are separate things!) covers lots of different situations:
Being attacked by those you cannot or do not perceive, such as invisible opponents or being caught by surprise.
Being distracted by other things, for example when you are climbing or balancing on something.
The result of various effects, such as being stunned.
Note that these are all very different, but use pretty unified mechanics (some are flat-footed and some just lose Dex to AC, but since we are talking about AC and ignoring uncanny dodge, I’m ignoring that distinction here since it doesn’t really come into play).
So someone with a shield and flat-footed might have their arms completely limp at their side, and the shield just dangling.
Or they could be holding up a huge wall, just not really certain where an attack is coming from.
Both of these situations use exact same mechanics. As such, keeping the shield bonus to AC is a compromise—chosen to keep the game simple and to make shields a little more valuable than they otherwise would be. In the first case where the shield bonus maybe shouldn’t really be in play, the bonus is small, but losing the large, expensive bonus of a tower shield in the latter situation is just wrong. So getting the latter situation right was favored here.
I'll address a few issues separately.
Deflection bonusses
Shields don't give these. They count to your AC while flat-footed because they are generated by magical effects and serve as a sort of always-on defensive barrier around your character. When someone swings a sword at you, your Deflection bonus is a magical force trying to push the sword away, with no action required by the wielder.
Attacking an un-aware guard while invisible
You make it sound much simpler than it is. The guard might be unaware of you, but he is not a statue and you are not inaudible. That means what you're trying to do is stab him in the tiny joint between the helmet and the breastplate, without making a noise or even so much as breathing on him. And he'll be occasionally moving around, coughing, talking, and other such things that make you likely to miss.
Obviously, if you succeed, you'll deal a lot of damage. If you fail, you deal none, because you're not swinging hard enough to dent his armor. The better his armor, the better you need to aim to stab him in the exposed area.
This is modeled simply by counting his Armor towards AC, because better armor will have less exposed area to stab him in and even if he is not aware of you, that will still mean aiming more.
Using your shield while flat-footed
This is two sided. If you know you are in combat and have your shield out, it will count towards your AC even if you are flat-footed. This is because even if you cannot actively parry, shields are big and you will intuitively use them to cover your weak spots. This simply leaves less area for an opponent to attack, which makes it harder for them to land a hit.
On the other hand, if you are not aware that you are in a combat, it is very likely that you aren't actually wielding your shield. It takes a Move-action to Don a shield. If you haven't done that, it's bonus does not count to your AC. While you are just walking around, you probably haven't actually donned it and you won't benefit from its bonus.
But what about stabbing someone flat-footed in the back?
Pathfinder by default does not have facing rules, which means there is no such thing as "in the back". If you have facing house-rules, it seems perfectly reasonable that your shield does not count if you get attacked in the back.
And how does my shield work against Ogres?
Realistically speaking, a 600 pound, 9 foot Ogre will maul you to death despite all your armor and shield. Then again, realistically speaking, the Ogre would probably not be physically possible any way. I guess here we have to say "Well, if we can accept dragons and magic and giants and other crazy things, we can also accept that in this world a hero can block a blow from one with his shield."
Otherwise, a lot of standard fantasy tropes wouldn't work and that's ultimately what the game is built on.
I'm not talking about a magic shield. I'm talking about physical shields: targes, bulwarks... So I'm asking about shield bonuses, indeed.
About the guard that can randomly move : Why then should a sleeping target be considered defenseless ?
And about the rest of the answer : We are not really looking when it comes to what you are wielding or not already wielding (apart from multiple weapons sometimes). Maybe this indicates we should pay closer attention.
Thanks anyway, I'll try that explanation with the player :)
@Eregrith As mentioned in KRyan's answer, the game has to use abstractions to reduce all possible scenarios into a set of finite cases with discrete rules. In this case it reduces them to: conscious = moving around enough to be hard to stab, not conscious = not moving around and thus easy to stab. As always, a GM can adjust the mechanics if they feel the situation calls for it.
+1 for pointing out that facing is a relevant casualty of abstraction.
| common-pile/stackexchange_filtered |
Solve integral symbolically by isolating integrand in sympy
I was wondering why sympy won't solve the following problem:
from sympy import *
ss = symbols('s', real = True)
a = symbols('a', real = True)
f = Function('f')
g = Function('g')
eq = Integral(a*g(ss) + f(ss),(ss,0,oo))
solve(eq, a)
The return is an empty solution list. I want to tell sympy enough stuff so that I get as a solution:
-1*Integral(f(ss),(ss,0,oo))/Integral(g(ss),(ss,0,oo))
That is, its safe to assume integrals converge, are real-valued and non-zero.
Is there any other assumption/function I can use to get the desired output?
Thanks
Are you sure about the solution you're expecting? Cause it seems to me that to get this solution, a should be outside the integral. Unless you have defined oo to be 1.
Sorry, it was wrong. I have edited with what I would expect now.
Provide also the declarations for ss and oo
Done. oo is imported from sympy
Nothing in the code gives an "empty solution list" so something is missing.
@OscarBenjamin OP had solve(eq, a) at the end, but accidentally deleted it in the edit.
Yes sorry, I added it back
Your assumption about the expected result is still inaccurate. For the equation to have a solution, Integral(g(ss),(ss,0,oo)) must be guaranteed to be real and non-zero, which is in no way implied by your equations, so no result is returned.
Further, it appears that if you want to solve equations involving an Integral, you need to use doit. Take a look below
from sympy import *
x = symbols('x', real = True)
a = symbols('a', real = True)
f = Function('f')
eq = a+Integral(f(x), (x, 0, oo))
print('Eq.1', solve(eq, a))
eq2 = Integral(a+f(x), (x, 0, oo))
print('Eq.2', solve(eq2.doit(), a))
eq3 = Integral(a+f(x), (x, 0, 1))
print('Eq.3', solve(eq3.doit(), a))
eq4 = Integral(a+2, (x, 0, 3))
print('Eq.4', solve(eq4, a))
print('Eq.4', solve(eq4.doit(), a))
Output:
Eq.1 [-Integral(f(x), (x, 0, oo))]
Eq.2 []
Eq.3 []
Eq.4 []
Eq.4 [-2]
Note that eq.1 is solvable, in the sense that you can move a on one side of the equation since it is not inside a limit (integrals with infinite bounds are shorthand for the limit of an integral with the respective bound approaching infinity). However, eq.2 and eq.3 are not solvable, because the limit of a sum is equal to the sum of the limits only if they converge to a real number (and, in your case, there is no guarantee that they do).
Finally, eq.4 is trivially solvable, but you have to use doit. In eq.1 you can get away without it.
That said, you can "overcome" the formalism, using expand. Take a look below.
from sympy import *
x = symbols('x', real = True)
a = symbols('a', real = True)
f = Function('f')
g = Function('g')
eq5 = a+Integral(a+f(x), (x, 0, 1))
print('Eq.5', solve(eq5.expand().doit(), a))
eq6 = Integral(a+f(x), (x, 0, 1))
print('Eq.6', solve(eq6.expand().doit(), a))
eq7 = Integral(a*g(x)+f(x), (x, 0, oo))
print('Eq.7', solve(eq7.expand().doit(), a))
Output:
Eq.5 [-Integral(f(x), (x, 0, 1))/2]
Eq.6 [-Integral(f(x), (x, 0, 1))]
Eq.7 [-Integral(f(x), (x, 0, oo))/Integral(g(x), (x, 0, oo))]
This works because it allows certain operations, by playing fast and loose with the details. But, it still doesn't work, when the results are plain-wrong (try to use oo as the upper bound in eq.6 or eq.7).
I guess then my follow up question is: how do I tell sympy I want to assume that the integral converges and is real? I have a more complicated case where I would like sympy to understand that I want it to solve out for terms which are constant inside the integral.
Thanks, your answer solves the problem. It seems doit() is crucial to the trick. I wonder though, how can we make it faster for more complex expressions? It seems sympy does not figure out quickly the terms that are constant so that it can pull it off.
@user191919 I don't think you can do much. Sympy is python based, so it is naturally slow. You can try to use symengine (written in C++ and hence compiled) along with sympy.
This is your equation:
In [9]: eq
Out[9]:
∞
⌠
⎮ (a⋅g(s) + f(s)) ds
⌡
0
You would like to solve for a to make this expression equal to zero. We can rearrange this expression to extract a so that solve understands how to isolate a:
In [10]: eq.expand()
Out[10]:
∞
⌠
⎮ (a⋅g(s) + f(s)) ds
⌡
0
In [11]: eq.expand(force=True)
Out[11]:
∞ ∞
⌠ ⌠
⎮ a⋅g(s) ds + ⎮ f(s) ds
⌡ ⌡
0 0
In [12]: factor_terms(eq.expand(force=True))
Out[12]:
∞ ∞
⌠ ⌠
a⋅⎮ g(s) ds + ⎮ f(s) ds
⌡ ⌡
0 0
In [13]: solve(factor_terms(eq.expand(force=True)), a)
Out[13]:
⎡ ∞ ⎤
⎢ ⌠ ⎥
⎢-⎮ f(s) ds ⎥
⎢ ⌡ ⎥
⎢ 0 ⎥
⎢───────────⎥
⎢ ∞ ⎥
⎢ ⌠ ⎥
⎢ ⎮ g(s) ds ⎥
⎢ ⌡ ⎥
⎣ 0 ⎦
We have to use force=True because expand will not presume to know that an integral with an upper limit of oo converges and splitting the integral into two integrals might turn a converging integral into a sum of non-converging integrals.
| common-pile/stackexchange_filtered |
getting data out of YML
Hello Stack Overflow community,
I am trying to include a html icon on hover.
This is my code:
<div class="country">{% include icons/home/icon-america.html %}</div>
this works fine, but the icon has to be different on each hover, so i tried this:
<div class="country">{% include icons/home/icon-{{project.country}}.html %}</div>
And this is my YML:
home:
- {folder: 'thumb_1', name: 'Chaffee', text: 'Hier komt tekst over de chaffee en nog meer', link: 'chaffee.html', country: 'america'}
this is not working, is there a way to get this work?
Thanks in advance.
This is my HTML
<div class="thumb-container">
{% for project in site.data.settings.home %}
<a href="{{project.link}}" class="thumb-unit">
<div class="backPic" style="background-image: url(assets/img/home/{{ project.folder}}/thumb.jpg)"></div>
<h3>{{ project.name}}</h3>
<p>{{ project.text}}</p>
<div class="thumb-overlay"></div>
<div class="country">{% include icons/home/icon-america.html %}</div>
</a>
{% endfor %}
</div>
Wim
Not very clear what you want to do. Where {{project.country}} come from ? Is it a for loop in your site.home variable ? Can you show your icons/home/icon-??? template ?
{{project.country}} comes from my YAML "icon-america.html" is just a html (with an SVG in it)document i have been trying to link, but i have also "icon-museum.html", "icon-russia.html" and so on. I have multiple divs that all have to show a certain icon.
Ok, I get it. Your links are pointing to site page or to external pages (eg: github, ...) ?
the above HTML is working like i want it to, but it only shows "icon-america.html" on each div. I have one div that has to show "icon-ussr.html" another "icon-museum.html" and so on. I dont know if i explain it right, but i am Dutch, and this is the best i can do in english.
Can you put your code on a github repository ?
this is the repository https://github.com/wimhuiskes/militair-mobiel-depot
I solved this one by putting the svg's in a seperate folder, and linking to them like this: {folder: 'thumb_1', country: 'america', name: 'M24 Chaffee', text: 'Hier komt tekst over de chaffee en nog meer', link: 'chaffee.html'} and the html like this:
I solved this one by putting the svg's in a seperate folder, and linking to them like this:
{folder: 'thumb_1', country: 'america', name: 'M24 Chaffee', text: 'Hier komt tekst over de chaffee en nog meer', link: 'chaffee.html'}
and the html like this:
<img src="assets/img/home_icons/{{ project.country}}/icon.svg" alt="" />
| common-pile/stackexchange_filtered |
UIView bottom to top animation issue
This is a simple function I am using for animating a view from top to bottom and vice versa (if is top to bottom animation and else is bottom to top animation) :
@objc func openMenu(sender: UIButton) {
if sender.tag == 1 {
self.buttonView.tag = 2
self.moduleView = ModulesCollectionView(frame: CGRect(x: 0, y: self.frame.origin.y + self.frame.size.height + 20, width: UIScreen.main.bounds.size.width, height: 0), collectionViewLayout: UICollectionViewLayout())
self.window?.addSubview(self.moduleView)
UIView.animate(withDuration: 0.7, animations: {
self.moduleView.frame = CGRect(x: 0, y: self.frame.origin.y + self.frame.size.height + 20, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height - self.frame.size.height - 22)
}, completion: { _ in
})
} else {
self.buttonView.tag = 1
UIView.animate(withDuration: 3, animations: {
self.moduleView.frame = CGRect(x: 0, y: self.frame.origin.y + self.frame.size.height + 20, width: UIScreen.main.bounds.size.width, height: 0)
}, completion: { _ in
self.moduleView.removeFromSuperview()
})
}
}
Top animation works fine and the view is animated from top to bottom pleasantly in 0.7 seconds. However, bottom to top animation does not happen. The view is removed instantly. This is the result I am getting :
But I want the animation to be clean while going from bottom to top as well. Just like here.
Secondary : What I finally plan to achieve is PullUpController with the exact reverse animation. So if anyone knows a similar library (pull down drag) can share there inputs.
Update : The issue is coming only with UICollectionView. I replaced collectionView with a simple UIView and it worked perfect.
what was the frame before animation starts
you also need to state the frame before animation like you done in if part you also have do in else part
@sanjaykmwt : I don't think so.
You are trying to move an object from the bottom of the view to the top of the view and animate it yeah? why do you keep the Y value the same? why are you animating height to 0?
@Scriptable : That is because the view is added on window and does not start from 0. It starts from bottom of navigation bar
yes when going from top to bottom. but thats not the issue is it, its when going from bottom to top? so surely it needs to start from the bottom and move to 0,0 (the top). if it starts at the bottom (frame.height) and you add to the Y value it will go further bottom and go off the screen
I added a playground, where the view moves to the bottom and then back to the top.
@Krunal : Added
@Krunal : Did that. Changes the height to 100 but without animation
set 0.7 duration instead 3
You should try to use layoutSubViews() method after at the end of animation block. Change the animation block like this.
For if block:
self.moduleView.frame = CGRect(x: 0, y: self.frame.origin.y + self.frame.size.height + 20, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height - self.frame.size.height - 22)
self.moduleView.layoutSubviews()
For else block:
self.moduleView.frame = CGRect(x: 0, y: self.frame.origin.y + self.frame.size.height + 20, width: UIScreen.main.bounds.size.width, height: 0)
self.moduleView.layoutSubviews()
Here is example code, hope it will help.
Show view:
self.containerView = ModulesCollectionView(frame: UIScreen.main.bounds)
self.containerView.center = CGPoint(x: self.view.center.x,
y: self.view.center.y + self.view.frame.size.height)
self.window?.addSubview(self.moduleView)
self.window?.bringSubview(toFront: self.moduleView)
self.window?.endEditing(true)
UIView.animate(withDuration: 0.3, delay: 0.0,
usingSpringWithDamping: 0.7, initialSpringVelocity: 3.0,
options: .allowAnimatedContent, animations: {
self.moduleView.center = self.view.center
}) { (isFinished) in
self.view.layoutIfNeeded()
}
hide view:
UIView.animate(withDuration: 0.7, delay: 0.0,
usingSpringWithDamping: 1, initialSpringVelocity: 1.0,
options: .allowAnimatedContent, animations: {
self.moduleView.center = CGPoint(x: self.view.center.x,
y: self.view.center.y + self.view.frame.size.height)
}) { (isFinished) in
self.moduleView.removeFromSuperview
}
What would be the initial frames I need to set for this to work ?
For example if you want it to cover whole screen, you can set it like this self.moduleView = ModulesCollectionView(frame: UIScreen.main.bounds). Adjust it to what you need
My class is a subclass of UIView. So I am not sure why you are using self.view.center..... Is this a copied code or are you sure this works ?
How could I know that your class is subclass of UIView? :) This code demonstrated how to show/hide view with animation. You can adjust it for your needs
The issue is coming with UICollectionView. Please check my updated question.
| common-pile/stackexchange_filtered |
Dice roll game some advice
This is my first project writen with python, im looking for some advices to improve my code. Everything works fine, but maybe someone has some ideas how to make my code more efective or to try it out in some other way?
Thanks
Her's my code:
print("Welcome to dice roll!")
game_on = ""
while game_on != "YES" and game_on != "NO":
game_on = input("Would you like to start the game? Type Yes or No: ")
if game_on.upper() != "YES" and game_on.upper() != "NO":
print("You must type Yes or NO")
elif game_on.upper() == "YES":
print(dice_roll())
play_again = input("Would you like to play again? Type Yes or No: ")
if play_again.upper() == "YES":
continue
else:
break
else:
break
For the rolling i use:
import random
def dice_roll():
return random.randint(1,6)
If you want a code review: https://codereview.stackexchange.com/ is a better place for that.
Thanks for your advice!
| common-pile/stackexchange_filtered |
Xcode6 - Swift: How to detect which object is touched and move/drag/drop?
I'm trying to have more than one off these types:
@IBOutlet weak var objectToMove1: UIImageView
and want to be able to detect when one of them is touched... If held down on the object and moving finger, I want the object to follow.. when dropped, I want to see if it interfere with another object of the same type...
I found this example:
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
var touch : UITouch! = touches.anyObject() as UITouch
location = touch.locationInView(self.view)
objectToMove1.center = location
}
This works, but only for the specific object (here: "objectToMove1")... And it moves to the position where I first put my finger (don't matter where I put my finger)...
So, how can I tweek this to be able to detect if I'm actually touching that object and only then follow my finger + detect if it interfere (collide) with another object when lifting my finger?
Thanx!
Kjetil
Use a UITouchGestureRecognizer. You can create a general one which uses a delegate call to handle the touch. You can then add this to any views you create programatically or in a viewDidLoad type methop you can attach it there.
Hi and thanx... Unfortunally I'm realy new to swift, xcode and mac, so could you please give me a code example?
Maybe it's the PanGestureRecognizer I should use?
FIXED!!!
Finally got pointed in the right direction and understood that we are dealing with "optional's", which I still don't fully understand (currently reading "The Swift Programming Language")...
Anyway, the solution was to put "!" after ".view"...
Credit to @DemetrakoPetros which helped me :-D
K.
| common-pile/stackexchange_filtered |
How to allow partitions to dynamically extend?
I have a virtual machine (on Hyper-V host) running Ubuntu server 16.04.3. It is set up to have dynamically expanding virtual hard disk (VHDX).
I have disk space issues when trying to "tab-complete" names:
-bash: cannot create temp file for here-document: No space left on device
I asked df -h and here is what the server responded:
Filesystem Size Used Avail Use% Mounted on
udev 221M 0 221M 0% /dev
tmpfs 48M 1.8M 47M 4% /run
/dev/mapper/zapp--vg-root 2.0G 2.0G 0 100% /
tmpfs 240M 0 240M 0% /dev/shm
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 240M 0 240M 0% /sys/fs/cgroup
/dev/sda1 472M 70M 379M 16% /boot
tmpfs 48M 0 48M 0% /run/user/1000
Obviously, that 2.0G partition is full. However, the virtual disk hadn't reached the size allowed size (3.0GB max, 2.69GB real).
We tried to expand the disk limit to 5GB, but the server doesn't seem to notice and use the available space - even after a restart.
Is it possible to allow these partitions to expand when needed until the cap of disk size is reached? Or what should be done here?
I don't know about Hyper-V, but the way VirtualBox does dynamic virtual disks is that the guest sees the drive as the maximum size, even though the file on the host is dynamic.
Yeah, the guest sees sda as having 5GB now. I was hoping the partitions could take up more space as needed, is that not possible?
I meant to say that you can avoid this issue in the future by setting the max VHD size higher, and it won't actually take up more space on the host unless the guest needs it.
First you need to run parted and use its resizepart command to expand the partition to use the whole disk, then run pvresize to tell LVM about the new space, then run lvresize to grow the logical volume, and finally resize2fs on the logical volume to grow the filesystem to use the new space. This can be done without a reboot.
If the machine sees the expanded space, and if you're using LVM (which appears to be the case), then you can use the lvresize command to resize the partition to fill up the new space. This does not happen automatically.
You'll want to become familiar with the man page of lvresize, and in particular the --resizefs and --size switches.
| common-pile/stackexchange_filtered |
How to use google oauth on a plugin on wordpress
I want to develop a plugin for wordpress, this plugin will be used in a lot of websites that they will buy it and install it.
On this plugin I want to use google oauth to get datas from analytics, But I have to define the callbackURL in my console and in the code, But I can't know which website will install my plugin.
Please if you have any Ideas how to it help me to get this done.
Possible duplicate of Service Applications and Google Analytics API V3: Server-to-server OAuth2 authentication?
@jpaljasma service application can not be used for wordpress plugin, It is an installed-app where as service application is used when you you want to see or show your data, how people will use how your plugin will know which website data I should display ?
| common-pile/stackexchange_filtered |
Parent Controller Class in ASP.NET MVC 2
I've been working on a rather large web application that requires a specific id param in the url for every page visited (for example, /controller/action/id?AccountId=23235325). This id has to be verified every time someone visits a page.
I want to reduce code replication as much as possible, and was wondering if there is a way to use an init method or constructor in a controller that inherits the MVC controller, and then have that controller extended by the others.
I'm using ASP.NET MVC 2.
Yes this is possible using either a base controller class that all your controllers inherit or by creating a custom attribute that you decorate your controller with.
Base controller:
public class BaseController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
// verify logic here
}
}
Your controllers:
public class AccountController : BaseController
{
// the Initialize() function will get called for every request
// thus running the verify logic
}
Custom Authorization Attribute:
public class AuthorizeAccountNumberAttribute : AuthorizationAttribute
{
protected override AuthorizationResult IsAuthorized(System.Security.Principal.IPrincipal principal, AuthorizationContext authorizationContext)
{
// verify logic here
}
}
On your controller(s):
[AuthorizeAccountNumber]
public class AccountController : Controller
{
// the IsAuthorized() function in the AuthorizeAccountNumber will
// get called for every request and thus the verify logic
}
You can combine both approaches to have another custom base controller class which is decorated with the [AuthorizeAccountNumber] which your controllers that require verification inherit from.
| common-pile/stackexchange_filtered |
How to stop Yarn Package Manager script from CLI
https://yarnpkg.com/en/docs/cli/
Is there a way to stop what is started from the command yarn run? Is my only option to lookup the process number and call kill on it?
what's wrong with pressing ctrl-c?
maybe I am just too much of a linux noob, but when I run yarn start the process is hidden. Maybe it is in the background? I am looking for a one command action to stop what I started.
Ctrl-C can be an ungraceful way to exit. I always check the docs first to make sure its a safe way to quit a program I'm not familiar with.
The usual way ctrl-c should work. If it doesn't work, than you have bug in the script. The script's author missed handler for shutdown (SIGINT/SIGTERM/etc).
I must have confused myself coming back in from the weekend. ctrl-c is all I need.
I know this is a well-answered question. However, it behaved once very strange when I was running a sample React code which was auto-created by the create-react-app CLI, on my Windows 10.
After hitting Ctrl+C, which is the most suggested standard way to stop the yarn run, though I got back the command prompt, there was a ghost process lingering around there, which was still actively listening to 3000(default) port, and localhost:3000 was working as normal.
So finally this is how I fixed it:
netstat -ano | grep ":3000" (yeah, I ran this from my git-bash instead of command prompt!)
Noted down the PID of the line where it says LISTENING on 3000
Pressed Ctrl+Shift+Esc to open the Task Manager
Went to the Process tab
Right clicked on one of the headings, say Name
Selected PID --> This added the PID column to the display
Located the PID in question
Right clicked on it and clicked "End task"
Luckily Windows knew how to kill that misbehaving, ghost process and the port became free for me.
NOTE: Prior to the above-mentioned steps, I tried to kill that PID from git-bash using the famous (or notorious as per its meaning?? >8)) kill -9 command. It was responding back with no such PID msg, however netstat -ano was clearly displaying the PID and browser was proving that the ghost process is up and alive!!
Same thing for me, residual ghost process after ^C. (Coincidentally port 3000.) I had to include -p among the netstat options to see the PID: netstat -apno ....
I had a similar issue having it running after ctl+c and then I thought, maybe it is just running on the cache
so went to http://localhost:3000/
ctrl+F5
which forces refresh without cache showed me that the actual project wasn't really running anymore!
;)
*hadn't it worked I would have had to sudo kill the 3000 port
| common-pile/stackexchange_filtered |
OpenGL / GLSL - Uniform block data values incorrect
My shader has a uniform block as such:
layout (std140) uniform LightSourceBlock
{
vec3 test;
vec3 color;
} LightSources;
The data for this block is supposed to come from a buffer object which is created like so:
GLuint buffer;
glGenBuffers(1,&buffer);
GLfloat data[6] = {
0,0,0,
0,0,1
};
glBindBuffer(GL_UNIFORM_BUFFER,buffer);
glBufferData(GL_UNIFORM_BUFFER,sizeof(data),&data[0],GL_DYNAMIC_DRAW);
The buffer is linked to the uniform block before rendering:
unsigned int locLightSourceBlock = glGetUniformBlockIndex(program,"LightSourceBlock");
glUniformBlockBinding(program,locLightSourceBlock,8);
glBindBufferBase(GL_UNIFORM_BUFFER,8,buffer);
From my understanding this should be setting 'color' inside the block in the shader to (0,0,1), but the value I'm getting instead is (0,1,0).
If I remove the 'test' variable from the block and only bind the three floats (0,0,1) to the shader, it works as intended.
What's going on?
As you did specify layout (std140) for your UBO, you must obey the alginment rules defined there. That layout was first specified (in core) in the OpenGL 3.2 core spec, section 2.11.4 "Uniform Variables" in subsection "Standard Uniform Block Layout":
If the member is a scalar consuming N basic machine units, the base alignment is N.
If the member is a two- or four-component vector with components consuming N basic machine units, the base alignment is 2N or 4N,
respectively.
If the member is a three-component vector with components consuming N basic machine units, the base alignment is 4N.
If the member is an array of scalars or vectors, the base alignment and array stride are set to match the base alignment of a single array
element, according to rules (1), (2), and (3), and rounded up to the
base alignment of a vec4. The array may have padding at the end; the
base offset of the member following the array is rounded up to the
next multiple of the base alignment.
If the member is a column-major matrix with C columns and R rows, the matrix is stored identically to an array of C column vectors with
R components each, according to rule (4).
If the member is an array of S column-major matrices with C columns and R rows, the matrix is stored identically to a row of S C column
vectors with R components each, according to rule (4).
If the member is a row-major matrix with C columns and R rows, the matrix is stored identically to an array of R row vectors with C
components each, according to rule (4).
If the member is an array of S row-major matrices with C columns and R rows, the matrix is stored identically to a row of S R row
vectors with C components each, according to rule (4).
If the member is a structure, the base alignment of the structure is N, where N is the largest base alignment value of any of its
members, and rounded up to the base alignment of a vec4. The
individual members of this substructure are then assigned offsets by
applying this set of rules recursively, where the base offset of the
first member of the sub-structure is equal to the aligned offset of
the structure. The structure may have padding at the end; the base
offset of the member following the sub-structure is rounded up to the
next multiple of the base alignment of the structure.
If the member is an array of S structures, the S elements of the array are laid out in order, according to rule (9).
For your case, point 3 applies. So, you need to pad another float before the second vector begins.
| common-pile/stackexchange_filtered |
nhibernate with subquery on database
I need to select a product for a user based on other data in the database.
If the data is filtered out on the database that will require less data to be send to the server.
User (Id)
Product (code)
Access (User_Id, code) // Matching users to object codes
Will this query execute on the database sending back the minimal amout of data?
var products = QueryOver.Of<Access>()
.Where(a => a.User_Id == User.Id())
.Select(Projections.Property<Acces>(a => a.Code));
var access = QueryOver.Of<Product>()
.WithSubquery.WhereProperty(h => h.Code)
.In(products)
.Future();
Try NHibernate Profiler: http://www.hibernatingrhinos.com/products/nhprof
It is difficult reply without trying, just activate teh query log and see what's happen.
This question appears to be off-topic because it is about a locol situation that is only answerable if we are at the computer of the OP
Thanks, I tried reading the logs but have no idea what to look for. I dont have nhibernate profiler.
This is very reasonable way how to filter data. The result of your queries would look like one SELECT against the DB:
SELECT ...
FROM Product
WHERE Code IN (SELECT Code FROM Access WHERE UserId = @userId)
So, this will for sure be executed on the DB Server, less data will be transfered, and what's more, it also would allow you to do the correct paging (if needed) - this scenario is the way how to filter parent over its one-to-many relations (find Parents which child has...)
Maybe check these Join several queries to optimise QueryOver query, NHibernate QueryOver - Retrieve all, and mark the ones already "selected"
| common-pile/stackexchange_filtered |
Selecting MySql table data into an array using PDO class?
I have found some info here, but can comment to ask additional info. So my problem is:
I want to select my data from mySQL.
I have two tables:
customers (id,name,ak,numeris)
prekes (id, customer_id, prek_name, prek_value)
id in both tables is auto incremented.
I try to fill array?
I have only one value passed (customers.id). there are 5 records with same prekes.customer_id.
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT * FROM prekes WHERE customer_id=' . $pirkejas . ''; //$pirkejas = id passed via $_POST.
$q = $pdo->prepare($sql);
foreach ($pdo->query($sql) as $row) {
// if ($row['prek_pav'] != '') {
$prekes = array($row['prek_name'], $row['prek_value']);
Database::disconnect();
How to fill array $prekes in correct way?
Edit:
I want to print value in my form:
<table class="table-bordered">
<tr>
<td><input class="input-medium" name="prekes[1][pavadinimas]" type="text" placeholder="Prekė" value=""></td>
<td><input class="input-medium" name="prekes[1][kaina]" type="text" placeholder="Kaina" value=""></td>
</tr>
<tr>
<td><input class="input-medium" name="prekes[2][pavadinimas]" type="text" placeholder="Prekė" value=""></td>
<td><input class="input-medium" name="prekes[2][kaina]" type="text" placeholder="Kaina" value=""></td>
</tr>
<tr>
<td><input class="input-medium" name="prekes[3][pavadinimas]" type="text" placeholder="Prekė" value=""></td>
<td><input class="input-medium" name="prekes[3][kaina]" type="text" placeholder="Kaina" value=""></td>
</tr>
<tr>
<td><input class="input-medium" name="prekes[4][pavadinimas]" type="text" placeholder="Prekė" value=""></td>
I my action does:
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO customers (name,pavarde,ak,data, numeris) values(?, ?, ?, ?,?)";
$q = $pdo->prepare($sql);
$q->execute(array($name, $pavarde, $ak, date("Y-m-d H:i:s", time()), $numeris));
$pirkejo_id = $pdo->lastInsertId();
foreach ($prekes as $preke) {
//prekiu uzpildymas
$sql = "INSERT INTO prekes (customer_id,prek_name,prek_value) values(?, ?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($pirkejo_id, $preke['pavadinimas'], $preke['kaina']));
}
Database::disconnect();
header("Location: default.php");
I don't know how to get all values from database,
depends on what you consider to be "the correct way". What do you want the array to look like exactly ?
I updated my question. I am making this array to set values in input forn to edit them and put to database again.
Don't inject values into your SQL queries. Use parameter binding instead.
$q = $pdo->prepare('SELECT id, prek_name, prek_value FROM prekes WHERE customer_id = ?');
$q->execute([$pirkejas]); // if PHP < 5.4, use array($pirkejas)
$prekes = $q->fetchAll(PDO::FETCH_ASSOC);
Now $prekes will be an array of rows where each row is an associative array.
<?php foreach ($prekes as $row) : ?>
<tr>
<td>
<input name="prekes[<?= (int) $row['id'] ?>][pavadinimas]"
value="<?= htmlspecialchars($row['prek_name']) ?>">
</td>
<td>
<input name="prekes[<?= (int) $row['id'] ?>][kaina]"
value="<?= htmlspecialchars($row['prek_value']) ?>">
</td>
</tr>
<?php endforeach ?>
How were his quotes messed up? He had an unnecessary . '' at the end, but they didn't hurt anything.
@Barmar Removed that note. I see two single quotes and I think SQL escaping :)
PDO has a method that does this for you. Also, you shouldn't substitute variables directly into the query, you should use parameters.
$q = $pdo->prepare('SELECT * FROM prekes WHERE customer_id= :id');
$q->execute(array(':id' => $pirkejas));
$prekes = $q->fetchAll();
Fixed it -- it's so easy to get mixed up between PDO and mysqli.
I think he meant you are not checking the return value of execute, to see if the query failed. if( $q && $q->execute() ) $prekes = $q->fetchAll();
The question has ERRMODE_EXCEPTION set, so I don't think it's necessary to test it.
In general it isn't, but ERRMODE_EXCEPTION only throws on an error. Sometime a failed query isn't an error, or at least that has been my experience. i.e. execute returns false, but errorInfo() returns no error codes (looks successful).
I think you may be confusing queries that return no rows with queries that get an error.
No, and maybe its a a bug in PDO for edge cases or maybe it was the mysql driver, I donno, but I've experienced it. execute fails, and nothing in errorInfo. No rows returns successful execute.
There aren't many reasons for execute() to fail as errors are usually covered in the prepare stage. Only thing that comes to mind is a parameter count mismatch which certainly does throw an exception.
There are actually a lot of cases, 2 of which, database doesn't exist, or table doesn't exist, as this can't be verified at the prepare statement level for most drivers, some mismatches can pass the prepare level for a bad formatted embedded query that fails the execute. Like I said, it could be an edge case for the query i was using, or a bug in the mysql driver itself.
| common-pile/stackexchange_filtered |
Eclipse-Kepler, Maven and Setup Tomcat 7 debug (hot deploy)
I have maven based project with following structure:
main_project
module_webproject
module_java_proj_1
module_java_proj_2
module_java_proj_3
... ...
Everything compiles and packages fine with command line maven goals execution. I need to setup this project into eclipse environment for developers with tomcat deployment. Anyone know setup instructions?
Also, i am looking into tomcat hot deploy for debugging capabilities.
I have tried mvn eclipse:eclipse, this does only creation of .project and .classpath files. But projects directories are not treated as java or web projects.
Answer from following forum some what helps...
[Running Maven project on Tomcat from Eclipse
There can be a few reasons why you don't see the project in the Add/Remove projects dialog for Tomcat. Verify the following:
You have m2e installed (http://eclipse.org/m2e/download/)
You have m2e-wtp installed (http://www.eclipse.org/m2e-wtp/download/)
Your Maven project imported as a Dynamic Web Application. Look for a Deployment Descriptor entry when you expand the project, it should be somewhere in the first few entries. It is the second one down for me on Eclipse Juno. Not there? It's probably not a web app. Go back and verify 1 & 2, then remove and re-import your project.
Make sure that your web application is not too new for the version of Tomcat that you are using. Right-click the project and go to Properties > Project Facets. Look for Dynamic Web Module and check the version. If this version is too new for your Tomcat version, Eclipse won't let you add it. For instance, your Dynamic Web Module version is 3.0 and you're using Tomcat 6.
| common-pile/stackexchange_filtered |
What happened to the Dataflow LinkTo parameter discardMessages?
In "Introduction to TPL Dataflow" Stephen Toub writes under LinkTo:
"... and what the behavior should be if the predicate is not met (e.g. should such a message simply be dropped, should such a message be declined and offered to other targets, etc.)"
In some examples I see a boolean being passed to the LinkTo method after the filter predicate and a parameter discardMessages is mentioned. For instance the links in this nice example Tpl Dataflow walkthrough do not compile:
linkBroadcaster.LinkTo(downloader, linkFilter, true);
I cannot find that parameter in the LinkTo overloads. Has this behavior changed to some default?
The discardMessages parameter has been replaced by
...LinkTo(DataflowBlock.NullTarget)
For a more detailed discussion see Dataflow MSDN forum
| common-pile/stackexchange_filtered |
Angular $resource POSTS $promise and $resolved to server on $save
I am having trouble with $resource on one of my angular projects. All of a sudden it has started to mess up the objects that are sent to the server on $save.
Calls to $save on $resource objects does not strip away $resolved and $promise from the JSON data that is posted to my server.
The resource behaves like normal except this.
So If i were to call $save on an article -> this is what's actually being sent to the server:
{
"id":999,
"title":"test 2",
"text":"",
"file":null,
"url":null,
"pdato":"0000-00-00 00:00:00",
"author_id":0,
"status":0,
"lang":"",
"parent":0,
"$promise":{},
"$resolved":true
}
The two last properties are the problem. I've never had this problem on other projects. Is it true that angular filters the resource object through angular.toJson before it sends it to the server, and this operation is supposed to remove the $promise/$resolved properties?
When I do a console.log(angular.toJson(article)); (article is a fetched resource object) - it also logs the $promise and $resolved properties.
What can cause this behaviour?
Turns out I had a different version of angular-resource than angular.
Changed my dependencies versions in bower.json to this:
"angular": "~1.3.0",
"angular-resource": "~1.3.0" // this was ~1.2.0
| common-pile/stackexchange_filtered |
Using dnsmasq to address machines by name and resolve external hostnames
I'm having some trouble with my dnsmasq setup. All I want it to do is resolve certain hostnames to certain ip addresses for any machine on my network. More specifically, I'm trying to enable all devices on my network to be able to reach some of the machines on my network using only a specified hostname. I think I must be missing something important because even though I got it working once, after my DNS server rebooted, it stopped forwarding requests for servers outside the LAN.
Here's my setup: (all ip addresses only have the last digit of the IPv4 address)
Apple Airport Extreme set up in DHCP and NAT mode (can't just have NAT on this router, so to get NAT, I have the DHCP range set to 253-254 and reserved some bogus mac addresses to those IPs). On my network this has the IP address of 1
Raspberry PI running raspbian and dnsmasq. This has the ip address 4 and has the hostname 'pi'
A machine named 'tower' at 3
Dnsmasq is set up to be a DNS and DHCP server. All machines that connect to the network get an ip address in the correct range that I specified in dnsmasq, and have the raspberry pi (IP 4) designated automatically as the DNS server. Dnsmasq is also set to forward any requests it can't find to other public dns servers. Here is the entirety of my dns servers with full ip addresses redacted:
/etc/dnsmasq.conf:
# Dnsmasq.conf for raspberry pi
# Full examples found here:
# http://www.thekelleys.org.uk/dnsmasq/docs/dnsmasq.conf.example
# Set up your local domain here
domain=hyrule.home
# Example: The option local=/localnet/ ensures that any domain name query which ends in .localnet will be answered if possible from /etc/hosts or DHCP, but never sent to an upstream server
# don't forward requests (andrewoberstar.com/blog/2012/12/30/raspberry-pi-as-server-dns-and-dhcp)
local=/hyrule.home/
#resolv-file=/etc/resolv.dnsmasq
resolv-file=/etc/resolv.conf
#min-port=4096
## DNS SERVERS
#openNic california
server=<IP_ADDRESS>
#openNic Washington
server=<IP_ADDRESS>
#google public DNS
server=<IP_ADDRESS>
server=<IP_ADDRESS>
# Max cache size dnsmasq can give us
cache-size=10000
# Use the hosts file on this machine
expand-hosts
# ethernet - ip address mappings from /etc/ethers file
read-ethers
# Below are settings for dhcp.
dhcp-range=XXX.XXX.X.10,XXX.XXX.X.200,12h
dhcp-option=3,XXX.XXX.X.1
dhcp-authoritative
log-queries
/etc/resolv.conf:
domain hyrule.home
#search hyrule.home
#nameserver <IP_ADDRESS>
/etc/hosts
<IP_ADDRESS> localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
<IP_ADDRESS> raspberrypi
XXX.XXX.X.3 tower
XXX.XXX.X.4 pi
And the /etc/ethers file contains the mac addresses of the ethernet interfaces of the respective machines
I can see that dnsmasq is logging requests, and everything looks normal, all the requests look like
Nov 2 17:29:21 raspberrypi dnsmasq[2067]: query[AAAA] time.apple.com.hsd1.ca.comcast.net from <IP_ADDRESS>
Nov 2 17:29:21 raspberrypi dnsmasq[2067]: forwarded time.apple.com.hsd1.ca.comcast.net to <IP_ADDRESS>
Nov 2 17:29:21 raspberrypi dnsmasq[2067]: forwarded time.apple.com.hsd1.ca.comcast.net to <IP_ADDRESS>
Nov 2 17:29:21 raspberrypi dnsmasq[2067]: forwarded time.apple.com.hsd1.ca.comcast.net to <IP_ADDRESS>
Nov 2 17:29:21 raspberrypi dnsmasq[2067]: forwarded time.apple.com.hsd1.ca.comcast.net to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: query[A] north-america.pool.ntp.org from <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded north-america.pool.ntp.org to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded north-america.pool.ntp.org to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded north-america.pool.ntp.org to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded north-america.pool.ntp.org to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: query[TXT] push.apple.com from <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded push.apple.com to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded push.apple.com to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded push.apple.com to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded push.apple.com to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: query[AAAA] time.apple.com.hyrule.home from <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: config time.apple.com.hyrule.home is NXDOMAIN-IPv6
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: query[A] time.apple.com.hyrule.home from <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: config time.apple.com.hyrule.home is NXDOMAIN-IPv4
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: query[AAAA] time.apple.com from <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded time.apple.com to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded time.apple.com to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded time.apple.com to <IP_ADDRESS>
Nov 2 17:29:24 raspberrypi dnsmasq[2067]: forwarded time.apple.com to <IP_ADDRESS>
EDIT:
I've decided just reset the pi to the default raspbian because I was doing a lot of experimentation on it, so I wanted to remove any other variables. I went ahead and loaded up minibian and installed dnsmasq. I edited my resolv.conf to look like this (thanks to @Chuck Kollars for pointing out what that file was really doing):
domain hyrule.home
search hyrule.home
nameserver XXX.XXX.X.4
and only set my dnsmasq.conf to query out to these name servers (reading my hosts file by default):
server=/localnet/<IP_ADDRESS> <--- still have the feeling this isn't right
## DNS SERVERS
#openNic california
server=<IP_ADDRESS>
#openNic Washington
server=<IP_ADDRESS>
In my hosts file, I also had the aliases set up as @Chuck Kollars suggested, with a format of
<ipv4> <subdomain> <fqdn>
At this point, I was still having trouble, so I noticed that whenever I pinged something like "tower", dnsmasq would try to resolve "tower.hsdn.comcast.com" or something like that, forwarding it on to the outside name servers because it didn't resolve internally. The comcast part looked familiar, so in my airport utility (5.6.1), under the internet tab, under TCP/IP, that same address was filled in the Domain Name field (ghosted, like it was inherited), so I changed that to also be hyrule.home, and everything worked as expected!
I'm still confused about why that domain name had to be in the router, and why it wasn't being respected from the resolv.conf file...
I say inherited in the sense that, since I have a custom, internal dns ip address, I've specified that in the router configuration, and consequently any machine on my network gets that same dns server address
Although I can't quite figure out all the details of why your system misbehaves, I do have the following suggestions of things you could profitably look at:
1) Dnsmasq uses /etc/resolv.conf only for queries that originated on that same machine - queries from all other machines go directly into Dnsmasq. So /etc/resolv.conf typically contains a pointer to nameserver <IP_ADDRESS> in order to get requests originating from apps on that machine into Dnsmasq. In fact, /etc/resolv.conf may even be overwritten when Dnsmasq starts. Be very wary about putting operational instructions in /etc/resolv.conf; in particular I don't think "domain hyrule.home" is doing what you think it's doing for some of your hosts.
2) Another way to handle local shortnames (the way I do it), is to explicitly put both the shortname and the longname of each local machine into /etc/hosts (rather than relying on any software mechanism), something like this:
XXX.XXX.X.1 router router.hynet.home
XXX.XXX.X.3 tower tower.hynet.home
XXX.XXX.X.4 pi pi.hynet.home
3) I'm not too sure what the definition equating "raspberrypi" to "localhost" is for. I'd be afraid of such an equivalence sometimes generating the wrong response to the wrong system at the wrong time, resulting in some queries going in the round file rather than where they were supposed to. My system works with no such definition.
4) For clarity in your various logs, you may want a definition of "localnet" too (analogous to your definition for "ip6-localnet"). You would expect this to go in /etc/networks ...and in fact that may work. But Dnsmasq itself only looks at /etc/hosts, so you may have to instead put the definition into /etc/hosts even though it's for a network, something like this:
XXX.XXX.X.0 localnet hynet.home
Thank you, @Chuck Kollars, I think it wasn't so much how I was configuring dnsmasq as it was how I set up the domain on my router.
| common-pile/stackexchange_filtered |
Input text file of strings and integers
I have a data file (ordered_data.txt) composed of 8 columns of integers and the last column is a string. It is 2912 rows long. I am inputting the data like so:
data = np.genfromtxt(('ordered_data.txt'), invalid_raise = False)
This obviously converts the last column to all 'nan'. This has been fine for running my code because I only need the integers to do that. The output of my code is essentially taking the original text file and splitting it into two different files based on certain parameters. The problem is that now the two new files I've created all have 'nan' as the 9th column, when I need the original strings to still be there.
I had tried inputting the data like this:
data = np.genfromtxt(('ordered_data.csv'), invalid_raise = False, delimiter = ',',
dtype = [('Glong', float), ('Glat', float), ('Rgal', float),
('Radius', float), ('Velocity', float),
('Second Velocity', (str,10)),
('Distance', float), ('Distance_Error', float),
('Name', (str,16))])
This produced the following output:
(0.279081, -0.481935, 0.392097, 60.0, 20.0, '18.5;12.6', 0.0, 0.0, 'G000.284-00.478')
The 6th column is technically supposed to be a string as well, but that can be ignored for now, it's not as important. It will be the exact same problem as the 9th column I think.
Now, instead of having 9 columns of values, where the last is a string, I now have the whole row grouped into one column.
I have tried reorganizing the data using vstack, hstack, and concatenating lists but I believe there should be a simple solution for this and I'm making it more difficult than it needs to be. I need a new pair of eyes to tell me what my mistake is because I have become too involved in it. If someone could tell me how to make a usable array or list of strings and integers I would be eternally grateful!
Does np stand for Numerical Python? Is there any specific reason you want to use NumPy to do the task of splitting CSV file into multiple files? It can also be done using the standard python libraries.
im guessing here that he is doing vectorized computations on the data ... but thats just a guess ...
can you clarify Now, instead of having 9 columns of values, where the last is a string, I now have the whole row grouped into one column. ... that looks like a row in the output example ... I dont understand what you mean by the whole row grouped into one column... you mean tuple(or list?)?
I guess I should explain more thoroughly. I'm not that experienced in using python, I usually work within a limited range of functions. So I don't really understand the big picture of how to use arrays versus lists or tuples. I think the output is a tuple. I can't access, for example, any single item in the row.
yes, np is for numpy. I'm not just splitting the file up I'm using doing operations with the values, and there are some gaps in it, so that's why I am using np.genfromtxt()
| common-pile/stackexchange_filtered |
JQuery 1.7.1 seemingly can't handle HTML5 element IDs
As you may be aware, HTML5 allows more characters to be used in ID names - see the HTML5 spec which now has space as the only invalid character. Attempting to use this with JQuery shows JQuery ignoring all characters in the ID after a particular valid character, '/'.
<section>
<div id='foo/bar'>
YAAY
</div>
<div id='foo'>
BOO
</div>
</section>
Logging the 'foo/bar' element
console.log($(document).find('div#foo/bar'))
Shows the incorrect element being returned:
[
<div id="foo">
BOO
</div>
]
This is using both the current stable JQuery (1.7.1) and the current JQuery edge.
Is this a JQuery bug, or am I doing something wrong?
is there a question hidden somewhere?
@Christoph Added question to clarify that I'm asking if this is a JQuery bug or I'm doing something wrong.
Next time, just use this tool: http://mothereff.in/css-escapes#0foo%2Fbar :)
Escape the slash (demo: http://jsfiddle.net/m9NT8/):
console.log($(document).find('div#foo\\/bar'))
PS. $(document).find('selector') is equivalent to $(selector).
This behaviour is defined in a RegEx at Sizzle's source code, line 374:
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
That works. Further research shows that JQuery mentions the need to escape characters for selectors on http://api.jquery.com/category/selectors/ "If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes" Annoying, but oh well.
Ack re: document.find, in my (non stackoverflow test case) app I'm working off a string in memory, rather than the document.
Ah, that was the trick :D Sorry for that, I will delete my previous comment.
| common-pile/stackexchange_filtered |
What does AttributeError: 'NoneType' object has no attribute 'tk' mean?
I am a beginner at programming and am writing a simple game of hangman with tkinter and do not know how to solve the error.
Traceback (most recent call last):
File "/Users/ana/Documents/primer7.py", line 62, in <module>
class MyGUI():
File "/Users/ana/Documents/primer7.py", line 93, in MyGUI
tkinter.mainloop()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 405, in mainloop
_default_root.tk.mainloop(n)
AttributeError: 'NoneType' object has no attribute 'tk'
can you help me with the solution?
overall the code should be fine, does anybody have any suggestions how to make it even easier/simple? or how to make better GUI (buttons), I do not understand it very well?
import tkinter
import tkinter.messagebox
import random
#fruit category
easyWords = ['apple', 'orange', 'mango', 'peach', 'guava']
#space category
mediumWords = ['atmosphere', 'jupiter', 'quasar', 'satellite', 'asteroid']
#science category
hardWords = ['biochemical', 'hemoglobin', 'emulsify', 'reactant', 'dynamo']
def setting():
wordChoice = ''
difficulty = input('''Welcome to hangman, select your difficulty.
Type, easy, medium, or hard to begin:''')
if difficulty == 'easy':
wordChoice = easyWords.random
print('You have selected easy mode, start guessing your letters now in the game window. The category is: fruit')
if difficulty == 'medium':
wordChoice = mediumWords.random
print('You have selected medium mode, start guessing your letters now in the game window. The category is: space')
if difficulty == 'hard':
wordChoice = hardWords.random
print('You have selected hard mode, start guessing your letters now in the game window. The category is: science')
def game():
missGuess = 0
guesses = ''
for char in wordChoice:
label3.print(char),
if char in guesses:
print(char),
else:
label3.print("_"),
missGuess += 1
if missGuess == 1:
label1.print('head')
if missGuess == 2:
label1.print('torso')
if missGuess == 3:
label1.print('left arm')
if missGuess == 4:
label1.print('right arm')
if missGuess == 5:
label1.print('left leg')
if missGuess == 6:
label1.print('right leg'),
class MyGUI():
def __init__(self):
self.main_window = tkinter.tk()
#create needed frames
self.top_frame = tkinter.Frame(self.main_window)
self.center_frame = tkinter.Frame(self.main_window)
self.bottom_frame = tkinter.Frame(self.main_window)
#create top frame labels
self.label1 = tkinter.Label(self.top_frame, text='Hangman parts:')
self.label2 = tkinter.Label(self.top_frame, text=' ')
#center frame labels
self.label3 = tkinter.Label(self.center_frame, text=' ')
#bottom frame labels
self.label4 = tkinter.Label(self.bottom_frame, text='Guess a letter:')
self.entry1 = tkinter.Entry(self.bottom_frame, width=5)
self.button1 = tkinter.Button(self.bottom_frame, text='Guess', command=self.game) #calls the game method
self.button2 = tkinter.Button(self.bottom_frame, text='Exit', command=self.main_window.destroy)
#pack top frame labels
self.label1.pack(side='left')
self.label2.pack(side='right')
#pack center frame
self.label3.pack(side='top')
#bottom frame
self.label4.pack(side='left')
self.entry1.pack(side='left')
self.button1.pack(side='left')
self.button2.pack(side='left')
tkinter.mainloop()
setting()
main()
Please [edit] your question title to something more meaningful. Your title should describe the problem you're having or question you're asking, and should contain information that will be useful when seen in a list of search results by future users of this site. Your current title contains nothing at all descriptive or meaningful. Thanks.
It means your variable is None, but you expect it to be some object. You need to figure out why your variable is None.
Giving us the full traceback will be appreciated
This error means you are trying to launch the mainloop() on the wrong object, tkinter is the module, not a class you can use to display a widget.
You should better instantiate a tkinter.Tk() object outside the class (move the self.main_window = tkinter.tk()) and apply the mainloop() on it. The rest of the code needs several fixes, take it step by step... btw, label1.print('some text') cannot work, you must change this to label1.config(text='some text')
mainloop() should be called on a tkinter.Tk() instance. Change this line:
tkinter.mainloop()
to:
self.main_window.mainloop()
Also, indent the line properly under the __init__ method in the MyGUI class.
So MyGUI becomes:
class MyGUI():
def __init__(self):
self.main_window = tkinter.tk()
#create needed frames
self.top_frame = tkinter.Frame(self.main_window)
self.center_frame = tkinter.Frame(self.main_window)
self.bottom_frame = tkinter.Frame(self.main_window)
#create top frame labels
self.label1 = tkinter.Label(self.top_frame, text='Hangman parts:')
self.label2 = tkinter.Label(self.top_frame, text=' ')
#center frame labels
self.label3 = tkinter.Label(self.center_frame, text=' ')
#bottom frame labels
self.label4 = tkinter.Label(self.bottom_frame, text='Guess a letter:')
self.entry1 = tkinter.Entry(self.bottom_frame, width=5)
self.button1 = tkinter.Button(self.bottom_frame, text='Guess', command=self.game) #calls the game method
self.button2 = tkinter.Button(self.bottom_frame, text='Exit', command=self.main_window.destroy)
#pack top frame labels
self.label1.pack(side='left')
self.label2.pack(side='right')
#pack center frame
self.label3.pack(side='top')
#bottom frame
self.label4.pack(side='left')
self.entry1.pack(side='left')
self.button1.pack(side='left')
self.button2.pack(side='left')
self.main_window.mainloop()
I hope it helps.
As a side note, MyGUI is not called anywhere in your code, and the main function is also not available in the submitted code. I don't know the logic of your game so what I did just addresses the error message, the rest is up to you to address.
Your first remark is debatable. As is, the mainloop function is called within the MyGUI class, which makes very little sense, so I'm not sure this can be rationally discussed. Besides, the tkinter.mainloop module function can be called instead of the mainloop instance method of the first widget created.
| common-pile/stackexchange_filtered |
updatedb error - mktemp: too few X's in template ‘updatedb’
When I run sudo /usr/libexec/locate.updatedb to manually update the locate database, I get this error:
❯ sudo /usr/libexec/locate.updatedb
Password:
mktemp: too few Xs in template ‘updatedb’
chown: missing operand after ‘nobody’
Try 'chown --help' for more information.
/usr/libexec/locate.updatedb: line 102: /var/db/locate.database: Permission denied
rm: missing operand
Try 'rm --help' for more information.
How do I resolve this?
The reason you hit this is because you have the GNU mktemp as the first item in your path.
You can verify this by running, type -a mktemp. If you don't see /usr/bin/mktemp as the first option then that is likely your issue.
For example I have:
❯ type -a mktemp
mktemp is /usr/local/opt/coreutils/libexec/gnubin/mktemp
mktemp is /usr/bin/mktemp
The reason I hit this is that I have run brew install coreutils, and then followed the option in the caveats section:
Commands also provided by macOS have been installed with the prefix "g".
If you need to use these commands with their normal names, you
can add a "gnubin" directory to your PATH from your bashrc like:
PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH
This can put the GNU mktemp ahead of the macOS one.
The fix is simply to stop doing that, remove the above line and just use the g-prefixed versions (e.g. gmktemp) when you need GNU tools.
You can reset the PATH with:
sudo env PATH=/usr/bin:/bin:/usr/sbin:/sbin /usr/libexec/locate.updatedb
| common-pile/stackexchange_filtered |
Confusion between ASCII and int values conversion
How does Java understand whether to substitute char or int?
String a="abc";
int b[]=new int[100];
System.out.println(a.charAt(0)); //prints 'a'
System.out.println(b[a.charAt(0)]); //accesses b[97] and does not give error for b['a']
I suggest marking an answer as accepted
The char is converted to an int using widening conversion. This is described in this section about unary numeric promotion from the Java Language Specification, specifically:
Otherwise, if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).
Java automatically casts char to int when an int would be used.
This is perfectly valid Java code:
public static void main(String[] args) {
int field1 = 'a';
System.out.println(field1);
}
There is an overload of println that specifically takes a char. This handles chars separately; without this overload, the int overload would still be present, the char would be promoted to int, and the int overload would print 97, which is the Unicode code point (ASCII lines up for English letters, numbers, and common punctuation).
However, in an array index context, it is promoted to an int per JLS Section 15.10.3, "Array Access Expressions".
The index expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs.
Unary numeric promotion is what promotes the char to an int, so that it accesses b[97].
It is usually best to avoid this implicit widening of a char to an int, to avoid something unexpected such as accessing b[97].
Thank you. This helped. I suppose explicit type casting is better and simpler to follow
As the asker of this question, at your discretion, you may accept exactly one answer that you think helps you the best.
This is inferred by the compiler. A char may be used instead of an int. The context of usage determines which one is used - the given types are preferred if there is ambiguity. However, if only the other type would work in the context (b['a'] would obviously be invalid were it not for the conversion), this type is inferred.
a.charAt(0) is a character, so it knows to print a in the first line.
In the second line, an index is always a number, so Java automatically converts the char value to its numeric counterpart.
That's not really a safe conversion because the specific numeric value of a might differ depending on your encoding.
Thank you. This helped. Yes, it will differ for Unicode and ASCII
For the following:
System.out.println(a.charAt(0));
Java calls the method PrintStream.println(char x) since you are passing a character. So no problem there.
But for the following:
System.out.println(b[a.charAt(0)]);
Once again, a.charAt(0) returns the character 'a', but this time, since you are trying to get the element of an array, it will convert the character to an int, since you need an int to access an array element.
| common-pile/stackexchange_filtered |
How do I choose the correct view for zooming with multiple UIScrollView objects in a view (iPhoneSDK obj-C)?
I have added several UIScrollViews as subviews of a single UIView and set the frames so that each one is clearly visable. I set scrollEnabled to YES and set the contentSize larger than the bounds/frame. I do this in a for loop, and with each pass of the loop I release the UIScrollView (though the object is still stored because it has been subviewed into the UIView). This works well for being able to scroll around the imageView stored in each particular UIScrollView but I cannot for the life of me figure out how to get the zoom to work. I included the in the interface. Here are the methods I have tried for choosing the correct view for zooming:
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return [[myView subviews] objectAtIndex:pageNum];
}
and
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return [myView viewWithTag:pageNum];
}
neither seems to work. The weird part is that scrolling works fine. I can't even get the viewForZooming method to get called at all if I put in an NSLog call. Any ideas? I think I've lost all my hair from getting frustrated with this.
Edit: Thanks a lot cduhn! All I needed was that little bump, I had forgotten to set the scrollView delegate to self... I've been working with various apps that take advantage of UIScrollView for months now and been using the delegate correctly and this most recent one I don't know where my brain went.
However, you do not need to override the scrollViewDidEndZooming:withView:atScale:, the delegate will call that no matter what after a zoom.
Also, after a little tweeking this worked:
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
return [[[myView viewWithTag:pageNum] subviews] objectAtIndex:0];
}
This simply calls the scrollView inside View container and then gets the UIImage inside of that... works well.
It sounds like you may not have set the delegate property on your UIScrollViews to point at the object that implements viewForZoomingInScrollView:
Also note this snippet from the UIScrollView Class Reference:
For zooming and panning to work, the delegate must implement both viewForZoomingInScrollView: and scrollViewDidEndZooming:withView:atScale:; in addition, the maximum (maximumZoomScale) and minimum ( minimumZoomScale) zoom scale must be different.
Finally, a word of warning: Be careful when accessing the subviews of UIScrollView. Your subviews are not alone in there. UIScrollView adds its own UIImageViews as subviews of itself to implement its scrollbar UI. So code like this...
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return [[myView subviews] objectAtIndex:pageNum];
}
... may not do what you expect.
| common-pile/stackexchange_filtered |
This AI we're building keeps making weird mistakes when we add new facts to its knowledge base.
Look at this case - we told it "Tweety is a bird" and it concluded "Tweety flies." Then we added "Tweety is a penguin" and suddenly it says Tweety doesn't fly anymore.
That's not a mistake though. The system should retract the flying conclusion once it learns Tweety's a penguin. Classical logic can't handle that kind of reasoning.
But doesn't that violate the basic principle that adding knowledge shouldn't reduce what we know? If we prove something from premises, adding more premises shouldn't make it unprovable.
That's exactly why we need non-monotonic logic here. In monotonic systems, if $\Gamma \vdash A$, then $\Gamma, \Delta \vdash A$ always holds. But real reasoning isn't like that.
Think about it this way - when you see wet grass, you'd normally conclude it rained. That's a reasonable default assumption based on typical patterns.
Right, but if you then learn a sprinkler was running, you have to abandon the rain explanation. The sprinkler information doesn't just add to your knowledge - it actively contradicts your previous conclusion.
So we need the system to reason with defaults and exceptions. "Birds typically fly" isn't the same as "All birds fly" - there's an implicit "unless proven otherwise" clause.
The key insight is that we're not doing deductive reasoning anymore. We're making abductive inferences - finding the most likely explanation given current evidence, but staying ready to revise.
But how do we formalize "unless proven otherwise"? The system needs rules for when to apply defaults and when to retract them.
We could use something like "If X is a bird and we have no information suggesting X cannot fly, then conclude X flies." The absence of contrary evidence becomes part of the reasoning.
That creates interesting computational | sci-datasets/scilogues |
Are Yajuj and Majuj (Gog Magog) humans?
Are Yajuj Majuj part of the human race or are they different creatures? Same question about Dajjal.
There are 2 verses in the Qur'an mentions about Gog Magog.
They said, "O Dhul-Qarnayn, indeed Gog and Magog are [great] corrupters in the land. So may we assign for you an expenditure that you might make between us and them a barrier?" (Surat Al-Kahf 18/94)
Until when [the dam of] Gog and Magog has been opened and they, from every elevation, descend. (Surat Al-'Anbya' 21/96)
We can't say anything about their humanity from these verses, but probably they are humans, because I never heard of a non-human intelligent creature apart from angels and djinns. I assumed that they are intelligent (at least more than animals) because of the corruption they made. They can't be angels because of the angels's nature. They might be djinns or humans.
About Dajjal, there are no verses for him/it. It is a very controversial topic. Some scholars say he is a human, some says he is not a living thing, and some says he is completely made up. Here are some hadith about the topic. Some people believe that Dajjal is not actually a human, but a source of greatest fitnah ever and accuse television, internet etc. Some scholars believe if it was real, it would have mentioned in The Qur'an. And they believe that all the hadith about Dajjal are completely made up.
So, Dajjal is a very controversial topic.
Salam
actually I wanted to comment on Kalahari's post, but I can't since my reputation is below 50 ^______^
According to some hadiths they are human. According to some other hadiths, they are not human but some sort of animals which are kept underground and will be released before the arrival of Jesus. It seems that they will mainly attack western lands and Jesus will fight them and drown them in some sea.
Wa alaikum salaam. I heard so much hadith about Dajjal, Gog-Magog, the return of Jesus(puh), Mahdi and mainly about The Signs of The Apocalypse. There are so much of them contradicting each other, I chose for now to be skeptical about them. Quran doesn't contain much about Gog-Magog and Signs of Apocalypse, and never mentions about Mahdi, Dajjal and the return of Jesus(puh), except Surat An-Nisa' 4/159. I am not sure what this verse says. I am going to ask about it in this site.
according to Al-Nawawi, Yajuj Majuj and Dajjal are a human
Selam Aleykum,
Of course none but Allah know what Gog and Magog really are. Coming from an Information technology and electrical engineering background, I would like to present my theory on what Gog and Magog (ref G&M) might be.
As the previous answers have eluded, there was a wall built to keep G&M out but what I found interesting from the standpoint of answering the question is the material this wall was composed of; iron and copper.
If we take iron to be a metaphor for magnetism and copper to symbolize electricity, we combine the two metaphors to symbolize electromagnetism. So with my background, I interpret the Quran as saying there are certain beings that will cause trouble for mankind but they can only come into existence at some time in the future when the electronic or electromagnetic technology to make them possible comes to fruition.
Noah Hariri in his best selling book "A history of the future" talks about a troubling trend where computer algorithms are replacing humans in many sectors of the economy particularly the online economy. Humans are really starting to become obsolete.
So we already see this trend where droids, robots, and software algorithms are taking over. If these droids ever start developing their own consciousness and listen to the whispers of the jinn or sheytan, we can at that threshold say that they are indeed G&M and will take over the earth as they will be much more intelligent and infallible than humans. Then only through Allah's mercy will there come a savior (return of Jesus, Mahdi ) to subdue G&M and bring Sharia to the whole earth.
I know the Quran Does not say about the nature of Yajuj majuj
| common-pile/stackexchange_filtered |
GoogleVis not working in R: Motion chart not loading in the browser. Getting blank browser
I'm having issues getting GoogleVis to work. When I plot using GoogleVis, I get a blank browser. Here's what I did:
I used the built-in R dataset, 'ChickWeight'
Installed RJSONIO and googleVis packages.
For simplicity, I truncated the ChickWeight dataframe to 24 rows: ChickWeight1<-ChickWeight[1:24,]
Then called the gvisMotionChart function, assigning it an object:
visualization1<-gvisMotionChart(ChickWeight1,idvar='weight',timevar='Time')
Running the above code gave me a warning message. Not sure if warning message is related:
Warning message:
In if (class(x[[.x]]) == "Date") as.character(x[[.x]]) else x[[.x]] :
the condition has length > 1 and only the first element will be used
I then plotted the object: plot(visualization1)
I expected a motion chart, but I just got a blank browser. I also tried converting the 'Time' column from a numeric to date class, but no luck.
I'm using R 3.0.2, Mac OS X version 10.6.8 and Safari Version 5.1.2 (6534.52.7). I also ran the the same code on my work Windows laptop, but no luck.
Any feedback would be greatly appreciated! Thanks!
The full error that you got after typing:
mchart1<-gvisMotionChart(ChickWeight1,idvar='weight',timevar='Time') was:
Error in gvisCheckMotionChartData(data, my.options) :
The data must have rows with unique combinations of idvar and timevar.
Your data has 578 rows, but idvar and timevar only define 375 unique rows.
In addition: Warning message:
In if (class(x[[.x]]) == "Date") as.character(x[[.x]]) else x[[.x]] :
the condition has length > 1 and only the first element will be used
This error would have clued you in to the fact that you hadn't designated the ids of the chicks. If you do mchart1<-gvisMotionChart(ChickWeight,idvar='Chick',timevar='Time') This will give you the motion plot of how the chicks gain weight over time.
?gvisMotionChart is very useful.
| common-pile/stackexchange_filtered |
Layers in PixiJS
I am using the PixiJS framework to create a 2D RPG Game.
How can I create a PIXI.Container with a transparent background which I can render on top of my main stage container?
My goal is it to have 4 layers which contain PIXI.Sprites and PIXI.Texts:
layer 1 should be rendered beneath the player
layer 2 should be rendered above layer 1
layer 3 should be rendered above the player and above layer 1 and layer 2
layer 4 should be rendered above everything else for debug information
In case I can cannot use multiple PIXI.Container then how else could I achieve this effect?
If you for some reason don't want to use preordered containers, then you need to sort the render list.
| common-pile/stackexchange_filtered |
Google API: How to pass zip-code value into the JavaScript code
I using a html form to input a zip-codes (PortZip)
Port ZipCode:<br>
<input type="text" id="PortZip" value="31402">
and I want pass the zip-code value to java script code line
var point1 = new google.maps.LatLng(-33.8975098545041,151.09962701797485);
Currently the java script code line takes LatLng values manually. How do I change the java script code line to take the zip-code value?
I don't see any Google Apps Script in this question. Maybe you meant to use the [[tag:javascript]] tag, instead of [[tag:google-apps-script]]?
Edit: Changed the tags and made the question to the point.
Use the Geocoder to translate addresses (or zipcodes) into geographic coordinates that can be used in the Google Maps Javascript API.
code snippet:
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
codeAddress(document.getElementById('PortZip').value);
}
google.maps.event.addDomListener(window, "load", initialize);
function codeAddress(address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
html,
body,
#map_canvas {
height: 500px;
width: 500px;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
Port ZipCode:
<br>
<input type="text" id="PortZip" value="31402">
<div id="map_canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
Can you point out the code line from above that converts zip code into the LatLng address? (I already have code that plots the address on Google map so I will be using it)
The Marker is placed at the resulting coordinates from the geocoder (results[0].geometry.location, the map is also centered there.
Can you help me with the exact code to be inserted in the code I wrote in question? I am new to js.
You didn't write anywhere near enough code for me to make a working example. The closes I can come is var point1 = results[0].geometry.location inside the callback function where that is available. What are you doing with `point``?
http://stackoverflow.com/questions/31278750/how-to-plot-path-between-3-zipcodes-on-google-maps
| common-pile/stackexchange_filtered |
The Monodromy and Parallel Form
According to famous Riemann-Hilbert correspondence, a flat connection gives a representation of fundamental group which is called monodromy. I would like to ask how does the monodromy relate to special form on the vector bundle.Here is my question:
1.Assume the $C^{r}\rightarrow E\rightarrow M$ is a vector bundle with flat connection $\nabla$, if the monodromy $\rho^{\nabla}:\pi_{1}(M,p)\rightarrow SL(r,C)$, show that: the $det$ is a parallel form on $\wedge^{r}E$.
2.If the monodromy lies in $U(r)$, then the vector bundle admits a parallel hermitian metric.
This is my idea: I try to directly compute it, the question means $\nabla det=0$, then I choose any frame $s_{1},...,s_{r}$, we have $\nabla det(s_{1},...,s_{}r)=d(set(s_{1},...,s_{r}))-\sum det(s_{1},...,\nabla s_{i},...,s_{r}).$ But how to show this is identically zero? I know because of flatness, we can locally choose parallel frame, but I think this doesn't give any help after my computation. Could you give me some help?
Look up the "holonomy principle" - should give you sufficient inspiration to answer these questions.
You mean here we only need the holonomy data? We do not need to use the fact that the monodromy is a representation?@Quaere Verum
No, I mean that you can use the same ideas that are used in the proof of that theorem.
| common-pile/stackexchange_filtered |
python plot error when reading .csv with pandas: 'Series' object has no attribute 'find'
I am trying to read few .csv files and do something line plot(x,y) with this code:
import numpy as np
import pandas
from matplotlib import pyplot as plt
%matplotlib inline
colnames = ['X','Y']
xfmr_x_y_file = pandas.read_csv('AMI_X_Y.csv', names=colnames)
gnode_x_y_file = pandas.read_csv('AMI_GNODE_X_Y.csv', names=colnames)
node_x_y_file = pandas.read_csv('AMI_NODE_X_Y.csv', names=colnames)
EX_XFMR_X_meas = (xfmr_x_y_file.X)
EX_XFMR_Y_meas = (xfmr_x_y_file.Y)
DB_GNODE_X_meas = (gnode_x_y_file.X)
DB_GNODE_Y_meas = (gnode_x_y_file.Y)
DB_NODE_X_meas = (node_x_y_file.X)
DB_NODE_Y_meas = (node_x_y_file.Y)
plt.plot(EX_XFMR_X_meas[1:],EX_XFMR_Y_meas[1:],label='XFMR')
plt.title('TUR117')
plt.xlabel('X')
plt.ylabel('Y')
plt.gcf().set_size_inches(18, 6)
#plt.savefig('TUR117.png')#,dpi=300
plt.show()
But it is generating a weird error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-24-0428c97a1c49> in <module>()
17 DB_NODE_Y_meas = (node_x_y_file.Y)
18
---> 19 plt.plot(EX_XFMR_X_meas[1:],EX_XFMR_Y_meas[1:],label='XFMR')
20 plt.title('TUR117')
21 plt.xlabel('X')
C:\Program Files (x86)\ActivePython 2.7.8\lib\site-packages\matplotlib\pyplot.pyc in plot(*args, **kwargs)
2985 ax.hold(hold)
2986 try:
-> 2987 ret = ax.plot(*args, **kwargs)
2988 draw_if_interactive()
2989 finally:
C:\Program Files (x86)\ActivePython 2.7.8\lib\site-packages\matplotlib\axes.pyc in plot(self, *args, **kwargs)
4135 lines = []
4136
-> 4137 for line in self._get_lines(*args, **kwargs):
4138 self.add_line(line)
4139 lines.append(line)
C:\Program Files (x86)\ActivePython 2.7.8\lib\site-packages\matplotlib\axes.pyc in _grab_next_args(self, *args, **kwargs)
315 return
316 if len(remaining) <= 3:
--> 317 for seg in self._plot_args(remaining, kwargs):
318 yield seg
319 return
C:\Program Files (x86)\ActivePython 2.7.8\lib\site-packages\matplotlib\axes.pyc in _plot_args(self, tup, kwargs)
274 ret = []
275 if len(tup) > 1 and is_string_like(tup[-1]):
--> 276 linestyle, marker, color = _process_plot_format(tup[-1])
277 tup = tup[:-1]
278 elif len(tup) == 3:
C:\Program Files (x86)\ActivePython 2.7.8\lib\site-packages\matplotlib\axes.pyc in _process_plot_format(fmt)
97 # handle the multi char special cases and strip them from the
98 # string
---> 99 if fmt.find('--') >= 0:
100 linestyle = '--'
101 fmt = fmt.replace('--', '')
C:\Program Files (x86)\ActivePython 2.7.8\lib\site-packages\pandas\core\generic.pyc in __getattr__(self, name)
1934 return self[name]
1935 raise AttributeError("'%s' object has no attribute '%s'" %
-> 1936 (type(self).__name__, name))
1937
1938 def __setattr__(self, name, value):
AttributeError: 'Series' object has no attribute 'find'
If I simply do plt.plot(EX_XFMR_X[1:]), it plots fine and it appears that for some reason it is not able to simulate plt.plot(x,y) format. Did anyone face this problem before? Is there something I am not doing right?
It may be an issue with your input. Generate the Series manually and test.
@bejota can you please elaborate on your comment?
You're using input that we cannot access. Begin with a simple example and see if you can reproduce the problem. For example: EX_XFMR_X_meas = range(10).
bejota. I had the same problem. You should try transform your "pandas.Series" to list.
I had a similar problem and the plt.plot(x,y) is indeed not respected in this case. Now both your inputs EX_XFMR_X_meas[1:] and EX_XFMR_Y_meas[1:] are still pandas.Series, so plt.plot(x,y) takes the Series' index as x and the Series' values as y. If the values of the first variable depict the x and the second the y, do:
plt.plot(EX_XFMR_X_meas[1:].values,EX_XFMR_Y_meas[1:].values,label='XFMR')
which passes them as numpy.ndarray .
I guess the weird error originates because plt.plot() does not know what to do with the second pandas.Series as input.
| common-pile/stackexchange_filtered |
Create a random background color in Wordpress
I've checked out all the related questions I could find and still cannot get this to work so am reaching out to you lovely folk!
I wish my site to have a random color background (one of multiple pre-selected colors) each time someone visits.
There are various times people have asked for it to call up a random image but I just wish to have a block color, assuming using bold background.
The two options I have seen used in similar ways, but to no avail, are:
jQuery (link: taken from a Tumblr query):
1) Creating a new 'background.js' file in /js/ with the code:
<script>
var bgcolorlist=new Array("background: #ff871b", "background: #15efa1", "background: #51ddff", "background: #ff1b6c", "background: #000000");
var color = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
$('body').css('backgroundColor', color);
</script>
2) Adding to function.php:
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_enqueue_script(
'your-script', // name your script so that you can attach other scripts and de-register, etc.
get_template_directory_uri() . '/js/your-script.js', // this is the location of your script file
array('jquery') // this array lists the scripts upon which your script depends
);
}
& PHP and CSS (link):
I put this whole string in the style.css file:
<?php
$input = array("#000080", "#00CED1", "#191970");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>
body {
background: <?php echo $color; ?>;
}
Unfortunately neither of these solutions seem to work for me and both threads are outdated so cannot get further answers hence starting a new thread.
Any ideas for where I might be going wrong for either?
Any other ways around this you think would be a better way to solve the problem?
Further info: I'm using the super simple Less theme, which only comes with 3 files: functions.php, index.php and style.css - which I'm using as a bare bones theme to completely customise my own theme.
Many thanks in advance!
The issue with your JavaScript implementation is that you have the whole CSS declaration in your array indexes. Also, since you are including the script in the head, you need to wrap the code in a document.ready handler, and take care of the noConflict mode WordPress puts jQuery in.
Try something like this:
jQuery(function($) {
var bgcolorlist=["#ff871b", "#15efa1", "#51ddff", "#ff1b6c", "#000000"];
var color = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
$('body').css('backgroundColor', color);
});
The reason your PHP did not work in the CSS file is because .css files do not normally run PHP code. You would need to put it in a separate .php file and enqueue it, or put the code in the head with header.php or an action.
<style>
<?php
$input = array("#000080", "#00CED1", "#191970");
$rand_key = array_rand($input);
$color = $input[$rand_key];
?>
body {
background: <?php echo $color; ?>;
}
?>
</style>
Thanks a lot Alexander! I tried a couple of the suggestions here but your jQuery update seems to be the simplest even though it requires an external file to handle it.
| common-pile/stackexchange_filtered |
creating an iOSOpenDev application and a tweak in the same package
I've spent three days looking how to create (using iOSOpenDev) one package (.deb) containing an application and a tweak at the same time and I could not find anything.
It is possible to do this?
What you can do is in the xcode project, create two targets (one tweak and one application), both using iOS open dev, and then package them in the same deb. The way you would package them both is creating the correct path to the applications folder (/Applications/YourApp.app) and the path to where your tweak goes (/Library/MobileSubstrate/DynamicLibraies) in the same deb folder, and then build the folder by typing this in terminal
sudo dpkg-deb -b YourDebFolder
The folder should look like this
Where DEBIAN contains the control file, Library contains a subfolder named MobileSubstrate, which then contains another subfolder DynamicLibraries, which contains the tweak, and the Applications folder contains the YourApp.app file.
Hi Chris, I did exactly this and the tweak works fine but the application opens and closes. Any suggestions?
Is the file you're putting in the Applications a .app bundle, and does it run correctly from Xcode?
Sorry, your method works perfect. It was a problem between iOS 5 and iOS 6 compatibility. Thanks for all the help.
| common-pile/stackexchange_filtered |
How to track more than one remote with a given branch using Git?
The situation is this:
I have more than one remote repository - for reference, lets say that one is the "alpha" repository, and we have recently set up a new "beta" repository, which some users have migrated to.
Both repositories have a "master" branch.
How do I set up my local master such that it will attempt to automatically push and pull to and from both the alpha and beta repositories, without manually specifying the remote I want to use each time?
I should elaborate that I don't want to set up two local branches 'master-alpha' and 'master-beta', I want the same local branch to track both remotes.
possible duplicate of pull/push from multiple remote locations
I don't think it is possible with one git command.
The other alternative would be to define a git alias which would git pull master from one repo, and then git pull master from the other.
But if the history of commits differ too greatly between the two master, that would quickly lead to a massive number of conflicts...
What kind of alias would you recommend? I suppose that the most reasonable constraints would be that we only need consider the fast-forward case - anything else should cause the command to fail, forcing me to pull each remote individually.
@Arafangion: initially, I though about a naive alias like git config --global alias.pullall "!git pull origin1 && git pull origin2". However, the receive.denyNonFastForwards config is for push, not pull...
Looks like I may just need to hack up a quick shell script to do the work, then, pulling each remote until an in-progress-merge is detected.
@Arafangion: true but you will need to take into account the case where the first pull works, and the second don't: a full reset to before the first pull will be needed.
I have written a script that may help with this:
git-list-upstream-commits
It won't do any pulling or merging, but it will look at all the remote branches, and show you which ones have commits which you do not have on your current branch.
It sorts the branches with the most recent commits at the bottom, and it shows the latest commit on each branch, with some basic info.
That looks pretty cool, I'll upvote that one!
| common-pile/stackexchange_filtered |
Updating textbox with dropdown value doesn't work in IE [JavaScript]
I'm trying to update the text in a textbox when a value is selected from a dropdown form element using onchange().
This works fine in Firefox, Safari, Chrome but not in Internet Explorer.
Here's the stripped down code:
<script type="text/javascript">
$(document).ready(function(){
document.forms['time_form'].elements['hours'].onchange = function(){
document.getElementById('hours_text').value = ''; // Clear the current value
document.forms['time_form'].elements['hours_text'].value += this.value;
};
});
</script>
<select name="hours" id="hours" class="time">
<option value"01">01</option>
<option value"02">02</option>
<option value"03">03</option>
<option value"04">04</option>
<option value"05">05</option>
<option value"06">06</option>
etc...
</select>
<input type="text" id="hours_text" name="hours_text" value="01" />
The current text is cleared as it should be but not updated with the new value.
Any ideas what's going on? Is this my error or IE's?
Change your code to something like:
$(document).ready(function(){
// apply a change event
$('#hours').change(function() {
// update input box with the currently selected value
$('#hours_text').val($(this).val());
});
});
You are using jQuery already so make use of it's abilties to control the events of an element and write your code the jQuery way. Do not mix code such as onchange on this (although it may work) but it's better to make things consistent.
Thank you. Works perfectly. I new there must be a better way to do this than my cobbled together method.
I've spent 5 minutes trying to figure out why your code doesn't work, only to find out you forgot the = character in your OPTION start tags. Grrrr.... :)
Replace <option value"01"> with <option value="01"> for every OPTION start tag.
Here you go:
$('#hours').change(function() {
$('#hours_text').val( this.value );
});
Live demo: http://jsfiddle.net/ubrcq/
Haha. Wow. I really am an idiot. Adding the = actually fixed it. I guess the other browsers are a little more intelligent than IE.
I don't see why you'd blank the value property and then immediately append more text using +=, you could achieve the same thing by simply setting the value property to this.value in one go.
Also, you are targeting the 'hours_text' element in 2 different ways:
document.getElementById('hours_text')
and
document.forms['time_form'].elements['hours_text']
It would be a little bit cleaner to assign to a variable like so:
var hours_text = document.getElementById('hours_text');
hours_text.value = this.value;
I'm still getting to grips with Js. I make silly mistakes. thanks for the input.
function ChangeValue()
{
$("#hours_text").val($("#hours").val());
}
<select name="hours" id="hours" class="time" onchange="ChangeValue()">
<option value"01">01</option>
<option value"02">02</option>
<option value"03">03</option>
<option value"04">04</option>
<option value"05">05</option>
<option value"06">06</option>
etc...
</select>
< input type="text" id="hours_text" name="hours_text" value="01" />
| common-pile/stackexchange_filtered |
Can (singular) homology classes always be represented by images of closed manifolds?
My intuition tells me that if $A \in H_2(M;\mathbf Z)$, then $A$ can be represented by a map $\Sigma \to M$, where $\Sigma$ is a closed (= compact boundaryless) surface, i.e., the connected sum of tori or of real projective planes. It would then seem that, in general, any $B \in H_k(M;\mathbf Z)$ can be represented by a map [closed $k$-manifold] $\to M$.
This is probably something really trivial but I'm not sure how to go about proving it "properly."
A representative of a homology class in $H_k(M;\mathbf Z)$ is a $k$-cycle, i.e., a formal linear combination ($\mathbf Z$ coefficients) of maps [$k$-simplex] $\to M$ such that the boundary is empty. So this can be viewed as a map [disjoint union of $k$-simplices] $\to M$ such that "the boundaries of the simplices get quotiented out." Thus, we can factor this map into [disjoint union of $k$-simplices] $\to$ [closed $k$-manifold] $\to M$, where the first map is just gluing the boundaries of the simplices together.
All this seems very hand-wavy to me and I'm not really convinced by my own pseudo-argument. Any help to make this more rigorous (or point out the fallacies!) would be appreciated.
You need orientations or else you don't have a fundamental class integrally. (So no real projective planes.)
http://mathoverflow.net/questions/1489/cohomology-and-fundamental-classes
This is a classical problem in algebraic topology, the Steenrod problem, which was more or less solved by Thom. Thom showed that this is true
$\bmod 2$,
rationally, and
integrally if $k \le 6$.
Integrally for $k \ge 7$ there are counterexamples; the obstructions involve Steenrod operations for odd primes. (It's harder to glue a bunch of simplices into a manifold than you're making it sound!) See this MO question and this MO question for more details, as well as this overview of Thom's work by Sullivan.
That's very interesting. (+1).
@Mike: I don't think it's a construction. I haven't read the paper, but I expect it's a homotopy-theoretic calculation involving oriented bordism. Classes in oriented bordism are always represented by smooth manifolds.
| common-pile/stackexchange_filtered |
Problems With Comparing Strings
I have the following code that was working a few days ago but then all the sudden, without any changes being made, gave me all these errors. Any help in troubleshooting would be appreciated.
init(name: String, arrayOfNodes: [SKSpriteNode]){
var SKnode = SKSpriteNode(imageNamed: "Cool Image")
SKnode.name = name //Error: Cannot apply value of type String to type String
for(node in arrayOfNodes){ //4 errors about random things like putting in commas at various points
//Stuff
}
if(name == "Billy"){ //Binary operator "==" cannot be applied to operands of type String and String
//Stuff
}
None of these errors seem right to me and they came about without any changes being made to the file. I've tried restarting Xcode, restarting the computer, none of it changes the error messages.
Try removing the parenthesis from your for..in statement, they shouldn't be there.
Thanks, that takes care of those errors, but any ideas for the others?
Also, the init method for SKSpriteNode should be SKSpriteNode(imageNamed: )
Sorry most of this is just code I filled in. The errors I'm really trying to address are the String to String ones.
You should post more of the class and code surrounding this method, something else is going on outside of this code.
Well part of the problem is the parenthesizes in your for loop. Remove them. Apple recommends that types start with a capital so your SKnode may be legal as a variable name but it is confusing to others. I am not sure about the other two errors.
Why isn't the parameter label in SKSpriteNode like this; SKSpriteNode(imageNamed: "Cool Image")?
| common-pile/stackexchange_filtered |
Clean git branch for customer
At work we have a git flow where
- developers correct a given defect in the development branch
- then they have to 'put'(*) their correction in the integ branch
- this integ branch must be accessible to our customers because they want to check out our code and recompile it themselves
The customer wants a clean branch, ideally with a commit per corrected defect.
But our developers might deliver their work in several commits (one defect corrected by several commits in the development branch)
If we simply merge the development branch into the integ branch, the client will see in the history all the atomic commits performed by the development guys, which shall be avoided.
Question related to (*):
How can we clean the branch for the customer?
- without imposing a "one commit per defect" rule to the developer
- ideally without cherry-picking and squashing the atomic commits corresponding to each defect in the integ branch (because cherry-picking duplicates the commits)
Edit:
I don't want to perform a git rebase interactive and squash the commits from the development branch. It's the developer branch and they split the commits for a good reason from the developer point of view (maybe technically or logically it makes sense to create several commits).
From the client point of view, they don't care about the fact that a defect was corrected by several commits, they want a clean history on THEIR branch
possible duplicate of How can I merge two commits into one?
I don't approve rewriting history, how about using tags instead? Create a tag for very resolved issue, so they can checkout the corresponding tag.
By using tags, the client won't see any history at all. They want to see a clean history (ie a history with one commit per defect corrected) instead of the full, real, technical history
You confuse a clean history with something your customer wants to see. Clean history is what your developers create, your customer wants to see commits related to the same defect squashed.
If the customer needs to really have the history with squashed commits, you have to create it, e.g. when interactively rebasing. Most probably this is not the case and your customer needs just a different view of the branch.
Yes I agree. My original explanation wasn't accurate enough, but that is the point. How can we make both things live together? A clean history (from dev point of view) might not be what the customer wants. I suppose I could push the integ branch to a remote repo and rework it there, without touching the developers repo
Each developer has his own repo and pushes the changes into a central repo. The customer cloned a copy of the central repo and pulls changes. (If this is not the setup, correct me.) The customer can get only a piece of history that already exists in the central repo. If they don’t want to pull the original history, you have to duplicate the history your developers create to create the squashed one. If pulling the original history is OK but a different view is needed, just take care of the display. This is a fundamental dilemma and the customer must say, why they need to see the history at all.
So, why does the customer need the squashed history? What do they want to do with the history? Do they need just a changelog, or do they actively work with the history you provide?
They only need access to the history to generate a changelog with their own format /display. And they need access to each tagged commits to recompile it as well
You could show only the merges into integ with git log --merges.
Well yeah it could help. The problem with my initial approach is that the client has access to the integ branch and he could run your 'git log --merges' but he also could see anything he wants in the repo.
What if I push the integ branch into a remote repository? Will the commits in the development branch be seen as well in the remote repo?
If I'm reading it right you just need to include the --no-ff flag (no fast forward) when you merge from dev branch. Your fixes will be merged from the dev branch into the integ branch as a single commit containing all the changes.
There is quite a well known blog post, A successful Git branching model, from a few years back that advocates this method of working.
I remember reading this article as well. The problem is that whatever the branching model, when develop is merged into release branch, or when feature X is merged into develop branch (even with --no-ff) everyone that has access to the repo can see all the history.
I need a way to publish a 'filtered' view of my history to the customer's repository
You seem to be asking for something different than your original question. You ask "The customer wants a clean branch, ideally with a commit per corrected defect." and that is what merging with --no-ff will give you. Combined with the answer from @Graham you can also get the history you want. Of course, as you point out, if they have access to the same repo as you (or a clone) then yes, they will have access to the whole history. That is a strength of git so perhaps your customers just need educating?
Yes that's a nice summary. I will try to talk them into doing that
| common-pile/stackexchange_filtered |
Reverse a string of characters
I tried this code but I don't know how input the characters one per line and how to stop the input sequence with the character 0.
def reverse(string):
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
a = str(input())
print(reverse(a))
Can you be more clear on what you want here? I'm not sure what your actual problem is.
Is doing it recursively required or can you just use a oneliner?
Your code snippet works...What exactly is the problem?
I need an input one per line and the input sequence with this code dosen't stop with 0. I want the program stops when input value is 0.
In python you can usually reverse an iterable with [::-1].
It should work on strings as well, I guess. So: 'hello'[::-1] gives 'olleh'.
| common-pile/stackexchange_filtered |
DataSource and ByteArrayDataSource not compatiable?
I have the following:
InputStream imageStream = classLoader.getResourceAsStream("email/logo.png");
DataSource fds = new ByteArrayDataSource(IOUtils.toByteArray(imageStream), "image/png");
Which throws me an error of:
Error:(65, 30) java: incompatible types: javax.mail.util.ByteArrayDataSource cannot be converted to org.apache.poi.poifs.nio.DataSource
Error:(66, 44) java: no suitable constructor found for DataHandler(org.apache.poi.poifs.nio.DataSource)
constructor javax.activation.DataHandler.DataHandler(javax.activation.DataSource) is not applicable
(argument mismatch; org.apache.poi.poifs.nio.DataSource cannot be converted to javax.activation.DataSource)
constructor javax.activation.DataHandler.DataHandler(java.net.URL) is not applicable
(argument mismatch; org.apache.poi.poifs.nio.DataSource cannot be converted to java.net.URL)
What am I doing wrong here?
We don't know what you're trying to achieve, which makes it very hard to help you. Are you sure you actually want to be using org.apache.poi.poifs.nio.DataSource? Perhaps you really want javax.activation.DataSource instead?
@JonSkeet, thats was it!
Most probably you have wrong imports.
You are trying to cast javax.mail.util.ByteArrayDataSource to org.apache.poi.poifs.nio.DataSource. Check your imports.
| common-pile/stackexchange_filtered |
The question mark syntax to retrieve final property
I am trying to figure out if these two expressions are functionally equivalent:
user && user.first_name ? user.first_name : ''
and
user?.first_name || ''
and fairly certain they are, but not 100% sure. Are there any cases where the two expressions differ?
I believe so, unless I'm also missing something as well. I usually do something like user?.first_name ?? '' instead of using || though
ahh what is the double ?? vs || ?
Nullish coalescing operator. Returns right-side if left-side is null or undefined, otherwise returns left-side
@rakim || if you want to check for falsy values. ?? is for nullish (only null and undefined)
thanks, that's pretty good info
| common-pile/stackexchange_filtered |
Can mvn install packages globally (e.g. command line tools like nutch)?
Command line tools written in Ruby can be installed through RubyGems. Command line tools written in Node.js can be installed through NPM.
Does mvn offer similar functionality, or should I look to package systems like apt-get for installing Java command line tools?
gems and node modules are both installed through package managers. npm stands for node package manager.
Maven usually download any dependencies that are needed to build an artefact. I am not sure what is your question. But maybe this would help. Take a look at the maven-exec plugin, http://mojo.codehaus.org/exec-maven-plugin/usage.html
| common-pile/stackexchange_filtered |
JavaScript obj[property] throwing "property not defined " instead of giving undefined value
<html>
<head>
<script>
function Person(name, age) {
this.name = name;
this.age = age;
}
var person = new Person('Tom', 25);
document.write(person[name] + ' age is ' + person[age]);
</script>
</head>
<body>
</body>
</html>
I am new to javaScript , in the above code I am aware of the error that person['name'] and person['age'] is right syntax, but my confusion is
person[name] giving undefined value but
person[age] throwing error in browser console.
Please help me understanding this behaviour.
Thanks
In person[name] you're trying to use variable name as key (accessor). name is not initialized, so you actually tell the interpreter to give you the value of person["undefined"]. In this case you have to use the dot notation: person.name. See MDN
function Person(name, age) {
this.name = name;
this.age = age;
}
let person = new Person('Tom', 25);
try {
console.log(person[name]);
} catch(err) {
console.log(err.name, err.message);
}
try {
console.log(person[age]);
} catch(err) {
console.log(err.name, err.message);
}
console.log(person.name + ' age is ' + person.age);
// this would work:
const name = "name";
const age = "age";
console.log(person[name] + ' age is ' + person[age]);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Hi Kooiinc , here I am assigning the values through let person = new Person('Tom', 25); , but why it is is still throwing error? Why it is throwing error for name variable , but not for age when called individually like person[name] and person[age]
You are creating an instance of Person with properties name and age. Assigning the variables name and age is something diffferent. person[age] will not work if the variable age is not assigned, I assure you.
Yeah , You are right, but here person[name] giving undefined value but person[age] throwing error in browser console. person[name] must give an error , right? why that behaviour?
person[name] is not returning undefined. See adjusted code: both person[name] and person[age] will throw a ReferenceError (meaning something like: "This is the JS-interpreter: I don't know the variable name or age you are using here").
| common-pile/stackexchange_filtered |
How can data be extracted from the Matter Modeling Beta?
As far as I can see, Beta sites are not part of StackExchange data dumps https://archive.org/details/stackexchange .
According to https://meta.stackexchange.com/a/216245/884991, sites in public beta should appear in the data explorer https://data.stackexchange.com/, but I cannot find the Matter Modeling site there.
If this is the case, how can data (questions, answers and comments) be systematically extracted from the Matter Modeling site?
I think this question is relevant because of the following: assume software X (within the remit of this site) is interested in effectively moving its support forums / mailing lists to Matter Modeling. This seems a valid use of the site according to, e.g., Can we ask code specific questions?. It would be reasonable to expect that there is a tool that allows to extract all Q/A that have label X, in case that at a later time they decide to move to a different platform, or the Matter Modeling site does not make it out of beta and ends up closing. The lack of such a tool may prevent code X from officially making the move, since the possibility of losing the curated Q/As their developers and users would generate is unacceptable (let's bear in mind that most contributors to this site will participate in their professional capacity, and that many questions and answers will require a certain degree of elaboration, far from popular Stack Overflow oneliners).
If enough codes think along these lines, we could have a catch-22 situation: codes don't move their support activity to Matter Modeling because of the limitations it has as long as it is in Beta, and Matter Modeling does not leave Beta (or even closes) because the volume of contributions is too low without the questions and answers those codes would bring.
SEDE doesn't know about the site name change, so it's still listed under 'Materials Modeling':
Site renames cause some problems for SEDE and it needs to be updated manually, see e.g.
A site URL changed and now its icon in SEDE is broken
Why hasn't Music.SE's name changed on data.stackexchange?
Thank you, this is really useful. Would it be possible for you to elaborate on how the Data Explorer can extract the data, rather than display it for browsing?
SELECT * FROM Posts, SELECT * FROM Comments and download as CSV?
Thank you (the enhanced tracker protection of Firefox was preventing me from executing queries and viewing the download as CSV option).
| common-pile/stackexchange_filtered |
Is there any way to reliably send data from a UWP[C#] application to commonly used Microsoft applications such as Excel, Word, WordPad & Notepad?
I have developed a UWP[C#] application that uses the Windows 10 BLE API in order to receive data from a custom BLE device that my company has developed. Now, the requirement of the application is to send data to any active Word file, Excel sheet, Notepad or WordPad document on the local machine.
The data transfer from the UWP App to Excel/Word/Notepad/WordPad has to be automatically done as soon as the UWP app receives any data from the BLE device.
I read about Dynamic Data Exchange Server (DDE Server), however that technology seems very old and I am unable to find any documentation to for it to help me implement a DDE Server in a UWP app.
I am fairly new to Windows App Development and UWP App Development and would appreciate any help provided.
You could simulate key press events for example to type text in notepad.
@Emil I tried that already using InputInjector, however the order of data sent to the Injector and its output is not the same always. Data is received using asynchronous events by my app and i cannot send all the data at once to the InputInjector
A UWP application cannot do this directly for security reasons. A UWP application can include a "full trust" component in its package though, and that component can communicate with Office via the standard OLE Automation interfaces.
You can read more about building UWP and full-trust components here, and you can learn about accessing Office via PIAs here.
is it possible to develop applications using WPF or WinForms that can achieve this? I am aware of the security issues surrounding DDE, however I would be grateful if you could guide me towards an example of an app using some other Windows development framework to achieve this capability.
If you are using WPF then just call the. Office PIAs directly.
| common-pile/stackexchange_filtered |
Base64encode image string gets truncated
My string is truncated. I can't get the original string.
$img_file = product6.jpg';
$imgData = base64_encode(file_get_contents($img_file));
$src = 'data:image/jpg;base64,'.$imgData;
Can you help me?
You have missing single quotes
$img_file = 'product6.jpg';
| common-pile/stackexchange_filtered |
ArgumentError: invalid index: :Position of type Symbol
I'm trying to run a julia script, but I keep getting this error terminal error
I've tried adding a delim arguments like the example in the documentation, but that didn't work.
here is the code:
# Load information for skaters table
skaters = CSV.File(path_skaters, normalizenames=true, delim=",")
# Load information for goalies table
goalies = CSV.File(path_goalies, normalizenames=true, delim=",")
Please, provide a [mcve].
The error you reference with "terminal error" does not appear to originate from the lines of code you provided.
If you post six lines before and a few lines after line 873
in your file /Users/aus10/Fantasy-Hockey-IP-Code/code_for_Github.jl
We might see the problem.
(It is possible that deleting lines 872,873,874 and retyping them could help, too)
| common-pile/stackexchange_filtered |
Deleted files still accessible without www in url
I have deleted all files and all hidden files off my server, there is nothing but log files which cannot be deleted.
Ironically, files are accessible when nothing is there. Cache cleared, multiple browsers and computers/devices checked.
Files show when I exclude "www" from the URL
http://sarastringfellow.com/assets/photo/c.jpg
http://www.sarastringfellow.com/assets/photo/c.jpg
What does this mean?
I get a 404 on both URLs. I'd guess that your files had to have been loading from a server cache.
I get a 404 error on both links too.
me too, it must have finally refreshed. thanks guys.
server cache finally refreshed...
I actually see the image on both URLs!? (And it's the first time I have visited those URLs.) - A B&W photo of a lady lying on the beach looking at the camera.
@w3d Me as well. Is this a CDN behavior?
I can confirm that I also still see the photo on both URLs.
Ironically, nothing was deleted!!! All show still to this date???
Deleted? You don't delete files when you don't want people accessing domainname.com without the www.
You should use a .htaccess in the root of your wordpress install folder.
Make this file '.htaccess' with the following:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^sarastringfellow\.com$ [NC]
RewriteRule ^(.*)$ http://www.sarastringfellow.com/$1 [R=301,L]
This will make anyone attempting to view the site or images without the www redirect to the site which has www. before it.
Your hosting company may have cached them or copied them to a second server. I've come across this and had to put in a support ticket to the hosting company explaining i've deleted all files from the root folder and they still appear. The hosting company had to do the deletion from whatever server they had been copied to.
| common-pile/stackexchange_filtered |
Isa relationship query in sql
I have a disjoint relationship among my tables: Employee(empId PK, name), HourlyEmployee(empId PK FK, hourlySalary) empId is a reference to Employee.empId,
MonthlyEmployee(empId Pk FK, monthlySalary) empId is a reference to Employee.empId.
How can I create a query resulting AllEmployees(empId,name,hourlySalary,monthlySalary).
For all hourly employees monthlySalary will be null and for all monthly employess hourly salary will be null
Regards,
Tural
Show us your query...What have you tried till now?
Use outer joins to get all employees no matter if they exist in HourlyEmployee or MonthlyEmployee (or neither of them).
select e.empid, e.name, h.hourlysalary, m.monthlysalary
from employee e
left outer join hourlyemployee h on h.empid = e.empid
left outer join monthlyemployee m on m.empid = e.empid;
So, left outer join means keep everything in the left table (first table) and put null if there no appropriate value in the right table(second table). Is this understanding right?
select e.empid, e.name, h.hourlysalary, m.monthlysalary
from employee e
left outer join hourlyemployee h on h.empid = e.empid
left outer join monthlyemployee m on m.empid = e.empid
where (h.hourlysalary is null) or (m.monthlysalary is null);
| common-pile/stackexchange_filtered |
WinForms, DataGridView: Filtering XML data using attributes from multiple nodes
I have an XML data file of format similar to this:
<?xml version="1.0" standalone="yes"?>
<Root>
<FirstLevel Id="1">
<SecondLevel Id="1">
<ThirdLevel Id="1">
<DataElement Id="1" Data="hello" />
<DataElement Id="2" Data="world" />
</ThirdLevel>
<ThirdLevel Id="2">
<DataElement Id="1" Data="blablabla" />
<DataElement Id="2" Data="blablabla" />
</ThirdLevel>
</SecondLevel>
<SecondLevel Id="2">
<ThirdLevel Id="1">
<DataElement Id="1" Data="asdf" />
<DataElement Id="2" Data="qwerty" />
</ThirdLevel>
<ThirdLevel Id="2">
<DataElement Id="1" Data="gggggg" />
<DataElement Id="2" Data="dddddd" />
</ThirdLevel>
</SecondLevel>
</FirstLevel>
</Root>
And I'm trying to create a WinForms application using DataGridView that binds to this XML file. And displays the following in the grid, depending on selected navigation parameters. For example, if user selects navigation of FirstLevel, SecondLevel, and ThirdLevel with Id of 1 for all, only the following 2 rows should be displayed, with ability to write back any changes to XML:
Id Data
----------
1 hello
2 world
So far, I can only get all the rows (datatables) to display:
Id Data
---------
1 hello
2 world
1 blablabla
2 blablabla
1 asdf
2 qwerty
... etc
Using the following code:
DataSet dataSet = new DataSet();
dataSet.ReadXML("Data.xml");
DataView dataView = new DataView(dataSet.Tables["DataElement"]);
BindingSource source = new BindingSource();
source.DataSource = dataView;
dataGridView1.DataSource = source;
How can I filter my data so that only 2 rows are displayed, as described above? Thanks!
UPDATE:
Thanks Conrad for your help! However, I'm still trying to figure out how to "navigate" between these three levels, as adding a DataMember doesn't quite add the filtering. So to be able to, say, display data for criteria of FirstLevel Id = 2, SecondLevel Id = 1, ThirdLevel Id = 5 (or something), would I have to add all three to:
DataView dataView = new DataView(dataSet.Tables["FirstLevel_SecondLevel_ThirdLevel"]);
And then add RowFilter with something like:
dataView.RowFilter = "Id = '2'";
(but what about other levels here?)
And then modify DataMember as follows:
source.DataMember = "FirstLevel_SecondLevel_ThirdLevel_DataElement";
It doesn't quite work for me yet. Am I really just going against the flow here, and this is not how editing XML data should be approached in WinForms? Thanks!
UPDATE
There is no relation "FirstLevel_SecondLevel_ThirdLevel" which is why that doesn't work. You can find out which ones exist by inspecting the DataSet.Relations collection.
When you have multiple levels as you do you need to create a view for each level.
DataView firstDataView = new DataView(dataSet.Tables["FirstLevel"]);
firstDataView.RowFilter = "Id = 1";
DataView secondDataView = firstDataView[0].CreateChildView("FirstLevel_SecondLevel");
secondDataView.RowFilter = "Id = 2";
DataView thirdDataView = secondDataView[0].CreateChildView("SecondLevel_ThirdLevel");
DataView dataElement = thirdDataView[0].CreateChildView("ThirdLevel_DataElement");
BindingSource source = new BindingSource();
source.DataSource = dataElement;
dataGridView1.DataSource = source;
Still having trouble doing "navigation" though. (see update).
You can filter the data in where clause passing the actual element name and fetching the exact data after filtering it.
var data= (from d in XDocument.Load(_pathXML).Descendants("ThirdLevel") where d.Attribute("Id").Value == 1 select d;
Now you can display the data
if (_appNme.Any())
{
foreach (var item in data)
{
MessageBox.Show(_appNme.Elements("Id").Single().Value);
MessageBox.Show(_appNme.Elements("Data").Single().Value);
}
}
Try XPath and Linq to XML.
Assuming the XML is in a string aclled XML:
var doc = XDocument.Parse(xml);
var firstLevel = "1";
var secondLevel = "1";
var thirdLevel = "1";
var query = string.Format("/Root/FirstLevel[@Id={0}]/SecondLevel[@Id={1}]/ThirdLevel[@Id={2}]/DataElement", firstLevel, secondLevel, thirdLevel);
var results = (from i in doc.XPathSelectElements(query)
select new { Id = i.Attribute("Id").Value, Data = i.Attribute("Data").Value }).ToList();
foreach (var item in results)
{
Console.WriteLine("{0} - {1}", item.Id, item.Data);
}
Thanks! However, it seems that two-way data binding is hard with Linq to XML. How would I two-way databind a DataGridView with this, so that edits are saved back to XML file? I asked a more generic question about this here: http://stackoverflow.com/questions/4446296/best-practices-for-crud-operations-on-xml-data-in-winforms
| common-pile/stackexchange_filtered |
Official documentation for JwtBearer middleware/configuration via appsettings.json?
Starting with NET 7, one can configure JWT validation values in appsettings.json, e.g. as mentioned in this blog post (section Simplified configuration for the JwtBearer middleware):
"Authentication": {
"Schemes": {
"Bearer": {
"Authority": "https://{DOMAIN}",
"ValidAudiences": [ "{AUDIENCE}" ],
"ValidIssuer": "{DOMAIN}"
}
}
}
I however was unable to find official documentation for this on the Microsoft website. Anyone knows where to find the official documentation on this? How do I know which other properties I could configure here?
No they don't have an official documentation for this. Right now they are using internal JwtBearerConfigureOptions to get section by schema name (in your case "Bearer") GitHub,and populate the JwtBearerOptions based on nameof(). They just added it to JwtBearerExtensions in line 77.
PR when it was added.
Issue create on github - still open.
Sample on GitHub.
You can create a whole appsettings.json section based on their code but I wouldn't be much confident in implementing this right now.
thanks for those great details. I also share your rating and decided to do it via code and not via appsettings.
thanks so much for the detail links, etc. -- the "best" docs imho
These properties work in .NET 8.0. The documentation would be nice.
{
"Authentication": {
"Schemes": {
"Bearer": {
"ValidateAudience": true,
"ValidAudience": "AudienceX",
"ValidAudiences": [
"AudienceX"
],
"ValidateIssuer": true,
"ValidIssuer": "IssuerY",
"ValidIssuers": [
"IssuerY"
],
"SigningKeys": [
{
"Issuer": "IssuerY",
"Value": "<base64 encoded string>"
}
]
}
}
}
}
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.