It might sound stupid question but I am looking a way to give ID to each side of x3dom object, lets say cube so that i can create different attributes for each individual face. The only method that I have seen so far is "def" function. It would be really helpful if anyone can provide a simple sample for a cube. Thanking you in advance.
def is for defining a shape for reuse
you can def an object and then reuse it in a scene. useful for say making a forest of similar trees. an example on x3dom site is here just take a look at the source.
http://x3dom.org/x3dom/example/x3dom_defUse.xhtml
if you are using just a x3d Box defining every side isnt possible as its a primitive shape, def or id on the box wouldnt be able to effect a single face
if you used indexed triangle sets each one of them could be assigned an id that way
more on them here
http://x3dgraphics.com/examples/X3dForWebAuthors/Chapter13-GeometryTrianglesQuadrilaterals/_pages/page03.html
for how to use css ids
http://x3dom.org/docs/dev/tutorial/styling.html
here is a simple example using both the getelement by tag and by id
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<link rel="stylesheet" type="text/css" href="http://x3dom.org/x3dom/example/x3dom.css"></link>
<script type="text/javascript" src = "http://x3dom.org/x3dom/example/x3dom.js"></script>
</head>
<body>
<X3D width="500px" height="400px" showLog='true' showStat="true">
<Scene DEF='scene' >
<Shape >
<Box onclick="toggleRendering();" onmouseover="toggleRendering2();" onmouseout="toggleRendering3();" />
<Appearance><Material id="themat" diffuseColor='0 1 0' /></Appearance>
</Shape>
</Scene>
</X3D>
<script>
var flag = true;
function toggleRendering()
{
flag = !flag;
var aMat = document.getElementById("themat");
if (flag) aMat.diffuseColor = "1 0 0";
else aMat.diffuseColor = "0 0 1";
return false;
}
function toggleRendering2()
{
var mat = document.getElementsByTagName("Material");
var aMat = mat[0];
aMat.diffuseColor = "1 1 1";
return false;
}
function toggleRendering3()
{
var mat = document.getElementsByTagName("Material");
var aMat = mat[0];
aMat.diffuseColor = "0 0 0";
return false;
}
</script>
</body>
</html>
Related
I want to load my predefined model from localstorage and if there isn't any model at there it may be created. After every epochend i want to save model for later loads.
I searched a lot of examples to save and load models. There are some examples (like API documents) but i can't find how can i check are there any applicable model at localstorage and if there isn't, create it.
NOTE: Tensorflow solutions are not adaptable to tensorflow.js (or i can't find a way)
//I need to load model from localstorage. It's not needed to use a try catch block, if there is a solution to check are there any model that can be loaded as a correct model, it can be applicable.
try{
/*
try-catch block or any function to check
*/
const model = await tf.loadLayersModel('localstorage://my-model-1');
}catch(err) {
//Create new model if not exists (i don't know it is ok or not)
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.add(tf.layers.dense({units: 1}));
}
const xs = tf.tensor([1,2,3,4,5]);
const ys = tf.tensor([3,5,7,9,11]);
async function trainModel(model, inputs, labels) {
const learningRate = 0.01;
const opt=tf.train.sgd(learningRate);
model.compile({ loss: 'meanSquaredError', optimizer: opt});
return await model.fit(xs, ys, {
epochs: 500,
callbacks:{
onEpochEnd: async(epoch, logs) =>{
document.getElementById("output").innerText="Epoch:"
+ epoch
+ " Loss:"
+ logs.loss;
/*
and then save model to the localstorage for it can load at top of this script for use later load
*/
}
}
})
}
var training = trainModel(model, xs, ys)
training.then(function(args){
var prediction = model.predict(tf.tensor([6]));
document.getElementById("output").innerText=prediction;
prediction.print();
})
<!DOCTYPE html>
<html lang="tr">
<head>
<title>tensorflow.js sofrası</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#2.7.0/dist/tf.min.js"></script>
</head>
<body>
<div id="output"></div>
<script src="script2.js"></script>
</body>
</html>
The model can be saved after each epoch with the following:
onEpochEnd: async(epoch, logs) =>{
document.getElementById("output").innerText="Epoch:"
+ epoch
+ " Loss:"
+ logs.loss;
await model.save('localstorage://model-name');
}
If the model is already saved, we can check if localStorage contains one of the following keys: tensorflowjs_models/model-name/info, tensorflowjs_models/my-model-1/model_topology, ... It will look as the following:
function createModel() {
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.add(tf.layers.dense({units: 1}));
return model
}
let myModel;
if (localStorage['tensorflowjs_models/model-name/model_info']) {
// the model exist
myModel = await model.save('localstorage://model-name');
} else {
myModel = createModel()
}
I want to use google spreadsheet with android. I Tried example program. I created new datasheet. I used example script code. I tried mit2 app program. This program is example program. I also used postman.
Postman show me error.
Postman error page.Postman connection error status 200 OK.
Postman error message is:
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="//ssl.gstatic.com/docs/script/images/favicon.ico">
<title>ERROR</title>
<style type="text/css" nonce="B6c+P2HTW+vClzlpE+anwg">body {background-color: #fff; margin: 0; padding: 0;}.errorMessage {font-family: Arial,sans-serif; font-size: 12pt; font-weight: bold; line-height: 150%; padding-top: 25px;}</style>
</head>
<body style="margin:20px">
<div>
<img alt="Google Apps Script" src="//ssl.gstatic.com/docs/script/images/logo.png">
</div>
<div style="text-align:center;font-family:monospace;margin:50px auto 0;max-width:600px">TypeError: Cannot read property 'getSheets' of null (line: 15, file: "denandroid")</div>
</body>
</html>
script code is :
function doGet(e) {
return ManageSheet(e);
}
function doPost(e) {
return ManageSheet(e);
}
function ManageSheet(e) {
//READ ALL RECORDS
if ( e.parameter.func == "ReadAll") {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheets()[0]; // Postman problem line.
var rg = sh.getDataRange().getValues();
var outString = '';
for(var row=0 ; row<rg.length ; ++row){
outString += rg[row].join(',') + '\n';
}
return ContentService.createTextOutput(outString).setMimeType(ContentService.MimeType.TEXT);
}
//DELETE SINGLE RECORD
else if (e.parameter.func == "Delete") {
var record = e.parameter.id;
var ss = SpreadsheetApp.getActive();
//var ss = SpreadsheetApp.openById(e.parameter.ID);
var sh = ss.getSheets()[0];
//var sh = ss.getSheetByName(e.parameter.SH);
sh.deleteRow(parseInt(record) + 1); //makes the correct row to delete (because of header row)
return ContentService.createTextOutput("Success, requested action completed");
}
}
postman says problem line in script code line 15. ( var sh = ss.getSheets()[0]; // Postman problem line)
Also I am using turkish language on google sheets. english name Sheet1 turkish language Sayfa1
I tried both names.
but unsuccess.
I am using this line for the connection spreadsheet.
https://script.google.com/macros/s/AKfycbyTt9oaz10WuKh0822hBncRoJZAw-D4hcGMwJwdy95l8H_mXfE/exec?ID=18NFZD7vZ-JySbbV7jiZMBpiBsoLJ4IQge9Wk9cL6Z4c&SH=Sheet1&func=ReadAll
Please help.
Thanks
Problem solved. The problem is the sharing problem. When sharing, it should be (Anyone, even anonymous). google always wanted me to sign in. When sharing (script code file) must be, In the 1st window, (me and gmail address) should be selected. (Anyone, even anonymous) should be selected in the 2nd window. sheet name not problem
The top and left properties in windows.create does not position the window. It is always positioned in center.
Two questions:
I can add a procedure to position the window after it is open by using browser.windows.update() but was wondering why it does not work as it is.
I would like to have it non-modal. Is this possible? I notice the popup returned has alwaysOnTop: false, but it is always on top. I am porting an old Chrome project - in Chrome the window is not modal.
On a side note: There also seems to be some inconsistency related to the popup returned from the create call.
type is "popup" when using both popup and panel.
left and top are sometimes 0 and other times has the actual value. Seems like when using popup as type the position is more often 0.
Example:
manfiest.json:
{
"name" : "Test winpos",
"short_name" : "ext_name_short",
"version" : "0.0.0.1",
"author" : "NW",
"manifest_version" : 2,
"browser_action" : {
"default_title" : "Test winpos"
},
"background" : {
"scripts" : ["./bg.js"]
}
}
bg.js:
"use strict";
var dbg = 1;
var popup_id = -1;
// normal, popup, panel, detatched_panel
var type = "panel";
browser.windows.onRemoved.addListener(function(w_id) {
if (dbg) console.log(';; onRemoved, (w_id, popup_id):', w_id, popup_id);
if (w_id === popup_id)
popup_id = -1;
});
browser.browserAction.onClicked.addListener(function (/* tab */) {
if (dbg) console.log(';; onClicked, (popup_id):', popup_id);
if (popup_id < 0) {
browser.windows.create({
allowScriptsToClose: true, // FF Only
url : browser.extension.getURL("popup.html"),
type : type,
// FF NOT SUPPORTED focused : true,
width : 450,
height : 320,
left : 50,
top : 50
}, function (pop) {
if (dbg) console.log(`;; windows.create-> ${type}:`, pop);
popup_id = pop.id;
// I can add positioning call here
});
} else {
if (dbg) console.log(';; window.update, (pupup_id)', popup_id);
browser.windows.update(popup_id, { "focused": true });
}
});
popup.html:
<!DOCTYPE html>
<html lang="en-US" dir="ltr">
<head>
<meta charset="utf-8">
<title>Test FF Popup</title>
</head>
<body>
<p>Hello</p>
</body>
</html>
I'm trying to get recapatcha v2 working in my ASP MVC project. The client's computers have IE10/IE11 and shows all intranet pages in compatibility view which causes the recaptcha not to show as it is intended.
The problem is it rarely accepts my answer even though it's right. It just shows a new image, but every once in awhile I get it right. Anyone else experience this?
If you enable compability view for google.com in IE and visit the demo site you can try it out.
reCAPTCHA requires that compatibility view is not enabled in order to work, see:
https://support.google.com/recaptcha/?hl=en-GB#6223838
You are seeing reCaptcha's fallback. It seems that you have to get two correct answers in a row. It then gives you a response code that you copy and paste into a <textarea> element.
So what you are possibly experiencing is that you aren't getting two consecutive reCaptchas correct.
You can test the fallback recaptcha by adding the fallback=true parameter to the JavaScript resource:
<script src="https://www.google.com/recaptcha/api.js?fallback=true" async defer></script>
As explained by #Coulton recaptcha does not support IE compatibility mode.
reCaptcha uses a function in javascript named querySelectorAll, and querySelector. IE 11 in compatibility mode renders as IE 7.0, and IE 7.0 and below don't seem to have the functions querySelectorAll and querySelector and that is why it fails.
Now, I am using .net webforms so you may have to adapt it a little for MVC, but here it is:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="reCaptcha.aspx.cs" Inherits="reCaptcha" %>
<!DOCTYPE html>
<script type="text/javascript">
// this defines these functions if they don't exist.
if (!document.querySelectorAll) {
document.querySelectorAll = function (selectors) {
var style = document.createElement('style'), elements = [], element;
document.documentElement.firstChild.appendChild(style);
document._qsa = [];
style.styleSheet.cssText = selectors +
'{x-qsa:expression(document._qsa && document._qsa.push(this))}';
window.scrollBy(0, 0);
style.parentNode.removeChild(style);
while (document._qsa.length) {
element = document._qsa.shift();
element.style.removeAttribute('x-qsa');
elements.push(element);
}
document._qsa = null;
return elements;
};
}
if (!document.querySelector) {
document.querySelector = function (selectors) {
var elements = document.querySelectorAll(selectors);
return (elements.length) ? elements[0] : null;
};
}
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.js' type="text/javascript"></script>
<script src='https://www.google.com/recaptcha/api.js' type="text/javascript"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js' type="text/javascript"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>reCaptcha Test</title>
</head>
<body>
<h1>reCaptcha Test</h1>
<form id="frmResult" runat="server">
<div class="g-recaptcha" data-sitekey=""></div>
<script type="text/javascript">
function IeVersion() {
//Set defaults
var value = {
IsIE: false,
TrueVersion: 0,
ActingVersion: 0,
CompatibilityMode: false
};
//Try to find the Trident version number
var trident = navigator.userAgent.match(/Trident\/(\d+)/);
if (trident) {
value.IsIE = true;
//Convert from the Trident version number to the IE version number
value.TrueVersion = parseInt(trident[1], 10) + 4;
}
//Try to find the MSIE number
var msie = navigator.userAgent.match(/MSIE (\d+)/);
if (msie) {
value.IsIE = true;
//Find the IE version number from the user agent string
value.ActingVersion = parseInt(msie[1]);
} else {
//Must be IE 11 in "edge" mode
value.ActingVersion = value.TrueVersion;
}
//If we have both a Trident and MSIE version number, see if they're different
if (value.IsIE && value.TrueVersion > 0 && value.ActingVersion > 0) {
//In compatibility mode if the trident number doesn't match up with the MSIE number
value.CompatibilityMode = value.TrueVersion != value.ActingVersion;
}
return value;
}
var ie = IeVersion();
var reCaptchaApi = "";
$(document).ready(function () {
$('.g-recaptcha').each(function (index, obj) {
grecaptcha.render(obj, { 'sitekey': reCaptchaApi });
});
if (ie.CompatibilityMode) {
// loading it twice makes it load in compatibility mode.
$('.g-recaptcha').each(function (index, obj) {
grecaptcha.render(obj, { 'sitekey': reCaptchaApi });
});
}
});
</script>
</form>
</body>
</html>
This allows reCaptcha V-2 to load in compatibility mode.
I'm tinkering with the code from the Angular Dart tutorial to make use of the Tooltip class. Rather than have the text for the tooltip in the Dart file, I want to place it in the html file. I've tried
dom.Element footnote;
footnote = querySelector("#fn1");
htext = footnote.innerhtml;
This code is in the Tooltip class. I get warnings on the last two lines and the Dart doesn't run nor does it throw an error. How do I retrieve HTML from the main html file (i.e., not from a component html file)?
The original code is from the angular dart website tutorial, chapter four. The unchanged code doesn't build cleanly, but it doesn't appear to affect it operation. This is a known bug for which there is an open issue.
pub build output
[Info from Dart2JS]:
Compiling tutorial|web/main.dart...
[Dart2JS on tutorial|web/main.dart]:
1 warning(s) suppressed in package:tutorial.
[Info from Dart2JS]:
Took 0:00:11.779928 to compile tutorial|web/main.dart.
Built 182 files to "build".
This output is with the last line commented out
tooltip.dart
library tooltip;
import 'dart:html' as dom;
import 'package:angular/angular.dart';
#Decorator(selector: '[tooltip]')
class Tooltip
{
final dom.Element element;
#NgOneWay('tooltip')
TooltipModel displayModel;
dom.Element tooltipElem;
dom.Element footnote;
Tooltip(this.element)
{
element..onMouseEnter.listen((_) => _createTemplate())
..onMouseLeave.listen((_) => _destroyTemplate());
}
void _createTemplate()
{
assert(displayModel != null);
tooltipElem = new dom.DivElement();
footnote = querySelector("#fn1");
htext = footnote.innerhtml;
if (displayModel.text != null)
{
dom.DivElement textSpan = new dom.DivElement()
..appendHtml(displayModel.text)
..style.color = "white"
..style.fontSize = "smaller"
..style.paddingBottom = "5px";
tooltipElem.append(textSpan);
}
tooltipElem.style
..padding = "5px"
..paddingBottom = "0px"
..backgroundColor = "black"
..borderRadius = "5px"
..width = "${displayModel.imgWidth.toString()}px";
// position the tooltip.
var elTopRight = element.offset.topRight;
tooltipElem.style
..position = "absolute"
..top = "${elTopRight.y}px"
..left = "${elTopRight.x + 10}px";
// Add the tooltip to the document body. We add it here because we need to position it
// absolutely, without reference to its parent element.
dom.document.body.append(tooltipElem);
}
void _destroyTemplate()
{
tooltipElem.remove();
}
}
class TooltipModel
{
final String text;
final int imgWidth;
TooltipModel(this.text, this.imgWidth);
}
As you can see, I'm not using the html yet. I'm trying to get it to work one step at a time.
index.html
<!DOCTYPE html>
<html ng-app>
<head>
<title>Chapter Four - A Simple Recipe Book</title>
<link rel="stylesheet" href="style.css">
<script src="packages/web_components/webcomponents.js"></script>
<script src="packages/web_components/dart_support.js"></script>
</head>
<body>
<recipe-book></recipe-book>
<div id="fn1">
<h2>Citation</h2>
<p>source specification</p>
<p>additional information</p>
</div>
<script type="application/dart" src="main.dart"></script>
<script type="text/javascript" src="packages/browser/dart.js"></script>
</body>
</html>
I added the div with the id fn1.
Answer
To summarize Günter Zöchbauer answers, I made the following changes to get it to work:
footnote = dom.querySelector("#fn1");
String htext = footnote.innerHtml;
You have import 'dart:html' as dom; which means that querySelector (without qualifier) can't be found or is used from another unqualified import if found.
With
footnode = dom.querySelector("#fn1");
// or
footnode = dom.document.querySelector("#fn1");
the whole document is searched except the content of shadow DOMs. If you want to search the shadow DOMs too you can use
footnote = dom.document.querySelector("* /deep/ #fn1");
or
footnote = dom.document.querySelector("* >>> #fn1");
The 2nd version is the newest but I don't know which browsers or polyfills support it yet.