my load image function is not working has it got something to do with my try? - try-catch

i am trying to create a function to load my images but every time i run it it returns "cannot load image"
def load_image(file_name, colorkey = None):
full_name = os.path.join('data', file_name)
try:
image = pygame.image.load(full_name)
except pygame.error, message:
print 'Cannot load image:', full_name
raise SystemExit, message
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image,image.get()

If you are on windows you will need to do something like this:
os.path.join('c:%s' % os.sep, 'data')

Related

Access JSON Array without array name

I have a JSON object:
{
"login_name":"hello#gmail.com",
"login_pass":"abc123",
"created_on":"2021-01-17 19:20:07",
"user_id":"1",
"active":"1"
}
I don't know how to access it because it doesn't have a name.
This is using Volley:
val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
{ response ->
val obj = JSONObject(response.toString()) // this works and outputs the JSON object
val test: JSONObject = obj.getJSONObject("login_name") // this doesn't work
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
},
{ error ->
Toast.makeText(this#Login, "Error!", Toast.LENGTH_LONG).show()
}
)
I also tried converting the Json object to an array but that didn't work either...
Looked at:
Get JSONArray without array name, How can i write Android Json parsing without array name
EDIT:
val obj = JSONObject(response)
That didn't work for me because:
None of the following functions can be called with the arguments supplied.
(String!) defined in org.json.JSONObject
((MutableMap<Any?, Any?>..Map<*, *>?)) defined in org.json.JSONObject
(JSONTokener!) defined in org.json.JSONObject
But after 2 days of trying, this worked... Didn't think I could just do that
val test = response.getString("login_name")
response is indeed a jsonObject, you could use it without know its name:
String login_name= response.getString("login_name");
You are all most doing it right. Ass i see you convert the object to a string, and thats why you cant access the data afterwards.
val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
{ response ->
val obj = JSONObject(response) // this works and outputs the JSON object
val test: JSONObject = obj.getJSONObject("login_name") // this doesn't work
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
},
{ error ->
Toast.makeText(this#Login, "Error!", Toast.LENGTH_LONG).show()
}
)
Try this, without the toString() function on response.

"No module named 'razorpay'" : Django restframework

def provider_factory(code):
......
payment_settings = StoreSetting.objects.filter(token='payment').first()
if code in payment_settings.data['payment']:
config = payment_settings.data['payment']
except:
pass
ProviderClass = get_class('sales.payment.', snake2camel(code) + 'Provider')
This is my project structure
code = 'razorpay',
Here, through this line "ProviderClass = get_class('sales.payment.', snake2camel(code) + 'Provider')", I am trying to get providerclass, but it cause "No module named 'razorpay"
Give me a solution to fix this
Edit,
def get_class(module_name, class_name):
# load the module, will raise ImportError if module cannot be loaded
m = importlib.import_module(module_name)
# get the class, will raise AttributeError if class cannot be found
c = getattr(m, class_name)
return c

Inject user index into body file in Gatling scenario

I want to use ELFileBody and put a variable in a txt file.
This file contains a soap request.
The request (scenario) is executed only one time but as many times as users.
I want to put into file variable, the user index (position in execution).
Something like this :
.set("myVar", userIndex) //myVar is the variable declared in the body file ( ${myVar} )
Here is my code for now :
val users = 1500
val baseUrl = "http://127.0.0.1:7001"
val httpProtocol = http
.baseURL(baseUrl)
.inferHtmlResources()
.acceptEncodingHeader("gzip,deflate")
.contentTypeHeader("text/xml;charset=UTF-8")
.userAgentHeader("Apache-HttpClient/4.1.1 (java 1.5)")
val headers_0 = Map("SOAPAction" -> """""""")
val uri1 = "http://127.0.0.1:7001/myProject-ws/myProjectWebService"
val scn = scenario("Scenario1Name")
.exec(http("scn.Scenario1Name")
.post("/myProject-ws/myProjectWebService")
.headers(headers_0)
.body(RawFileBody("File_0000_request.txt")))
setUp(scn.inject(atOnceUsers(users))).protocols(httpProtocol)
How can I inject the user index into myVar variable in the request body ?
finally, i used a function that return a dynamic reference (id) and I call it from my scenario.
def getDynamicId(): String = {
val formatter = new SimpleDateFormat("yyyyMMddHHmmss.SSS")
val result = "PM".concat(formatter.format(Calendar.getInstance().getTime()))
result
}
//[...]
scenario("ScenarioName")
.exec(session => session.set("myVar", getDynamicId))
// [...]
.body(ElFileBody("BodyFile_0000_request.txt")))
And in the body file, I have the variable ${myVar}
You need read file like e.g.
val customSeparatorFeeder = separatedValues(pathToFile, separator).queue circular
after scenario("Scenario1Name") you need to add .feed(customSeparatorFeeder)
you can read more about it here https://gatling.io/docs/2.3/session/feeder/

