#I need to print if i found problem='FRAUDED BILL' or another phrase inside of those dict and print your respective key, (ex: EP1_2) for FRAUDED BILL
dict_ep = {'EP1_2':['FRAUDED BILL','IMPROPER BILLING - FRAUDED CARD (CARDS)','EMBEZZLEMENT','FRAUD'],
'EP1_4':['2nd COPY OF CONTRACT (CONSIGNEE)','ACCIDENT WITH DISPOSED VEHICLE'],
'EP1_6':['BANK STRIKE'],
'EP1_8':['ACCESS TO BALANCE AND CARD LIMIT','PAYMENT AGREEMENT']}
problem = ('frauded bill').upper()
for i in dict_ep:
if problem == dict_ep.keys():
print('EP found')
else:
print('EP no exist, try again!')
RESULTS:
EP no exist, try again!
EP no exist, try again!
EP no exist, try again!
EP no exist, try again!
You can use any() to test if the string is found in list:
dict_ep = {
"EP1_2": [
"FRAUDED BILL",
"IMPROPER BILLING - FRAUDED CARD (CARDS)",
"EMBEZZLEMENT",
"FRAUD",
],
"EP1_4": [
"2nd COPY OF CONTRACT (CONSIGNEE)",
"ACCIDENT WITH DISPOSED VEHICLE",
],
"EP1_6": ["BANK STRIKE"],
"EP1_8": ["ACCESS TO BALANCE AND CARD LIMIT", "PAYMENT AGREEMENT"],
}
problem = "frauded bill".upper()
for key, lst in dict_ep.items():
if any(problem in v for v in lst):
print("EP Found:", key)
else:
print("EP NOT Found:", key)
Prints:
EP Found: EP1_2
EP NOT Found: EP1_4
EP NOT Found: EP1_6
EP NOT Found: EP1_8
Related
I have this code running fine but then it shows too much information and I only want the last line in the code.
Code here:
import scala.io.Source
object CovidWorld {
def main(args: Array[String]): Unit = {
val filename = Source.fromFile("OOPAssignment3.txt")
try{
for (line <- filename.getLines.toList) {
if (line.contains("Malaysia") && line.split(",").apply(7).nonEmpty) {
val allDeathString: String = line.split(",").apply(7)
print("\n\n Malaysia latest total amount of death: " + allDeathString)
}
}
}
finally{
filename.close
//print("\nThe file is now closed")
}
}
}
This is the result I obtain from it.result of the running code
I just want the last line of the information instead of the entire thing. Anyone can figure out how? Thanks in advance for the help :)
You can replace the inside of your try block with:
filename
.getLines
.filter(line => line.contains("Malaysia") && line.split(",").apply(7).nonEmpty)
.toList
.takeRight(1)
.foreach(line => {
val allDeathString: String = line.split(",").apply(7)
print("\n\n Malaysia latest total amount of death: " + allDeathString)
})
The key part for your purposes is takeRight which selects n elements from the end of the list. When n == 1 you're taking only the last match which is what you want here.
I am an error ReferenceError: weakly-referenced object no longer exists in my code, I have tried to debug it that I don't know why am I getting this.
I am using mongodb and python 3.6.10
here is my code, please help
a = 't1'
b = ['v1', 'v2', 'v3']
services = dict()
for value in b:
record = MyModel.objects.filter(myid=id, a=a, value=value).first()
keys = record['services'].keys()
for key in keys:
key_value = record['services'][key]
if key in services:
services[key].extend(key_value) # Getiing error here in this line
else:
services.update({key: key_value})
print(services)
MyModel looks like
{
"myid" : "1",
"a" : "t1",
"b" : "v1",
"services" : {
"service_1" : [
{
"serviceid" : "1012",
"service_type" : "service_1"
}
]
}
{
"myid" : "1",
"a" : "t1",
"b" : "v2",
"services" : {
"service_2" : [
{
"serviceid" : "1013",
"service_type" : "service_2"
}
]
}
code works fine if there is only one value in b, but if code iterate the second time and tries to perform services[key].extend(key_value), code generates the error.
I don't think it is related to this code phrase. It can be caused by your db connector. You may try to close the connection without closing the cursor.
It generally happens when you use a destructor __del__ for a weak referenced object. When your destructor runs before the garbage collector, it throws that kind of exception. You can read more about weakref here.
after a lot of try and error, I have found that if I put values in empty list then code works fine so I have updated my code. I am still don't know why the above code is giving me an error, this is just an alternative to the above code.
Hope this will help someone facing the same problem.
a = 't1'
b = ['v1', 'v2', 'v3']
services = dict()
for value in b:
record = MyModel.objects.filter(myid=id, a=a, value=value).first()
keys = record['services'].keys()
for key in keys:
key_value = record['services'][key]
if not key in services:
services[key] = list()
services[key].extend(key_value)
print(services)
The backend of my application makes a request to:
https://graph.facebook.com/v2.8/me?access_token=<firebase-access-token>&fields=id,name,first_name,birthday,email,picture.type(large){url}&format=json&method=get&pretty=0&suppress_http_code=1
I get a successful (200) response with the JSON data I expect and picture field as such:
"picture": {
"data": {
"url": "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=<asid>&height=200&width=200&ext=<ext>&hash=<hash>"
}
}
(where in place of <asid> and <ext>, there are numbers and <hash> is some alphanumeric string).
However, when I make a GET request to the platform-lookaside URL above, I get a 404 error.
It's been happening every time since my very first graph.facebook request for the same user. The very first one returned a platform-lookaside URL which pointed to a proper image (not sure if this is simply coincidence).
Is there something I'm doing wrong or is this likely a bug with the Facebook API?
FB currently seems to have issues with some CDNs and therefore your issue might be only temporary. You should also see missing/broken images on some places on fb dot com. Worst time to debug your issue :)
Try this code it worked for me
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Insert your code here
try {
String name = object.getString("name");
String email = object.getString("email");
String last_name = object.getString("last_name");
String first_name = object.getString("first_name");
String middle_name = object.getString("middle_name");
String link = object.getString("link");
String picture = object.getJSONObject("picture").getJSONObject("data").getString("url");
Log.e("Email = ", " " + email);
Log.e("facebookLink = ", " " + link);
Log.e("name = ", " " + name);
Log.e("last_name = ", " " + last_name);
Log.e("first_name = ", " " + first_name);
Log.e("middle_name = ", " " + middle_name);
Log.e("pictureLink = ", " " + picture);
} catch (JSONException e) {
e.printStackTrace();
Log.e("Sttaaaaaaaaaaaaaaaaa", e.getMessage());
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,link,last_name,first_name,middle_name,picture");
request.setParameters(parameters);
request.executeAsync();
I am facing a very strange behavior in using the API to create the customer profiles. Although i have read the documentation thoroughly but did not succeed.
I am creating a customer profile at first when no profile is available along with a payment profile but next time when a user return and add the payment profile ( as the customer profile already exist) i am using only createCustomerPaymentProfile. The thing is, in first step i am not including $billto->setZip("44628"); and it goes well. But when i make only payment Profile it demands me to include the zip code too other wise it gives error
"There is one or more missing or invalid required fields."
I am using the exact same code which is in the php section of the documentation just a change in text/parameters.
create customer profile
create customer payment profile
For making the customer profile :
private function createCustomerProfile($data)
{
/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName("auth");
$merchantAuthentication->setTransactionKey("transkey");
// Set the transaction's refId
$refId = 'ref' . time();
$paymentProfile=$this->newPaymentProfile($data);
// Create a new CustomerProfileType and add the payment profile object
$customerProfile = new AnetAPI\CustomerProfileType();
$customerProfile->setDescription("Customer 2 Test PHP");
$customerProfile->setMerchantCustomerId($name. time());
$customerProfile->setEmail($email);
$customerProfile->setpaymentProfiles($paymentProfile);
// Assemble the complete transaction request
$request = new AnetAPI\CreateCustomerProfileRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setRefId($refId);
$request->setProfile($customerProfile);
// Create the controller and get the response
$controller = new AnetController\CreateCustomerProfileController($request);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
$paymentProfiles = $response->getCustomerPaymentProfileIdList();
//Insert into database for the profile and payment profile update
} else {
echo "ERROR : Invalid response\n";
$errorMessages = $response->getMessages()->getMessage();
echo "Response : " . $errorMessages[0]->getCode() . " " .$errorMessages[0]->getText() . "\n";
}
return $response;
For making the customer payment profile
private function createCustomerPaymentProfile($data){
/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName("name");
$merchantAuthentication->setTransactionKey("transkey");
// Set the transaction's refId
$refId = 'ref' . time();
$paymentProfile=$this->newPaymentProfile($data);
// Assemble the complete transaction request
$paymentprofilerequest = new AnetAPI\CreateCustomerPaymentProfileRequest();
$paymentprofilerequest->setMerchantAuthentication($merchantAuthentication);
// Add an existing profile id to the request
$paymentprofilerequest->setCustomerProfileId($data['profile_id']);
$paymentprofilerequest->setPaymentProfile($paymentProfile[0]);
$paymentprofilerequest->setValidationMode("liveMode");
// Create the controller and get the response
$controller = new AnetController\CreateCustomerPaymentProfileController($paymentprofilerequest);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") ) {
echo "Create Customer Payment Profile SUCCESS: " . $response->getCustomerPaymentProfileId() . "\n";
//Insert into database for the profile and payment profile update
} else {
echo "Create Customer Payment Profile: ERROR Invalid response\n";
$errorMessages = $response->getMessages()->getMessage();
echo "Response : " . $errorMessages[0]->getCode() . " " .$errorMessages[0]->getText() . "\n";
}
return $response;
}
for the re-usability purpose i have make a common make payment profile which return the payment profile array
private function newPaymentProfile($data){
// Set credit card information for payment profile
$creditCard = new AnetAPI\CreditCardType();
$creditCard->setCardNumber($data['account_number']);
$creditCard->setExpirationDate($data['date']);
$creditCard->setCardCode($data['securiy_no']);
$paymentCreditCard = new AnetAPI\PaymentType();
$paymentCreditCard->setCreditCard($creditCard);
// Create the Bill To info for new payment type
$billTo = new AnetAPI\CustomerAddressType();
$billTo->setFirstName($data['holder_name']);
$billTo->setAddress($data['billing_address']);
$billTo->setPhoneNumber($data['phone']);
$billTo->setfaxNumber($data['fax']);
// Create a new CustomerPaymentProfile object
$paymentProfile = new AnetAPI\CustomerPaymentProfileType();
$paymentProfile->setCustomerType('individual');
$paymentProfile->setBillTo($billTo);
$paymentProfile->setPayment($paymentCreditCard);
$paymentProfiles[]=$paymentProfile;
return $paymentProfiles;
}
The following snippet is able to return all the cars in my database as a JSON when I call the URL 1 and I can display them in the browser. However, when I use the URL 2, I get nothing and the browser displays the 404 error. But it is weird that the error does not show the message "Car not found". It shows "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.".
I tested the RegexUtil class and it does return the Long as 1 when I call the URL 2 and Long equal to null when I call the URL 1.
What am I doing wrong?
1) http://localhost:8080/Cars/cars
2) http://localhost:8080/Cars/cars/1
String requestUri = request.getRequestURI();
Long id = RegexUtil.matchId(requestUri);
if (id != null) {
//this if test is never executed even when id != null
// id was informed
Car car = carService.getCar(id);
if (car != null) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(car);
ServletUtil.writeJSON(response, json);
} else {
response.sendError(404, "Car not found");
}
} else {
//this else executes fine
// Show car list
List<Car> cars = carService.getCars();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(cars);
ServletUtil.writeJSON(response, json);
}
Issue resolved.
The servlet annotation was incorrect.
The asterisk was missing
#WebServlet(urlPatterns = { "/cars/*" },