How to import javascript code in python with variable? - python

I have file javascript and python, I want to call javascript function in python code with send variable from python. example my javascript file
var msg = 'this is the encrypt key, very long character';
function split (value, msg){
if(value == msg){
return true;
}else{
return false;
}
}
function process(value){
var a = split(value, msg);
if (a == "true"){
return a;
}else{
return "Error";
}
}
now I want to add this file to my python code, I want to send variable from python to my javascript code. example like this
value = "aaa"
js = open('example.js','r')
print(js.process(value))
I want to import javascript file to python code, and I want to use the process function in the javascript file. I know my code is wrong, I don't understand how to make a function like that. Please help me

You need a wonderful module named as js2py. Install by :
pip install js2py
The code looks like this :
import js2py
process=js2py.eval_js('''function process(value,a){
if (a == "true"){
return a;
}else{
return "Error";
}
}''')
split=js2py.eval_js('''function split (value){
var msg = 'this is the encrypt key, very long character';
if(value == msg){
return true;
}else{
return false;
}
}''')
value="aaa"
a=split(value)
print(process(value,a))

Related

How to replace get_declared_classes() from CakePHP to Python?

I have been moving website made in Cakephp into Django. In one place I found get_declared_classes(). I thinks this function returns list of previously used classes before running current class.
First time when I encounter this, I just store list of classes manually in one file and I was using that and this solution worked only for a particular web page but Now I have multiple pages calling this class and everytime list of classnames are very different so I can not store class name list.
This code is actually connecting and fetching data from here and I want to replace this class in python(We are replacing whole website). The only problem I have is how to replace get_declared_classes.
class HrbcConnect{
private $scope = '';
private $token = null;
private $token_expire = 0;
private $request_opt = array();
public $id;
public $id_arr = array();
public $write_error;
public function read($resource,$condition='',$field=array(),$order=null){
$declared_classes = get_declared_classes();
foreach(App::objects('Model') as $v){
if(in_array($v,$declared_classes)){
$instance = new $v;
if(property_exists($instance,'hrbc_cols') && array_key_exists(ucfirst($resource),$instance->hrbc_cols)){
foreach($instance->hrbc_cols[ucfirst($resource)] as $vv){
if(is_array($vv)){
$field[] = $vv[0];
}else{
$field[] = $vv;
}
}
}elseif(property_exists($instance,'hrbc_cols_arr')){
foreach($instance->hrbc_cols_arr as $kk=>$vv){
if(array_key_exists(ucfirst($resource),$vv)){
foreach($vv[ucfirst($resource)] as $vvv){
if(is_array($vvv) && !in_array($vvv[0],$field)){
$field[] = $vvv[0];
}elseif(!is_array($vvv) && !in_array($vvv,$field)){
$field[] = $vvv;
}
}
}
}
}
}
}
}
}
When I print the $v in the above code to find what are classes being used, I found list of classes that defined in my models.
If question is not clear please let me know, I can provide more information.
Is there any other library that can replace this function in Python? Or Is there any other solution I can try ?

PythonKit/PythonLibrary.swift:46: Fatal error: Python library not found. Set the PYTHON_LIBRARY environment variable with the path to a Python library

Ok I'm fairly new to swift and am trying to create an app with a button that uses python. I have seem code looking like
//
// ContentView.swift
// Shared
//
// Created by Ulto4 on 10/17/21.
//
import SwiftUI
import PythonKit
struct ContentView: View {
#State private var showDetails = false
#State var result : String = " "
var body: some View {
HStack{
Text("Hello, world!")
.padding()
Button(action : {
self.coolPerson()
}, label: {
Text("Respones")
})
Text("\(result)")
}
}
func coolPerson(){
let sys = Python.import("sys")
sys.path.append("/Users/ulto4/Documents/vsc")
let example = Python.import("ahhhhh")
let response = example.hi()
result = response.description
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.preferredColorScheme(.dark)
}
}
The code in the python file is
def hello():
return "cool"
However, when I click the button I get this error
2021-10-17 17:53:16.943097-0700 GAAIN[27059:2277939] PythonKit/PythonLibrary.swift:46: Fatal error: Python library not found. Set the PYTHON_LIBRARY environment variable with the path to a Python library.
(lldb)
I also clicked the .xcodeproj and deleted the Apple Sandbox. But it still doesn't work. Since I'm fairly new I don't know how to do this. Any help would be appreciated.
EDIT: As per the comments, IOS doesn't support PythonKIT

