Snippets Collections
curl --request POST \
  --url 'https://api.apyhub.com/convert/rss-file/json?detailed=true' \
  --header 'apy-token: APY0BOODK2plpXgxRjezmBOXqID51DGpFq8QnHJeBQrrzuIBc25UIglN93bbwvnkBWlUia1' \
  --header 'content-type: multipart/form-data' \
  --form 'file=@"test.xml"'
curl --request POST \
  --url 'https://api.apyhub.com/convert/word-file/pdf-file?output=test-sample.pdf&landscape=false' \
  --header 'apy-token: APY0BOODK2plpXgxRjezmBOXqID51DGpFq8QnHJeBQrrzuIBc25UIglN93bbwvnkBWlUia1' \
  --header 'content-type: multipart/form-data' \
  --form 'file=@"test.doc"'
curl --request POST \
  --url 'https://api.apyhub.com/generate/charts/bar/file?output=sample.png' \
  --header 'Content-Type: application/json' \
  --header 'apy-token: APY0BOODK2plpXgxRjezmBOXqID51DGpFq8QnHJeBQrrzuIBc25UIglN93bbwvnkBWlUia1' \
  --data '{
    "title":"Simple Bar Chart",
    "theme":"Light",
    "data":[
        {
            "value":10,
            "label":"label a"
        },
        {
            "value":20,
            "label":"label b"
        },
        {
            "value":80,
            "label":"label c"
        },
        {
            "value":50,
            "label":"label d"
        },
        {
            "value":70,
            "label":"label e"
        },
        {
            "value":25,
            "label":"label f"
        },
        {
            "value":60,
            "label":"label g"
        }
    ]
}'
curl --request POST \
  --url 'https://api.apyhub.com/generate/charts/bar/file?output=sample.png' \
  --header 'Content-Type: application/json' \
  --header 'apy-token: APY0BOODK2plpXgxRjezmBOXqID51DGpFq8QnHJeBQrrzuIBc25UIglN93bbwvnkBWlUia1' \
  --data '{
    "title":"Simple Bar Chart",
    "theme":"Light",
    "data":[
        {
            "value":10,
            "label":"label a"
        },
        {
            "value":20,
            "label":"label b"
        },
        {
            "value":80,
            "label":"label c"
        },
        {
            "value":50,
            "label":"label d"
        },
        {
            "value":70,
            "label":"label e"
        },
        {
            "value":25,
            "label":"label f"
        },
        {
            "value":60,
            "label":"label g"
        }
    ]
}'
curl --request POST \
  --url 'https://api.apyhub.com/generate/qr-code/file?output=sample.png' \
  --header 'Content-Type: application/json' \
  --header 'apy-token: APY0BOODK2plpXgxRjezmBOXqID51DGpFq8QnHJeBQrrzuIBc25UIglN93bbwvnkBWlUia1' \
  --data '{
    "content": "https://apyhub.com",
    "logo": "https://apyhub.com/logo.svg",
    "background_color": "#000000",
    "foreground_color": ["#e8bf2a", "#e8732a"]
}'
add_action('rest_api_init', 'register_reset_password_route');

function register_reset_password_route() {
    register_rest_route('wp/v1', '/users/resetpassword', array(
        'methods' => 'POST',
        'callback' => 'reset_password_callback',
        'permission_callback' => '__return_true',
    ));
}

function reset_password_callback($request) {
    $user_data = $request->get_params();

    if (empty($user_data['email'])) {
        return new WP_REST_Response(array(
            'success' => false,
            'message' => 'البريد الإلكتروني مطلوب',
        ), 400);
    }

    $user = get_user_by('email', $user_data['email']);

    if (!$user) {
        return new WP_REST_Response(array(
            'success' => false,
            'message' => 'المستخدم غير موجود',
        ), 404);
    }

    $reset = wp_generate_password(12, false);

    $result = wp_set_password($reset, $user->ID);

    if (is_wp_error($result)) {
        return new WP_REST_Response(array(
            'success' => false,
            'message' => $result->get_error_message(),
        ), 500);
    } else {
        wp_mail($user->user_email, 'إعادة تعيين كلمة المرور', 'تمت إعادة تعيين كلمة مرورك بنجاح. كلمة مرورك الجديدة هي: ' . $reset);

        return new WP_REST_Response(array(
            'success' => true,
            'message' => 'تم إعادة تعيين كلمة المرور بنجاح. يرجى التحقق من بريدك الإلكتروني للحصول على كلمة المرور الجديدة.',
        ), 200);
    }
}
package main

import (
"fmt"
"net/http"
"io/ioutil"
)

func main() {
    url := "https://api.currencyapi.com/v3/latest"
    method := "GET"

    client := &http.Client {
}
req, err := http.NewRequest(method, url, nil)

if err != nil {
    fmt.Println(err)
    return
}
req.Header.Add("apikey", "YOUR-API-KEY")

res, err := client.Do(req)
if err != nil {
    fmt.Println(err)
    return
}
defer res.Body.Close()

body, err := ioutil.ReadAll(res.Body)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(string(body))
}
import json
import requests
API_URL = "https://api-inference.huggingface.co/models/gpt2"
headers = {"Authorization": f"Bearer {API_TOKEN}"}
def query(payload):
    data = json.dumps(payload)
    response = requests.request("POST", API_URL, headers=headers, data=data)
    return json.loads(response.content.decode("utf-8"))
