Require json file dynamically in react-native (from thousands of files) - ios

I googled so far and tried to find out the solution but not yet.
I know require() works only with static path, so I want alternative ways to solve my problem. I found this answer here but it doesnt make sense for thousands of resources.
Please advise me the best approach to handle such case.
Background
I have thousand of json files that containing app data, and declared all the file path dynamically like below:
export var SRC_PATH = {
bible_version_inv: {
"kjv-ot": "data/bibles/Bible_KJV_OT_%s.txt",
"kjv-nt": "data/bibles/Bible_KJV_NT_%s.txt",
"lct-ot": "data/bibles/Bible_LCT_OT_%s.txt",
"lct-nt": "data/bibles/Bible_LCT_NT_%s.txt",
"leb": "data/bibles/leb_%s.txt",
"net": "data/bibles/net_%s.txt",
"bhs": "data/bibles/bhs_%s.txt",
"n1904": "data/bibles/na_%s.txt",
.....
"esv": "data/bibles/esv_%s.txt",
.....
},
....
As you can see, file path contains '%s' and that should be replace with right string depends on what the user selected.
For example if user select the bible (abbreviation: "kjv-ot") and the chapter 1 then the file named "data/bibles/Bible_KJV_OT_01.txt" should be imported.
I'm not good enough in react-native, just wondering if there is other alternative way to handle those thousands of resource files and require only one at a time by dynamically following the user's selection.
Any suggestions please.

Instead of exporting a flat file, you could export a function that took a parameter which would help build out the paths like this:
// fileInclude.js
export const generateSourcePath = (sub) => {
return {
bible_version_inv: {
"kjv-ot": `data/bibles/Bible_KJV_OT_${sub}.txt`
}
}
}
//usingFile.js
const generation = require('./fileInclude.js');
const myFile = generation.generateSourcePath('mySub');
const requiredFile = require(myFile);
then you would import (or require) this item into your project, execute generateSourcePath('mysub') to get all your paths.

Related

ImageJ/Fiji - Save CSV using macro

I am not a coder but trying to turn ThunderSTORM's batch process into an automated one where I have a single input folder and a single output folder.
input_directory = newArray("C:\\Users\\me\\Desktop\\Images");
output_directory = ("C:\\Users\\me\\Desktop\\Results");
for(i = 0; i < input_directory.length; i++) {
open(input_directory[i]);
originalName = getTitle();
originalNameWithoutExt = replace( originalName , ".tif" , "" );
fileName = originalNameWithoutExt;
run("Run analysis", "filter=[Wavelet filter (B-Spline)] scale=2.0 order=3 detector "+
"detector=[Local maximum] connectivity=8-neighbourhood threshold=std(Wave.F1) "+
"estimator=[PSF: Integrated Gaussian] sigma=1.6 method=[Weighted Least squares] fitradius=3 mfaenabled=false "+
"renderer=[Averaged shifted histograms] magnification=5.0 colorizez=true shifts=2 "+
"repaint=50 threed=false");
saveAs(fileName+"_Results", output_directory);
}
This probably looks like a huge mess but the original batch file used arrays and I can't figure out what that is. Taking it out brakes it so I left it in. The main issues I have revolve around the saveAs part not working.
Using run("Export Results") works but I need to manually pick a location and file name. I tried to set this up to take the file name and rename it to the generic image name so it can save a CSV using that name.
Any help pointing out why I'm a moron? I would also love to only open one file at a time (this opens them all) and close it when the analysis is complete. But I will settle for that happening on a different day if I can just manage to save the damn CSV automatically.
For the most part, I broke the code a whole bunch of times but it's in a working condition like this.
I appreciate any and all help. Thank you!

TYPO3 - Retrieved TypoScript in itemsProcFunc are incomplete

I have following problem:
We are overriding the tt_content TCA with a custom column which has an itemsProcFunc in it's config. In the function we try to retrieve the TypoScript-Settings, so we can display the items dynamically. The problem is: In the function we don't receive all the TypoScript-Settings, which are included but only some.
'itemsProcFunc' => 'Vendor\Ext\Backend\Hooks\TcaHook->addFields',
class TcaHook
{
public function addFields($config){
$objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Extbase\\Object\\ObjectManager');
$configurationManager = $objectManager->get('TYPO3\\CMS\\Extbase\\Configuration\\ConfigurationManagerInterface');
$setup = $configurationManager->getConfiguration(
\TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT
);
}
$setup is now incomplete and doesn't contain the full TypoScript, for example some of the static-included TypoScript is missing.
Used TYPO3 7 LTS (7.6.18), PHP 7.0.* in composer-mode.
Does anybody know where the problem is? Is there some alternative?
You maybe misunderstood the purpose of TypoScipt. It is a way of configuration for the Frontend. The Hook you mentioned is used in the TCA, whích is a Backend part of TYPO3. TypoScript usually isn't used for backend related stuff at all, because it is bound to a specific page template record. Instead in the backend, there is the TSConfig, that can be bound to a page, but also can be added globally. Another thing you are doing wrong is the use of the ObjectManager and the ConfigurationManager, which are classes of extbase, which isn't initialized in the backend. I would recommend to not use extbase in TCA, because the TCA is cached and loaded for every page request. Instead use TSConfig or give your configuration settings directly to the TCA. Do not initialize extbase and do not use extbase classes in these hooks.
Depending on what you want to configure via TypoScript, you may want to do something like this:
'config' => [
'type' => 'select',
'renderType' => 'singleSelect',
'items' => [
['EXT:my_ext/Resources/Private/Language/locallang_db.xlf:myfield.I.0', '']
],
'itemsProcFunc' => \VENDOR\MyExt\UserFunctions\FormEngine\TypeSelectProcFunc::class . '->fillSelect',
'customSetting' => 'somesetting'
]
and then access it in your class:
class TypeSelectProcFunc{
public function fillSelect(&$params){
if( $params['customSetting'] === 'somesetting' ){
$params['items'][] = ['New item',1];
}
}
}
I had a similar problem (also with itemsProcFunc and retrieving TypoScript). In my case, the current page ID of the selected backend page was not known to the ConfigurationManager. Because of this it used the page id of the root page (e.g. 1) and some TypoScript templates were not loaded.
However, before we look at the solution, Euli made some good points in his answer:
Do not use extbase configuration manager in TCA functions
Use TSconfig instead of TypoScript for backend configuration
You may like to ask another question what you are trying to do specifically and why you need TypoScript in BE context.
For completeness sake, I tested this workaround, but I wouldn't recommend it because of the mentioned reasons and because I am not sure if this is best practice. (I only used it because I was patching an extension which was already using TypoScript in the TCA and I wanted to find out why it wasn't working. I will probably rework this part entirely.)
I am posting this in the hope that it may be helpful for similar problems.
public function populateItemsProcFunc(array &$config): array
{
// workaround to set current page id for BackendConfigurationManager
$_GET['id'] = $this->getPageId((int)($config['flexParentDatabaseRow']['pid'] ?? 0));
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$configurationManager = $objectManager->get(BackendConfigurationManager::class);
$setting = $configurationManager->getTypoScriptSetup();
$templates = $setting['plugin.']['tx_rssdisplay.']['settings.']['templates.'] ?? [];
// ... some code removed
}
protected function getPageId(int $pid): int
{
if ($pid > 0) {
return $pid;
}
$row = BackendUtility::getRecord('tt_content', abs($pid), 'uid,pid');
return $row['pid'];
}
The function getPageId() was derived from ext:news which also uses this in an itemsProcFunc but it then retrieves configuration from TSconfig. You may want to also look at that for an example: ext:news GeorgRinger\News\Hooks\ItemsProcFunc::user_templateLayout
If you look at the code in the TYPO3 core, it will try to get the current page id from
(int)GeneralUtility::_GP('id');
https://github.com/TYPO3/TYPO3.CMS/blob/90fa470e37d013769648a17a266eb3072dea4f56/typo3/sysext/extbase/Classes/Configuration/BackendConfigurationManager.php#L132
This will usually be set, but in an itemsProcFunc it may not (which was the case for me in TYPO3 10.4.14).

Save spreadsheet in a Specific Folder of GDrive

I need help with this Google AdWords script: https://developers.google.com/adwords/scripts/docs/solutions/keyword-performance.
Every time I run this script in Google AdWords account (for my PPC campaign), it creates report (spreadsheet) and save it on my google drive.
I would like to save spreadsheet file to specific subfolder on my google drive (for example Report/Campaign01). I found the article which describes how to save spreadsheet to specific folder. But I don't know how edit this script and use it. Article describing this function is here:
http://www.freeadwordsscripts.com/2014/07/save-file-or-spreadsheet-in-specific.html
Can you help me solve the problem?
Assuming your folder and file names are unique, use can save to a folder this way
function myFunction() {
var folderIterator = DriveApp.getFoldersByName("YOUR_FOLDER_NAME");
while ( folderIterator.hasNext() ) {
var folder = folderIterator.next();
folder_count++;
var spreadsheet = SpreadsheetApp.create("YOUR_SPREADSHEET_NAME");
// INSERT YOUR SPREADSHEET LOGIC HERE.
// YOU CAN CREATE YOUR SHEET HOWEVER YOU WANT,
// SO LONG AS YOU HAVE YOUR ACTIVE SPREADSHEET OBJECT.
// EITHER WAY, IT WILL SAVE TO YOUR ROOT DIRECTORY.
// THIS LOGIC MOVES YOUR FILE BY ID FROM ROOT TO YOUR SELECTED FOLDER.
var files = DriveApp.getRootFolder().getFilesByName("YOUR_SPREADSHEET_NAME");
while ( files.hasNext() ) {
var file = files.next();
if ( spreadsheet.getId() == file.getId() ) {
Logger.log("Found File! Moving...");
folder.addFile(file);
DriveApp.getRootFolder().removeFile(file);
} else {
Logger.log("Wrong File, id[%s]" , file.getId());
}
}
}
}

"Temp" directory in Windows, IO.getFile

I would like to write to the C:\windows\temp directory (or it's configured equivalent) inside my Firefox-addon.
https://developer.mozilla.org/en/FileGuide/FileWriting
Gives the impression that there are system independent names for these paths:
var file = IO.getFile("Desktop", "myinfo.txt");
var stream = IO.newOutputStream(file, "text");
stream.writeString("This is some text");
stream.close();
But I can't find any reference in the specified references, as to what "Desktop" points to. So that leaves me not knowing what exactly is referred to in the names given by the documentation.
How to I use IO.getFile() to open a file in the windows global temp folder?
See also Code snippets: File I/O on developer.mozilla.org. It answers your question (Matthew is right, it's "TmpD"), and provides many other file-related examples.
[edit] Oh, and does IO actually work for you? I thought it was unavailable. [edit2] I added a warning at the top of the pages I could find, that mention it.
The keys are described here.
I believe you want TmpD, which is listed here
// Writing stackoverflow.txt to TEMP dir
const { OS } = Cu.import("resource://gre/modules/osfile.jsm", {})
const path = OS.Path.join(OS.Constants.Path.tmpDir, "stackoverflow.txt")
OS.File.writeAtomic(path, "Hello, StackOverflow!", {
encoding: "utf-8",
tmpPath: "stackoverflow.txt.tmp", // it's not necessary but I'd recommend to use it
}).then(() => console.log(path, "has been written"))
// C:\Users\traxium\AppData\Local\Temp\stackoverflow.txt has been written
// Reading stackoverflow.txt from TEMP dir
const { OS } = Cu.import("resource://gre/modules/osfile.jsm", {})
const path = OS.Path.join(OS.Constants.Path.tmpDir, "stackoverflow.txt")
OS.File.read(path, { encoding: "utf-8" }).then(txt => console.log(txt))
// "Hello, StackOverflow!"

Printing in icefaces

I would like to print reports in icefaces, but could got find any proper method for it. Please guide me for implementation of the same in my project.
I've used the ice:outputResource tag to let the user download a PDF report file. The resource attribute of that tag should point a managed bean property that implements com.icesoft.faces.context.Resource.
after getting idea from JOTN I'm finally able to put it together.
We can use the outputresource tag to link to any type of resource, not only static ones but also dynamically generated files(on the fly).
Let us have a look at the following example:
JSF Page:
..
..
<ice:outputResource id="outputResource1" attachment="false" fileName="File1.pdf" label="Click to download attachment" mimeType="application/pdf" rendered="true" resource="#{ReportParam01.reportfilers}" shared="false"/>
..
..
Here I've observed that the outputresource link won't appear until the file is actually generated(i case of on the fly documents).
Let us assume we wish to generate a pdf file dynamically. The following steps will link it to the above mentioned outputrespurce.
Managed Bean:
public class....{
....
// This is the resource linked to the <ice:outputresource> tag.
// Encapsulation has been done to link it.
Reource reportfilers;
....
public void createDocument() {
Document reportDoc = new Document(PageSize.A4);
File file1 = new File("Report.pdf");
PdfWriter.getInstance(reportDoc, new FileOutputStream(f));
// writing to pdf code continues
reportfilers = new FileResource(file1);
}
....
....
}
Calling the above method (if it has no exceptions) will make the link to show up and the user can download the file.

Resources