Load Country Flag From Geonames API using JSONP technique - json

This Request.JSON http://mootools.net/demos/?demo=Request.JSON using JSON data in a way like this,
var data = {"previews":[
{"Countrycode":"us", "src":"us.jpg", "description":"desc will be here"},
{"Countrycode":"uk", "src":"uk.jpg", "description":"desc will be here"},
]};
In the above method we use Countrycode & images by writing name of each image our self.
I'm looking for a method to use Geonames via http://api.geonames.org/export/geonamesData.js?username=orakzai to retrieve Countrycode and CountryFlags via http://www.geonames.org/flags/x/xx.gif where xx is 2 letter ISO country code

The flags are returned as GIF files instead of any sort of JSON. You would just use
<img id='myImage' src="http://www.geonames.org/flags/x/??.gif" />
But fill in the ?? with the country code that geonames uses.
You can put the tag in your page somewhere and use some javascript to change the URL to the one you have computed or you can figure the URL on your server and insert it as the HTML page is created.
If you want to do it in javascript, for example, in jQuery you would have something like this to change the URL on an already loaded image tag with id='myImage'
$("#myImage").attr('src', "http://www.geonames.org/flags/x/" + countryCode + ".gif")

Similar service, like geonames.org:
var country_code = 'uk',
img_uri = 'https://flagpedia.net/data/flags/normal/' + country_code + '.png';

Related

Dynamic text based on URL parameters

I'm building a website on Instapage and I have a form on the homepage with two fields: State & Practice Area. When a visitor submits his selections, he is redirected to another page with "area" and "state" as URL parameters.
All good so far, but now I want to write a paragraph on the page, let's just say "[practice area] in [state]", where the brackets would contain the corresponding information from the URL parameters. I'm guessing it would be a simple HTML code that replaces a parameter's name within the paragraph I'm writing with its description from the URL.
I also want to have a default text if there are no parameters in the URL.
Just to be clear, I'm trying to do all of this within the same paragraph, so most of the paragraph stays the same, and just a couple of words within it would change based on the parameters (or have a default value if there are no parameters).
Any help would be appreciated. Thank you!
If your URL is like this:
[protocol]://[hostname]/[state]/[practice area]
You can get the state and practice like this:
let state = window.location.pathname.split('/')[1] || 'your default value for state'
let practiceArea = window.location.pathname.split('/')[2] || 'your default value for practice area'
p = document.getElementById('text')
p.innerText = `${state} in ${practiceArea}`
<p id='text'></p>
Update
If your URL is like this:
"[protocol]://[hostname]/?state=statevalue&practiceArea=practiceValue"
You can get the state and practice like this:
var urlParams = new URLSearchParams(window.location.search)
let state = urlParams.get('state') || 'your default value for state'
let practiceArea = urlParams.get('practiceArea') || 'your default value for practice area'
let p = document.getElementById('text')
p.innerText = `${state} in ${practiceArea}`
<p id='text'></p>

.text is scrambled with numbers and special keys in BeautifuSoup