data = query("Can you please let us know more details about your ")
    @IBAction func signUpPressed(_ sender: Any) {
        
        if nameTextField.text == "" {
            self.showToast(message: "Please enter your name")
            return
        } else if emailTextField.text == "" {
            self.showToast(message: "Please enter your email")
            return
        } else if passwordTextField.text == "" {
            self.showToast(message: "Please enter password")
            return
        }
        
        let parameters: [String: Any] = [
            "name" : nameTextField.text ?? "",
            "email" : emailTextField.text ?? "",
            "password" : passwordTextField.text ?? "",
            "fcmToken" : "asfnasdbhj",
            "osType" : "iPhone"
        ]
        AppDelegate.signUpUrl = "https://vital-server.herokuapp.com/signup"
        SVProgressHUD.show()
        AF.request(AppDelegate.signUpUrl , method: .post, parameters: parameters, encoding: JSONEncoding.default)
            .responseDecodable(of: RegistrationAPI.self) { (response) in
                print("resp : ", response)
                switch response.result {
                case .success(let response):
                    print("Success :: ", response.message)
                    if response.message == "Password is invalid" {
                        self.showToast(message: "Please enter a valid password")
                    } else if response.message == "Account already registered with this email" {
                        self.showToast(message: response.message)
                    } else {
                        print("Get token and continue")
                        UserDefaults.standard.set(response.token, forKey: "token")
                    }
                             
                    break
              case .failure(let error):
                    // Handle error
                    print("Failure : ", error)
                }
                
                SVProgressHUD.dismiss()
            }
    }

class RegistrationAPI: Codable {
    var message: String = ""
    var token: String = ""
    
    private enum CodingKeys: String, CodingKey {
        case token
        case message
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        if let token = try container.decodeIfPresent(String.self, forKey: .token) {
            self.token = token
        }
        if let message = try container.decodeIfPresent(String.self, forKey: .message) {
            self.message = message
        }
    }
}
fetch('https://geolocation-db.com/json/')
  .then(res => res.json())
  .then(prom => console.log(prom));
AIzaSyCiCwfEoY1wboiAbM1hs1Utetiwl_QnODQ
node -e "console.log(crypto.randomBytes(32).toString('hex'))"

// 8142e7beb79d8b0988fd0c22ceaf8b92c29a4ca264d70632ce0ee18e31110cdc
curl --location --request GET 'api.hived.space/user/login' \
--header 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' \
--data-raw ''
var inputvalue = document.querySelector('#cityinput')
var btn = document.querySelector('#sub')
var city = document.querySelector('#cityoutput')
var description = document.querySelector('#description')
var temp = document.querySelector('#temp')
var wind = document.querySelector('#wind')
 
apikey = "de9fd8a722542a526890360832401551"
 
function convertion(val) {
    return (val - 273).toFixed(2)
}
 
