How do you append text in CodeMirror - codemirror

I know you use
editor.setValue("");
to set one value but how do you append in CodeMirror?
IE:
editor.appendText();?

Use replaceRange. For example editor.replaceRange(myString, CodeMirror.Pos(editor.lastLine())). Re-setting the entire editor is needlessly expensive.

Here is a little script I wrote to add code to any editor (in Joomla):
function addCodeToEditor(code_string, editor_id, merge, merge_target){
if (Joomla.editors.instances.hasOwnProperty(editor_id)) {
var old_code_string = Joomla.editors.instances[editor_id].getValue();
if (merge && old_code_string.length > 0) {
// make sure not to load the same string twice
if (old_code_string.indexOf(code_string) == -1) {
if ('prepend' === merge_target) {
var _string = code_string + "\n\n" + old_code_string;
} else if (merge_target && 'append' !== merge_target) {
var old_code_array = old_code_string.split(merge_target);
if (old_code_array.length > 1) {
var _string = old_code_array.shift() + "\n\n" + code_string + "\n\n" + merge_target + old_code_array.join(merge_target);
} else {
var _string = code_string + "\n\n" + merge_target + old_code_array.join('');
}
} else {
var _string = old_code_string + "\n\n" + code_string;
}
Joomla.editors.instances[editor_id].setValue(_string.trim());
return true;
}
} else {
Joomla.editors.instances[editor_id].setValue(code_string.trim());
return true;
}
} else {
var old_code_string = jQuery('textarea#'+editor_id).val();
if (merge && old_code_string.length > 0) {
// make sure not to load the same string twice
if (old_code_string.indexOf(code_string) == -1) {
if ('prepend' === merge_target) {
var _string = code_string + "\n\n" + old_code_string;
} else if (merge_target && 'append' !== merge_target) {
var old_code_array = old_code_string.split(merge_target);
if (old_code_array.length > 1) {
var _string = old_code_array.shift() + "\n\n" + code_string + "\n\n" + merge_target + old_code_array.join(merge_target);
} else {
var _string = code_string + "\n\n" + merge_target + old_code_array.join('');
}
} else {
var _string = old_code_string + "\n\n" + code_string;
}
jQuery('textarea#'+editor_id).val(_string.trim());
return true;
}
} else {
jQuery('textarea#'+editor_id).val(code_string.trim());
return true;
}
}
return false;
}
The advantage it this script is you can work with multiple editors on the page.

Related

LootLocker - How to show local rank