Hello I am currently using Python 3, BeautifulSoup 4 and, requests to scrape some information from supremenewyork.com UK. I have implemented a proxy script (that I know works) into the script. The only problem is that this website does not like programs to scrape this information automatically and so they have decided to scramble this script which I think makes it unusable as text.
My question: is there a way to get the text without using the .text thing and/or is there a way to get the script to read the text? and when it sees a special character like # to skip over it or to read the text when it sees & skip until it sees ;?
because basically how this website scrambles the text is by doing this. Here is an example, the text shown when you inspect element is:
supremetshirt
Which is supposed to say "supreme t-shirt" and so on (you get the idea, they don't use letters to scramble only numbers and special keys)
this  is kind of highlighted in a box automatically when you inspect the element using a VPN on the UK supreme website, and is different than the text (which isn't highlighted at all). And whenever I run my script without the proxy code onto my local supremenewyork.com, It works fine (but only because of the code, not being scrambled on my local website and I want to pull this info from the UK website) any ideas? here is my code:
import requests
from bs4 import BeautifulSoup
categorys = ['jackets', 'shirts', 'tops_sweaters', 'sweatshirts', 'pants', 'shorts', 't-shirts', 'hats', 'bags', 'accessories', 'shoes', 'skate']
catNumb = 0
#use new proxy every so often for testing (will add something that pulls proxys and usses them for you.
UK_Proxy1 = '51.143.153.167:80'
proxies = {
'http': 'http://' + UK_Proxy1 + '',
'https': 'https://' + UK_Proxy1 + '',
}
for cat in categorys:
catStr = str(categorys[catNumb])
cUrl = 'http://www.supremenewyork.com/shop/all/' + catStr
proxy_script = requests.get(cUrl, proxies=proxies).text
bSoup = BeautifulSoup(proxy_script, 'lxml')
print('\n*******************"'+ catStr.upper() + '"*******************\n')
catNumb += 1
for item in bSoup.find_all('div', class_='inner-article'):
url = item.a['href']
alt = item.find('img')['alt']
req = requests.get('http://www.supremenewyork.com' + url)
item_soup = BeautifulSoup(req.text, 'lxml')
name = item_soup.find('h1', itemprop='name').text
#name = item_soup.find('h1', itemprop='name')
style = item_soup.find('p', itemprop='model').text
#style = item_soup.find('p', itemprop='model')
print (alt +(' --- ')+ name +(' --- ')+ style)
#print(alt)
#print(str(name))
#print (str(style))
When I run this script I get this error:
name = item_soup.find('h1', itemprop='name').text
AttributeError: 'NoneType' object has no attribute 'text'
And so what I did was I un-hash-tagged the stuff that is hash-tagged above, and hash-tagged the other stuff that is similar but different, and I get some kind of str error and so I tried the print(str(name)). I am able to print the alt fine (with every script, the alt is not scrambled), but when it comes to printing the name and style all it prints is a None under every alt code is printed.
I have been working on fixing this for days and have come up with no solutions. can anyone help me solve this?
I have solved my own answer using this solution:
thetable = soup5.find('div', class_='turbolink_scroller')
items = thetable.find_all('div', class_='inner-article')
for item in items:
alt = item.find('img')['alt']
name = item.h1.a.text
color = item.p.a.text
print(alt,' --- ', name, ' --- ',color)

How can I display a TemporaryUploadedFile from Django in HTML as an image?

In Django, I have programmed a form in which you can upload one image. After uploading the image, the image is passed to another method with the type TemporaryUploadedFile, after executing the method it is given to the HTML page.
What I would like to do is display that TemporaryUploadedFile as an image in HTML. It sounds quite simple to me but I could not find the answer on StackOverflow or on Google to the question: How to display a TemporaryUploadedFile in HTML without having to save it first, hence my question.
All help is appreciated.
Edit 1:
To give some more information about the code and the variables while debugging.
input_image = next(iter(request.FILES.values()))
output_b64 = (input_image.content_type, str(base64.b64encode(input_image.read()), 'utf8'))
Well, you can encode the image to base64 and use a data url as the value for src.
A base64 data url looks like this:
<img src="data:image/png;base64,SGLAFdsfsafsf098sflf">
\_______/ \__________________/
| |
File type base64 encoded data
Read the Mozilla docs for more on data urls.
Here's some relevant code:
import base64
def my_view(request):
# assuming `image` is a <TemporaryUploadedFile object>
image_b64 = base64.b64encode(image.read())
image_b64 = image_b64.decode('utf8') # convert bytes to string
image_type = image.content_type # png or jpeg or something else
return render('template', {'image_b64': image_b64, 'image_type': image_type})
Then in your template:
<img src="data:{{ image_type }};base64,{{ image_b64 }}">
I want to thank xyres for pushing me in the right direction. As you can see, I used some parts of his solution in the code below:
# As input I take one image from the form.
temp_uploaded_file = next(iter(request.FILES.values()))
# The TemporaryUploadedFile is converted to a Pillow Image
input_image = pil_image.open(temp_uploaded_file)
# The input image does not have a name so I set it afterwards. (This step, of course, is not mandatory)
input_image.filename = temp_uploaded_file.name
# The image is saved to an InMemoryFile
output = BytesIO()
input_image.save(output, format=img.format)
# Then the InMemoryFile is encoded
img_data = str(base64.b64encode(output.getvalue()), 'utf8')
output_b64 = ('image/' + img.format, img_data)
# Pass it to the template
return render(request, 'visualsearch/similarity_output.html', {
"output_image": output_b64
})
In the template:
<img id="output_image" src="data:{{ image.0 }};base64,{{ image.1 }}">
The current solution works but I don't think it is perfect because I expect that it can be done with less code and faster, so if you know how this can be done better you are welcome to post your answer here.

Set view to orthographic

How to take current view and set the view to orthographic?
I tried using viewer.getCamera() to get parameters how the view is currently set and then setting it with viewer.applyCamera().
var camera = viewer.getCamera();
console.log('Camera: ' + JSON.stringify(camera));
Which returns:
Camera: {
"metadata": {"version":4.3,"type":"Object","generator":"ObjectExporter"},
"object":{"uuid":"78D2EA86-853B-473F-9E0E-E3F0C8874E40",
"type":"Camera",
"matrix":[1,0,0,0,0,1,0.00009999999747378752,0,0,-0.00009999999747378752,1,0,114010.796875,88329.0078125,135503.609375,1],
"children":[
{"uuid":"53C7FA49-B00C-4616-9E7A-CCB94A661A45",
"type":"DirectionalLight",
"color":8355711,"intensity":0,
"matrix":1,0,0,0,0,1,0,0,0,0,1,0,-0.5,0.20000000298023224,0.05999999865889549,1]},
{
"uuid":"7D5EC244-7268-4190-8480-4BD1DD56F8CB",
"type":"Object3D","matrix":[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]
}]}}
Then I tried setting, with the "matrix" array as params, but the view jumps.
viewer.setViewFromArray(params);
I followed the format of an array with the data from current camera and applied them by viewer.setViewFromArray. I kept all other parameters, but only set the last param to 1 (ortho).It looks working well at my side.
viewerApp.myCurrentViewer.setViewFromArray([
viewerApp.myCurrentViewer.getCamera().position.x,
viewerApp.myCurrentViewer.getCamera().position.y,
viewerApp.myCurrentViewer.getCamera().position.z,
viewerApp.myCurrentViewer.getCamera().target.x,
viewerApp.myCurrentViewer.getCamera().target.y,
viewerApp.myCurrentViewer.getCamera().target.z,
viewerApp.myCurrentViewer.getCamera().up.x,
viewerApp.myCurrentViewer.getCamera().up.y,
viewerApp.myCurrentViewer.getCamera().up.z,
viewerApp.myCurrentViewer.getCamera().aspect,
viewerApp.myCurrentViewer.getCamera().fov,
1,
1
]);
you can also check the source Viewer3D.js to get the workflow how setViewFromArray works.
Viewer3D.prototype.setViewFromArray = function(params, name){....}
IF you simply want to switch the view between perspective and orthographic, you can use the direct API:
Viewer.navigation.toOrthographic()
Viewer.navigation.toPerspective()

modifying google-maps default directions title

I'm using the Google maps V3 JavaScript API and I'm currently using the default directions formatting (because this is the easiest way to get the map pins and step icons integrated into the listing). I'm setting the text that is displayed for each 'address' for example:
var loc = 'The Old Ballpark Bar and Lounge';
var addr = '1234 Main st. Chicago, IL.';
...
route.legs[0].start_address = loc + ' - ' + addr;
I'd like to enhance the readability of this start_address in 2 ways:
I'd like to put the addr part on a separate line.
I'd like to highlight the loc part in bold
Since the text for this start_address is placed in a td (class="adp-text") within a table (class="adp-placemark"); I thought that putting a <br/> between the loc and addr would get me the newline I wanted; but it doesn't work, the api translates this into <br/>. Similarly, trying to put <b> before the loc part, gets translated into & lt;b& gt;.
I've tried escaping the markup code with quotes and backslashes, etc.; but can't find a way to do what I want. Is there any way to insert such mark up so as to get it past the Google code translators? Are there some lower-level CSS tags that might be used to accomplish this?
You must modify the elements after they have been inserted into the DOM.
assign the desired markup:
route.legs[0].start_address = '<div style="font-weight:bold">'+ loc + '</div>' + addr;
hide the panel(to avoid undesired effects)
//directionsDisplay is the google.maps.DirectionsRenderer-instance
directionsDisplay.getPanel().style.visibility='hidden';
set the direction:
directionsDisplay.setDirections(response);
wait a moment until you modify the elements:
setTimeout(function(){
//fetch the elements
var nodes=directionsDisplay.getPanel().querySelectorAll('td.adp-text');
for(var n=0;n<nodes.length;++n){
//assign the text-content of the element to the innerHTML-property
nodes[n].innerHTML=nodes[n].firstChild.data;
}
//show the panel
directionsDisplay.getPanel().style.visibility='visible';
},100);