btn.addEventListener('click', function () {
 
    fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputvalue.value+'&appid='+apikey)
        .then(res => res.json())
 
        .then(data => {
 
            var namevalue = data['name']
            var descri = data['weather']['0']['description']
            var tempature = data['main']['temp']
            var wndspd = data['wind']['speed']
 
            city.innerHTML = `Weather of <span>${namevalue}<span>`;
            temp.innerHTML = `Temparature : <span>${convertion(tempature)} C</span>`
            description.innerHTML = `Sky Condition : <span>${descri}<span>`
            wind.innerHTML = `Wind Speed : <span>${wndspd} km/h<span>`
        })
 
        .catch(err => alert('Entered City Name is Wrong, Please try again!'))
})
const searchForm = document.querySelector("form");
2
const searchResultDiv = document.querySelector(".search-result");
3
const container = document.querySelector(".container");
4
let searchQuery = "";
5
const APP_ID = "Use Your Own App ID Here";
6
const APP_key = "Use Your Own App Key Here";
7
// console.log(container)
8
searchForm.addEventListener("submit", (e) => {
9
  e.preventDefault();
10
  searchQuery = e.target.querySelector("input").value;
11
  fetchAPI();
12
});
13
​
14
async function fetchAPI() {
15
  const baseURL = `https://api.edamam.com/search?q=${searchQuery}&app_id=${APP_ID}&app_key=${APP_key}&from=0&to=20`;
16
  const response = await fetch(baseURL);
# Load Inference Engine and Show Info
from openvino.runtime import Core
ie = Core()

devices = ie.available_devices

for device in devices:
    device_name = ie.get_property(device_name=device, name="FULL_DEVICE_NAME")
    print(f"{device}: {device_name}")

# Loading a Model
from openvino.runtime import Core

ie = Core()
classification_model_xml = "model/classification.xml"

model = ie.read_model(model=classification_model_xml)
compiled_model = ie.compile_model(model=model, device_name="CPU")

from openvino.runtime import Core

ie = Core()
onnx_model_path = "model/segmentation.onnx"
model_onnx = ie.read_model(model=onnx_model_path)
compiled_model_onnx = ie.compile_model(model=model_onnx, device_name="CPU")

from openvino.offline_transformations import serialize

serialize(model=model_onnx, model_path="model/exported_onnx_model.xml", weights_path="model/exported_onnx_model.bin")

# Getting Information about a Model
from openvino.runtime import Core

ie = Core()
classification_model_xml = "model/classification.xml"
model = ie.read_model(model=classification_model_xml)
model.input(0).any_name

input_layer = model.input(0)

print(f"input precision: {input_layer.element_type}")
print(f"input shape: {input_layer.shape}")

from openvino.runtime import Core

ie = Core()
classification_model_xml = "model/classification.xml"
model = ie.read_model(model=classification_model_xml)
model.output(0).any_name

output_layer = model.output(0)
output_layer

print(f"output precision: {output_layer.element_type}")
print(f"output shape: {output_layer.shape}")

from openvino.runtime import Core

ie = Core()
classification_model_xml = "model/classification.xml"
model = ie.read_model(model=classification_model_xml)
compiled_model = ie.compile_model(model=model, device_name="CPU")
input_layer = compiled_model.input(0)
output_layer = compiled_model.output(0)

import cv2

image_filename = "data/coco_hollywood.jpg"
image = cv2.imread(image_filename)
image.shape

# N,C,H,W = batch size, number of channels, height, width
N, C, H, W = input_layer.shape
# OpenCV resize expects the destination size as (width, height)
resized_image = cv2.resize(src=image, dsize=(W, H))
resized_image.shape

import numpy as np

input_data = np.expand_dims(np.transpose(resized_image, (2, 0, 1)), 0).astype(np.float32)
input_data.shape

# Do Inference
result = compiled_model([input_data])[output_layer]

request = compiled_model.create_infer_request()
request.infer(inputs={input_layer.any_name: input_data})
result = request.get_output_tensor(output_layer.index).data

from openvino.runtime import Core, PartialShape

ie = Core()
segmentation_model_xml = "model/segmentation.xml"
segmentation_model = ie.read_model(model=segmentation_model_xml)
segmentation_input_layer = segmentation_model.input(0)
segmentation_output_layer = segmentation_model.output(0)

print("~~~~ ORIGINAL MODEL ~~~~")
print(f"input shape: {segmentation_input_layer.shape}")
print(f"output shape: {segmentation_output_layer.shape}")

new_shape = PartialShape([1, 3, 544, 544])
segmentation_model.reshape({segmentation_input_layer.any_name: new_shape})
segmentation_compiled_model = ie.compile_model(model=segmentation_model, device_name="CPU")
# help(segmentation_compiled_model)
print("~~~~ RESHAPED MODEL ~~~~")
print(f"model input shape: {segmentation_input_layer.shape}")
print(
    f"compiled_model input shape: "
    f"{segmentation_compiled_model.input(index=0).shape}"
)
print(f"compiled_model output shape: {segmentation_output_layer.shape}")

# Change Batch Size
from openvino.runtime import Core, PartialShape

ie = Core()
segmentation_model_xml = "model/segmentation.xml"
segmentation_model = ie.read_model(model=segmentation_model_xml)
segmentation_input_layer = segmentation_model.input(0)
segmentation_output_layer = segmentation_model.output(0)
new_shape = PartialShape([2, 3, 544, 544])
segmentation_model.reshape({segmentation_input_layer.any_name: new_shape})
segmentation_compiled_model = ie.compile_model(model=segmentation_model, device_name="CPU")

print(f"input shape: {segmentation_input_layer.shape}")
print(f"output shape: {segmentation_output_layer.shape}")

import numpy as np
from openvino.runtime import Core, PartialShape

ie = Core()
segmentation_model_xml = "model/segmentation.xml"
segmentation_model = ie.read_model(model=segmentation_model_xml)
segmentation_input_layer = segmentation_model.input(0)
segmentation_output_layer = segmentation_model.output(0)
new_shape = PartialShape([2, 3, 544, 544])
segmentation_model.reshape({segmentation_input_layer.any_name: new_shape})
segmentation_compiled_model = ie.compile_model(model=segmentation_model, device_name="CPU")
input_data = np.random.rand(2, 3, 544, 544)

output = segmentation_compiled_model([input_data])

print(f"input data shape: {input_data.shape}")
print(f"result data data shape: {segmentation_output_layer.shape}")

# Caching a Model
import time
from pathlib import Path

from openvino.runtime import Core, PartialShape

ie = Core()

device_name = "GPU"  # Model Caching is not available for CPU

if device_name in ie.available_devices and device_name != "CPU":
    cache_path = Path("model/model_cache")
    cache_path.mkdir(exist_ok=True)
    # Enable caching for Inference Engine. To disable caching set enable_caching = False
    enable_caching = True
    config_dict = {"CACHE_DIR": str(cache_path)} if enable_caching else {}

    classification_model_xml = "model/classification.xml"
    model = ie.read_model(model=classification_model_xml)

    start_time = time.perf_counter()
    compiled_model = ie.compile_model(model=model, device_name=device_name, config=config_dict)
    end_time = time.perf_counter()
    print(f"Loading the network to the {device_name} device took {end_time-start_time:.2f} seconds.")
else:
    print("Model caching is not available on CPU devices.")

if device_name in ie.available_devices and device_name != "CPU":
    del compiled_model
    start_time = time.perf_counter()
    compiled_model = ie.compile_model(model=model, device_name=device_name, config=config_dict)
    end_time = time.perf_counter()
    print(f"Loading the network to the {device_name} device took {end_time-start_time:.2f} seconds.")
pip install django-blockchain

 
--Add app in your settings.py

INSTALLED_APPS = [
    "django_blockchain",
]

--And something in your urls.py

urlpatterns = patterns('',
    url(r'^blockchain$', 'django_blockchain.urls', name='blockchain_urls'),
curl --location --request POST 'api.hived.space/shipment' \
--header 'token: YOUR_TOKEN' \
--header 'Content-Type: application/json' \
--data-raw '{
  "tracking_id": "123456789ABCDEFGHIJ1",
  "consignment_id": "123456789ABCDEFGHIJ",
  "recipient": "Jane Doe",
  "recipient_address_line_1": "Flat 1",
  "recipient_address_line_2": "10 Downing Street",
  "recipient_address_line_3": "Westminster",
  "recipient_town": "London",
  "recipient_postcode": "SW1A 2AA",
  "recipient_email_address": "jane@gmail.com",
  "recipient_phone_number": "0987456321",
  "delivery_instructions": "Leave with neighbour",
  "sender": "John Doe",
  "sender_address_line_1": "Flat 2",
  "sender_address_line_2": "1 Buckingham Palace Road",
  "sender_address_line_3": "Buckingham Palace",
  "sender_town": "London",
  "sender_postcode": "SW1A 1AA",
  "sender_email_address": "john@gmail.com",
  "account_number": 1,
  "order_number": "#1009",
  "shipping_class": "Next-Day",
  "parcel_count": 3,
  "parcel_index": 1,
  "weight_kg": 1.5,
  "length_cm": 30,
  "width_cm": 30,
  "height_cm": 30,
  "fragile": false,
  "value_gbp": 119.90,
  "age_verification_required": true,
  "collection_contact_name": "Jimmy Doe",
  "collection_address_line_1": "1 Parliament Square",
  "collection_address_line_2": "Big Ben",
  "collection_address_line_3": "Palace of Westminster",
  "collection_town": "London",
  "collection_postcode": "SW1A 0AA",
  "collection_instructions": "Ring doorbell please",
  "collection_phone_number": "01234567489",
  "collection_email_address": "jimmy@gmail.com",
  "sender_chosen_collection_date": "2022-06-28",
  "sender_chosen_delivery_date": "2022-06-29",
  "sku": "123456789"
}'
fetch('http://example.com/songs')
	.then(response => response.json())
	.then(data => console.log(data))
	.catch(err => console.error(err));
/* 
HTML
<h1>
 Recent Ramblings
</h1>
<div id="articles">
</div>
*/

const fetchArticles = async (query, variables = {}) => {
  const data = await fetch("https://api.hashnode.com/", {
    method: "POST",
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query,
      variables
    })
  });
  return data.json();
}