In my game, I am able to show the GlobalRank, however, I would also like to show the position of a player in Ranking according to the global results.
So in the bottom line, there should be the local (on this device) results.
Basically, on the left bottom corner, I want to get the RANK from the LootLocker, but I am struggling to get the rank...
IEnumerator ShowScores()
{
yield return new WaitForSeconds(2);
LootLockerSDKManager.GetScoreList(ID, maxScores, (response) =>
{
if (response.success)
{
LootLockerLeaderboardMember[] scores = response.items;
for (int i = 0; i < scores.Length; i++)
{
playerNames[i].text = (scores[i].member_id +"");
playerScores[i].text = (scores[i].score +"");
playerRank[i].text = (scores[i].rank + "");
//Rank of the localPlayer
Rank.text = (scores["here_Should_Be_This_Player_ID"].rank + "");
LootLockerSDKManager.GetPlayerName
// Entries[i].text = (scores[i].rank + ". " + scores[i].score + ". " + scores[i].member_id);
}
if (scores.Length < maxScores)
{
for (int i = scores.Length; i < maxScores; i++)
{
// Entries[i].text = (i + 1).ToString() + ". none";
}
}
}
else
{
}
});
}
Fixed it with the LootLocker support team
Step 1 - load LootLocker and get the resonse
Step 2 - load the rank and get the resonse2
Step 3 - use the "Response2.rank from the LootLocker
Rank.text = (response2.rank + "");
string playerIdentifier = "PlayerNameRecordOnThisDevice";
LootLockerSDKManager.StartSession(playerIdentifier, (response) =>
{
if (response.success)
{
Debug.Log("session with LootLocker started");
}
else
{
Debug.Log("failed to start sessions" + response.Error);
}
LootLockerSDKManager.GetMemberRank(ID, playerIdentifier, (response2) =>
{
if (response2.statusCode == 200)
{
Debug.Log("GetMemberRank Successful");
}
else
{
Debug.Log("GetMemberRank failed: " + response2.Error);
}
Rank.text = (response2.rank + "");
});
}); ```

Firebase fetch inside for loop not working properly

In my project, I took data from the android accessibility stream in a headless background function turned them into an array and split them into chunks for firebase limits, and used a for loop to iterate over them and check in firebase. Sometimes this is not working, especially since I can see the associability service runner but showing data from a bit ago. I think this happens when the user is offline and tried to fetch data from firebase. Can you please have a look at this code and tell me what the issue is and How I should solve it?
N.B: I changed some variable names for privacy purposes. There are no issues with them.
FlutterAccessibilityService.accessStream.listen((event) {
if (event.capturedText != null &&
event.capturedText != "" &&
isCold) {
text = event.capturedText!.toLowerCase();
List textList = getArray(text);
final sharedItems = getSimilarArray(fbtag, textList, sensitivity);
final sharedLocalItems =
getSimilarLocalArray(fbtag, textList, sensitivity);
final sharedAbsItems = getAbsLocalArray(fbtag, textList);
final sharedItemWithLastEval =
getSimilarArray(lastEvaluatedText, textList, sensitivity);
if (text != lastEventText &&
(sharedItemWithLastEval.length == 0 ||
lastEvaluatedText[0] == "first")) {
print("called related content");
print("bg currant text: " +
text.toString() +
" sensitivity: " +
sensitivity.toString() +
" minimumAbsMatch: " +
minimumAbsMatch.toString() +
" shared local items: " +
sharedLocalItems.toString() +
" shared abs items: " +
sharedAbsItems.toString() +
" shared items: " +
sharedItems.toString() +
" last : " +
lastEventText +
" last eval text: " +
lastEvaluatedText.toString() +
" Cold: " +
isCold.toString());
print("captured text: " + text.toString());
//GetRelatedContent(fbtag, event.capturedText);
print(sharedItems);
if (sharedLocalItems.length >= accuracy &&
sharedAbsItems.length >= minimumAbsMatch) {
print("main called");
List result = [];
lastEvaluatedText = sharedItems;
List chunkedList = chunking(sharedItems);
for (int i = 0; i < chunkedList.length; i++) {
FirebaseFirestore.instance
.collection('Content')
.where('keyWords', arrayContainsAny: chunkedList[i])
.get()
.then((value) {
for (int i = 0; i < value.docs.length; i++) {
result.add(value.docs[i].data());
print("sep");
print("result: " + result.toString());
}
if (i == chunkedList.length - 1) {
if (result.isNotEmpty) {
print("final result: " +
result[HighestMatchingIndex(sharedItems, result)[0]]
.toString());
print('result length called' +
' result: ' +
result.toString());
if (HighestMatchingIndex(sharedItems, result)[1] >=
accuracy) {
print('overlay called');
isCold = false;
Timer(Duration(seconds: 60), () {
print("Cold down");
isCold = true;
});
var FinalResult = result[
HighestMatchingIndex(sharedItems, result)[0]];
if (FinalResult['availableCountry']
.contains(country) &&
FinalResult['availableR']
.contains(r)) {
print("all passed");
String l = FinalResult[r]
[country] ??
FinalResult[r]['EN'];
String o =
FinalResult[r]['origin'];
ShowAlert(l, o, r);
}
}
}
}
});
}
}
//
}
lastEventText = text;
}
});

when I pushed the phone button to back previous page in Unity webviewScript

using System.Collections;
using UnityEngine;
using System;
using System.Collections.Generic;
public class SampleWebView : MonoBehaviour
{
public string Url;
public GUIText status;
WebViewObject webViewObject;
IEnumerator Start()
{
webViewObject = (new GameObject("WebViewObject")).AddComponent<WebViewObject>();
webViewObject.Init(
cb: (msg) =>
{
Debug.Log(string.Format("CallFromJS[{0}]", msg));
status.text = msg;
status.GetComponent<Animation>().Play();
},
err: (msg) =>
{
Debug.Log(string.Format("CallOnError[{0}]", msg));
status.text = msg;
status.GetComponent<Animation>().Play();
},
started: (msg) =>
{
Debug.Log(string.Format("CallOnStarted[{0}]", msg));
},
ld: (msg) =>
{
Debug.Log(string.Format("CallOnLoaded[{0}]", msg));
#if UNITY_EDITOR_OSX || !UNITY_ANDROID
// NOTE: depending on the situation, you might prefer
// the 'iframe' approach.
// cf. https://github.com/gree/unity-webview/issues/189
#if true
webViewObject.EvaluateJS(#"
if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
window.Unity = {
call: function(msg) {
window.webkit.messageHandlers.unityControl.postMessage(msg);
}
}
} else {
window.Unity = {
call: function(msg) {
window.location = 'unity:' + msg;
}
}
}
");
#else
webViewObject.EvaluateJS(#"
if (window && window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.unityControl) {
window.Unity = {
call: function(msg) {
window.webkit.messageHandlers.unityControl.postMessage(msg);
}
}
} else {
window.Unity = {
call: function(msg) {
var iframe = document.createElement('IFRAME');
iframe.setAttribute('src', 'unity:' + msg);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
}
}
");
#endif
#endif
webViewObject.EvaluateJS(#"Unity.call('ua=' + navigator.userAgent)");
},
//ua: "custom user agent string",
enableWKWebView: true);
#if UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
webViewObject.bitmapRefreshCycle = 1;
#endif
webViewObject.SetMargins(10, 140, 10, Screen.height / 360);
webViewObject.SetVisibility(true);
#if !UNITY_WEBPLAYER
if (Url.StartsWith("http")) {
webViewObject.LoadURL(Url.Replace(" ", "%20"));
} else {
var exts = new string[]{
".jpg",
".js",
".html" // should be last
};
foreach (var ext in exts) {
var url = Url.Replace(".html", ext);
var src = System.IO.Path.Combine(Application.streamingAssetsPath, url);
var dst = System.IO.Path.Combine(Application.persistentDataPath, url);
byte[] result = null;
if (src.Contains("://")) { // for Android
var www = new WWW(src);
yield return www;
result = www.bytes;
} else {
result = System.IO.File.ReadAllBytes(src);
}
System.IO.File.WriteAllBytes(dst, result);
if (ext == ".html") {
webViewObject.LoadURL("file://" + dst.Replace(" ", "%20"));
break;
}
}
}
#else
if (Url.StartsWith("http")) {
webViewObject.LoadURL(Url.Replace(" ", "%20"));
} else {
webViewObject.LoadURL("StreamingAssets/" + Url.Replace(" ", "%20"));
}
webViewObject.EvaluateJS(
"parent.$(function() {" +
" window.Unity = {" +
" call:function(msg) {" +
" parent.unityWebView.sendMessage('WebViewObject', msg)" +
" }" +
" };" +
"});");
#endif
yield break;
}
#if !UNITY_WEBPLAYER
//void OnGUI()
//{
// GUI.enabled = webViewObject.CanGoBack();
// if (GUI.Button(new Rect(10, 10, 80, 80), "<")) {
// webViewObject.GoBack();
// }
// GUI.enabled = true;
// GUI.enabled = webViewObject.CanGoForward();
// if (GUI.Button(new Rect(100, 10, 80, 80), ">")) {
// webViewObject.GoForward();
// }
// GUI.enabled = true;
// GUI.TextField(new Rect(200, 10, 300, 80), "" + webViewObject.Progress());
//}
#endif
This is my webview Scirpt for my newspaper App in C#. I need code, when I pushed the phone button to go back previous page in the newspaper.
I tried,
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
However it quits from the app. It does not go back previous page in the newspaper..
Thank you for your help...
if i understand it correctly you should be good if you replace
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
by this:
if(Input.GetKeyDown(KeyCode.Escape))
{
webViewObject.GoBack();
}
According to the example you are using from here https://github.com/gree/unity-webview/blob/master/sample/Assets/Scripts/SampleWebView.cs this is the build in back function. You can see it in the commented out part in your code.

How to pass parameters to a MobileFirst HTTP adapter

I need to run an HTTP adapter to access a SOAP WSDL service. It has 2 fields userid and password.
I have auto generated the adapter by discover backend services. Can anyone guide me to how to pass values from adapter initially to access the service?
function userlogin_ep_process(params, headers){
var soapEnvNS = '';
soapEnvNS = 'http://schemas.xmlsoap.org/soap/envelope/';
var mappings = {
roots: {
'process': { nsPrefix: 'client', type: 'client:process' }
},
types: {
'client:process': {
children: [
{'username': { nsPrefix: 'client' }},
{'userpwd': { nsPrefix: 'client' }}
]
}
}
};
var namespaces = 'xmlns:client="http://xmlns.oracle.com/InternetMobile/AbsManagement/BPELProcessUserLogin" xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype" ';
var request = buildBody(params, namespaces, mappings, soapEnvNS);
var soapAction = 'process';
return invokeWebService(request, headers, soapAction);
}
function buildBody(params, namespaces, mappings, soapEnvNS){
var body =
'<soap:Envelope xmlns:soap="' + soapEnvNS + '">\n' +
'<soap:Body>\n';
var fixedParams = {};
for (var paramName in params) {
if (mappings['roots'][paramName]) { //There is mapping for this param
var root = mappings['roots'][paramName];
var name = paramName;
if (root['nsPrefix'])
name = root['nsPrefix'] + ':' + paramName;
fixedParams[name] = handleMappings(params[paramName], root['type'], mappings['types']);
}
else {
fixedParams[paramName] = params[paramName];
}
}
body = jsonToXml(fixedParams, body, namespaces);
body +=
'</soap:Body>\n' +
'</soap:Envelope>\n';
return body;
}
function handleMappings(jsonObj, type, mappings) {
var fixedObj = {};
var typeMap = mappings[type]['children']; //Get the object that defines the mappings for the specific type
// loop through the types and see if there is an input param defined
for(var i = 0; i < typeMap.length; i++) {
var childType = typeMap[i];
for(var key in childType) {
if(jsonObj[key] !== null) { // input param exists
var childName = key;
if (childType[key]['nsPrefix'])
childName = childType[key]['nsPrefix'] + ':' + key;
if (!childType[key]['type']) //Simple type element
fixedObj[childName] = jsonObj[key];
else if (typeof jsonObj[key] === 'object' && jsonObj[key].length != undefined) { //Array of complex type elements
fixedObj[childName] = [];
for (var i=0; i<jsonObj[key].length; i++)
fixedObj[childName][i] = handleMappings(jsonObj[key][i], childType[key]['type'], mappings);
}
else if (typeof jsonObj[key] === 'object') //Complex type element
fixedObj[childName] = handleMappings(jsonObj[key], childType[key]['type'], mappings);
else if (childType[key]['type'] == '#') //Attribute
fixedObj['#' + childName] = jsonObj[key];
}
}
}
return fixedObj;
}
function getAttributes(jsonObj) {
var attrStr = '';
for(var attr in jsonObj) {
if (attr.charAt(0) == '#') {
var val = jsonObj[attr];
attrStr += ' ' + attr.substring(1);
attrStr += '="' + xmlEscape(val) + '"';
}
}
return attrStr;
}
function jsonToXml(jsonObj, xmlStr, namespaces) {
var toAppend = '';
for(var attr in jsonObj) {
if (attr.charAt(0) != '#') {
var val = jsonObj[attr];
if (typeof val === 'object' && val.length != undefined) {
for(var i=0; i<val.length; i++) {
toAppend += "<" + attr + getAttributes(val[i]);
if (namespaces != null)
toAppend += ' ' + namespaces;
toAppend += ">\n";
toAppend = jsonToXml(val[i], toAppend);
toAppend += "</" + attr + ">\n";
}
}
else {
toAppend += "<" + attr;
if (typeof val === 'object') {
toAppend += getAttributes(val);
if (namespaces != null)
toAppend += ' ' + namespaces;
toAppend += ">\n";
toAppend = jsonToXml(val, toAppend);
}
else {
toAppend += ">" + xmlEscape(val);
}
toAppend += "</" + attr + ">\n";
}
}
}
return xmlStr += toAppend;
}
function invokeWebService(body, headers, soapAction){
var input = {
method : 'post',
returnedContentType : 'xml',
path : '/soa-infra/services/Mobile/AbsManagement/userlogin_ep',
body: {
content : body.toString(),
contentType : 'text/xml; charset=utf-8'
}
};
//Adding custom HTTP headers if they were provided as parameter to the procedure call
//Always add header for SOAP action
headers = headers || {};
if (soapAction != 'null')
headers.SOAPAction = soapAction;
input['headers'] = headers;
return WL.Server.invokeHttp(input);
}
function xmlEscape(obj) {
if(typeof obj !== 'string') {
return obj;
}
return obj.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, '&apos;')
.replace(/</g, '<')
.replace(/>/g, '>');
}
To invoke the adapter and pass the parameters you need to call WL.Client.invokeProcedure in your particular case you can use
var invocationData = {
adapter: 'YOUR_ADAPTER_NAME',
procedure: 'userlogin_ep_process',
parameters: {
process: {
username: 'YOUR_USERNAME',
userpwd: 'YOUR_PASSWORD'
}
}
};
WL.Client.invokeProcedure(invocationData, {
onSuccess: yourSuccessFunction,
onFailure: yourFailureFunction
});

Copy MongoDb indexes between databases

I am trying to copy mongo indexes between two environments. Checked the API and found no direct method of doing it. So I started writing a script that connects to one db, iterates over the collections, grabs indexes, mutates them (because getIndexes() and ensureIndex()) have different format), connects to the other db, wipes the indexes and copies the new ones in.
This all feels slightly over the top so I think that I must be missing something.
Any suggestions/good practices? Apart from having an index creation strategy.
Cheers!
Please run it on the database that you want to copy indexes.
db.getCollectionNames().forEach(function(collection) {
indexes = db[collection].getIndexes();
indexes.forEach(function (c) {
opt = ''
ixkey = JSON.stringify(c.key, null, 1).replace(/(\r\n|\n|\r)/gm,"")
ns = c.ns.substr(c.ns.indexOf(".") + 1, c.ns.length)
for (var key in c) {
if (key != 'key' && key != 'ns' && key != 'v') {
if (opt != '') { opt+= ','}
if (c.hasOwnProperty(key)) {
if (typeof(c[key]) == "string") {
opt += (key + ': "' + c[key] + '"')
} else {
opt+= (key + ": " + c[key])
}
}
}
}
if (opt != '') { opt = '{' + opt + '}'}
print ('db.' + ns + '.ensureIndex(' + ixkey + ','+ opt + ')')
})});
I've updated script of Adamo Tonete
db.getCollectionNames().forEach(function(col) {
var indexes = db[col].getIndexes();
indexes.forEach(function (c) {
var fields = '', result = '', options = {};
for (var i in c) {
if (i == 'key') {
fields = c[i];
} else if (i == 'name' && c[i] == '_id_') {
return;
} else if (i != 'name' && i != 'v' && i != 'ns') {
options[i] = c[i];
}
}
var fields = JSON.stringify(fields);
var options = JSON.stringify(options);
if (options == '{}') {
result = "db." + col + ".createIndex(" + fields + "); ";
} else {
result = "db." + col + ".createIndex(" + fields + ", " + options + "); ";
}
result = result
.replace(/{"floatApprox":-1,"top":-1,"bottom":-1}/ig, '-1')
.replace(/{"floatApprox":(-?\d+)}/ig, '$1')
.replace(/\{"\$numberLong":"(-?\d+)"\}/ig, '$1');
print(result);
});
});
Try with this script:
var i, c,
co_name, co_new,
co_old, co_old_i,
_db = db.getSiblingDB('logs'),
_colls = ['activity.games', 'activity.session', 'activity.social', 'activity.store'];
for (i in _colls){
co_name = _colls[i];
co_old = _db[co_name];
co_old_i = co_old.getIndexes();
if(co_old.count() > 0){
co_old.renameCollection(co_name + '.old');
_db.createCollection(co_name);
co_new = _db[co_name];
for(c in co_old_i){
co_new.ensureIndex(co_old_i[c].key);
}
}
}
https://gist.github.com/alejandrobernardis/8261327
Regards,
A
Here is a version to recreate them all with options, and with the new createIndex command instead of ensureIndex (since mongoDB 3.0). With that, it's very easy to copy (recreate) all indexes from one DB to another.
function createIndex2( coll, keys, options ) {
var ret = db[coll].createIndex(keys, options)
if (ret.createdCollectionAutomatically) print( "Collection " + coll + " was created")
if (ret.errmsg || (ret.note != "all indexes already exist" && ret.ok != 1)) {
ret.coll = coll
ret.keys = keys
ret.options = options
print(tojson(ret))
} else {
//print( "Everything normal", JSON.stringify(ret))
}
}
db.getCollectionInfos().forEach(function(coll) {
//print( JSON.stringify( coll ))
if (coll.type === "collection" ) {
db[coll.name].getIndexes().forEach(function(index) {
if ("_id_" !== index.name) {
//print( JSON.stringify( index ))
var indexKey = index.key // save the key, and transform index into the "options"
delete index.key
delete index.ns // namespace - not necessary
delete index.v // not necessary
index.background = true // optional: force background to be true
//native version: print("db." + coll.name + ".createIndex(" + JSON.stringify(indexKey) + ", " + JSON.stringify(index) + ")");
// this gives much more debug info
print("createIndex2(\"" + coll.name + "\", " + JSON.stringify(indexKey) + ", " + JSON.stringify(index) + ")");
}
});
}
});
The result looks like that if using the "native" version, otherwise, it will display only errors:
db.dishes.createIndex({"submenu":1},
{"name":"submenu_1","ns":"dishly.dishes","background":true})
db.dishes.createIndex({"loc":"2dsphere"},
{"name":"loc_2dsphere","ns":"dishly.dishes","2dsphereIndexVersion":3,"background":true})
db.dishes.createIndex({"rs":-1},
{"name":"rs_-1","ns":"dishly.dishes","partialFilterExpression":{"rs":{"$gte":3}},"background":true})
db.dishes.createIndex({"loc":"2d","type":1,"status":1,"FSid":1,"rs":-1},
{"name":"loc_2d_type_1_status_1_rs_-1","ns":"dishly.dishes","background":true,"partialFilterExpression":{"rs":{"$gte":2}}})
db.dishes.createIndex({"_fts":"text","_ftsx":1,"loc.0":1,"loc.1":1,"rs":-1},
{"name":"d2_menu_submenu_text__loc__rs","ns":"dishly.dishes","background":true,"weights":{"d2":1,"menu":1,"submenu":1},"default_language":"english","language_override":"language","textIndexVersion":3})