Gmail API .NET: Get full message

How do I get the full message and not just the metadata using gmail api?
I have a service account and I am able to retrieve a message but only in the metadata, raw and minimal formats. How do I retrieve the full message in the full format? The following code works fine
var request = service.Users.Messages.Get(userId, messageId);
request.Format = UsersResource.MessagesResource.GetRequest.FormatEnum.Metadata;
Message message = request.Execute();
However, when I omit the format (hence I use the default format which is FULL) or I change the format to UsersResource.MessagesResource.GetRequest.FormatEnum.Full
I get the error: Metadata scope doesn't allow format FULL
I have included the following scopes:
https://www.googleapis.com/auth/gmail.readonly,
https://www.googleapis.com/auth/gmail.metadata,
https://www.googleapis.com/auth/gmail.modify,
https://mail.google.com/
How do I get the full message?
I had to remove the scope for the metadata to be able to get the full message format.
The user from the SO post have the same error.
Try this out first.
Go to https://security.google.com/settings/security/permissions
Choose the app you are working with.
Click Remove > OK
Next time, just request exactly which permissions you need.
Another thing, try to use gmailMessage.payload.parts[0].body.dataand to decode it into readable text, do the following from the SO post:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
System.out.println(StringUtils.newStringUtf8(Base64.decodeBase64(gmailMessage.payload.parts[0].body.data)));
You can also check this for further reference.
try something like this
public String getMessage(string user_id, string message_id)
{
Message temp =service.Users.Messages.Get(user_id,message_id).Execute();
var parts = temp.Payload.Parts;
string s = "";
foreach (var part in parts) {
byte[] data = FromBase64ForUrlString(part.Body.Data);
s += Encoding.UTF8.GetString(data);
}
return s
}
public static byte[] FromBase64ForUrlString(string base64ForUrlInput)
{
int padChars = (base64ForUrlInput.Length % 4) == 0 ? 0 : (4 - (base64ForUrlInput.Length % 4));
StringBuilder result = new StringBuilder(base64ForUrlInput, base64ForUrlInput.Length + padChars);
result.Append(String.Empty.PadRight(padChars, '='));
result.Replace('-', '+');
result.Replace('_', '/');
return Convert.FromBase64String(result.ToString());
}

One Minute Man, python 3

Well, i have this code that is supposed to check if the html is changed by first checking and downloading the html into a string, then checking again every two seconds and printing html if it has changed. The problem is that the script says it has changed all the time, and keeps giving me the same html code back.
#!/usr/bin/env python
import time
start = time.time()
from urllib.request import urlopen
data = str
html = str
def firstcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
html = data
def secondcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
if not html == data:
print(data)
while True:
secondcheck()
time.sleep(2)
print ("it took", time.time() - start, "seconds.")
Thanks in advance;)
You need to tell the interpreter to set the global html variable in the firstcheck() function.
def firstcheck():
url = 'http://www.hacker.org/challenge/misc/minuteman.php'
hogniergay = urlopen(url)
data = hogniergay.read()
hogniergay.close()
global html
html = data
Right now the secondcheck() function is checking against the html value "str".
It doesn't look like you are calling firstcheck at all, so html is always going to be str. You could make it work by replacing the block inside the while True with:
while True:
firstcheck()
secondcheck()
but it would be cleaner to have a script that looked something like this
while True:
hogniergay = urlopen(url)
result = hogniergay.read()
hogniergay.close()
if result != current:
print (result)
current = result
time.sleep(2)

Resources