const articleQuery = `
query GetUserArticles($page: Int!) {
        user(username: "sarahcodes") {
            publication {
                posts(page: $page) {
                    title
                    brief
                    coverImage
                    slug
                }
            }
        }
    }
`;

fetchArticles(articleQuery, {
    page: 0
  })
  .then(result => {
    console.log(result.data.user)
    const articles = result.data.user.publication.posts;
    let container = document.createElement('div');
    container.classList.add("row");
    articles.forEach(article => {

      let link = document.createElement('a');
      link.href = `https://sarahdepalo.hashnode.dev/${article.slug}`;
      
      let articleContainer = document.createElement('div');
      articleContainer.classList.add("col")

      let title = document.createElement('h2');
      title.innerText = article.title;

      let image = document.createElement('img');
      image.src = article.coverImage;

      let brief = document.createElement('p');
      brief.innerText = article.brief;
			
      container.appendChild(link);
      link.appendChild(articleContainer);
      articleContainer.appendChild(title);
      articleContainer.appendChild(image);
      articleContainer.appendChild(brief);
    })
    document.querySelector('#articles').appendChild(container);
  })
(Invoke-WebRequest -Uri https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py -UseBasicParsing).Content | python -
async function cdnjs(query){
	return await fetch("https://2qwlvlxzb6-2.algolianet.com/1/indexes/*/queries", {
		headers: {
		  accept: "*/*",
		  "content-type": "application/x-www-form-urlencoded",
		  "x-algolia-api-key": `2663c73014d2e4d6d1778cc8ad9fd010`,
		  "x-algolia-application-id": `2QWLVLXZB6`,
		},
		body: JSON.stringify({
		  requests: [{ indexName: "libraries", params: e`query=${q}` }],
		}),
		method: "POST",
	      })
		.then((res) => res.json())
		.then((res) => {
		  let results = res.results[0].hits;
		  return results.map((item) => ({
		    name: item.name,
		    keywords: item.keywords,
		    snippet: item.description,
		    author: item.author,
		  }));
		});
}
async function autocomplete(text){
	return JSON.parse(await fetch("https://www.google.com/complete/search?q=testing&client=Firefox").then(res => res.text()))[1];
}
function checkGrammar(text){
    const opts = {
        headers: {
            "accept": "application/vnd.splat+json",
        }
    }
    return new Promise(async (resolve) => {
        let job = await fetch("https://api.cram.com/article-evaluations", {
          "body": JSON.stringify({
              "text": text,
              "evaluate":["grammar","plagiarism"]
          }),
          "method": "POST",
          ...opts,
        }).then(res => res.json())
        let int = setInterval(async () => {
            let res = await fetch(`https://api.cram.com/article-evaluations/${job.data.id}`, {
              "headers": {
                "accept": "application/vnd.splat+json",
              },
              "method": "GET",
            }).then(res => res.json())
            if (res.data.is_success === 1){
                clearInterval(int);
                return resolve(res.data.result);
            }
        }, 500)
    });
}
/**
 * @param {String} text The text to check
 * @returns {Promise.<Object>}
 * @example
 *  // ⇒ {
 *  //   "Corrections": [...],
 *  //   "Sentences": [...]
 *  //}
 */