How do I block the IP for those who enter my website twice?

I have this code:
$accounts = fopen("accounts.txt", "r+");
$give_account = fgets($accounts);
$fileContents = file_get_contents("ips.txt");
fclose($accounts);
if(strpos($fileContents, $ip) !== false){
echo $give_account;
}else{
echo "you have already received an account";
}
i want to get his ip(i got this point),and I want you to receive your account,and I want to delete from the list the account that I gave and not be able to receive another one and print the else.If you can help me with something, even a little, I would appreciate it.Thanks
Imagining that you do not have any kind of database usage in your website, This code should give you a quick heads up on how to handle your scenario.
TIP: Try not to parse files like strings. Instead, use JSON or XML or some kind of markup language.
<?php
if(!function_exists('get_client_ip')){
function get_client_ip() {
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else
$ipaddress = null;
return $ipaddress;
}
}
if(!function_exists('log_ip_address')){
function log_ip_address($ip, $account_id){
// Get the JSON object from the IP Logs file and add this IP to the object
// $ip_logged is true if JSON object is updated. false otherwise
$ip_logged = true;
return $ip_logged ? true : false;
}
}
if(!function_exists('allot_account_to_client')){
function allot_account_to_client($account_id, $ip){
if(empty($account_id) || empty($ip)){
throw new Exception("Parameter missing");
}
// Do your magic here and allot an account to your client if he deserves
$alloted = true;
// When alloted, remove the current $account_id from the accounts JSON objects so that you won't allot the same account_id to anyone else
// Log the IP address
$log = log_ip_address($ip, $account_id);
// return true only if ip is logged. If IP logging fails, write a mechanism to put back the account_id back to the accounts Array.
return $log ? true : false;
}
}
$ip = get_client_ip();
if($ip == null){
throw new Exception("Unable to get IP. Do you even exist?");
}
// contains an JSON object of IP addresses that an account was taken from and it's details
$list_of_ips = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/logs/ips.json'));
// Contains JSON Array of account_ids
$accounts = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'].'/accounts/available_accounts.json'));
if(isset($list_of_ips[$ip])){
$taken_on = new DateTime($list_of_ips[$ip]['taken_on']);
throw new Exception("You already got your account on ".$taken_on->format('m-d-Y H:i:sP'));
}
$available_account_id = $accounts[0];
// If he comes until here, he deserves the account
$alloted = allot_account_to_client($account_id, $ip);
if(!$alloted){
echo "Unable to allot you an account.";
exit(0);
}
echo "Your account id is : ".$account_id;
?>
EDIT:
I do not suggest you to use the files located in your server like this as these files are accessible to the user and it compromises whatever you are doing. Use Databases instead.
If you are so determined to use the files, instead of storing the unencrypted data, use some encryption methods to encrypt the data so that at least a normal non techie user would not know what it is.
You can write the IPs from the visitor in a local-file on your server. If someone visits your site, read this file either complete as an array in and check with array_key_exists if this IP is inside your list (compare with !== -1 for exists) or read line by line in and check if they are equal.
If the IP is twice then you can make a redirect to another site perhaps something like "Upps, your here again. I only like new vistors" or you just put the whole following code in an if-block that it won't be evaluated.

IronPython | Redirect Output To Textbox

Ok so, let's say I am executing a script with IronPython in C#:
ScriptEngine engine = Python.CreateEngine();
string Script = textBox1.Text();
engine.Execute(Script);
Now let's say the script was:
print("Hello")
Output in VS Console: Hello
What I am trying to achieve here is to redirect that output to a TextBox in C#. I have tried the following method which didn't work:
class TextBoxWriter : TextWriter
{
private RichTextBox _textBox;
public TextBoxWriter(RichTextBox textbox)
{
_textBox = textbox;
}
public override void Write(char value)
{
base.Write(value);
_textBox.AppendText(value.ToString());
}
public override System.Text.Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}
}
Form1_Load:
engine.Runtime.IO.RedirectToConsole();
TextWriter _writer = TextWriter.Synchronized(new TextBoxWriter(textBox1));
Console.SetOut(_writer);
I have just that in my code and its functional for me.
engine.Runtime.IO.RedirectToConsole();
Console.SetOut(new TextBoxWriter(textBox1));