async function grammar(text){
	let res = await fetch(`https://services.gingersoftware.com/Ginger/correct/jsonSecured/GingerTheTextFull?callback=$&text=${encodeURIComponent(text)}&apiKey=GingerWebsite&clientVersion=2.0&lang=US`).then(res => res.text())
	return JSON.parse(res.replace(/^\$\(/, "").replace(/\);?$/, ""));//Returns a 'callback'
}
/**
* Gets parts of speech for a sentence
* @param {String} text The text to get parts of speech for.
* @returns {Promise.<Object>} Resolves into a list of parts of speech. (Or rejects with an error)
* @example 
* var parts_of_speech  = await parts_of_speech("Sometimes I just want to code in JavaScript all day.");
* // ⇒
* // {entities: Array(1), sentiments: Array(1), documentInfo: {…}, wordFreq: Array(4), taggedText: '<span class="tag ADV">Sometimes</span> <span class…>all</span> <span class="tag DURATION">day</span>'}
function parts_of_speech(text) {
*/
function parts_of_speech(text) {
  return new Promise(async (resolve, reject) => {
    fetch("https://showcase-serverless.herokuapp.com/pos-tagger", {
      headers: {
        accept: "application/json",
        "content-type": "application/json",
      },
      body: JSON.stringify({ sentence: text }),
      method: "POST",
    })
      .then((res) => res.json())
      .then(resolve)
      .catch(reject);
  });
}
/**
* Rewrites text
* @param {String} text The text to rewrite.
* @returns {Promise.<String[]>} Resolves into a list of about 10 rewritten versions. (Or rejects with an error)
* @example 
* var rewritten  = await rewrite("Sometimes I just want to code in JavaScript all day.");
* // ⇒ [
* //    "I sometimes just want to code JavaScript all day.",
* //    "JavaScript is my favorite programming language sometimes.",
* //    "I sometimes wish I could code in JavaScript all day.",
* //    "JavaScript is sometimes all I want to do all day.",
* //    "I like JavaScript sometimes and want to code all day long.",
* //    "Some days I just want to work all day in JavaScript.",
* //    "It's not uncommon for me to just want to code in JavaScript all day.",
* //    "My favorite thing to do sometimes is just code JavaScript all day.",
* //    "My favourite coding language is JavaScript, which I can code all day.",
*//     "JavaScript is my preferred language sometimes, since it lets me code all day.",
*// ];
*/
function rewrite(text) {
  return new Promise(async (resolve, reject) => {
    var { suggestions, error_code, error_msg, error_msg_extra } = await fetch(
      "https://api.wordtune.com/rewrite-limited",
      {
        headers: {
          accept: "*/*",
          "accept-language": "en-US,en;q=0.9",
          "content-type": "application/json",
          "x-wordtune-origin": "https://www.wordtune.com",
        },
        referrer: "https://www.wordtune.com/",
        body: JSON.stringify({
          action: "REWRITE",
          text: text,
          start: 0,
          end: text.length,
          selection: {
            wholeText: text,
            start: 0,
            end: text.length,
          },
        }),
        method: "POST",
      }
    ).then((res) => res.json());
    if (error_code || error_msg || error_msg_extra) {
      reject({
        code: error_code,
        message: error_msg,
        message_extra: error_msg_extra,
      });
    } else {
      resolve(suggestions);
    }
  });
}
/**
 * Translates text to a certain language.
 * @param {String} text The text to translate (or an options object)
 * @param {String} target The target language to translate to.
 * @param {String} source The source language.
 * @returns {Promise.<object>} Returns a promise resolving into an object with the translated text, raw response JSON, the original text, and the target and source languages.
 * @example
 * var translated = await translate("Hello world", "fr");
 * // ⇒ 
 * // {
 * //   source: "en", 
 * //   original: "Hello world",
 * //   translated: "Bonjour le monde",
 * //   result: "weird google stuff here"
 * // }
 *
 */
async function translate(text, target, source, proxy) {
  if (typeof text == "object") {
    target = text.target;
    source = text.source;
    proxy = text.proxy;
    text = text.text;
  }
  var opts = {
    text: text || "",
    source: source || 'auto',
    target: target || "en",
    proxy: proxy || "",
	}
  var result = await fetch(
    `https://${opts.proxy}translate.googleapis.com/translate_a/single?client=gtx&sl=${opts.source}&tl=${opts.target}&dt=t&q=${encodeURI(opts.text)}`
  ).then(res => res.json());
  return {
    source: opts.source,
    target: opts.target,
    original: text,
    translated: result[0]?.[0]?.[0],
    result,
  };
}
async function quizlet(id){
    let res = await fetch(`https://quizlet.com/webapi/3.4/studiable-item-documents?filters%5BstudiableContainerId%5D=${id}&filters%5BstudiableContainerType%5D=1&perPage=5&page=1`).then(res => res.json())
    let currentLength = 5;
    let token = res.responses[0].paging.token
    let terms = res.responses[0].models.studiableItem;
    let page = 2;
    console.log({token, terms})
    while (currentLength >= 5){
        let res = await fetch(`https://quizlet.com/webapi/3.4/studiable-item-documents?filters%5BstudiableContainerId%5D=${id}&filters%5BstudiableContainerType%5D=1&perPage=5&page=${page++}&pagingToken=${token}`).then(res => res.json());
        terms.push(...res.responses[0].models.studiableItem);
        currentLength = res.responses[0].models.studiableItem.length;
        token = res.responses[0].paging.token;
    }
    return terms;
}
SOLIDWORKS PDM Professional API Help
Traverse Folders and Files in Vault Example (VB.NET)
This example shows how to recursively traverse all of the folders and files in a vault. 

NOTE: If using the .NET Framework 4.0 primary interop assembly provided with SOLIDWORKS PDM Professional, see Using .NET Framework 4.0 in Stand-alone Applications.

'----------------------------------------------------------------------------
' Preconditions:
'  1. Start Microsoft Visual Studio 2010 or later.
'  2. Click File > New > Project > Visual Basic > Windows Forms Application.
'  3. Type TraverseFilesFolders in Name.
'  4. Click Browse and navigate to the folder where to create the project.
'  5. Click OK. 
'  6. Replace the code in Form1.vb with this code.
'  7. Replace the code in Form1.Designer.vb with this code.
'  8. If using Microsoft Visual Studio 2012 and .NET Framework 4.5, ensure
'     that the Prefer 32-bit check box is cleared (right-click the project 
'     name in the Solution Explorer and click Properties. On the Compile tab, 
'     if Target CPU is set to AnyCPU, ensure that Prefer 32-bit is cleared.)
'  9. Add EPDM.Interop.epdm.dll as a reference (right-click the project
'     name in the Solution Explorer, click Add Reference, click Browse, 
'     navigate to the top folder of your SOLIDWORKS PDM Professional installation, 
'     locate and select EPDM.Interop.epdm.dll).
' 10. Right-click EPDM.Interop.epdm in References, click Properties, and set 
'     Embed Interop Types to False to handle methods that pass arrays of 
'     structures.
' 11. Ensure that the vault contains one or more checked-out files.
' 12. Click Debug > Start Debugging or press F5.
'
' Postconditions: 
' 1. Displays a Traverse Folders and Files dialog.
' 2. Select a vault.
' 3. Click Log in, get client log, get checked-out files in vault.
' 4. Displays a message box with the vault type.
' 5. Click OK.
' 6. Populates Client log and Checked-out files.
' 7. Close the dialog.
'---------------------------------------------------------------------------- 
 

'Form1.vb
 
Imports EPDM.Interop.epdm
 