NativeProcess communication giving error

I am trying to communicate to a python script through actionscript. it gives me error on line :
var stdOut:ByteArray = process.standardOutput;
from the function shown below :
public function onOutputData(event:ProgressEvent):void
{
var stdOut:ByteArray = process.standardOutput; //error
var data:String = stdOut.readUTFBytes(process.standardOutput.bytesAvailable);
trace("Got: ", data);
}
Error is:
Implicit coercion of a value with static type IDataInput to a possibly
unrelated type ByteArray.
I am following the same approach as on Adobe's page. Here is some testable code :
package
{
import flash.display.Sprite;
import flash.desktop.NativeProcessStartupInfo;
import flash.filesystem.File;
import flash.desktop.NativeProcess;
import flash.events.ProgressEvent;
import flash.utils.ByteArray;
public class InstaUtility extends Sprite
{
public var nativeProcessStartupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
public var file:File = new File("C:/Python27/python.exe");
public var process:NativeProcess = new NativeProcess();
public function InstaUtility()
{
nativeProcessStartupInfo.executable = file;
nativeProcessStartupInfo.workingDirectory = File.applicationDirectory.resolvePath(".");
trace("Location " + File.applicationDirectory.resolvePath(".").nativePath);
var processArgs:Vector.<String> = new Vector.<String>();
processArgs[0] = "test.py";
nativeProcessStartupInfo.arguments = processArgs;
var process:NativeProcess = new NativeProcess();
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
process.start(nativeProcessStartupInfo);
}
public function onOutputData(event:ProgressEvent):void
{
var stdOut:ByteArray = process.standardOutput; //error
var data:String = stdOut.readUTFBytes(process.standardOutput.bytesAvailable);
trace("Got: ", data);
}
}
}
The NativeProcess could not be started. Not supported in current
profile.
Are you testing in Flash IDE?
Test within IDE : In your AIR Publish Settings make sure you ticked only "extended Desktop" when debugging through IDE. This way you also get traces etc.
Test after Publish : You must tick both "Desktop" and "extended Desktop" and also tick "Windows Installer (.exe)". Install your App using the generated .exe file (not the .air file).
Implicit coercion of a value with static type IDataInput to a possibly
unrelated type ByteArray.
var stdOut:ByteArray = process.standardOutput; //error is not how it's done!! Don't make any var each time the progress event fires up. Each firing holds around 32kb or 64kb of bytes only (can't remember), so if the expected result is larger it will continue to fire in multiple chunks... Use and recycle a single public byteArray to hold all the result data.
Try a setup like below :
//# Declare the public variables
public var stdOut : ByteArray = new ByteArray();
public var data_String : String = "";
Your process also needs a NativeProcessExitEvent.EXIT listener.
process.addEventListener(NativeProcessExitEvent.EXIT, on_Process_Exit );
Before you .start a process, also clear the byteArray ready for new data with stdOut.clear();.
Now your progressEvent can look like this below... (Process puts result data into stdOut bytes).
public function onOutputData (event:ProgressEvent) : void
{
//var stdOut:ByteArray = process.standardOutput; //error
//# Progress could fire many times so keep adding data to build the final result
//# "stdOut.length" will be zero at first but add more data to tail end (ie: length)
process.standardOutput.readBytes( stdOut, stdOut.length, process.standardOutput.bytesAvailable );
//# Below should be in a Process "Exit" listener but might work here too
stdOut.position = 0; //move pointer back before reading bytes
data_String = stdOut.readUTFBytes( stdOut.length );
trace("function onOutputData -- Got : " + data_String );
}
But you really need to add an "onProcessExit" listener and then only check for results when the process itself has completed. (Tracing here is much safer for a guaranteed result).
public function on_Process_Exit (event : NativeProcessExitEvent) : void
{
trace ("PYTHON Process finished : ############# " )
stdOut.position = 0; //# move pointer back before reading bytes
data_String = stdOut.readUTFBytes( stdOut.length );
trace("PYTHON Process Got : " + data_String );
}

Categories