Public Class TraverseFilesFolders
 
    Dim vault As IEdmVault20
    Public Sub TraverseFilesFolders_Load(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles MyBase.Load
 
        Try
 
            Dim Views() As EdmViewInfo = Nothing
            Dim vault5 As IEdmVault5 = New EdmVault5()
            vault = DirectCast(vault5, IEdmVault20)
 
            vault.GetVaultViews(Views, False)
            
            VaultsComboBox.Items.Clear()
            For Each View As EdmViewInfo In Views
                VaultsComboBox.Items.Add(View.mbsVaultName)
            Next
            If VaultsComboBox.Items.Count > 0 Then
                VaultsComboBox.Text = VaultsComboBox.Items(0)
            End If
 
        Catch ex As Runtime.InteropServices.COMException
            MessageBox.Show("HRESULT = 0x" +ex.ErrorCode.ToString("X") + vbCrLf +ex.Message)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
 
    Public Sub TraverseFoldersButton_Click(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles TraverseFoldersButton.Click
 
        Try
 
            'Log into selected vault as the current user
            vault.LoginAuto(VaultsComboBox.Text,Me.Handle.ToInt32())
 
            MessageBox.Show(vault.GetVaultType().ToString(), "Vault type")
 
            Dim log As String = Nothing
            vault.GetClientLog(log)
            TextBox1.Text = log
 
            TraverseFolder(vault.RootFolder)
 
        Catch ex As Runtime.InteropServices.COMException
            MessageBox.Show("HRESULT = 0x" +ex.ErrorCode.ToString("X") + vbCrLf +ex.Message)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
 
    Public Sub TraverseFolder(ByVal CurFolder As IEdmFolder5)
 
        Try
 
            'Enumerate the files in the folder
            Dim FilePos As IEdmPos5
            FilePos = CurFolder.GetFirstFilePosition
            Dim file As IEdmFile5
            While Not FilePos.IsNull
                file = CurFolder.GetNextFile(FilePos)
                'Get its checked out status
                If file.IsLocked Then
                    ListBox2.Items.Add(file.LockPath)
                End If
            End While
 
            'Enumerate the subfolders in the folder
            Dim FolderPos As IEdmPos5
            FolderPos = CurFolder.GetFirstSubFolderPosition
            While Not FolderPos.IsNull
                Dim SubFolder As IEdmFolder5
                SubFolder = CurFolder.GetNextSubFolder (FolderPos)
                TraverseFolder(SubFolder)
            End While
  
        Catch ex As Runtime.InteropServices.COMException
            MessageBox.Show("HRESULT = 0x" +ex.ErrorCode.ToString("X") + vbCrLf +ex.Message)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
 
End Class

Back to top

'Form1.Designer.vb

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class TraverseFilesFolders
    Inherits System.Windows.Forms.Form
 
    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub
 
    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer
 
    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.VaultsComboBox = New System.Windows.Forms.ComboBox()
        Me.TraverseFoldersButton = New System.Windows.Forms.Button()
        Me.Label2 = New System.Windows.Forms.Label()
        Me.Label3 = New System.Windows.Forms.Label()
        Me.ListBox2 = New System.Windows.Forms.ListBox()
        Me.TextBox1 = New System.Windows.Forms.TextBox()
        Me.SuspendLayout()
        '
        'Label1
        '
        Me.Label1.AutoSize = True
        Me.Label1.Location = New System.Drawing.Point(22, 34)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(91, 13)
        Me.Label1.TabIndex = 0
        Me.Label1.Text = "Select vault view:"
        '
        'VaultsComboBox
        '
        Me.VaultsComboBox.FormattingEnabled = True
        Me.VaultsComboBox.Location = New System.Drawing.Point(25, 50)
        Me.VaultsComboBox.Name = "VaultsComboBox"
        Me.VaultsComboBox.Size = New System.Drawing.Size(121, 21)
        Me.VaultsComboBox.TabIndex = 1
        '
        'TraverseFoldersButton
        '
        Me.TraverseFoldersButton.Location = New System.Drawing.Point(25, 89)
        Me.TraverseFoldersButton.Name = "TraverseFoldersButton"
        Me.TraverseFoldersButton.Size = New System.Drawing.Size(212, 34)
        Me.TraverseFoldersButton.TabIndex = 2
        Me.TraverseFoldersButton.Text = "Log in, get client log, get checked-out files in vault"
        Me.TraverseFoldersButton.UseVisualStyleBackColor = True
        '
        'Label2
        '
        Me.Label2.AutoSize = True
        Me.Label2.Location = New System.Drawing.Point(22, 144)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(53, 13)
        Me.Label2.TabIndex = 4
        Me.Label2.Text = "Client log:"
        '
        'Label3
        '
        Me.Label3.AutoSize = True
        Me.Label3.Location = New System.Drawing.Point(24, 310)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(89, 13)
        Me.Label3.TabIndex = 5
        Me.Label3.Text = "Checked-out files:"
        '
        'ListBox2
        '
        Me.ListBox2.FormattingEnabled = True
        Me.ListBox2.HorizontalScrollbar = True
        Me.ListBox2.Location = New System.Drawing.Point(27, 326)
        Me.ListBox2.Name = "ListBox2"
        Me.ListBox2.ScrollAlwaysVisible = True
        Me.ListBox2.SelectionMode = System.Windows.Forms.SelectionMode.None
        Me.ListBox2.Size = New System.Drawing.Size(210, 160)
        Me.ListBox2.TabIndex = 6
        '
        'TextBox1
        '
        Me.TextBox1.Location = New System.Drawing.Point(25, 160)
        Me.TextBox1.Multiline = True
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both
        Me.TextBox1.Size = New System.Drawing.Size(212, 147)
        Me.TextBox1.TabIndex = 7
        '
        'TraverseFilesFolders
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(258, 509)
        Me.Controls.Add(Me.TextBox1)
        Me.Controls.Add(Me.ListBox2)
        Me.Controls.Add(Me.Label3)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.TraverseFoldersButton)
        Me.Controls.Add(Me.VaultsComboBox)
        Me.Controls.Add(Me.Label1)
        Me.Name = "TraverseFilesFolders"
        Me.Text = "Traverse Folders and Files"
        Me.ResumeLayout(False)
        Me.PerformLayout()
 
    End Sub
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents VaultsComboBox As System.Windows.Forms.ComboBox
    Friend WithEvents TraverseFoldersButton As System.Windows.Forms.Button
    Friend WithEvents Label2 As Label
    Friend WithEvents Label3 As Label
    Friend WithEvents ListBox2 As ListBox
    Friend WithEvents TextBox1 As TextBox
End Class
{
  "name": "frontend",
    // add proxy, so instead of looking at front end server, our api requests look at backend server
    // call it prox, then add the loopback address and the backend server port
  "proxy": "http://127.0.0.1:8080",
  "version": "0.1.0",
const express = require('express');
const router = express.Router();

// this is our crud route so it'll have the most routes
// SIGNTAURE TYPE ENDPOINT
// @route       GET api/contacts
// @desc        get user's contacts
// @access      private (theses are all private to user so all private)
// we said anything that goes to this file is coming from /api/auth so we just need a slash
router.get('/', (req, res) => {
    res.send(`Get all the user's contacts`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       POST api/contacts
// @desc        add a new contact
// @access      private 
router.post('/', (req, res) => {
    res.send(`Add a new contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       PUT api/contacts/:id (we need to id which contact is getting updated)
// @desc        update contact
// @access      private 
router.put('/:id', (req, res) => {
    res.send(`Update a contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       DELETE api/contacts/:id (we need to id which contact is getting deleted)
// @desc        delete contact
// @access      private 
router.delete('/:id', (req, res) => {
    res.send(`DESTROY a contact`)
})

// export router so we can access ittttt
module.exports = router
  def search
    baseurl = "https://api.themoviedb.org/3/discover/movie?api_key=#{ENV['REACT_APP_TMDB_API_KEY']}&language=en-						US&sort_by=popularity.desc&with_watch_monetization_types=flatrate&include_adult=false&include_video		=false&page=${moviePageIndex}";
    urladdon = params[:urlAddon]

    require 'uri'
    require 'net/http'

    uri = URI("#{baseurl}#{urladdon}")
    res = Net::HTTP.get_response(uri)

    if res.is_a?(Net::HTTPSuccess)
      render json: res.body
    else
      render json: res.body, status: :bad_request
    end
  end
  const getMovies = async (url) => {
    setError(null);
    try {
      const response = await fetch(url);

      if (!response.ok) {
        throw new Error("Something went wrong!");
      }

      const data = await response.json();
      
      if (data.results.length === 0) {
        throw new Error("Sorry, no movies were found.");
      }
      
      const transformedMovies = data.results.map((movie) => {
        return {
          id: movie.id,
          title: movie.title,
          description: movie.overview,
          rating: movie.vote_average,
          genres: movie.genre_ids,
          poster_path: movie.poster_path,
          backdrop_path: movie.backdrop_path,
          year: movie.release_date
        }
      })
      setTotalPages(data.total_pages);
      setMovies(transformedMovies);
      chooseMovie(transformedMovies);
    } catch (errorThrown) {
      setError(errorThrown.message);
    }
  }
https://restcountries.eu/rest/v2/name/{query}(?fields=name;alpha2Code)
star

Fri Mar 22 2024 16:44:48 GMT+0000 (Coordinated Universal Time) https://apyhub.com/utility/converter-rss-json

#api #data
star

Fri Mar 22 2024 16:43:55 GMT+0000 (Coordinated Universal Time) https://apyhub.com/utility/converter-doc-pdf

#api #data
star

Fri Mar 22 2024 16:42:46 GMT+0000 (Coordinated Universal Time) https://apyhub.com/utility/bar-graph

#api #data
star

Fri Mar 22 2024 16:42:45 GMT+0000 (Coordinated Universal Time) https://apyhub.com/utility/bar-graph

#api #data
star

Fri Mar 22 2024 16:41:45 GMT+0000 (Coordinated Universal Time) https://apyhub.com/utility/generate-qr-code

#api #data
star

Fri Mar 22 2024 16:40:29 GMT+0000 (Coordinated Universal Time) https://apyhub.com/utility/analyse-keywords

#api #data
star

Sat Jan 20 2024 02:03:22 GMT+0000 (Coordinated Universal Time) https://github.com/LaravelDaily/laravel-tips/blob/master/api.md

#php #laravel #api #api_tips #tips
star

Tue Dec 19 2023 10:36:08 GMT+0000 (Coordinated Universal Time) https://css-tricks.com/headless-form-submission-with-the-wordpress-rest-api/

#contactform7 #api #headless
star

Tue Aug 08 2023 08:07:35 GMT+0000 (Coordinated Universal Time) https://currencyapi.com/docs/examples/go-currency-converter

#go #currencyconverter #exchangerates #currency #api
star

Mon Jul 24 2023 02:28:33 GMT+0000 (Coordinated Universal Time) https://huggingface.co/docs/api-inference/quicktour

#huggingface #hf #api
star

Tue Feb 07 2023 05:39:59 GMT+0000 (Coordinated Universal Time)

#ios #swift #api #signup
star

Tue Nov 29 2022 11:03:51 GMT+0000 (Coordinated Universal Time) https://www.folkstalk.com/2022/07/get-user-location-without-permission-with-code-examples.html

#js #api
star

Sat Oct 15 2022 17:45:59 GMT+0000 (Coordinated Universal Time)

#api
star

Wed Sep 07 2022 09:03:24 GMT+0000 (Coordinated Universal Time)

#terminal #private-key #api
star

Wed Jul 20 2022 14:19:06 GMT+0000 (Coordinated Universal Time)

#api #shipment
star

Wed Jul 20 2022 13:52:54 GMT+0000 (Coordinated Universal Time)

#api #shipment #authentication
star

Sun Jun 19 2022 04:41:58 GMT+0000 (Coordinated Universal Time)

#javascript #weather #api
star

Fri Jun 17 2022 18:42:45 GMT+0000 (Coordinated Universal Time) https://codepen.io/Web_Cifar/pen/oNxLYRY?editors

#js #api #food #recipe
star

Thu Jun 09 2022 16:41:35 GMT+0000 (Coordinated Universal Time) https://github.com/openvinotoolkit/openvino_notebooks/blob/main/notebooks/002-openvino-api/002-openvino-api.ipynb

#python #openvino #onnx #openvino-notebook #api #openvino-api
star

Sun May 29 2022 19:51:50 GMT+0000 (Coordinated Universal Time) https://pythonrepo.com/repo/null-none-django-blockchain-python-django-utilities

#api #blockchain #django #cli
star

Wed Apr 27 2022 11:16:38 GMT+0000 (Coordinated Universal Time)

#api #shipment
star

Wed Apr 27 2022 10:18:16 GMT+0000 (Coordinated Universal Time)

#authentication #api
star

Mon Apr 11 2022 00:40:36 GMT+0000 (Coordinated Universal Time)

#javascript #api
star

Wed Mar 09 2022 21:19:03 GMT+0000 (Coordinated Universal Time)

#javascript #api #hashnode #vanilla
star

Mon Feb 07 2022 20:32:15 GMT+0000 (Coordinated Universal Time) https://python-poetry.org/docs/

#python #env #environments #api #program
star

Mon Jan 10 2022 17:04:09 GMT+0000 (Coordinated Universal Time) https://github.com/explosion-scratch/cool_apis

#javascript #js #cdnjs #searcha #api
star

Mon Jan 10 2022 17:03:43 GMT+0000 (Coordinated Universal Time) https://github.com/explosion-scratch/cool_apis

#javascript #api #js #autocomplete #google
star

Mon Jan 10 2022 17:03:25 GMT+0000 (Coordinated Universal Time) https://github.com/explosion-scratch/cool_apis

#javascript #js #api
star

Mon Jan 10 2022 17:03:08 GMT+0000 (Coordinated Universal Time) https://github.com/explosion-scratch/cool_apis

#javascript #js #api
star

Mon Jan 10 2022 17:02:49 GMT+0000 (Coordinated Universal Time) https://github.com/explosion-scratch/cool_apis

#js #javascript #text #api
star

Mon Jan 10 2022 17:02:27 GMT+0000 (Coordinated Universal Time) https://github.com/explosion-scratch/cool_apis

#js #javascript #rewrite #api
star

Mon Jan 10 2022 17:02:09 GMT+0000 (Coordinated Universal Time) https://github.com/explosion-scratch/cool_apis

#javascript #google #translate #api
star

Thu Dec 16 2021 22:56:56 GMT+0000 (Coordinated Universal Time) https://gist.github.com/Explosion-Scratch/154792ea7faf4254c9abdcd771e68868

#javascript #quizlet #api
star

Tue Nov 23 2021 13:45:09 GMT+0000 (Coordinated Universal Time)

#solidworks #pdm #api
star

Tue Aug 17 2021 16:32:31 GMT+0000 (Coordinated Universal Time) https://rust-lang.github.io/api-guidelines/

#rust #api
star

Thu Jul 15 2021 09:01:59 GMT+0000 (Coordinated Universal Time)

#nodejs #api #routing #rest
star

Mon May 24 2021 18:07:47 GMT+0000 (Coordinated Universal Time)

#react #api #ruby #rubyonrails
star

Mon May 24 2021 17:37:55 GMT+0000 (Coordinated Universal Time)

#react #api #fetch #async #error
star

Tue Dec 08 2020 17:26:47 GMT+0000 (Coordinated Universal Time)

#api

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension