text
stringlengths
14
21.4M
Q: Gradle script won't download dependencies I want to add a library in Android Studio as dependency to use it in my project. I tried both adding the dependency via Module Settings menu and via direct input in build.gradle-file of the Module (s. snapshot). I also tried entering mavenCentral()-repository (snapshot) as described here. Building/synching the project with gradle is successful but org.apache.olingo lib never appears in log nor is added to my lib folder (or external libraries). Of course I already tried refreshing the project tree-view (w/o success). Why isn't the library downloaded (since I can search for the lib in the dependencies-add menu the internet access should be no barrier) and how could I fix this issue? (As you may have realized, I'm a newbie in this environment - any hint might help)
Q: Unable to use iOS framework which is internally using .xib file I am trying to make a universal framework, for iOS by following steps specified in this URL: Universal-framework-iOS I have a viewController class within, that framework which internally loads a .xib file. Below is a part of code which shows, how I am initializing that viewController and showing related view: /*** Part of implementation of SomeViewController class, which is outside the framework ***/ - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.viewControllerWithinFramework = [[ViewControllerWithinFramework alloc] initWithTitle:@"My custom view"]; } - (IBAction)showSomeView:(id)sender { [self.viewControllerWithinFramework showRelatedView]; } /*** Part of implementation of ViewControllerWithinFramework class, which is inside the framework ***/ - (id)initWithTitle:(NSString *)aTitle { self = [super initWithNibName:@"ViewControllerWithinFramework" bundle:nil]; // ViewControllerWithinFramework.xib is within the framework if (self) { _viewControllerTitle = aTitle; } return self; } While creating the framework, I included all .xib files, including ViewControllerWithinFramework.xib within its Copy Bundle Resources build phase. Now my problem is when I try to integrate that framework within other project, it crashes with below stack trace: Sample[3616:a0b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle </Users/miraaj/Library/Application Support/iPhone Simulator/7.0/Applications/78CB9BC5-0FCE-40FC-8BCB-721EBA031296/Sample.app> (loaded)' with name 'ViewControllerWithinFramework'' *** First throw call stack: ( 0 CoreFoundation 0x017365e4 __exceptionPreprocess + 180 1 libobjc.A.dylib 0x014b98b6 objc_exception_throw + 44 2 CoreFoundation 0x017363bb +[NSException raise:format:] + 139 3 UIKit 0x004cc65c -[UINib instantiateWithOwner:options:] + 951 4 UIKit 0x0033ec95 -[UIViewController _loadViewFromNibNamed:bundle:] + 280 5 UIKit 0x0033f43d -[UIViewController loadView] + 302 6 UIKit 0x0033f73e -[UIViewController loadViewIfRequired] + 78 7 UIKit 0x0033fc44 -[UIViewController view] + 35 Any ideas, how could I resolve this problem? Note: It works fine if there is no any xib within the framework. A: If you're using Universal-framework-iOS all resources (including Nibs and images), will be copied inside a separate bundle (folder) such as MyApp.app/Myframework.bundle/MyNib.nib. You need to specify this bundle by passing a NSBundle object instead of nil. Your can get your bundle object as follows: NSString *path = [[NSBundle mainBundle] pathForResource:@"Myframework" ofType:@"bundle"]; NSBundle *resourcesBundle = [NSBundle bundleWithPath:path]; As for images you can just prepend Myframework.bundle/ to their names: [UIImage imageNamed:@"Myframework.bundle/MyImage" This also works in Interface Builder. Finally your users to install/update a framework is a pain, specially with resources, so better try to use CocoaPods. A: Unfortunately because iOS does not have an exposed concept of dynamic fragment loading some of NSBundle's most useful functionality is a little hard to get to. What you want to do is register the framework bundle with NSBundle, and from then on you can find the bundle by it's identifier - and the system should be able to correctly find nibs, etc. within that bundle. Remember, a framework is just a kind of bundle. To make NSBundle "see" your bundle and it's meta information (from it's Info.plist), you have to get it to attempt to load the bundle. It will log an error because there will be no CFPlugin class assigned as a principal class, but it will work. So for example: NSArray *bundz = [[NSBundle bundleForClass:[self class]] URLsForResourcesWithExtension:@"framework" subdirectory:nil]; for (NSURL *bundleURL in bundz){ // This should force it to attempt to load. Don't worry if it says it can't find a class. NSBundle *child = [NSBundle bundleWithURL:bundleURL]; [child load]; } Once that is done, you can find your framework bundle using bundleWithIdentifier:, where the identifier is the CFBundleIdentifier in your framework's Info.plist. If you need to use UINib directly to load your view controller nib directly at that point, it should be easy to locate the bundle using bundleWithIdentifier: and give that value to nibWithNibName:bundle: . A: As an another option you can directly put your xib file into your framework project and can get your nib with calling Swift 3 and Swift 4 let bundleIdentifier = "YOUR_FRAMEWORK_BUNDLE_ID" let bundle = Bundle(identifier: bundleIdentifier) let view = bundle?.loadNibNamed("YOUR_XIB_FILE_NAME", owner: nil, options: nil)?.first as! UIView Objective-C NSString *bundleIdentifier = @"YOUR_FRAMEWORK_BUNDLE_ID"; NSBundle *bundle = [NSBundle bundleWithIdentifier:bundleIdentifier]; UIView *view = [bundle loadNibNamed:@"YOUR_XIB_FILE_NAME" owner:nil options:nil]; A: The simplest way is to use [NSBundle bundleForClass:[self class]] to get the NSBundle instance of your framework. This won't enable the ability to get the framework's NSBundle instance by its Bundle ID but that isn't usually necessary. The issue with your code is the initWithNibName:@"Name" bundle:nil gets a file named Name.xib in the given bundle. Since bundle is nil, it looks in the host app's bundle, not your framework. The corrected code for the OP's issue is this: /*** Part of implementation of ViewControllerWithinFramework class, which is inside the framework ***/ - (id)initWithTitle:(NSString *)aTitle { NSBundle *bundle = [NSBundle bundleForClass:[self class]]; self = [super initWithNibName:@"ViewControllerWithinFramework" bundle:bundle]; // ... return self; } The only thing changed is giving the correct bundle instance. A: Frameworks that come with XIBs usually come with bundles too - so you probably should not pass nil in the framework part. Right click the framework -> Show in finder Open it up and see what's the bundle name in the resources folder (For example - Facebook uses FBUserSettingsViewResources.bundle) and use it. In general - static libraries do not include xib or resource files. Frameworks is basically a wrapper to a static library, headers and some resources (usually inside a bundle) A: You need to specify the bundle to search inside for the nib. Otherwise, it just (shallowly) searches your application's resources directory. - (id)initWithTitle:(NSString *)aTitle { // replace 'framework' with 'bundle' for a static resources bundle NSURL *frameworkURL = [[NSBundle mainBundle] URLForResource:@"myFrameworkName" withExtension:@"framework"]; NSBundle *framework = [NSBundle bundleWithURL:frameworkURL]; self = [super initWithNibName:@"ViewControllerWithinFramework" bundle:framework]; if (self) { _viewControllerTitle = aTitle; } return self; } A: I'm going to answer this the way I achieved the results you intended, but it may not be the best approach, improvements are more than welcome! I did it on a Cocoa Touch Framework subproject, but it should be easy to adapt to a Cocoa Touch Static Library, if it doesn't work already. This will be more like a tutorial than an answer, to be honest, but anyway... First things first. Quick overview of my solution: you'll have two projects on the same workspace. One is the framework, the other one is the app itself. You'll create the xib/storyboard on the framework, and use it either on the framework or the app (although the latter doesn't make much sense to me). The framework project will contain a build run script that will copy all it's resources (images, xibs, storyboards) to a bundle, and that bundle will be part of the app project. Also, the framework project will be a dependency of your app project. This way, whenever you compile your app, the build run script should run automatically and update the resources bundle before packaging your app. It sure is NOT a quick & easy thing to set up, but that's why I'm answering your question. This way I'll be able to come back here myself and remember how I achieved the same goal. You never know when Alzheimer's gonna hit you :) Anyway, let's get to work. * *Create/open your app's project. I'll be referring to this as AppProject. *Create a framework/library project and add it as subproject to the AppProject, or just drag your current framework project to the AppProject. What matters here is that the framework project is a subproject of AppProject. I'll be referring to the framework project as MyFramework. *Configure whatever you need for your specific projects. I guess it's a standard thing to use linker flags -ObjC and -all_load, at least. This isn't really useful for the purpose of this mini-tutorial, but the project should at least be compiling. Your workspace should be looking something like this: *Open the AppProject folder and create a new directory called MyBundle.bundle. *Drag the MyBundle.bundle to the AppProject (this is important: you are NOT supposed to drag it to the library project!). You probably want to un-check the Copy items if needed and select/check the targets where this bundle will be copied to when compiling your app. *Leave MyBundle.bundle alone for now. *Go to MyFramework's Build Settings and add a new Run script phase. *This step might be optional, but it worked like this for me, so I'm including it. Drag the just-created Run script right above the Compile sources phase. *Edit the Run script phase, changing it's shell to /bin/sh if it's not that already. Set the script to the following (comments should explain the script): Run script #!/bin/bash echo "Building assets bundle." # Bundle name (without the ".bundle" part). I separated this because I have different app targets, each one with a different bundle. BUNDLE_NAME='MyBundle' CURRENT_PATH=`pwd` # This should generate the full path to your bundle. Might need to be adapted if the bundle # directory you created was in another directory. BUNDLE_PATH="$CURRENT_PATH/$BUNDLE_NAME.bundle" # Check if the bundle exists, and removes it completely if it does. if [ -d "$BUNDLE_PATH" ]; then rm -rf "$BUNDLE_PATH" fi # Re-creates the same bundle (I know this is weird. But at least I am SURE the bundle will # be clean for the next steps) mkdir "$BUNDLE_PATH" # Copy all .jpg files to the bundle find ./ -name *.jpg -type f -print0 | xargs -0 -J% cp % "$BUNDLE_PATH" # Copy all .png files to the bundle find ./ -name *.png -type f -print0 | xargs -0 -J% cp % "$BUNDLE_PATH" # Copy all .xib files to the bundle. find ./ -name *.xib -type f -print0 | xargs -0 -J% cp % "$BUNDLE_PATH" # Copy all .storyboard files to the bundle. find ./ -name *.storyboard -type f -print0 | xargs -0 -J% cp % "$BUNDLE_PATH" # This is the golden thing. iOS code will not load .xib or storyboard files, you need to compile # them for that. That's what these loop do: they get each .xib / .storyboard file and compiles them using Xcode's # ibtool CLI. for f in "$BUNDLE_PATH/"*.xib ; do # $f now holds the complete path and filename a .xib file XIB_NAME="$f"; # Replace the ".xib" at the end of $f by ".nib" NIB_NAME="${f%.xib}.nib"; # Execute the ibtool to compile the xib file ibtool --compile "$NIB_NAME" "$XIB_NAME" # Since the xib file is now useless for us, remove it. rm -f "$f" done for f in "$BUNDLE_PATH/"*.storyboard ; do # $f now holds the complete path and filename a .storyboard file STORYBOARD_NAME="$f"; # Replace the ".storyboard" at the end of $f by ".storyboardc" (could've just added the final "c", but I like # to keep both loops equal) COMPILED_NAME="${f%.storyboard}.storyboardc"; # Execute the ibtool to compile the storyboard file ibtool --compile "$COMPILED_NAME" "$STORYBOARD_NAME" # Since the .storyboard file is now useless for us, remove it. rm -f "$f" done *Your workspace/settings should be looking something like this now: *Go to AppProject Build phases, and add your framework to the Link Binary with Libraries section. Also add the framework as the Target dependencies section. *Everything seems to be set up. Create a xib or storyboard file on the framework project, and create the view (or view controller) just the way you usually do. Nothing special here. You can even set custom classes for your components and everything (as long as the custom class is inside the framework project, and not in the app project). Before compiling the app project After compiling the app project *On your code, wherever you need to load your NIB/Xib, use one of the following codes. If you managed to follow so far, I don't even need to tell you you'll need to adapt these codes to whatever you wanna do with the xib/Storyboard, so... Enjoy :) Registering cell xib for a UITableView: NSString* bundlePath = [[NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"]; NSBundle* bundle = [NSBundle bundleWithPath:bundlePath]; UINib* nib = [UINib nibWithNibName:@"TestView" bundle:bundle]; [tableView registerNib:nib forCellReuseIdentifier:@"my_cell"]; Pushing a UIViewController to the navigation controller: NSString* bundlePath = [[NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"]; NSBundle* bundle = [NSBundle bundleWithPath:bundlePath]; UIViewController* vc = [[UIViewController alloc] initWithNibName:@"BundleViewController" bundle:bundle]; // You can use your own classes instead of the default UIViewController [navigationController pushViewController:vc animated:YES]; Presenting modally a UIStoryboard from it's initial UIViewController: NSString* bundlePath = [[NSBundle mainBundle] pathForResource:@"MyBundle" ofType:@"bundle"]; NSBundle* bundle = [NSBundle bundleWithPath:bundlePath]; UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"BundleStoryboard" bundle:bundle]; UIViewController* vc = [storyboard instantiateInitialViewController]; vc.modalPresentationStyle = UIModalPresentationFormSheet; vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve; [self presentViewController:vc animated:YES completion:^{}]; If it doesn't work for you (or whoever is visiting this question/answer), please let me know and I'll try to help. A: Try this in main.m #import "ViewControllerWithinFramework.h" //import this int main(int argc, char *argv[]) { @autoreleasepool { [ViewControllerWithinFramework class]; //call class function return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } } I hope this will work for you.
Q: Two parallely polling tasks on an event driven platform I am currently working on a server platform, which is based on an event driven architecture. An event should enter the system via a websocket connection, and after some processing the response for it should also leave the system via the same websocket connection. The implementation logic behind the idea is, that if a connection is made to the server, I put it in a while cycle, and await it to send me data until it disconnects. The incoming data is put into a queue, from which a worker thread will pull it out and process it. On the other part, I have created a task, which is polling an outgoing event queue, and if there is an event in the queue, it sends it to the corresponding recipient. Unfortunately my current asyncio logic is flawed, in the way that polling the outgoing event queue blocks the receiving task, and I cannot wrap my head around a way to fix it. Here are some code snippets, which should represent the problem presented above: Starting the websocket server def run(self, address: str, port: int, ssl_context: ssl.SSLContext = None): start_server = websockets.serve( self.websocket_connection_handler, address, port, ssl=ssl_context) event_loop = asyncio.get_event_loop() event_loop.create_task(self.send_heartbeat()) event_loop.create_task(self.dispatch_outgoing_events()) print(f'Running on {"wss" if ssl_context else "ws"}://{address}:{port}') event_loop.run_until_complete(start_server) event_loop.run_forever() The dispatcher function which infinitely polls data from the outgoing queue async def dispatch_outgoing_events(self): while not self.exit_state.should_exit: if len(self.outgoing_event_queue) == 0: await asyncio.sleep(0) else: event = self.outgoing_event_queue.get_event() destination = event.destination client_id = re.findall( r'[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}', destination)[0] client = self.client_store.get(client_id) await client.websocket.send(serializer.serialize(event)) The connection handler function for the websocket async def websocket_connection_handler(self, websocket, path): client_id = await self.register(websocket) try: while not self.exit_state.should_exit: correlation_id = str(uuid4()) message = await websocket.recv() else: try: event = serializer.deserialize( message, correlation_id, client_id) event.return_address = f'remote://websocket/{client_id}' self.incoming_event_queue.add_event(event) except Exception as e: event = type('evt', (object,), dict(system_entry=str( datetime.datetime.utcnow()), destination=f'remote://websocket/{client_id}'))() self.exception_handler.handle_exception( e, event) except Exception as exception: print( f'client {client_id} suddenly disconnected. Reason: {type(exception).__name__} -> {exception}') self.client_store.remove(client_id) self.topic_factory.remove_client(client_id) self.topic_factory.get_topic('server_notifications').publish(ClientDisconnectedNotification(client_id), str(uuid4()))
Q: C++ map really slow? i've created a dll for gamemaker. dll's arrays where really slow so after asking around a bit i learnt i could use maps in c++ and make a dll. anyway, ill represent what i need to store in a 3d array: information[id][number][number] the id corresponds to an objects id. the first number field ranges from 0 - 3 and each number represents a different setting. the 2nd number field represents the value for the setting in number field 1. so.. information[101][1][4]; information[101][2][4]; information[101][3][4]; this would translate to "object with id 101 has a value of 4 for settings 1, 2 and 3". i did this to try and copy it with maps: //declared as a class member map<double, map<int, double>*> objIdMap; ///// lower down the page, in some function map<int, double> objSettingsMap; objSettingsMap[1] = 4; objSettingsMap[2] = 4; objSettingsMap[3] = 4; map<int, double>* temp = &objSettingsMap; objIdMap[id] = temp; so the first map, objIdMap stores the id as the key, and a pointer to another map which stores the number representing the setting as the key, and the value of the setting as the value. however, this is for a game, so new objects with their own id's and settings might need to be stored (sometimes a hundred or so new ones every few seconds), and the existing ones constantly need to retrieve the values for every step of the game. are maps not able to handle this? i has a very similar thing going with game maker's array's and it worked fine. A: Do not use double's as a the key of a map. Try to use a floating point comparison function if you want to compare two doubles. A: 1) Your code is buggy: You store a pointer to a local object objSettingsMap which will be destroyed as soon as it goes out of scope. You must store a map obj, not a pointer to it, so the local map will be copied into this object. 2) Maps can become arbitrarily large (i have maps with millions of entrys). If you need speed try hash_maps (part of C++0x, but also available from other sources), which are considerably faster. But adding some hundred entries each second shouldn't be a problem. But befre worring about execution speed you should always use a profiler. 3) I am not really sure if your nested structures MUST be maps. Depending of what number of setting you have, and what values they may have, a structure or bitfield or a vector might be more accurate. A: If you need really fast associative containers, try to learn about hashes. Maps are 'fast enough' but not brilliant for some cases. Try to analyze what is the structure of objects you need to store. If the fields are fixed I'd recommend not to use nested maps. At all. Maps are usually intended for 'average' number of indexes. For low number simple lists are more effective because of insert / erase operations lower complexity. For great number of indexes you really need to think about hashing. Don't forget about memory. std::map is highly dynamic template so on small objects stored you loose tons of memory because of dynamic allocation. Is it what you are really expecting? Once I was involved in std::map usage removal which lowered memory requirements in about 2 times. If you only need to fill the map at startup and only search for elements (don't need to change structure) I'd recommend simple std::vector with sort applied after all the elems inserted. And then you can just use binary search (as you have sorted vector). Why? std::vector is much more predictable thing. The biggest advantage is continuous memory area.
Q: Is it possible to force Windows 10 to use higher TCP window scale? I have two Windows 10 machines (bld 2004) I am trying to send data to between two sites. The sites average about 50ms RTT with no packet loss. I am having an issue where the max transfer rate I can achieve is approximately 30Mbps (either direction). Site A is 100Mbps and B is 500Mbps. I have tested using different protocols such as SMB, FTP. IPerf tests confirm the same avg speed. These tests have been performed with the hosts directly attached to the ISP router. I was told from Network Engineering, that my Window size is too small. Is there any way I can change it to help improve my transfer rate? I was thinking adjusting the TCP window scale size? https://networkengineering.stackexchange.com/questions/73491/need-help-isolating-bandwidth-issues-between-sites A: Microsoft has some detailed information on this: To set the receive window size to a specific value, add the TcpWindowSize value to the registry subkey specific to your version of Windows. To do so, follow these steps: Select Start > Run, type Regedit, and then select OK. Expand the registry subkey specific to your version of Windows: For Windows 2000, expand the following subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces For Windows Server 2003, expand the following subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters On the Edit menu, point to New, and then select DWORD Value. Type TcpWindowSize in the New Value box, and then press Enter Select Modify on the Edit menu. Type the desired window size in the Value data box.
Q: Creating an array list of objects I have two classes A and B. B extends A. Now, in B, can I create an array list of objects of A. public class A { // class fields // class methods } import java.util.*; public class B extends A { List<Object> listname=new ArrayList<Object>(); A obj=new A(); listname.add(obj); } Can I create an array list of objects at all ? By the way, above code gives error ! A: Yes, I see no reason you cannot create an ArrayList of an object A. But you can't do it the way you are doing it, you must do it in a method. You're trying to do it in the field declarations. Try maybe adding it in the constructor? So something like public B() { A obj=new A(); listname.add(obj); } Or maybe I just don't understand your question and I'm completely wrong. A: The error is because you have code outside a method. Try this: public class B extends A { private static List<Object> listname = new ArrayList<Object>(); public static void main(String[] args) { A obj = new A(); listname.add(obj); } } A: Use an instance initializer if you want to add items to your list outside of any method: public class B extends A{ private List<A> listOfA = new ArrayList<A>(); { listOfA.add(new A()); } public B(){ } }
Q: Shiboken2 qobject.h:46:10: fatal: 'QtCore/qobjectdefs.h' file not found I'm trying to create a Python binding for a Qt C++ class with Shiboken2. As far as I can tell, there's no official example on how to do so (the only example on the Qt Blog deals with a generic C++ class https://www.qt.io/blog/2018/05/31/write-python-bindings). So I'm following this blog post instead: https://blog.basyskom.com/2019/using-shiboken2-to-create-python-bindings-for-a-qt-library/ The example works on Linux, but Shiboken2 fails to build on a Mac with the error qobject.h:46:10: fatal: 'QtCore/qobjectdefs.h' file not found This is a log of what happens: (pyside2build) MacBook-Pro-i7:build andreac$ cmake .. -- The C compiler identification is AppleClang 11.0.0.11000033 -- The CXX compiler identification is AppleClang 11.0.0.11000033 -- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- QtCore include folders: /Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework;/Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework/Headers;/Users/andreac/Qt/5.12.6/clang_64/.//mkspecs/macx-clang -- Using python interpreter: /Users/andreac/pyside2build/bin/python -- Found Python3: /Users/andreac/pyside2build/bin/python3.7 (found version "3.7.5") found components: Interpreter Development -- Using PySide2 installation: /Users/andreac/pyside2build/lib/python3.7/site-packages/PySide2 -- Configuring done -- Generating done -- Build files have been written to: /Users/andreac/pyside2build/src/binding-example/build (pyside2build) MacBook-Pro-i7:build andreac$ make Scanning dependencies of target libexamplebinding_autogen [ 9%] Automatic MOC for target libexamplebinding [ 9%] Built target libexamplebinding_autogen Scanning dependencies of target libexamplebinding [ 18%] Building CXX object CMakeFiles/libexamplebinding.dir/libexamplebinding_autogen/mocs_compilation.cpp.o [ 27%] Building CXX object CMakeFiles/libexamplebinding.dir/qobjectwithenum.cpp.o [ 36%] Linking CXX shared library libexamplebinding.dylib [ 36%] Built target libexamplebinding Scanning dependencies of target Shiboken2QtExample_autogen [ 45%] Running generator for /Users/andreac/pyside2build/src/binding-example/bindings.xml. (bindings) clang_parseTranslationUnit2(0x0, cmd[17]=-nostdinc -isystem/opt/X11/include -isystem/usr/local/include -isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1 -isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/11.0.0/include -isystem/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -isystem/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -iframework/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks -fPIC -Wno-expansion-to-defined -Wno-constant-logical-operand -std=c++14 -I/Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework -I/Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework/Headers -I/Users/andreac/Qt/5.12.6/clang_64/mkspecs/macx-clang -I/Users/andreac/pyside2build/src/binding-example /private/var/folders/8v/8h2g7jz573g9rlwyp4zh87qm0000gn/T/bindings_eyZJOr.hpp) /Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework/Headers/qobject.h:46:10: fatal error: 'QtCore/qobjectdefs.h' file not found (bindings) Errors in /private/var/folders/8v/8h2g7jz573g9rlwyp4zh87qm0000gn/T/bindings_eyZJOr.hpp: /Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework/Headers/qobject.h:46:10: fatal: 'QtCore/qobjectdefs.h' file not found /private/var/folders/8v/8h2g7jz573g9rlwyp4zh87qm0000gn/T/bindings_eyZJOr.hpp:1:10: note: in file included from /private/var/folders/8v/8h2g7jz573g9rlwyp4zh87qm0000gn/T/bindings_eyZJOr.hpp:1: /Users/andreac/pyside2build/src/binding-example/bindings.h:3:10: note: in file included from /Users/andreac/pyside2build/src/binding-example/bindings.h:3: /Users/andreac/pyside2build/src/binding-example/qobjectwithenum.h:2:10: note: in file included from /Users/andreac/pyside2build/src/binding-example/qobjectwithenum.h:2: /Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework/Headers/QObject:1:10: note: in file included from /Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework/Headers/QObject:1: (bindings) Clang: 1 diagnostic messages: /Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework/Headers/qobject.h:46:10: fatal: 'QtCore/qobjectdefs.h' file not found /private/var/folders/8v/8h2g7jz573g9rlwyp4zh87qm0000gn/T/bindings_eyZJOr.hpp:1:10: note: in file included from /private/var/folders/8v/8h2g7jz573g9rlwyp4zh87qm0000gn/T/bindings_eyZJOr.hpp:1: /Users/andreac/pyside2build/src/binding-example/bindings.h:3:10: note: in file included from /Users/andreac/pyside2build/src/binding-example/bindings.h:3: /Users/andreac/pyside2build/src/binding-example/qobjectwithenum.h:2:10: note: in file included from /Users/andreac/pyside2build/src/binding-example/qobjectwithenum.h:2: /Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework/Headers/QObject:1:10: note: in file included from /Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework/Headers/QObject:1: Keeping temporary file: /private/var/folders/8v/8h2g7jz573g9rlwyp4zh87qm0000gn/T/bindings_eyZJOr.hpp shiboken: Error running ApiExtractor. Command line: --generator-set=shiboken --enable-parent-ctor-heuristic --enable-return-value-heuristic --use-isnull-as-nb_nonzero --avoid-protected-hack -I/Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework -I/Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework/Headers -I/Users/andreac/Qt/5.12.6/clang_64/.//mkspecs/macx-clang -T/Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework -T/Users/andreac/Qt/5.12.6/clang_64/lib/QtCore.framework/Headers -T/Users/andreac/Qt/5.12.6/clang_64/.//mkspecs/macx-clang -I/Users/andreac/pyside2build/src/binding-example -T/Users/andreac/pyside2build/src/binding-example --output-directory=/Users/andreac/pyside2build/src/binding-example/build /Users/andreac/pyside2build/src/binding-example/bindings.h /Users/andreac/pyside2build/src/binding-example/bindings.xml make[2]: *** [Shiboken2QtExample/qobjectwithenum_wrapper.cpp] Error 1 make[1]: *** [CMakeFiles/Shiboken2QtExample_autogen.dir/all] Error 2 make: *** [all] Error 2 Any ideas on how to fix the problem? A: It looks like I need to use the -F option for Shiboken2 to specify the location of a Framework. Adding the following to the invocation command solves the issue: -F/Users/andreac/Qt/5.12.6/clang_64/lib/
Q: How to install a CA in Minikube so image pulls are trusted I want to use Minikube for local development. It needs to access my companies internal docker registry which is signed w/ a 3rd party certificate. Locally, I would copy the cert and run update-ca-trust extract or update-ca-certificates depending on the OS. For the Minikube vm, how do I get the cert installed, registered, and the docker daemon restarted so that docker pull will trust the server? A: I had to do something similar recently. You should be able to just hop on the machine with minikube ssh and then follow the directions here https://docs.docker.com/engine/security/certificates/#understanding-the-configuration to place the CA in the appropriate directory (/etc/docker/certs.d/[registry hostname]/). You shouldn't need to restart the daemon for it to work. A: Well, the minikube has a feature to copy all the contents of ~/.minikube/files directory to its VM filesystem. So you can place your certificates under ~/.minikube/files/etc/docker/certs.d/<docker registry host>:<docker registry port> path and these files will be copied into the proper destination on minikube startup automagically. A: Shell into Minikube. Copy your certificates to: /etc/docker/certs.d/<docker registry host>:<docker registry port> Ensure that your permissions are correct on the certificate, they must be at least readable. Restart Docker (systemctl restart docker) Don't forget to create a secret if your Docker Registry uses basic authentication: kubectl create secret docker-registry service-registry --docker-server=<docker registry host>:<docker registry port> --docker-username=<name> --docker-password=<pwd> --docker-email=<email> A: Have you checked ImagePullSecrets. You can create a secret with your cert and let your pod use it. A: By starting up the minikube with the following : minikube start --insecure-registry=internal-site.dev:5244 It will start the docker daemon with the --insecure-registry option : /usr/local/bin/docker daemon -D -g /var/lib/docker -H unix:// -H tcp://0.0.0.0:2376 --label provider=virtualbox --insecure-registry internal-site.dev:5244 --tlsverify --tlscacert=/var/lib/boot2docker/ca.pem --tlscert=/var/lib/boot2docker/server.pem --tlskey=/var/lib/boot2docker/server-key.pem -s aufs but this expects the connection to be HTTP. Unlike in the Docker registry documentation Basic auth does work, but it needs to be placed in a imagePullSecret from the Kubernetes docs. I would also recommend reading "Adding imagePulSecrets to service account" (link on the page above) to get the secret added to all pods as they are deployed. Note that this will not impact already deployed pods. A: One option that works for me is to run a k8s job to copy the cert to the minikube host... This is what I used to trust the harbor registry I deployed into my minikube cat > update-docker-registry-trust.yaml << END apiVersion: batch/v1 kind: Job metadata: name: update-docker-registry-trust namespace: harbor spec: template: spec: containers: - name: update image: centos:7 command: ["/bin/sh", "-c"] args: ["find /etc/harbor-certs; find /minikube; mkdir -p /minikube/etc/docker/certs.d/core.harbor-${MINIKUBE_IP//./-}.nip.io; cp /etc/harbor-certs/ca.crt /minikube/etc/docker/certs.d/core.harbor-${MINIKUBE_IP//./-}.nip.io/ca.crt; find /minikube"] volumeMounts: - name: harbor-harbor-ingress mountPath: "/etc/harbor-certs" readOnly: true - name: docker-certsd-volume mountPath: "/minikube/etc/docker/" readOnly: false restartPolicy: Never volumes: - name: harbor-harbor-ingress secret: secretName: harbor-harbor-ingress - name: docker-certsd-volume hostPath: # directory location on host path: /etc/docker/ # this field is optional type: Directory backoffLimit: 4 END kubectl apply -f update-docker-registry-trust.yaml A: You should copy your root certificate to $HOME/.minikube/certs and restart the minikube with --embed-certs flag. For more details please refer to minikube handbook: https://minikube.sigs.k8s.io/docs/handbook/untrusted_certs/ A: As best as I can tell, there is no way to do this. The next best option is to use the insecure-registry option at startup. minikube --insecure-registry=foo.com:5000
Q: How can I manage multiple threads in c with pthread? I am trying to write a program that can scale to use a dynamic number of pthreads based on core count to parallelize a simple algorithm. The algorithm is simple it takes an integer array of inputs and if each location is %10 != 0 it stores 0 in the corresponding output array location, else it stores 10. I don't think the problem is there as it is such a simple problem... but I don't understand why this doesn't work: /*This variable is our reference to the child threads */ pthread_t childThreads[threadCount]; /* ...other setup code to initialize the parameters... */ /* create child threads*/ for(int i = 0; i< threadCount; i++) { printf("running_P...\n"); if(pthread_create(&(childThreads[i]), NULL, runParallelAlgorithm, (void *) &(parallelDataPakages[i]))) { fprintf(stderr, "Error creating thread\n"); return 1; } } /* join child threads*/ for(int i = 0; i< threadCount; i++) { if(pthread_join(childThreads[i], NULL)) { fprintf(stderr, "Error joining thread\n"); return 2; } printf("not_running_P...\n"); } and the output from this is: running_P... running_P... running_P... running_P... not_running_P... Error joining thread Process returned 2 (0x2) execution time : 0.047 s Press any key to continue. I have tried looking at other solutions, but it looks like most people are trying to use the same pthread_t variable to make threads, whereas I have an array... but it still seems to fail to join? Why? I tried to cut it down to only the relevant code, but because I can provide more information if necessary. Edit: Sorry I didn't provide enough information. The actual program is nearly 200 lines and I didn't really want to post it all here initially. But if the issue isn't in this section I'm not sure what it causing this issue. Seeing as this isn't the issue though, I will link a gist with the code included. The actual join that is causing issues is on line 140, sorry I can't really figure out what else it would be specifically: https://gist.github.com/firestar9114/d77b72254d4ef93664fbda14a9ed1a19 Update: The pthread_join() function returns an int equal to ESRCH which is listed as "No thread with the ID thread could be found." in the manual. I am using the same array of childThreads[] to create and to join the threads, and I am using the same control variable of threadCount which is always 4, so I don't understand why the thread id can't be found? I tried adding a pthread_exit(NULL); statement, but it still doesn't seem to work... Any ideas given this new information??? A: You are looking for the problem at the completely wrong place. The root cause is a buffer overrun, here: /*advance the element pointer*/ inputPointer = inputPointer + (sizeof(int) * elementsToProcess[i]); outputPointer = outputPointer + (sizeof(int) * elementsToProcess[i]); You want to advance int *inputPointer and int *outputPointer by elementsToProcess[i]. The multiplication by the size of an int is completely bogus: incrementing or decrementing a pointer changes the address by the size of the pointed to type, so that it points to the next or previous element if in an array. So, it should be inputPointer = inputPointer + elementsToProcess[i]; outputPointer = outputPointer + elementsToProcess[i]; or better yet, inputPointer += elementsToProcess[i]; outputPointer += elementsToProcess[i]; Essentially, your code is scribbling over other data, including childThreads[] and C library internal allocation metadata.
Q: GAE - "Connection failed: Unknown database" on local server I can connect to and query my db on my app, but I can't on my local server. I know it is authenticating correctly because if I misspell the user or password, I get an access denied error. My code is: <?php $servername = "173.194.xxx.xxx"; $username = "admin"; $password = "mypassw0rd"; $dbname = "dev"; // Create connection $conn = new mysqli(null, $username, $password, $dbname, null, "/cloudsql/myappname:mydbinstance"); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?> Which returns: Warning: mysqli::mysqli(): (HY000/1049): Unknown database 'dev' in C:\Users\myusername\myfolder\dbconnect.php on line 9 Connection failed: Unknown database 'dev' But it's fine online! Any ideas? A: As the docs say, "You do not use the "/cloudsql/"-based connection string to connect to a Cloud SQL instance if your App Engine app is running locally in the Development Server." So, "/cloudsql/myappname:mydbinstance" is fine when you're running on appspot, but not when you're running locally in the development server: in that case, it should be the $servername (the public IP of the Cloud SQL instance -- I assume with real numbers rather than xxx, pointing this out just because you're setting but not using it in your snippet so it's not certain that you actually set it correctly) followed of course by :3306 to specify the port. A: This is a possible solution, but I don't want to mark it as the answer if it's not best practice: if($_SERVER["REMOTE_ADDR"]=="::1"){ echo 'local'; $conn = new mysqli($servername, $username, $password, $dbname, 3306, "/173.194.xxx.xxx/myappname:mydbinstance"); }else{ $local = False; echo 'app engine'; $conn = new mysqli(null, $username, $password, $dbname, null, "/cloudsql/myappname:mydbinstance"); } Basically, I can't yet use the same code for both environments so I'm using different connection strings for each environment.
Q: How can I get Json data with Python? What I want to do is to get Json data out as a list (or array) with Python, I tried several times but didn't work. My json data is like this: { "status":"OK", "List":{ "stuff":[{ "id":"326", "name":"a", "url":"autob-fulla.tgz", },{ "id":"327", "name":"b", "url":"auto-fullb.tgz", },{ "id":"328", "name":"c", "url":"auto-fullc.tgz", }] } } I want to return all the value of "id". Now my code is like this: import json def retrieve(): print('retrieving results...') testQueueID = '1'; base_url1 = 'http://localhost:8080/stuff' conn = Connection(base_url1, username='admin', password='admin') resp = conn.request_get("", args={}, headers={'content-type':'application/xml', 'accept':'application/xml'}) decoded_json = json.loads(json.dumps(resp, sort_keys=True, indent=4, skipkeys=True)) return decoded_json A: Just leave out the json.dumps call. You already have a string with JSON in it, so all you need is json.loads(). A: 1.) xml != Json 2.) Try this http://www.doughellmann.com/PyMOTW/json/ first. It ll teach you. 3.) Simple code to get you started . See what data prints. import json from pprint import pprint json_data=open('json_datafile') data = json.load(json_data) pprint(data) json_data.close()
Q: Unable to save the file correctly I have a text file contains a text about a story and I want to find a word "like" and get the next word after it and call a function to find synonyms for that word. here is my code: file = 'File1.txt' with open(file, 'r') as open_file: read_file = open_file.readlines() output_lines = [] for line in read_file: words = line.split() for u, word in enumerate(words): if 'like' == word: next_word = words[u + 1] find_synonymous(next_word ) output_lines.append(' '.join(words)) with open(file, 'w') as open_file: open_file.write(' '.join(words)) my only problem I think in the text itself, because when I write one sentence including the word (like) it works( for example 'I like movies'). but when I have a file contains a lot of sentences and run the code it deletes all text. can anyone know where could be the problem A: You have a couple of problems. find_synonymous(next_word ) doesn't replace the word in the list, so at best you will get the original text back. You do open(file, 'w') inside the for loop, so the file is overwritten for each line. next_word = words[u + 1] will raise an index error if like happens to be the last word on the line and you don't handle the case where the thing that is liked continues on the next line. In this example, I track an "is_liked" state. If a word is in the like state, it is converted. That way you can handle sentences that are split across lines and don't have to worry about index errors. The list is written to the file outside the loop. file = 'File1.txt' with open(file, 'r') as open_file: read_file = open_file.readlines() output_lines = [] is_liked = False for line in read_file: words = line.split() for u, word in enumerate(words): if is_liked: words[u] = find_synonymous(word) is_liked = False else: is_liked = 'like' == word output_lines.append(' '.join(words) + '\n') with open(file, 'w') as open_file: open_file.writelines(output_lines)
Q: Where is the percentile function in CRAN -R I do not understand all the terminology inside R. I have only 100 level statistics, trying to learn more. I am guessing R has a built-in percentile function named something I don't recognize or know how to search for. I can write my own, but rather use the built in one for obvious reasons. Here's the one I wrote: percentile <- function(x) return((x - min(x)) / (max(x) - min(x)) A: You can do this via scale(x,center=min(x,na.rm=TRUE),scale=diff(range(x,na.rm=TRUE))) but I'm not sure there is actually a built-in function that does the scaling you're asking for. A: If you are looking to find out specific percentiles from a data set, take a look at the quantile function: ?quantile. By multiplying by 100, you get percentiles. If you are looking into converting numbers to their percentiles, take a look at rank, though you will need to determine how to address ties. You can simply rescale from rank to quantile by dividing by the length of the vector. A: The quantile function might be what you are looking for. If you have vector x and you want to know the 25th, 43rd, and 72nd percentiles you would execute this: quantile(x, c(.25, .43, .72)); The semicolon is, of course, optional. See http://www.r-tutor.com/elementary-statistics/numerical-measures/percentile A: You can search for functions (or for just about anything else) via RSiteSearch e.g., RSiteSearch("percentile") A: On the off chance you are thinking about a percentile based on a distribution, here is a different answer. Each probability distribution has a set of 4 functions associated with it: a density, distribution, quantile, and generating function. These are prefixes of d-, p-, q-, and r-, respectively (with the same suffix based on the distribution). You have a uniform distribution, and are asking about percentiles (distribution) so you want punif. It takes min and max as two of its arguments. A: I made this function function, check it. Data is any vector, row of any matrix o data frame. percentiles<-function(Data) return(quantile(Data, seq(0,1, by=.01)))
Q: Node.js : How to enable non strict or ECMASCRIPT3 in V8 engine? I believe V8 underlying Node.js supports strict mode or ES5 by default. Can we enable non strict or ECMASCRIPT 3 in V8 engine? almost 100% of ES5 features are available in Chrome (V8) see compatibility table . But some developers(including me) are still comfortable with ES3, can we have that option? A: Just don't include the string "use strict" in your code. V8 supports strict mode, it doesn't use it unless you tell it to (i.e. it follows the ES5 specification). Compare the following scripts: Input: foo = "Hello"; console.log(foo); Output: quentin@workstation:tmp # node test.js Hello and Input: "use strict"; foo = "Hello"; console.log(foo); Output: quentin@workstation:tmp # node test.js node.js:201 throw e; // process.nextTick error, or 'error' event on first tick ^ ReferenceError: foo is not defined at Object.<anonymous> (/Users/quentin/tmp/test.js:2:5) at Module._compile (module.js:432:26) at Object..js (module.js:450:10) at Module.load (module.js:351:31) at Function._load (module.js:310:12) at Array.0 (module.js:470:10) at EventEmitter._tickCallback (node.js:192:40)
Q: How do you handle testing with Selenium when you are running AB tests? We just started using Selenium to test our site and its working really well, except that it breaks 1/2 of the time when we introduce an AB test. How do you guys handle Ab tests when testing with Selenium? Thanks! A: This really depends on exactly what you're looking for. I would suggest one of three options: * *Disable A/B testing for Selenium. One of the keys to testing is determination. With randomized return, you won't be able to be as confident in your results. To accomplish this, I would pass in a parameter, e.g. http://my.website.com/?ab=0. This could always select one specific path which will be tested. *Build a parameter for Selenium to "choose" an ab test-case. http://my.website.com/?ab[show-panel]=1. Again, this will give you a deterministic result, and allow you to actually test the ab test cases you have. This can also be accomplished through creative the use of cookies in your setup. *Hack- don't "check" the a-b tested aspects of your site, and build selenium to navigate around them. This depends on exactly what you are testing, but if it's images or text, this shouldn't be an issue. Non-deterministic workflows should not be tested. Hope these ideas help. The take-away here is to make sure to keep things deterministic for your tests. Random will only ever lead you astray.
Q: duplicate records need to delete oracle db I need to delete the duplicate records, having ID columns unique values and other columns having duplicate values, first need to find frmo table those records and delete. select * FROM HOURLY_REPORT_TABLE where API_DATE = TO_DATE('27-SEP-20','dd-MON-yy') and API_HOUR = 17; ID APPLICATION API_DATE API_HOUR SO APP API ACTUAL_API AVG_RUN TOTAL_TRANS GOOD_TRANS FAIL_TRANS FAIL_PERC COUNTS_TO1 PERC_TO1 COUNTS_TO15 PERC_TO15 COUNTS_OVER15 PERC_OVER15 COUNTS_1TO5 PERC_1TO5 COUNTS_5TO10 PERC_5TO10 COUNTS_10TO15 PERC_10TO15 COUNTS_15TO30 PERC_15TO30 COUNTS_30TO60 PERC_30TO60 COUNTS_OVER60 PERC_OVER60 CREATED_USER_ID CREATED_TIME_STAMP METRIC AVG_RUN_GOOD AVG_RUN_FAIL 106508413 LS 27-SEP-20 19 ATAPortReset G2 GetCustomerSnapshot GetCustomerSnapshot 0.403 7 7 0 0 7 1 7 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 UFOSODRPT 30-SEP-20 S 0.403 0 105398782 LS 27-SEP-20 19 ATAPortReset G2 GetCustomerSnapshot GetCustomerSnapshot 0.403 7 7 0 0 7 1 7 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 UFOSODRPT 29-SEP-20 S 0.403 0 Thanks is this query is right for getting 27th sept 2020 records and API_HOUR=17 select * from hourly_report_table t1 where exists ( select * from hourly_report_table t2 where t2.id <> t1.id and t2.application = t1.application and t2.api_date = t1.api_date and t2.api_hour = t1.api_hour and t2.SO=t1.so and t2.APP=t1.APP and t2.API=t1.API and t2.ACTUAL_API=t1.ACTUAL_API and t2.AVG_RUN=t1.avg_run and t2.total_trans=t1.total_trans and t2.good_trans=t1.good_trans and t2.fail_trans=t1.fail_trans and t2.fail_perc=t1.fail_perc --and t2.counts_t01=t1.counts_t01 --and t2.perc_t01=t1.perc_t01 and t2.COUNTS_TO15=t1.COUNTS_TO15 and t2.PERC_TO15 =t1.PERC_TO15 and t2.COUNTS_5TO10=t1.COUNTS_5TO10 and t2.PERC_5TO10 =t1.PERC_5TO10 and t2.COUNTS_10TO15 =t1.COUNTS_10TO15 and t2.PERC_10TO15 =t1.PERC_10TO15 and t2.COUNTS_15TO30 = t1.COUNTS_15TO30 and t2.PERC_15TO30 =t1.PERC_15TO30 and t2.COUNTS_30TO60 = t1.COUNTS_30TO60 and t2.PERC_30TO60 =t1.PERC_30TO60 and t2.COUNTS_OVER60 = t1.COUNTS_OVER60 and t2.PERC_OVER60 = t1.PERC_OVER60 and t2.CREATED_USER_ID = t1.CREATED_USER_ID --and t2.CREATED_TIME_STAMP = t1.CREATED_TIME_STAMP and t2.METRIC = t1.METRIC and t2.AVG_RUN_GOOD = t1.AVG_RUN_GOOD and t2.AVG_RUN_FAIL = t1.AVG_RUN_FAIL ) and t1.API_DATE = TO_DATE('27-SEP-20','dd-MON-yy') and t1.API_HOUR = 17; so is below query fine: to remove multiple duplicate entries for all hours between 9/27 17:00 and 9/30 13:00 , added the requested change. select * from hourly_report_table t1 where exists ( select * from hourly_report_table t2 where t2.id <> t1.id and t2.application = t1.application and t2.api_date = t1.api_date and t2.api_hour = t1.api_hour and t2.SO=t1.so and t2.APP=t1.APP and t2.API=t1.API and t2.ACTUAL_API=t1.ACTUAL_API and t2.AVG_RUN=t1.avg_run and t2.total_trans=t1.total_trans and t2.good_trans=t1.good_trans and t2.fail_trans=t1.fail_trans and t2.fail_perc=t1.fail_perc and t2.COUNTS_TO1=t1.COUNTS_TO1 and t2.PERC_TO1=t1.PERC_TO1 and t2.COUNTS_TO15=t1.COUNTS_TO15 and t2.PERC_TO15 =t1.PERC_TO15 and t2.COUNTS_5TO10=t1.COUNTS_5TO10 and t2.PERC_5TO10 =t1.PERC_5TO10 and t2.COUNTS_10TO15 =t1.COUNTS_10TO15 and t2.PERC_10TO15 =t1.PERC_10TO15 and t2.COUNTS_15TO30 = t1.COUNTS_15TO30 and t2.PERC_15TO30 =t1.PERC_15TO30 and t2.COUNTS_30TO60 = t1.COUNTS_30TO60 and t2.PERC_30TO60 =t1.PERC_30TO60 and t2.COUNTS_OVER60 = t1.COUNTS_OVER60 and t2.PERC_OVER60 = t1.PERC_OVER60 and t2.CREATED_USER_ID = t1.CREATED_USER_ID --and t2.CREATED_TIME_STAMP = t1.CREATED_TIME_STAMP and t2.METRIC = t1.METRIC and t2.AVG_RUN_GOOD = t1.AVG_RUN_GOOD and t2.AVG_RUN_FAIL = t1.AVG_RUN_FAIL ) and api_date + interval '1' hour * api_hour between timestamp '2020-09-27 17:00:00' and timestamp '2020-09-30 13:00:00'; I used this below query it's deleted all previous data, and it's commited now, can you please suggest wht to do now DELETE FROM HOURLY_REPORT_TABLE WHERE ROWID NOT IN ( SELECT min(ROWID) FROM HOURLY_REPORT_TABLE where -- api_date + interval '1' hour * api_hour between timestamp '2020-09-27 17:00:00' and timestamp '2020-09-30 13:00:00'; --API_DATE=TO_DATE('28-SEP-20','dd-MON-yy') --and API_HOUR=17 GROUP BY ID,APPLICATION, API_DATE, API_HOUR, SO, APP, API, ACTUAL_API, AVG_RUN, AVG_RUN_GOOD, AVG_RUN_FAIL, TOTAL_TRANS, GOOD_TRANS, FAIL_TRANS, FAIL_PERC, COUNTS_TO1, PERC_TO1, COUNTS_TO15, PERC_TO15, COUNTS_OVER15, PERC_OVER15, COUNTS_1TO5, PERC_1TO5, COUNTS_5TO10, PERC_5TO10, COUNTS_10TO15, PERC_10TO15, COUNTS_15TO30, PERC_15TO30, COUNTS_30TO60, PERC_30TO60, COUNTS_OVER60, PERC_OVER60, CREATED_USER_ID, CREATED_TIME_STAMP, METRIC, AVG_RUN_GOOD, AVG_RUN_FAIL); A: The rows are identical except for their ID and creation timestamp. In order to find duplicates, you must compare all other columns: The query, finding both rows by looking for duplicates with another ID (t2.id <> t1.id): select * from hourly_report_table t1 where exists ( select * from hourly_report_table t2 where t2.id <> t1.id and t2.application = t1.application and t2.api_date = t1.api_date and t2.api_hour = t1.api_hour and ... ); The delete statement only keeping one row of a group of duplicates by comparing t2.id < t1.id: delete from hourly_report_table t1 where exists ( select * from hourly_report_table t2 where t2.id < t1.id and t2.application = t1.application and t2.api_date = t1.api_date and t2.api_hour = t1.api_hour and ... ); If you want to restrict this to a particular date and hour, do so. where exists (...) and api_date = date '2020-09-27' and api_hour = 17 Thus you are only dealing with part of the table, but you must make sure that the DBMS can find this data quickly (and not to have to read the hole table again and again). Provide an index for this: create index idx1 on hourly_report_table (api_date, api_hour);
Q: Rspec controller test failing with Apostrophe Character? Right now I have unit tests that are failing using the "Faker" Company Name. it seems like the expect(response.body).to match(@thing.name) is whats getting messed up. When looking at the error, the Faker Company names will sometimes have things like "O'Brian Company" or "O'Hare Company" or similar. Is faker an encoded string? since I know it's not a good idea to match on encoded strings, and I really don't want to just specify a specific company name in the Factory im using. Thanks A: Assuming you are referring to Faker::Company of the Faker gem The correct way to make your example expectation pass would be to use a Regexp as in the @rafael-costa example. Doing so escapes things like apostrophes. The problem with using Faker is that your tests are not deterministic. It is best practice to provide static, known inputs for your test and expect the outputs to pass certain expectations based on those inputs. It is difficult to provide a pertinent example without more information but maybe something like this: company = Company.new(name: 'Acme Anvils') get :show, params: {id: company.to_param}, session: {} expect(response.body).to match(Regexp.new('Acme Anvils', Regexp::MULTILINE)) Also you typically should not test specific body output within your controller specs. To do so is testing across purposes. You would normally write a view test for that. A: You could try passing a Regexp instead of the string: expect(response.body).to match(Regexp.new(@thing.name)) Also, If the problem is only when you get this type of names from faker, then you should take a look at this QA, It gives some good insights. A: Faker won't do any encoding for you. It will just give you a string like O'Malley. But the response should have HTML escaping (or some other kind, depending on the format), like O'Malley. You could always puts response.body to see for sure. The RSpec matches matcher is really designed for either expected or actual to be a regular expression, but in your case both are strings. Because the code has an optimization calling values_match? which does a simple comparison, you are effectively saying expect(response.body).to eq(@thing.name). If you do want a regular expression, you are right that you should be careful using uncontrolled values to create it. Fortunately Ruby has Regexp.escape for that, so you can say Regexp.new("foo" + Regexp.escape(@thing.name) + "bar"). But from your objection to include, it sounds like you actually want the response to contain nothing but the name, right? In that case, you don't need a regex at all. In any case, the problem isn't about what's around the name, but how the name is escaped. So before comparing you should either (1) decode the response or (2) encode the faker string. It doesn't really matter which. Both are pretty easy: expect(CGI.unescapeHTML(response.body)).to eq @thing.name or expect(response.body).to eq CGI.escapeHTML(@thing.name) Naturally, if your response is JSON, you should replace all this HTML escaping stuff with JSON, etc. A: You could try using #include instead of using #match. expect(response.body).to include(@thing.name)
Q: Problems importing mixin into another app for apply to Class Based View I have the file userprofiles/mixins.py in which I've created this mixin from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required class LoginRequiredMixin(object): @method_decorator(login_required(login_url = '/login/')) def dispatch(self, request, *args, **kwargs): return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) In my file userprofiles/views.py I have the following class based view named ProfileView of this way: from .mixins import LoginRequiredMixin class ProfileView(LoginRequiredMixin,TemplateView): template_name = 'profile.html' def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) if self.request.user.is_authenticated(): context.update({'userprofile': self.get_userprofile()}) return context def get_userprofile(self): return self.request.user.userprofile In this class based view named ProfileView I could inherit from LoginRequiredMixin without any trouble These mixin LoginRequiredMixin I also applied to the class based view named AlbumListView which is located in other module or app artists/views.py. The class based view AlbumListView is this: from sfotipy.userprofiles.mixins import LoginRequiredMixin class AlbumListView(LoginRequiredMixin,ListView): model = Album template_name = 'album_list.html' def get_queryset(self): if self.kwargs.get('artist'): queryset = self.model.objects.filter(artist__slug__contains=self.kwargs['artist']) else: queryset = super(AlbumListView, self).get_queryset() return queryset The unique way for my IDE don't mark error when I import the LoginRequiredMixin for I inherit from it is of this way: from sfotipy.userprofiles.mixins import LoginRequiredMixin I know that this import way is not correct, because is a absolute import and the right way is doing a relative import. Other way in where should work is this: from userprofiles.mixins import LoginRequiredMixin But, when I want test I get the following error message... How to can I do this import and that works? Thanks for the orientation :D
Q: get attribute of paperclip by string I have a model User with an attachment avatar, and I need to find the avatar path only having the string "avatar" user = Client.find 1 attribute = "avatar" this way is getting me nil: user[attribute].path how can I correctly get the avatar path? A: You can try this: user.send(attribute).path
Q: android.database.sqlite.SQLiteConstraintException: error code 19: constraint failedexception I created a table named resources but when I insert values in it, this exception is thrown: android.database.sqlite.SQLiteConstraintException: error code 19: constraint failedexception Here is my create table statement: public static final String DATABASE_CREATE = "CREATE TABLE " + table_resources + "(ID INTEGER PRIMARY KEY, KEY_TYPE text, KEY_ENCODING text, KEY_WIDTH text, KEY_HEIGHT text, KEY_DATA text, KeyIId text)"; The following is my insert code: JSONObject show = data.getJSONObject(i); if (show.get("type").equals("resource_updates")) { JSONArray resources = show.getJSONArray("resources"); try { System.out.println("length of resources is is " + resources.length()); for (int resourceIndex = 0; resourceIndex < resources.length(); resourceIndex++) { type = resources.getJSONObject(resourceIndex).getString("type").toString(); encoding = resources.getJSONObject(resourceIndex).getString("encoding").toString(); data1 = resources.getJSONObject(resourceIndex).getString("data").toString(); id = resources.getJSONObject(resourceIndex).getString("id").toString(); try { width = resources.getJSONObject(resourceIndex).getString("width").toString(); } catch (Exception e) { System.out.println(e); width = "null"; } try { height = resources.getJSONObject(resourceIndex).getString("height").toString(); } catch (Exception e) { e.printStackTrace(); height = "null"; } db.insert(type,encoding,width,height, data1,iid); } } catch (Exception e) { e.printStackTrace(); System.out.println(e + "exception"); System.out.println("exception in the resources"); } } Can anyone tell me where could be the problem? A: Constraint failed usually indicates that you did something like pass a null value into a column that you declare as not null when you create your table. A: In order to get more information about SQLite errors, one can use ADB dumpsys: adb shell dumpsys dbinfo -v combined with grep: adb shell dumpsys dbinfo -v | grep executeForLastInsertedRowId or grep'ed twice: adb shell dumpsys dbinfo -v | grep executeForChangedRowCount | grep failed
Q: How do I use keyPressed in JFrame I've made a litte game and want to be able to use the button "Enter" on a keyboard to run it but nothing happenes when i click enter. It's supposed to do what the button click does but as i said, nothing happenes. Here is my code: package com.Rohanzpc.Games; import java.awt.Color; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import java.awt.Font; import javax.swing.SwingConstants; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.text.DecimalFormat; public class RNGF extends JFrame implements KeyListener{ private static final long serialVersionUID = 1L; private JPanel contentPane; private JTextField txtDice; private JTextField textCount; private JTextField textRN; private JTextField textIn; private JTextField textMess; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { RNGF frame = new RNGF(); frame.setVisible(true); frame.setTitle("RNG"); frame.setResizable(false); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public RNGF() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); txtDice = new JTextField(); txtDice.setHorizontalAlignment(SwingConstants.CENTER); txtDice.setText("Dice Game"); txtDice.setBorder(null); txtDice.setBackground(new Color(240,240,240)); txtDice.setFont(new Font("Trebuchet MS", Font.PLAIN, 18)); txtDice.setEditable(false); txtDice.setBounds(159, 11, 106, 27); contentPane.add(txtDice); txtDice.setColumns(10); textCount = new JTextField(); textCount.setEditable(false); textCount.setBounds(20, 80, 100, 30); contentPane.add(textCount); textCount.setColumns(10); textCount.setText("3"); textRN = new JTextField(); textRN.setEditable(false); textRN.setBounds(314, 80, 100, 30); contentPane.add(textRN); textRN.setColumns(10); textIn = new JTextField(); textIn.setBounds(159, 143, 106, 27); contentPane.add(textIn); textIn.setColumns(10); JButton btnEnter = new JButton("BET"); btnEnter.setFont(new Font("Trebuchet MS", Font.PLAIN, 11)); btnEnter.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent enter) { double rn = Math.random() * 10; DecimalFormat rnFormat = new DecimalFormat("#.0000"); textRN.setText(rnFormat.format(rn)); //Random Number String InS = textIn.getText(); double in; in = Double.parseDouble(InS); if(in > 6) { in = 6; } if(in < 0) { in = 0; } //Input double credit = 6 - in; String CoS = textCount.getText(); double count; count = Double.parseDouble(CoS); if(in > rn) { textMess.setText("You won!"); count += credit; String countT = Double.toString(count); textCount.setText(countT); } else { count -= 1; textMess.setText("You lost!"); String countT = Double.toString(count); textCount.setText(countT); } if(count <= 0) { textCount.setText("0"); textMess.setText("Game over!"); textIn.setEditable(false); } System.out.println(rn); } }); btnEnter.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { double rn = Math.random() * 10; DecimalFormat rnFormat = new DecimalFormat("#.0000"); textRN.setText(rnFormat.format(rn)); //Random Number String InS = textIn.getText(); double in; in = Double.parseDouble(InS); if(in > 6) { in = 6; } if(in < 0) { in = 0; } //Input double credit = 6 - in; String CoS = textCount.getText(); double count; count = Double.parseDouble(CoS); if(in > rn) { textMess.setText("You won!"); count += credit; String countT = Double.toString(count); textCount.setText(countT); } else { count -= 1; textMess.setText("You lost!"); String countT = Double.toString(count); textCount.setText(countT); } if(count <= 0) { textCount.setText("0"); textMess.setText("Game over!"); textIn.setEditable(false); } System.out.println(rn); } }); btnEnter.setBounds(166, 181, 90, 23); contentPane.add(btnEnter); textMess = new JTextField(); textMess.setEditable(false); textMess.setFont(new Font("Tahoma", Font.PLAIN, 13)); textMess.setBounds(146, 71, 136, 39); contentPane.add(textMess); textMess.setColumns(10); } @Override public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } } A: The easiest way to make a JButton the default button for the frame is to use: getRootPane().setDefaultButton( btnEnter ); now pressing the Enter key will invoke the button whether it has focus or not. A: you can try this getContentPane().registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) {//instructions} }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0),JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
Q: Creating RDD from sequence of GenericRecord in spark will change field values in generic record When I create RDD from GenericRecords (avro), immiediately collect it and print those records I am receiving wrong field values - modified in strange way: all values of the field has value equal to the first field prior to schema i.e def createGenericRecord(first: String, second: String) = { val schemaString = """ |{ | "type": "record", | "name": "test_schema", | "fields":[ | { "name": "test_field1", "type": "string" }, | { "name": "test_field2", "type": ["null", "string"] } |] |} """.stripMargin val parser = new Schema.Parser() parser.setValidate(true) parser.setValidateDefaults(true) val schema = parser.parse(schemaString); val genericRecord = new Record(schema) genericRecord.put("test_field1", first) genericRecord.put("test_field2", second) genericRecord } val record1 = createGenericRecord("test1","test2") val record2 = createGenericRecord("test3","test4") println(record1)//prints {"test_field1": "test1", "test_field2": "test2"} println(record2)//prints {"test_field1": "test3", "test_field2": "test4"} val t = sc.makeRDD(Seq(record1, record2)) val collected = t.collect() println(collected(0))//prints {"test_field1": "test1", "test_field2": "test1"} println(collected(1))//prints {"test_field1": "test3", "test_field2": "test3"} I am using spark 1.2.0 with spark.serialiazier configured to org.apache.spark.serializer.KryoSerializer A: The solution for this problem is to update arg.apache.avro % avro dependency to the version 1.7.7.
Q: How to calculate progression ratio of a set of numbers? English is not my native language, so I will try to explain my problem. I am doing web design and I am trying to use math to calculate the width of an element within different screen resolutions. I found out that on resolution 1200, the element should have a width of 150. On resolution 991, the element should have a width of 78. So the two sets are (991,1200) and (78,150). 991 -> 78 1200 -> 150 In CSS there is a unit (vw) which is equal to the current resolution. So for example if the user is on 1100 resolution, 100vw is equal to 1100. I will be using this unit to automate calculation for different resolutions and it will be incredibly useful if there is a formula for calculating the ratio between the two sets of numbers. My question is how to find the ratio on any current resolution? Also, is this called geometric progression? A: If I understand your question correctly, you're looking for an arithmetic progression (not geometric). The formula is: $78+(R-991)\frac{72}{209}$ where $R$ is the screen resolution. Method: For two "sets" (as you call them) $(a,b)$ and $(c,d)$, you can easily find the formula like this: $$b+(R-a)\frac{d-b}{c-a}.$$
Q: Spark Scala compiler not complaining about double vs. triple equals I get a compiler error if I try this df.filter($"foo" == lit(0)) forgetting that I need a triple equals in Spark. However, if I do this, I get the wrong answer but no error: df.filter($"foo".between(baz, quux) || $"foo" == lit(0)) Can someone explain why compile-time checks help me in the first case, but not the second? A: Because $"foo" == lit(0) is always evaluated as Boolean = false. So in the first case, you trying to call method filter by passing a Boolean whereas it expects a string expression or column expression. Thus you get an error. Now in the second, case: $"foo".between(baz, quux) || $"foo" == lit(0) is evaluated as: (((foo >= baz) AND (foo <= quux)) OR false) which is accepted beacause you doing an OR || between a column expression ($"foo".between(baz, quux)) and a literal boolean false. In other words, it is interpreted as $"foo".between(baz, quux) || lit(false)
Q: conditional style on button in html table I am using a for loop to display data inside a table. my html code: <tbody> {% for deal_id, deal_name, deal_status in deals_list %} <tr> <td>{{deal_id}}</td> <td><a href="/deal_data?deal_id={{deal_id}}&vendor_id={{vendor_id}}">#{{deal_id}}</a></td> <td>{{deal_name}}</td> <td><button type="button" class="btn btn-success" disabled="true">{{deal_status}}</button></td> </tr> {% endfor %} </tbody> currently i am using class btn btn-success for all the deal status. I want when deal_status is 'ACTIVE', btn btn-success must be used. if deal_status is 'INACTIVE', btn btn-danger must be used. How to do that? A: use the if-else blocks to control only the conditional output, which is the button class <button type="button" class="btn {% if deal_status == 'ACTIVE' %} btn-sucess {% else %} btw-danger {% endif %}" disabled="true"> A: Try: <tbody> {% for deal_id, deal_name, deal_status in deals_list %} <tr> <td>{{deal_id}}</td> <td><a href="/deal_data?deal_id={{deal_id}}&vendor_id={{vendor_id}}">#{{deal_id}}</a></td> <td>{{deal_name}}</td> <td>{% if deal_status.INACTIVE %}<button type="button" class="btn btn-success" disabled="true">{{deal_status}}</button>{% else %}<button type="button" class="btn btn-danger" disabled="true">{{deal_status}}</button>{% endif %}</td> </tr> {% endfor %}
Q: List of lists duplicate removal based on 2 elements I have a list of lists that looks like: [[Joel,Green,597], [Katie,Higgins,623], [Joel,Green,123], ...] I want to remove elements of the list by looking at name and surname (elements that have the same name AND surname should be removed). In the above example the resulting list should contain only: [[Katie,Higgins,623]] I have tried the below code, but it performs duplicate removal only if all three elements of some lists are identical: newlist = [] reader = csv.reader(f,delimiter=",") # read content my_list = list(reader) #put content in my_list for i in my_list: if i not in newlist: newlist.append(i) Can anybody help? A: use DataFrame.drop_duplicates: pd.read_csv(filename, header=None, names=['first','last','val']) \ .drop_duplicates(['first','last'], keep=False) \ .values.tolist() from docs: keep : {'first', 'last', False}, default 'first' first : Drop duplicates except for the first occurrence. last : Drop duplicates except for the last occurrence. False : Drop all duplicates. A: Since you tag pandas here is the pandas' way , by using drop_duplicates pd.Series(l).apply(pd.Series).drop_duplicates([0,1],keep=False).values.tolist() Out[1267]: [['Katie', 'Higgins', 623]] More info : l=[['Joel','Green',597], ['Katie','Higgins',623], ['Joel','Green',123]] A: You better use a Counter here that keeps track of tuples containing the name and surname of the person. We can then perform a two-pass algorithm: * *first construct the Counter; *next filter the list. We can do this like: from collections import Counter from operator import itemgetter reader = csv.reader(f,delimiter=",") my_list = list(reader) getter = itemgetter(0,1) counter = Counter(map(getter, my_list)) new_list = [item for item in my_list if counter[getter(item)] <= 1] So we filter all items out of the list, if the getter(item) (a tuple containing the first two items) has occured two times or more.
Q: Linear power supply using LM338 I'm trying to design a linear power supply to provide 32V and up to 10 amps from a 50V source. Is this the correct way of using multiple LM338 regulators to achieve this? A: Problem 1 The LM338 has an input-output voltage differential of 40V, and you've got those great big caps in the feedback path. That will cause the output to start low and ramp up slowly (8-10 volts/second) -- so unless that 50V supply ramps up slower than that, you have problems. You can alleviate this with zeners across the in/out pins, though. Problem 2 The LM338 has 50 to 100\$\mu\$A of current coming out of its adjustment pin. That means that the output voltage, as you've designed it, is between 36V and 41V. You need to reduce the values of all the resistors so the standing current in the adjust resistors better swamps the current from the adjust pin. Problem 3 They're not going to share current nicely. One will try to carry the whole load until it fries, and then the other will try until it fries. Generally you want to design one power supply; when things get this power-hungry, you want to use a controller chip (like the LM723, if you insist on being old school) and pass transistors. Problem 4 They're going to get hot. You're dropping 18V at 5A -- that's 90 watts per device. The junction-to-case thermal resistance is 0.7 degrees/W, so you would need to keep the case at 62 degrees C to keep the junction temperature to 125 degrees C. That's going to limit the ambient temperature you can operate in, and even assuming a 25 degree C room temperature (which, trust me, is unrealistic), you'll need a big heat sink.
Q: perl while loop not working Below is my file which I am seperating by delimeneter and further sending through email list : Device1|City|Street|roadname|region|state|area|country|countrycode ________________________________________________ Device1|City|Street|roadname|region|state|area|country|countrycode Device2|City|Street|roadname|region|state|area|country|countrycode Device3|No data found Device4|No data found _________________________________________________ my $filename = '/tmp/list.txt'; open my $ifh, '<', $filename or die "Cannot open '$file' for reading: $!"; local $/ = ''; my $filename = <$ifh>; my @arr = split(/\|/, $filename , -1); $Device = $arr[0]; $Region = $arr[2]; $State = $arr[3]; $area = $arr[10]; $country = $arr[19]; $logger->debug("$logid >> file information Device Name: $Device"); $logger->debug("$logid >> file information Region: $Region"); $logger->debug("$logid >> file information State: $State"); $logger->debug("$logid >> file information Area: $area"); $logger->debug("$logid >> file information Country: $country"); close( $ifh ); I am able to get below info but my requirement is whenever in the line it shows "No data found" assign it to variable for eg.. "pattern" which i will further send via email. $smtp->datasend("$Device1|$region|$state|$area|$country\n"); $smtp->datasend("$pattern\n"); Thanks A: I think what you want is something like this: use strict; use warnings; open my $INPUT, '<', '/tmp/list.txt' or die $!; while (<$INPUT>) { chomp; my ($device, $data) = split(/\|/, $_, 2); if ($data eq 'No data found') { # Do whatever you need to do when there is no data } else { my @values = split(/\|/, $data); my ($region, $state, $area) = @values[3,4,5]; # Further processing as needed } } close $INPUT; A few notes: * *always use strict and use warnings - it will catch many problems for you. Like the fact that you declare my $filename twice. *The third argument to split is optional and only meaningful if it is positive. *You're setting $/ = '' presumably to slurp the whole file at once, but you want to process it line-by-line.
Q: how to make xulrunner with python I want make a stand application use python and xulrunner, but I am very confused, I use pyxpcomext with xulrunner 1.9.1,and it can word, but with python logic can not import pyd? I used lxml in this app. In lxml there is a etree.pyd.and can not import it. But I saw a Miro, it is xulrunner and python. I want rebuild my app like Miro, can any one give me some point? and how to build to make a framework like Miro. thanks~
Q: CRITICAL_SECTION / CONDITION_VARIABLE Deadlock in Win32 Why does this code cause a deadlock? THREAD 1: EnterCriticalSection( &lock_ ); ... Create thread 1 EnterCriticalSection( &lock_ ); while (pred) { SleepConditionVariableCs( &cond_, &lock_ ); // At this point, I would expect thread #2 to wake up, but it doesn't. } LeaveCriticalSection( &lock_ ); LeaveCriticalSEction( &lock_ ); THREAD 2: EnterCriticalSection( &lock_ ); // This never runs ... Do something else for a while LeaveCriticalSection( &lock_ ); According to the Win32 API, EnterCriticalSection can be called twice in a row from the same thread without deadlocking. It appears that SleepConditionVariableCS only unlocks the critical section once, which means that thread #2 will never run. Is my reasoning correct here? Basically, what I want is something like Java's ReentrantLock. What's the difference between ReentrantLock and CRITICAL_SECTION? A: It appears that SleepConditionVariableCS only unlocks the critical section once, which means that thread #2 will never run.
Q: How to create a set of unique random numbers? I've made this code for practicing and I want to make a list that keeps every number that this code wrote before so I don't want to get duplicates. It's just guessing random numbers and I don't want it to guess the number that it already guessed before. Just to be clear I want to make it as a list int password = 432678; int valt = 999999; for (int i = 0; i < valt; i++) { int[] test2 = new int[valt]; Random randNum = new Random(); for (int j = 0; j < test2.Length; j++) { test2[i] = randNum.Next(1, valt); Console.WriteLine("CURRENT: " + test2[i]); if (test2[i] == password) { goto Back; } } } Back: Console.WriteLine("password: "+ password); Console.ReadLine(); A: You can use Hashtable or Dictionary for this. Generate a number, try to check if that already exists. If not let's use that. If it is a duplicate, go on and generate another number. You might also look for GUID if that supports your scenario. There is one more approach that might suit you. Instead of generating random numbers, you could also increment numbers with each turn. So next will always be different from the previous. A: Should work: Random randNum = new Random(); int password = 432678; int valt = 999999; //INITIALIZE LIST List<int> list = new List<int>(); for (int i = 0; i < valt; i++) list.Add(i); while (list.Count > 0) { int index = randNum.Next(1, list.Count); Console.WriteLine("CURRENT: " + list[index] + ", LIST SIZE: " + list.Count); //BREAK WHILE if (list[index] == password) break; //REMOVE INDEX FROM LIST list.RemoveAt(index); } Console.WriteLine("password: " + password); Console.ReadLine(); A: Martin's code: I would set the random to static. static Random randNum = new Random(); int password = 432678; int valt = 999999; //INITIALIZE LIST List<int> list = new List<int>(); for (int i = 0; i < valt; i++) list.Add(i); while (list.Count > 0) { int index = randNum.Next(1, list.Count); Console.WriteLine("CURRENT: " + list[index] + ", LIST SIZE: " + list.Count); //BREAK WHILE if (list[index] == password) break; //REMOVE INDEX FROM LIST list.Remove(index); } Console.WriteLine("password: " + password); Console.ReadLine();
Q: iptables INPUT command On a machine called ubuntu1, this is the iptables command: sudo iptables -A INPUT -p icmp -j DROP on the other computer (xp1) I can not ping the ubuntu1.So this is OK. But On ubuntu1 can ping xp1. and I think this is not OK. I do not have problem with ping request but I have problem with ping replay from xp1. Why does that command not drop the replay of ping which is an ICMP packet? UPDATE: I did a mistake . I did not see the replay on terminal!!! I just see the replay on wireshark.!!! A: The command which you are entering is just for blocking incoming ICMP connection if you want to block outgoing ICMP connection you have to choose output chain i.e sudo iptables -A OUTPUT -p icmp -j DROP
Q: Integrating Facebook SDK with Xcode Swift project - AppDelegate errors? I'm trying to integrate the Facebook SDK according to the guidelines here: https://developers.facebook.com/docs/swift/getting-started I've done the CocoaPods steps and am at the stage headed 'Connect Your App Delegate'. However I'm getting errors from Xcode preventing compilation: Use of unresolved identifier: SDKApplicationDelegate User of unresolved identifier: SDKApplicationDelegate This is my AppDelegate. Am I missing an import statement or something? // // AppDelegate.swift // TestFBSDK // // Created by laurie hocking on 09/02/2019. // Copyright © 2019 laurie hocking. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { SDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) return true } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { return SDKApplicationDelegate.sharedInstance().application(app, open: url, options: options) } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } A: I can only think that the way that I had been trying to use Cocoapods wasn't right. When I ended up importing the frameworks manually it worked ok as follows: import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) incrementAppRuns() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. incrementAppRuns() } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options) } } A: You should import the SDK: import FacebookCore And I think the call should be: SDKApplicationDelegate.shared not SDKApplicationDelegate.sharedInstance() Hope this helps.
Q: coroutine Flow : Not sure how to convert a Cursor to this method's return type When I am trying to change the Dao to the new FlowApi, I am getting the compilation error stating that Not sure how to convert a Cursor to this method's return type public abstract kotlinx.coroutines.flow.Flow<java.util.List<com.ezek.ezign.model.ECampaign>> readCampaigns(); The Dao is @Dao interface CampaignDao { @Query("SELECT * FROM campaign ORDER BY timeStamp ASC") fun readCampaigns(): Flow<List<ECampaign>> @Query("SELECT * FROM campaign WHERE id = :campaignId") fun readCampaign(campaignId: Int): Flow<ECampaign> } and the dependencies are implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2' implementation "android.arch.persistence.room:runtime:$rootProject.ext.room_version" kapt "android.arch.persistence.room:compiler:$rootProject.ext.room_version" //room_version = "2.1.0" I have tried with Both List and ArrayList, but No luck. Thanks in advance. A: You've left a comment that you're using 2.1.0 as Room version. Please give this a read and you'll find that 2.2.0-alpha2 is required for using Flow. Update the version and it should work. Room 2.2.0-alpha02 advertised Flow support A: Do not use both suspend and Flow<> on the same method! Like this @Query("SELECT * FROM user") suspend fun loadAll(): Flow<Array<User>> Just @Query("SELECT * FROM user") suspend fun loadAll(): Array<User> OR @Query("SELECT * FROM user") fun loadAll(): Flow<Array<User>> A: I tried the approaches provided in the other answers, namely avoiding Flow and LiveData in DAO that have suspend function but I was still getting the error. In the end, my problem was related to my dependencies. I had multiple room dependencies like: def room_version = "2.2.5" implementation "androidx.room:room-runtime:$room_version" kapt "android.arch.persistence.room:compiler:1.1.1" implementation "androidx.room:room-ktx:$room_version" When only the last one was required (SEE EDIT): implementation "androidx.room:room-ktx:2.2.5" EDIT Actually, this is not event true. It compiled fine but when I launched the app, I had an error at runtime. I could make it work by swapping the compiler version: def room_version = "2.2.5" implementation "androidx.room:room-runtime:$room_version" kapt "androidx.room:room-compiler:$room_version" implementation "androidx.room:room-ktx:$room_version"
Q: How to obtain a certain expression as an expectation I have a probability space $(\Omega, M, \mathbb{P})$, where each $\omega \in \Omega$ is a random subset of natural numbers (i.e. This is a probability space of sequence of natural numbers sometimes used in probabilistic number theory. Even though it is referred to as sequences, it is actually subsets). Suppose I have a collection of triplets of natural numbers $F$. Denote $F(\omega) = \{ \theta = \{ n_1, n_2, n_3 \} \in F : \theta \subseteq \omega \}$. In particular, for each $\omega \in \Omega$, $|F(\omega)|$ counts the number of triplets in $F$ that is a subset of $\omega$, and it is a random variable. I know that the expectation is defined to be $$ \mathbb{E} (|F(\omega)|) = \int_{\Omega} |F(\omega)| d\mathbb{P}. $$ Could someone please explain me why $$ \mathbb{E}(|F(\omega)|) = \sum_{\theta \in F} \mathbb{P}( \theta \subseteq \omega ) $$ holds true? Thanks!
Q: Solutions for file sharing - local office plus cloud We have a main office of 8 computers, 3 Windows 10 PCs and 5 Mac desktops and laptops. We have a MacOS server as well. We have about 200 GB of files on local network shares from the Mac server. Increasingly, this is a paint point. Access to the shares on the LAN is fine, of course. But we now have remote staff who reside all across the country, and even some of our local staff work occasionally from home. I'm looking for a solution for providing the best and simplest access to all files. What I have tried: Network Shares Work OK for computers on the LAN. Using WebDAV, access is exactly the same on campus and off-campus. However, WebDAV is noticeably slower than SMB2 on campus, and SMB over VPN is intolerably slow. Access on iOS devices is not great. SharePoint as the central repository, sync files to server using OneDrive for Business, share OneDrive folder across LAN We have an Office365 subscription that comes with lots of SharePoint storage. But, I ran into all manner of permissions issues, and not all files were available off campus on the Macs (only MS Office files were accessible) unless the user synced folders (in which case a single user editing a file would trigger everybody in the office downloading a new copy—and required all folders to be synced to user machines which isn't helpful and raises issues about backups, etc. etc.). What I'm really looking for How to streamline/improve access for phone/tablet users and local PC/Mac users on the LAN; or how to browse a Sharepoint site from Mac finder; or another solution altogether that will provide a smooth experience for local and remote users (most not technically savvy, who are accustomed to browsing network shares like they browse their local file hierarchy).
Q: For loop is returning only last value For the below for loop I am able to see all values. But when I assign new object to it, the value returned is only last (Refer last code). can anyone help me here please. Is it not possible to all values displayed with assigning a value? for(i in 1:5) + { + for(j in 1:2) + { + print(i*j); + } + } Assigned a object. for(i in 1:5) + { + for(j in 1:2) + { + as <- i*j + } + } A: Here is a canonical R way of doing this: as.vector(seq(1:2)%*%t(seq(1:5))) [1] 1 2 2 4 3 6 4 8 5 10 This approach takes the dot product product between [1,2] and t[1,2,3,4,5]. Instead of using explicit loops, it used vectors to represent the bounds of your two original loops. The intermediate result is a matrix, which we can easily convert to a 1D vector in either column or row order, depending on the bounds of the loops. A: for loop approach If you want to append new values to as, you can try to update as by as <- c(as,i*j), which concatenates i*j with existing as and the result is assigned to as, i.e., as <- c() for(i in 1:5) { for(j in 1:2) { as <- c(as,i*j) } } outer approach A more efficient way to achieve the same goal can be using outer, i.e., as <- c(t(outer(1:5,1:2))) A: So, the for loop is very inefficient here. You should multiply vectors instead. E.g. rep(1:5, each = 2) gives you [1] 1 1 2 2 3 3 4 4 5 5 and if you multiply this with 1:2 the shorter vector gets recycled and you get this: rep(1:5, each = 2) * 1:2 [1] 1 2 2 4 3 6 4 8 5 10
Q: Android LiveData Transformation: Changing LiveData object value I have one LiveData object that holds a list of Users and I am trying to transfer over the data to another LiveData object to be used elsewhere. I am using MVVM with Room so I get LiveData from the database and on the ViewModel, I am trying to convert the User object in the LiveData to a Person object to show in the UI. So I have one variable that is LiveData<List<User>> class User(var firstName: String, var lastName: String, var age: Integer) and I am trying to convert it to LiveData<List<Person>> (as an example) class Person() { lateinit var firstName: String lateinit var age: Integer } and the way I am trying to change them is by using LiveData Transformations.map ViewModel: val list2: LiveData<List<User>> = repo.getAll() var liveList: LiveData<ArrayList<Person>> = MutableLiveData() liveList = Transformations.map(list2) { list -> val newList: ArrayList<Person> = ArrayList() list?.forEach { val temp = Person() temp.firstName = it.firstName temp.age = it.age newList.add(temp) } return@map newList } but when I run it, it crashes or doesn't update the UI. Thanks! A: The main problem with your code is that it uses var in var liveList: LiveData instead of using val. You should declare the liveList variable like this: val liveList = Transformations.map(list2) { list -> ... } Why? Generally, a LiveData variable should always be declared with val. The reason is that the purpose of LiveData is to allow us to observe the up-to-date value held by the LiveData. We do it by code like this: liveList.observe(this) { list -> showList(list) } With this code, we ensure that the updated list is always shown. Whenever the list value which is held by liveList changes, the UI is updated as a result. But if the liveList itself also changes, the code will only observe the first LiveData of the liveList variable, and the UI will not be updated correctly. A: val liveList = MutableLiveData(repo.getAll().value.orEmpty().map { user -> Person(user.firstName, user.age) }) This would be a more compact way, you could pull out the repo.getAll() call into its own variable if you like
Q: How to limit connections to a single client on a TcpNioServerConnectionFactory? I currently have a Spring Integration application which is utilizing a number of TCP inbound and outbound adapter combinations for message handling. Each Inbound Adapter in these combinations uses a TcpNioServerConnectionFactory. I want these connection factories to be configured in a way that only a single client can establish a connection to the corresponding port at a time. Any additional connections attempted on the given port need to be rejected until the current client connection is either dropped or removed. Through some initial research, I have come across the Multi Accept property on the TcpNioServerConnectionFactory which seems promising. Is setting this property to false going to accomplish what I need or is there more that needs to be done to ensure the connection factories will handle connections as I need them to? A: No; that property is unrelated, it is about prioritizing reads over accepting new connections. You can capture connection open events and immediately close the additional connection(s); here's a simple boot app as an example: @SpringBootApplication public class So59429748Application { private static final Logger logger = LoggerFactory.getLogger(So59429748Application.class); public static void main(String[] args) { SpringApplication.run(So59429748Application.class, args).close(); } @Bean public TcpNioServerConnectionFactory server() { return new TcpNioServerConnectionFactory(1234); } @EventListener public void connectionChecker(TcpConnectionOpenEvent event) { int connections = server().getOpenConnectionIds().size(); if (event.getConnectionFactoryName().equals("server") && connections > 1) { logger.info(String.format("Too many connections (%d); closing %s", connections, event.getConnectionId())); server().closeConnection(event.getConnectionId()); } } @Bean public ApplicationRunner runner() { return args -> { server().registerListener(msg -> false); server().start(); Thread.sleep(2000); Socket socket1 = SocketFactory.getDefault().createSocket("localhost", 1234); Socket socket2 = SocketFactory.getDefault().createSocket("localhost", 1234); logger.info("EOF on second socket:" + socket2.getInputStream().read()); socket1.close(); }; } } 2019-12-20 13:50:18.842 INFO 86323 --- [pool-1-thread-1] com.example.demo.So59429748Application : Too many connections (2); closing localhost:49562:1234:b4d65f24-158c-4784-87dd-9b5e875aa08a 2019-12-20 13:50:18.843 INFO 86323 --- [ main] com.example.demo.So59429748Application : EOF on second socket:-1
Q: API welcomescreen.close(); doesnt works javascript I'm trying to close welcomescreen using welcomescreen.open(false);. I'm also trying welcomescreen.close(); but it doesn't work either. Can somebody show me right way to solve this? I can hide welcome screen by set open: false but when i put in event like this in app.js it still opened onDeviceReady: function() { this.receivedEvent('deviceready'); StatusBar.styleLightContent(); window.setTimeout(function () { navigator.splashscreen.hide(); }, 0 - 0); welcomescreen.open(false); }, Here welcomescreen.js based on this library A: welcomescreen.open(false); is not work try read documentation first. try this onDeviceReady: function() { this.receivedEvent('deviceready'); StatusBar.styleLightContent(); window.setTimeout(function () { navigator.splashscreen.hide(); }, 0 - 0); welcomescreen.close(true); },
Q: How to tell Firebug to skip debugging jquery.js I've set a breakpoint in my javascript code and started to debug. At certain points, the debugger jumps into the linked jquery.min.js file and just stops. Is there any way to tell Firebug to skip certain files and stay in my code only?
Q: Merge two array list into a TreeMap in java I want to combine these two text files Driver details text file: AB11; Angela AB22; Beatrice Journeys text file: AB22,Edinburgh ,6 AB11,Thunderdome,1 AB11,Station,5 And I want my output to be only the names and where the person has been. It should look like this: Angela Thunderdone Station Beatrice Edinburgh Here is my code. I'm not sure what i'm doing wrong but i'm not getting the right output. ArrayList<String> names = new ArrayList<String>(); TreeSet<String> destinations = new TreeSet<String>(); public TaxiReader() { BufferedReader brName = null; BufferedReader brDest = null; try { // Have the buffered readers start to read the text files brName = new BufferedReader(new FileReader("taxi_details.txt")); brDest = new BufferedReader(new FileReader("2017_journeys.txt")); String line = brName.readLine(); String lines = brDest.readLine(); while (line != null && lines != null ){ // The input lines are split on the basis of certain characters that the text files use to split up the fields within them String name [] = line.split(";"); String destination [] = lines.split(","); // Add names and destinations to the different arraylists String x = new String(name[1]); //names.add(x); String y = new String (destination[1]); destinations.add(y); // add arraylists to treemap TreeMap <String, TreeSet<String>> taxiDetails = new TreeMap <String, TreeSet<String>> (); taxiDetails.put(x, destinations); System.out.println(taxiDetails); // Reads the next line of the text files line = brName.readLine(); lines = brDest.readLine(); } // Catch blocks exist here to catch every potential error } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); // Finally block exists to close the files and handle any potential exceptions that can happen as a result } finally { try { if (brName != null) brName.close(); } catch (IOException ex) { ex.printStackTrace(); } } } public static void main (String [] args){ TaxiReader reader = new TaxiReader(); } A: You are reading 2 files in parallel, I don't think that's gonna work too well. Try reading one file at a time. Also you might want to rethink your data structures. The first file relates a key "AB11" to a value "Angela". A map is better than an arraylist: Map<String, String> names = new HashMap<String, String>(); String key = line.split(",")[0]; // "AB11" String value = line.split(",")[1]; // "Angela" names.put(key, value) names.get("AB11"); // "Angela" Similarly, the second file relates a key "AB11" to multiple values "Thunderdome", "Station". You could also use a map for this: Map<String, List<String>> destinations = new HashMap<String, List<String>>(); String key = line.split(",")[0]; // "AB11" String value = line.split(",")[1]; // "Station" if(map.get(key) == null) { List<String> values = new LinkedList<String>(); values.add(value); map.put(key, values); } else { // we already have a destination value stored for this key // add a new destination to the list List<String> values = map.get(key); values.add(value); } To get the output you want: // for each entry in the names map for(Map.Entry<String, String> entry : names.entrySet()) { String key = entry.getKey(); String name = entry.getValue(); // print the name System.out.println(name); // use the key to retrieve the list of destinations for this name List<String> values = destinations.get(key); for(String destination : values) { // print each destination with a small indentation System.out.println(" " + destination); } }
Q: Django login lost during redirect from IFRAME. I have got IFRAME with login screen for design reasons. And when user logged in I trigger the parent redirect to '/my_app/welcome/' using redirect.html. After redirect user becomes not logged in. I checked request.user.username in a view (for '/my_app/welcome/') but login was lost. Please advise how to keep it logged in ? File views.py: def login(request, template_name): username = password = '' if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) request.user = user if user is not None: if user.is_active: return TemplateResponse(request, 'accounts/redirect.html', {'redirect_url':'/my_app/welcome/'}) return render_to_response(template_name, locals(), context_instance=RequestContext(request)) File redirect.html: <html> <head> <script> window.top.location.href = '{{ redirect_url }}'; </script> </head> <body></body> </html> Thanks A: I'm not sure why you think that simply assigning the user to request.user is enough to log them in. It isn't, because it doesn't do anything like setting the session cookie. The correct way to log a user in, as the documentation explains, is to call the appropriately-named login function . You probably want to call your view function something different to avoid name confusion. A: You need add auth_login(request, user) after if user.is_active: from django.contrib.auth import login as auth_login
Q: Position laser-controls entity after camera rotation I have the following code for the laser controls which are perfectly positioned when the camera looks straight ahead after entering VR mode. <a-entity position="0.25 1.25 -0.2" class="laser-controls"> <a-entity laser-controls="hand: right" line="color: red"></a-entity></a-entity> The issue is: when I rotate my head (camera), I would like to let the controls follow my head rotation smoothly (I have some code which looks if the rotation is greater than 110 degrees). I don't want the controllers be part of the camera since they should keep their own independent rotation. What I like is the behaviour of the controller model in Oculus Home (Gear VR). How can I achieve this is my custom component, let's say in my tick function, which is called every two seconds (that code works already). Thanks! A: How about using getAttribute() to check the rotation of the camera component and the laser control's entity? Then you could check if the difference exceeds 110 degrees or not: let angle = laser.getAttribute('rotation'); if (camera.getAttribute('rotation').y - laser.getAttribute('rotation').y>110){ angle.y++; laser.setAttribute('rotation',angle); } else if(camera.getAttribute('rotation').y - laser.getAttribute('rotation').y<-110){ angle.y--; laser.setAttribute('rotation',angle); } UPDATE If You want to position Your controller near Your head You can: 1.Instead of angle.y++/-- change it to Your camera's rotation. You can also change its x/y position close to the camera ( like camera.position.x + 0.5 ) 2.But the above is instant, if You want to make it smooth, You could use the animation component, when the delta degree is >110 deg, set the animation attributes to move to the camera component location/rotation, emit a beginning event, disable the rotation check, listen for the animation end event, and enable the check. a bit like this: init: function(){ this.check = true; let check = this.check; animationel.addEventListener('animationend',function(){ check = true; }); },tick(){ if(this.check){ if(rotationCheck()){ this.check = false; } } }
Q: Filter numpy array if elements in subarrays are repeated position-wise in the other subarrays Unluckily it is terribly similar to: Filter a numpy array if any list within it contains at least one value of a previous row which is a question I asked some minutes ago. In this case I have a list b = np.array([[1,2], [1,8], [2,3], [4,2], [5,6], [7,8], [3,3], [10,1]]) What I want to do is slightly different now. I want to start at the beginning of the list and for each subarray. I want to check whether the element in position i (with respect to the subarray) is encountered in position i also in other subarrays. Hence, removing all such elements. For instance: * *Look at [1,2]: eliminate [1,8] cause 1 is in position 0, eliminate [4,2] cause 2 is in position 1. However do not eliminate [10,1] or [2,3] since 1 and 2 are in different positions. *Look at [2,3] ,eliminate [3,3] since 3 is in position 1. *Look at [5,6], nothing to eliminate. *Look at [7,8], nothing to eliminate So the result would be b = np.array([[1,2], [2,3], [5,6], 7,8], [10,1]]) My Try As you can see in my previous post I tried different things. Now, I noticed that a==b gives a useful array, that could be used for filtering, but I can't quite decide how to put it all together. A: Edit: My initial solution doesn't consistently produce the result you're looking for, example at bottom. So here's an alternative solution, which actually iterates through the rows as seems necessary: ar = b.copy() new_rows = [] while ar.shape[0]: new_rows.append(ar[0]) ar = ar[(ar != ar[0]).all(axis=1)] np.stack(new_rows) Out[463]: array([[ 1, 2], [ 2, 3], [ 5, 6], [ 7, 8], [10, 1]]) Original Answer: You can use np.unique with the argument return_index=True to identify rows which are the first to contain a value in a given column. You can then select these rows, in order, and do the same for the next column. ar = b.copy() num_cols = ar.shape[1] for col in range(num_cols): ar = ar[np.sort(np.unique(ar[:, col], return_index=True)[1])] ar Out[30]: array([[ 1, 2], [ 2, 3], [ 5, 6], [ 7, 8], [10, 1]]) Case where original fails: Consider ar = b[:, ::-1], with columns in reversed order. Then, num_cols = ar.shape[1] for col in range(num_cols): ar = ar[np.sort(np.unique(ar[:, col], return_index=True)[1])] Gives ar Out[426]: array([[ 2, 1], [ 3, 2], [ 6, 5], [1, 10]]) missing the desired [8, 7] row. A: Your question and example need some clarifications (why is [10, 1] not part of the final answer? If a subarray gets eliminated, does that mean it doesn't contribute to eliminating any further subarrays?), but here's a first shot. It's not very num-pythonic (or pythonic for that matter) but all it requires is a single loop through the larger array, with a map to keep track of the numbers you've seen, and a set for each number to keep track of the indices in which it's appeared. final_arr = [] found_nums = {} for subarray in array: found = False for i in xrange(len(subarray)): num = subarray[i] if num in found_nums: if i in found_nums[num]: found = True break else: found_nums[num].add(i) else: found_nums[num] = set([i]) if not found: final_arr.append(subarray)
Q: Add custom styles for stencil web component we are using stencil web components to develop our apps. I would like to add a css to my application component app-checkbox which uses stencil-checkbox component. I do not have access to edit the original web components (here stencil-checkbox)to expose "parts" or anything else. I tried to add the below code in componentDidLoad in app-checkbox but i am getting an error as index-39363c72.js:2934 TypeError: Cannot read properties of null (reading 'querySelector') for the initial load . when I navigate again to the same screen without reloading it works fine . componentDidLoad() { document.querySelector('app-checkbox')?.shadowRoot.querySelector('stencil-checkbox')?.shadowRoot.querySelector('label').setAttribute('style', 'flex-direction:column'); } Could someone please shed some light on why on initial load the hook is not getting the right document. Any other way to add the styles to the original stencil web component. I tried using ref, element etc. Thank you in advance.
Q: Is there a way to iterate over a mutable tree to get a random node? I am trying to update a node of a tree structure. A node which is to be updated is selected randomly. To sample a node in the tree using the Reservoir Sampling algorithm, I have to iterate over the nodes, so I have tried to make an Iterator for my Node enum. The problem is that, on the one hand, I have to store references for child nodes in a stack or queue, however on the other hand, I have to return a mutable reference for a parent node. Rust does not allow to make multiple mutable references for one value, neither to convert an immutable reference into a mutable reference. Is there a way to iterate over a mutable tree? Or is there another approach to randomly get a mutable reference to a node in a tree? Here is my code. #![feature(box_syntax, box_patterns)] extern crate rand; // Simple binary tree structure #[derive(Debug)] enum Node { Leaf(u8), Branch(Box<Node>, Box<Node>), } impl Node { fn iter_mut(&mut self) -> IterMut { IterMut { stack: vec![self], } } fn pick_random_node_mut<'a>(&'a mut self) -> &'a mut Node { // Revervoir sampling let rng = &mut rand::thread_rng(); rand::seq::sample_iter(rng, self.iter_mut(), 1) .ok().and_then(|mut v| v.pop()).unwrap() } } // An iterator for `Node` struct IterMut<'a> { stack: Vec<&'a mut Node>, } impl <'a> Iterator for IterMut<'a> { type Item = &'a mut Node; fn next(&mut self) -> Option<&'a mut Node> { let node = self.stack.pop()?; // I am stucking here: cannot borrow `*node` as mutable more than once at a time if let &mut Node::Branch(box ref mut a, box ref mut b) = node { self.stack.push(b); self.stack.push(a); } Some(node) } } fn main() { use Node::*; let mut tree: Node = Branch(box Leaf(1), box Leaf(2)); println!("{:?}", tree); { let node: &mut Node = tree.pick_random_node_mut(); *node = Leaf(3); } println!("{:?}", tree); } A: No, it is not safe to write an iterator of the mutable references to the nodes of a tree. Assume we have this tree structure: +-+ +----+ +----+ | +-+ | | | | | +--v-+ +--v--+ | 50 | | 100 | +----+ +-----+ If such an iterator existed, we could call it like this: let mut all_nodes: Vec<&mut Node> = tree.iter_mut().collect(); Assume that the parent node ends up in index 0, the left node in index 1, and the right node in index 2. let (head, tail) = all_nodes.split_at_mut(1); let x = match &mut head[0] { Branch(ref mut l, _) => l, Leaf(_) => unreachable!(), }; let y = &mut tail[1]; Now x and y are mutable aliases to each other. We have violated a fundamental Rust requirement in completely safe code. That's why such an iterator is not possible. You could implement an iterator of mutable references to the values in the tree: impl<'a> Iterator for IterMut<'a> { type Item = &'a mut u8; fn next(&mut self) -> Option<Self::Item> { loop { let node = self.stack.pop()?; match node { Node::Branch(a, b) => { self.stack.push(b); self.stack.push(a); } Node::Leaf(l) => return Some(l), } } } } This is safe because there's no way to go from one mutable reference to a value to another one. You can then build your random selection on top of that: { let rando = match rand::seq::sample_iter(&mut rand::thread_rng(), tree.iter_mut(), 1) { Ok(mut v) => v.pop().unwrap(), Err(_) => panic!("Not enough elements"), }; *rando += 1; }
Q: Android 2.3.3 and XmlPullParser.nextText() Article on this link (android developer's blog) says: Using XmlPullParser is an efficient and maintainable way to parse XML on Android. Historically Android has had two implementations of this interface: - KXmlParser, via XmlPullParserFactory.newPullParser(). - ExpatPullParser, via Xml.newPullParser(). The implementation from Xml.newPullParser() had a bug where calls to nextText() didn't always advance to the END_TAG as the documentation promised it would. As a consequence, some apps may be working around the bug with extra calls to next() or nextTag(): ... I do not understand if this refers to XmlPullParserFactory.newPullParser() or Xml.newPullParser() or to both. For example, will this code on Android 2.3.3 and lower create a bug: XmlPullParser xpp = XmlPullParserFactory.newInstance().newPullParser(); int event = xpp.getEventType(); while (...event not end doc and tag not equal search term...){ event = xpp.next(); } myClass.setSomeText(xpp.nextText());
Q: Problem with bluetooth in Ubuntu 12.10 I am a new user of Ubuntu and I am really fascinated by its performance. Coming to the question, I am facing some problems with the bluetooth connection. When I connect my mobile with the computer through bluetooth, and then click on 'Browse Device', the phone folder opens, but after 1 second, the folder gets closed by itself. But I am able to connect the internet through my phone. Can anyone help me?
Q: How to pass a variable from WordPress button or link to dyanmically fill field in a gravity form I created a signup button on each event on a page that links to a single form and dynamically fills in the hidden title field so that when we view the submissions from an CSV that the WordPress system we have a way to sort by the event. The problem we had is when we pass that variable via the URL, people figured out they could signup by going to another open event and change the event to a closed one in the URL and signup. Is there a way to "hide" or pass that title as a variable so that it can still dynamically fill that hidden field?
Q: Select specific fields with google BigQuery I am using firebase analytics with an app. When i do: SELECT * FROM `analytics_xxx.events_xxxxx` where event_name="level_quit" it works fine and shows that event values. When I try to select specific fields or order by specific field I always get a syntax error. For example: SELECT level_retry FROM `analytics_xxx.events_xxxxx` where event_name="level_quit" I receive an error "Unrecognized name: level_retry at [8:9]" I am not sure how to use the 'event_params.value.int_value' values in the query and why something that seems simple is getting complicated. What I am trying to achieve is to display in which levels I got most retires. This is the result set: A: Try doing: SELECT t.* EXCEPT (event_params), struct(e) as event_params FROM `analytics_xxx.events_xxxxx` t, t.even_params e WHERE e.key in UNNEST(['level', 'level_retry']) Please let me know if it helps you A: Below is for BigQuery Standard SQL #standardSQL SELECT * EXCEPT(event_name, event_params), (SELECT value.int_value FROM t.event_params WHERE key = 'level') AS level, (SELECT value.int_value FROM t.event_params WHERE key = 'level_retry') AS level_retry FROM `project.analytics_xxx.events_xxxxx` t WHERE event_name = 'level_quit' for the sample in your question - result will be as below Row event_date event_timestamp level level_retry 1 20200114 1579008893128003 20 0
Q: Updating state object inside an array from child component First I want to apologize because I'm newbie using react, so for sure I'm doing something really messed up. That said, I need to update a specific state at parent component from child component, i'm using a handler inside the parent component to handle all the state changes, but it doesn't seem to work when I have arrays and objects, also I can add objects into 'inpHotel' state, so far what I got: Parent state = { activeStep: 0, fade: false, inpDestino: null, inpPeriodo: null, inpHotel: [{ "nomeHotel": null, "urlMenorPreco": null, "quartos":[] }], inpNome: null, inpEmail: null, inpCelular: null, }; //Handle function handleChange = input => e => { this.setState({ [input]: e.target.value }); }; Child <Grid item xs={12}> <TextField defaultValue={values.inpHotel[length].quartos[i].categoriaQuarto} onChange={ handleChange(`inpHotel[${length}].quartos[${i}].categoriaQuarto`) } /> </Grid> EDIT 1 My state needs to look like this JSON { "chCidade": 0, "dataCheckIn": "", "dataCheckOut": "", "nome": "", "sobrenome": "", "celular": "", "email": "", "hoteis": [ { "nomeHotel": "", "urlMenorPreco": "", "quartos":[{ "categoriaQuarto": "", "menorPrecoDiaria": 0, "quantidadeAdulto": "", "criancas":[{"idade":0},{"idade":0}] },{ "categoriaQuarto": "", "menorPrecoDiaria": 0, "quantidadeAdulto": 0, "criancas":[] }] }, { "nomeHotel": "", "urlMenorPreco": "", "quartos":[{ "categoriaQuarto": "", "menorPrecoDiaria": 0, "quantidadeAdulto": 0, "criancas":[{"idade":0},{"idade":0}] }] } ] } A: I found out that you are using e.target.value which is the event, but you are not passing the event object on your onChange. Try this onChange={(e) => handleChange(inpHotel[${length}].quartos[${i}].categoriaQuarto, e)} Here's a sample code: https://codepen.io/gadawag/pen/vPoavP?editors=1010 A: You are calling the function handleChange() directly and it will return undefined. So you are setting onChange event to undefined.You could use wrapper function onChange={() => handleChange(`inpHotel[${length}].quartos[${i}].categoriaQuarto`)}
Q: Mock forwardRef components jest mockImplementation with typescript How are you suppose to handle mocking components in test files when the Component is wrapped in forwardRef? The mockImplementation is not on method, but instead is on a property render. import React from 'react'; import Component from './Component'; import mocked from 'ts-jest/utils' jest.mock('./Component'); const mockComponent(Component); mockComponent.mockImplementation(() => <></>) /* this returns type error that mockImplementation is not a function */ mockComponent.render.mockImplementation(() => <></>) /* this works but get a typescript error */ The typescript error I see is TS2339: Property 'render' does not exist on type 'MockedFunction "li", {}>, "button" | "slot" | "style" | "title" | "className" | "classes" | "innerRef" | "selected" | "dense" | "key" | "value" | "defaultChecked" | ... 261 more ... | "focusVisibleClassName"> & RefAttributes...>>>'. I understand why I get the type error as mockComponent.mockImplementation is undefined, but how do I get the type correctly inferred? The mock appears as { '$$typeof': Symbol(react.forward_ref), render: [Function: mockConstructor] { _isMockFunction: true, getMockImplementation: [Function], mock: [Getter/Setter], mockClear: [Function], mockReset: [Function], mockRestore: [Function], mockReturnValueOnce: [Function], mockResolvedValueOnce: [Function], mockRejectedValueOnce: [Function], mockReturnValue: [Function], mockResolvedValue: [Function], mockRejectedValue: [Function], mockImplementationOnce: [Function], mockImplementation: [Function], mockReturnThis: [Function], mockName: [Function], getMockName: [Function] } } A: import React from 'react'; // Asuming Component is a default exported component import * as Component from './Component'; jest.mock('./Component'); const MockComponent = jest.fn(() => <div />); jest.spyOn(Component.default.type, 'render').mockImplementation(MockLaneMarkup); //now you can test if the MockComponent has beenCalled
Q: Is it possible to find if a new topic is created in activemq I am developing a system which, if someone creates a topic in ActiveMQ, is required to detect the new creation of a topic by a user logging in and create a Java instance which will subscribe to that topic to talk to the user. What is the best way? I know there is DestinationSource by which I can iterate over the currently generated topics or queues so that I can find if a given topic is new or not. Is this iteration over topic list is the best way to see if there are the new topic generated? A: Just subscribe to: ActiveMQ.Advisory.Topic Then you get a datastructure DestinationInfo each time a topic is created or deleted.
Q: Android Studio gradle minimum version error I am completely new to android studio and I'm referring to the Android Developers course and they mentioned about gradle completing to sync properly and I installed everything properly. The thing is I'm getting a gradle error every time and I can't find a fix to it: Gradle sync failed: Minimum supported Gradle version is 6.5. Current version is 6.1.1. If using the gradle wrapper, try editing the distributionUrl in C:\Users\saketh\AndroidStudioProjects\Sample\gradle\wrapper\gradle-wrapper.properties to gradle-6.5-all.zip Consult IDE log for more details How do I fix this? Any help would be appreciated A: There's a gradle.properties file in your project, if you find this (it's easier to find with a CMD + shift + f for "distributionUrl") and change the version number in that URL to 6.5. After changing this make sure you Sync the project again.
Q: JSON parsing and printing JSON object with variable name I'm having trouble printing an object with a variable name. It works when I hard code it. var objectVarName = "lat"; var obj = jQuery.parseJSON(JSON.stringify(msg)); // {"lat":"93"} is what JSON.stringify(msg) prints $('#display').prepend("<br/><br/>" + JSON.stringify(msg)); //obj['lat'] works, obj[objectVarName] does not $('#display').prepend("<br/><br/>" + obj['lat']); A: Double check that your variable name, casing, etc are correct...your code works if msg is a valid object, here's what I tested: var msg = {"lat":"93"}; You can test/see the result here, I changed .prepend() to .append() so the output is in order, no other changes besides that, the result is: {"lat":"93"} 93
Q: Working with orientation change in mono for android I've used following code snippet for my activity in order to deal with orientation change. [Activity (Label = "Activity",ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.KeyboardHidden)] and public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig) { base.OnConfigurationChanged (newConfig); if (newConfig.Orientation == Android.Content.Res.Orientation.Landscape) { Console.WriteLine("landscape"); } else if (newConfig.Orientation == Android.Content.Res.Orientation.Portrait) { Console.WriteLine("portrait"); } } I start with Portrait mode, then switch to Landscape mode and again switch back to Portrait mode. So the expected output should be: landscape portrait but Console Output shows landscape landscape portrait i.e. When switching from Landscape mode to Portrait mode, if and else both gets executed. I've no idea why this is happening. I'm absolute beginner to Mono for Android, so any help appreciated. A: Here's my code if (Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape) { SetContentView(Resource.Layout.Main); //set layout for Landscape mode } else { SetContentView(Resource.Layout.MainPortrait); //set layout for Portrait mode } A: try this its working ... 1) declare above oncreate() int prev_orientation =0; 2) overide below method: @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub int orientation = getResources().getConfiguration().orientation; if(prev_orientation!=orientation){ prev_orientation = orientation; if(orientation ==1){ //por Toast.makeText(getApplicationContext(),"ort::pot"+orientation,Toast.LENGTH_LONG).show(); }else if(orientation ==2){ //land Toast.makeText(getApplicationContext(),"ort::land"+orientation,Toast.LENGTH_LONG).show(); } } super.onConfigurationChanged(newConfig); } 3) Add below line in manifeast file of activity: android:configChanges="keyboardHidden|orientation" A: i am pasting code here..try this.. public void onConfigurationChanged(Configuration orient) { super.onConfigurationChanged(orient); // Checks the orientation of the screen if (orient.orientation == Configuration.ORIENTATION_LANDSCAPE) { //code here for LANDSCAPE.. )); } else if (orient.orientation == Configuration.ORIENTATION_PORTRAIT) { //code here for PORTRAIT .. } } Call Method Like; @Override public void onCreate(Bundle savedInstanceState) { onConfigurationChanged(getResources().getConfiguration()); }
Q: Firefox add-on execute only in debugging state I have developed an add-on to communicate with a smart card. I have used winscard.dll and its functions (such as Establishment, Connecting, Transmitting). //less-privileged scope like jsp var element = document.createElement("MyExt1"); document.documentElement.appendChild(element); var evt = document.createEvent("Events"); evt.initEvent("SCardConnect", true,false); element.dispatchEvent(evt); var CardHandle = element.getAttribute("CardHandle"); alert(CardHandle); and //privileged scope which exist in my add-on . . . var MyExtension1 = { Connect : function(evt){ ... evt.target.setAttribute("CardHandle", CH.toString()); var doc = evt.target.ownerDocument; var AnswerEvt = doc.createElement("SCardConnect"); doc.documentElement.appendChild(AnswerEvt); var event = doc.createEvent("HTMLEvents"); event.initEvent("ConnectEvent",true,false); AnswerEvt.dispatchEvent(event); } } . . . document.addEventListener("SCardConnect", function(e){myExtension1.Connect(e);}, false, true); After a small introduction, this is my problem: When I install the add-on in Firefox and debug the code step by step through F10 it works fine, however if I want to run the external script without interruption (without debugging), it returns null when I get attributes. This is an event-based approach to call an add-on function from an external script function. There is another approach that used export function which I get following problem: https://stackoverflow.com/questions/32450103/calling-a-firefox-add-on-function-from-an-external-javascript-file A: You might want to move 'var CardHandle = element.getAttribute("CardHandle");' into a new function and check if its value has been valid or not in specified intervals. var varTimer = setInterval(function(){ myTimer() }, 1000); function myTimer() { var CardHandle = element.getAttribute("CardHandle"); if(CardHandle is valid) stopTimer(); } function stopTimer() { clearInterval(varTimer); }
Q: Formatting data in C# How would you format the following data outcome in C#. My controller class returns the data like the one below; I used Dapper as ORM. The problem here is it returns the number of teams times teams members (eg, Teams X Team Members)instead of team members within a team; [HttpGet("GetMyTeamsDemo")] public async Task <List<JTeam>> GetMyTeamsDemo(int UId) { List<JTeam> teams = new List<JTeam>(); JTeam jteam = new JTeam(); List<JMember> members = new List<JMember>(); var result = await _userDataStore.GetMyTeams(UId); foreach (var item in result) { jteam.TeamId = item.Id; jteam.TeamName = item.TeamName; jteam.TeamsCode = item.TeamsCode; jteam.Description = item.Description; jteam.CreatedById = item.CreatedById; jteam.CreatedByName = item.CreatedByName; jteam.TeamProfilePhoto = item.TeamProfilePhoto; jteam.CoverPhoto = item.CoverPhoto; jteam.DateCreated = item.DateCreated; var res = await _userDataStore.GetTeamMembersByTeamId(item.Id); if (res is not null) { foreach (var item1 in res) { members.Add(new JMember { MemberId = item1.MemberId, MemberName = item1.MemberName, TeamId = item1.TeamId }); //teams.Members.Add(new JTeam.JMember { MemberId = itar.MemberId, MemberName = itar.MemberName, TeamId = itar.TeamId }); jteam.Members = members; teams.Add(jteam); } } jteam = new JTeam(); } return teams; } public class JTeam { public int TeamId { get; set; } public string TeamName { get; set; } public string TeamsCode { get; set; } public string Description { get; set; } public int CreatedById { get; set; } public string CreatedByName { get; set; } public string TeamProfilePhoto { get; set; } public string CoverPhoto { get; set; } public DateTime DateCreated { get; set; } public JMember Members { get; set; } } public class JMember { public int MemberId { get; set; } public int TeamId { get; set; } public string MemberName { get; set; } } A: foreach (var item1 in res) { ... jteam.Members = members; teams.Add(jteam); } You are adding the team to the list within the foreach for the team members instead of after the members have been added to the team. It's the same object in memory, so when the JSON serializer loops through the "teams" it has multiple references to the same team and adds it multiple times to the JSON. Move teams.Add(jteam); outside of the inner foreach loop (and the if that contains it). I would also initialize jteam within the loop instead of defining it outside of the loop and resetting it at the end.
Q: Spring SAML - Use CA Root Cert instead of Server public cert in JKS I have a Spring SAML project that has a JKS with the public certificate of the IDP loaded into it. I have a theoretical question: If I were to load in the issuing root or intermediate CA into the JKS, would that be sufficient for trusting the IDP and validating the IDP SAML messages? The benefit to doing this would be that future IDPs with a common issuer would be trusted without having to load in their certificate. My understanding is that the actual public certificate of the IDP needs to be in the JDK so that Spring SAML can validate the request, however, isn't the X509 in the request sufficient for doing this and it's just a matter of validating that the certificate in the IDPs public metadata is from a trusted issuer? I'm a bit over my head with this. Any insight or explanation will be greatly appreciated! A: Yes, you can do that with the PKIX security profile. Loading the IDP certs into the keystore should be enough (provided the trustedKeys in extendedMetadata is null, which is the default). See the manual, chapter security profiles for all the details.
Q: PHP + cURL not working Trying to get the content of the a certain URL using cURL and PHP. The code is supposed to run on the sourceforge.net project web hosting server. code: <?php function get_data($url) { $ch = curl_init(); $timeout = 10; curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data = curl_exec($ch); curl_close($ch); return $data; } $url1 = urlencode("http://www.google.com"); $url2 = "http://www.google.com"; $output = get_data($url2); echo $output; ?> I've checked that cURL is supported. But the above code is not working, the page is loading till timeout with no output. I've tried the encoded url as well. Why? Error 503 Service Unavailable. PHP version 5.3.2 A: You might want to use file_get_contents $content = file_get_contents('http://www.google.com'); /some code here if needed/ return $content; You can also set files inside file_get_contents ex: $content = file_get_contents('textfile.txt'); More information about the function file_get_conents Some info which I noticed when working with cUrl: One thing I've also noticed when working with cUrl is that it works differently when the URL has http or https. You need to make sure that you code can handle this A: I replaced my curl code with yours and its not working. I tried with 'gmail.com' and it showed fine with my code and with yours it gave a '301 Moved' Error. My Code is as follows: function get_web_page($url) { //echo "curl:url<pre>".$url."</pre><BR>"; $options = array( CURLOPT_RETURNTRANSFER => true, // return web page CURLOPT_HEADER => false, // don't return headers CURLOPT_FOLLOWLOCATION => true, // follow redirects CURLOPT_ENCODING => "", // handle all encodings CURLOPT_USERAGENT => "spider", // who am i CURLOPT_AUTOREFERER => true, // set referer on redirect CURLOPT_CONNECTTIMEOUT => 15, // timeout on connect CURLOPT_TIMEOUT => 15, // timeout on response CURLOPT_MAXREDIRS => 10, // stop after 10 redirects ); $ch = curl_init($url); curl_setopt_array( $ch, $options ); $content = curl_exec( $ch ); $err = curl_errno( $ch ); $errmsg = curl_error( $ch ); $header = curl_getinfo( $ch,CURLINFO_EFFECTIVE_URL ); curl_close( $ch ); $header['errno'] = $err; $header['errmsg'] = $errmsg; //change errmsg here to errno if ($errmsg) { echo "CURL:".$errmsg."<BR>"; } return $content; }
Q: Percona XtraDB Cluster multi-node writing and unexpected deadlocks outside of transaction? I am having trouble finding an answer to this using google or Stack Overflow, so perhaps people familiar with Percona XtraDB can help answer this. I fully understand how unexpected deadlocks can occur as outlined in this article, and the solution is to make sure you wrap your transactions with retry logic so you can restart them if they fail. We already do that. https://www.percona.com/blog/2012/08/17/percona-xtradb-cluster-multi-node-writing-and-unexpected-deadlocks/ My questions is about normal updates that occur outside of a transaction in auto commit mode. Normally if you are writing only to a single SQL DB and perform an update, you get a last in wins scenario so whoever executes the statement last, is golden. Any other data is lost so if two updates occur at the same time, one of them will take hold and the others data is essentially lost. Now what happens in a multi master environment with the same thing? The difference in cluster mode with multi master is that the deadlock can occur at the point where the commit happens as opposed to when the lock is first taken on the table. So in auto commit mode, the data will get written to the DB but then it could fail when it tries to commit that to the other nodes in the cluster if something else modified the exact same record at the same time. Clearly the simply solution is to re-execute the update again and it would seem to me that the database itself should be able to handle this, since it is a single statement in auto commit mode? So is that what happens in this scenario, or do I need to start wrapping all my update code in retry handling as well and retry it myself when this fails? A: Autocommit is still a transaction; a single statement transaction. Your single statement is just wrapped up in BEGIN/COMMIT for you. I believe your logic is inverted. In PXC, the rule is "commit first wins". If you start a manual transaction on node1 (ie: autocommit=0; BEGIN;) and UPDATE id=1 and don't commit then on node2 you autocommit an update to the same row, that will succeed on node2 and succeed on node1. When you commit the manual UPDATE, you will get a deadlock error. This is correct behavior. It doesn't matter if autocommit or not; whichever commits first wins and the other transaction must re-try. This is the reason why we don't recommend writing to multiple nodes in PXC. Yes, if you want to write to multiple nodes, you need to adjust your code to "try-catch-retry" handle this error case.
Q: TextBox wraps after 9600 characters even with TextWrapping=NoWrap The title pretty much says it all. Paste a string longer than 9600 characters into a TextBox that has TextWrapping set to TextWrapping.NoWrap, and it will split it into 9600-character lines, wrap them, and grow vertically. Is there a good reason for this? Any way to prevent it? Note that "you shouldn't use TextBox for a string that long" is a valid opinion, but doesn't answer the question. :) The XAML to demonstrate this doesn't need to be any more complicated than: <Window x:Class="TestApp.TestWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Title="TestWindow" Height="300" Width="300"> <TextBox TextWrapping="NoWrap" HorizontalAlignment="Left" VerticalAlignment="Top" /> </Window> A: My solution to this was to add MaxLines="1" to the TextBox. This doesn't stop WPF from breaking very long strings into multiple lines, but it does prevent the control from growing vertically when this happens, which means users can't break my layout by pasting the full text of War and Peace into the search box. :)
Q: Run discord.py client on current event loop i am working on a discord.py bot and I want to run the discord.py client from the current event asyncio loop from discord.ext import commands import asyncio async def start(): client = commands.Bot(command_prefix = '!') @client.event async def on_ready(): print("Ready") client.run('token') asyncio.run(start()) Is it possible to do such?
Q: How to print Loop like this format i already tryout you can see my solution but its not working how to print loop exactily like 3 section i and i^2 and i^3. dont use any function just tell me is this posssible? if possible then how? i i^2 i^3 0 0 0 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 here is my solution. i am new in Programming. for(let i=0; i <= 10; i++){ document.write(`i${i} i^2 ${i**2} i^3 ${i**3}`); document.write("</br>"); };
Q: What's the formula for the number of possible answers to this puzzle? I'm trying to find what the formula is for the number of possible variations to this puzzle. I know that there is only one answer (or 4, when taking into account the variations when the grid is flipped on either axis). Does a formula exist to describe the number of combinations/permutations here? One that could be applied if the rules of the puzzle were changed? (ie, if preceding/following numbers could be placed diagonally to each other, but still not vertically or horizontally, how many possible combinations/permutations would there be? Correct me if I'm wrong, but the way I'm looking at it, the number of possible permutations when it comes to the original problem is 1, and the number of possible combinations is 4. Perhaps I'm looking in completely the wrong direction? A: With the original rules, note that the two center squares must be $1$ and $8$. Each of the center squares is next to all the other squares but one, so if any other number is in the center it will have a neighbor that is one less or one more. We might as well put the $1$ on the left. Then $7$ must be the extreme left and $2$ must be the extreme right, so the center line is $$7182$$. Now $3$ has to go above or below the $1$ and it might as well go above. $6$ has to go above or below the $8$ and putting it above will have $4$ and $5$ next to each other. Then $5$ has to go above the $8$ and $4$ below the $1$, giving the solution $$\ \ 35\\7182\\ \ \ 46$$ We made two arbitrary binary choices and can show that changing the first leaves the second available, so there are four total arrangements, which consist of flipping it horizontally, vertically, or both. If you weaken the restrictions there will be many more possibilities. One of the things that makes this a good puzzle is that you can get an answer without too much work but that you can't just randomly fill in numbers and hope to get there.
Q: Is it possible GHCJS to reuse code generated by Template Haskell At this moment GHCJS fails to compile postgresql-simple package (see [1]). I want to use persistent package to generate DB models. I wonder is it possible to compile models with GHC itself and re-use code generated by Template Haskell in GHCJS sources? I have a workaround for my issue already, but the question is still relevant however. I'll leave it open for few days and if no one will answer how to use code generated with Template Haskell I'll close it. I've pasted resulting code at the bottom. UPDATE: thomie suggested me -dth-dec-file flag, which could be written as language pragma in models file, e.g. {-# OPTIONS_GHC -dth-dec-file #-}. Then after running stack build command there is a file Model.th.hs under .stack-work/dist/<arch>/<cabal-version>/build/src folder. This file looks like valid Haskell, however GHC rejects it because of parse error (see code at the bottom). However, I've found a way to compile model with GHCJS. I've added condition in cabal file to remove postgresql-simple from dependencies: -- project.cabal library -- ... if impl(ghcjs) build-depends: persistent , persistent-template else build-depends: persistent , persistent-postgresql , persistent-template , postgresql-simple Code generated by Template Haskell (to test this code I copied this file in project source folder and added module declaration at top) -- src/Model.hs:(16,1)-(17,54): Splicing declarations instance Database.Persist.Class.PersistField.PersistField Manufacturer where Database.Persist.Class.PersistField.toPersistValue = \ ent_a9ov -> (Database.Persist.Types.Base.PersistMap GHC.Base.$ (GHC.List.zip (GHC.Base.map Data.Text.pack ["name"]) ((GHC.Base.map Database.Persist.Class.PersistField.toPersistValue) GHC.Base.$ (Database.Persist.Class.PersistEntity.toPersistFields ent_a9ov)))) Database.Persist.Class.PersistField.fromPersistValue = ((\ x_a9ow -> let columns_a9ox = Data.HashMap.Strict.fromList x_a9ow in (Database.Persist.Class.PersistEntity.fromPersistValues GHC.Base.$ ((GHC.Base.map (\ name_a9oy -> case Data.HashMap.Base.lookup (Data.Text.pack name_a9oy) columns_a9ox of { GHC.Base.Just v_a9oz -> v_a9oz GHC.Base.Nothing -> Database.Persist.Types.Base.PersistNull })) GHC.Base.$ ["name"]))) Control.Monad.<=< Database.Persist.Class.PersistField.getPersistMap) instance Database.Persist.Sql.Class.PersistFieldSql Manufacturer where Database.Persist.Sql.Class.sqlType _ = Database.Persist.Types.Base.SqlString data Manufacturer = Manufacturer {manufacturerName :: !Text} deriving (Show, Read, Typeable) type ManufacturerId = Database.Persist.Class.PersistEntity.Key Manufacturer instance Database.Persist.Class.PersistEntity.PersistEntity Manufacturer where type Database.Persist.Class.PersistEntity.PersistEntityBackend Manufacturer = Database.Persist.Sql.Types.SqlBackend data Database.Persist.Class.PersistEntity.Unique Manufacturer = UniqueManufacturer Text newtype Database.Persist.Class.PersistEntity.Key Manufacturer = ManufacturerKey {unManufacturerKey :: Database.Persist.Class.PersistStore.BackendKey Database.Persist.Sql.Types.SqlBackend} deriving (GHC.Show.Show, GHC.Read.Read, GHC.Classes.Eq, GHC.Classes.Ord, Web.PathPieces.PathPiece, Web.HttpApiData.Internal.ToHttpApiData, Web.HttpApiData.Internal.FromHttpApiData, Database.Persist.Class.PersistField.PersistField, Database.Persist.Sql.Class.PersistFieldSql, Data.Aeson.Types.Class.ToJSON, Data.Aeson.Types.Class.FromJSON) data Database.Persist.Class.PersistEntity.EntityField Manufacturer typ = typ ~ Database.Persist.Class.PersistEntity.Key Manufacturer => ManufacturerId | typ ~ Text => ManufacturerName Database.Persist.Class.PersistEntity.keyToValues = ((GHC.Types.: []) GHC.Base.. (Database.Persist.Class.PersistField.toPersistValue GHC.Base.. unManufacturerKey)) Database.Persist.Class.PersistEntity.keyFromValues = ((GHC.Base.fmap ManufacturerKey) GHC.Base.. (Database.Persist.Class.PersistField.fromPersistValue GHC.Base.. Database.Persist.TH.headNote)) Database.Persist.Class.PersistEntity.entityDef _ = Database.Persist.Types.Base.EntityDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "Manufacturer")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "manufacturer")) (Database.Persist.Types.Base.FieldDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "Id")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "id")) (Database.Persist.Types.Base.FTTypeCon GHC.Base.Nothing (Database.Persist.TH.packPTH "ManufacturerId")) Database.Persist.Types.Base.SqlInt64 [] GHC.Types.True (Database.Persist.Types.Base.ForeignRef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "Manufacturer")) (Database.Persist.Types.Base.FTTypeCon (GHC.Base.Just (Database.Persist.TH.packPTH "Data.Int")) (Database.Persist.TH.packPTH "Int64")))) [Database.Persist.TH.packPTH "json"] [Database.Persist.Types.Base.FieldDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "name")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "name")) (Database.Persist.Types.Base.FTTypeCon GHC.Base.Nothing (Database.Persist.TH.packPTH "Text")) Database.Persist.Types.Base.SqlString [] GHC.Types.True Database.Persist.Types.Base.NoReference] [Database.Persist.Types.Base.UniqueDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "UniqueManufacturer")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "unique_manufacturer")) [(Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "name"), Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "name"))] []] [] [Database.Persist.TH.packPTH "Show", Database.Persist.TH.packPTH "Read", Database.Persist.TH.packPTH "Typeable"] (Data.Map.Base.fromList []) GHC.Types.False Database.Persist.Class.PersistEntity.toPersistFields (Manufacturer x_a9oA) = [Database.Persist.Class.PersistField.SomePersistField x_a9oA] Database.Persist.Class.PersistEntity.fromPersistValues [x1_a9oC] = Manufacturer Data.Functor.<$> ((Database.Persist.TH.mapLeft (Database.Persist.TH.fieldError (Database.Persist.TH.packPTH "name"))) GHC.Base.. Database.Persist.Class.PersistField.fromPersistValue) x1_a9oC Database.Persist.Class.PersistEntity.fromPersistValues x_a9oB = (Data.Either.Left GHC.Base.$ (GHC.Base.mappend (Database.Persist.TH.packPTH "Manufacturer: fromPersistValues failed on: ") (Data.Text.pack GHC.Base.$ (GHC.Show.show x_a9oB)))) Database.Persist.Class.PersistEntity.persistUniqueToFieldNames (UniqueManufacturer {}) = [(Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "name"), Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "name"))] Database.Persist.Class.PersistEntity.persistUniqueToValues (UniqueManufacturer x_a9oD) = [Database.Persist.Class.PersistField.toPersistValue x_a9oD] Database.Persist.Class.PersistEntity.persistUniqueKeys (Manufacturer _name_a9oE) = [UniqueManufacturer _name_a9oE] Database.Persist.Class.PersistEntity.persistFieldDef ManufacturerId = Database.Persist.Types.Base.FieldDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "Id")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "id")) (Database.Persist.Types.Base.FTTypeCon GHC.Base.Nothing (Database.Persist.TH.packPTH "ManufacturerId")) Database.Persist.Types.Base.SqlInt64 [] GHC.Types.True (Database.Persist.Types.Base.ForeignRef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "Manufacturer")) (Database.Persist.Types.Base.FTTypeCon (GHC.Base.Just (Database.Persist.TH.packPTH "Data.Int")) (Database.Persist.TH.packPTH "Int64"))) Database.Persist.Class.PersistEntity.persistFieldDef ManufacturerName = Database.Persist.Types.Base.FieldDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "name")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "name")) (Database.Persist.Types.Base.FTTypeCon GHC.Base.Nothing (Database.Persist.TH.packPTH "Text")) Database.Persist.Types.Base.SqlString [] GHC.Types.True Database.Persist.Types.Base.NoReference Database.Persist.Class.PersistEntity.persistIdField = ManufacturerId Database.Persist.Class.PersistEntity.fieldLens ManufacturerId = Database.Persist.TH.lensPTH Database.Persist.Class.PersistEntity.entityKey (\ (Database.Persist.Class.PersistEntity.Entity _ value_a9oF) key_a9oG -> Database.Persist.Class.PersistEntity.Entity key_a9oG value_a9oF) Database.Persist.Class.PersistEntity.fieldLens ManufacturerName = Database.Persist.TH.lensPTH (manufacturerName GHC.Base.. Database.Persist.Class.PersistEntity.entityVal) (\ (Database.Persist.Class.PersistEntity.Entity key_a9oH value_a9oI) x_a9oJ -> Database.Persist.Class.PersistEntity.Entity key_a9oH (value_a9oI {manufacturerName = x_a9oJ})) instance Database.Persist.Class.PersistStore.ToBackendKey Database.Persist.Sql.Types.SqlBackend Manufacturer where Database.Persist.Class.PersistStore.toBackendKey = unManufacturerKey Database.Persist.Class.PersistStore.fromBackendKey = ManufacturerKey instance Data.Aeson.Types.Class.ToJSON Manufacturer where Data.Aeson.Types.Class.toJSON (Manufacturer name_a9oL) = Data.Aeson.Types.Internal.object [((Data.Text.pack "name") Data.Aeson.Types.Instances..= name_a9oL)] instance Data.Aeson.Types.Class.FromJSON Manufacturer where Data.Aeson.Types.Class.parseJSON (Data.Aeson.Types.Internal.Object obj_a9oK) = ((GHC.Base.pure Manufacturer) GHC.Base.<*> (obj_a9oK Data.Aeson.Types.Instances..: (Data.Text.pack "name"))) Data.Aeson.Types.Class.parseJSON _ = GHC.Base.mzero instance Data.Aeson.Types.Class.ToJSON (Database.Persist.Class.PersistEntity.Entity Manufacturer) where Data.Aeson.Types.Class.toJSON = Database.Persist.Class.PersistEntity.entityIdToJSON instance Data.Aeson.Types.Class.FromJSON (Database.Persist.Class.PersistEntity.Entity Manufacturer) where Data.Aeson.Types.Class.parseJSON = Database.Persist.Class.PersistEntity.entityIdFromJSON migrateAll :: Database.Persist.Sql.Types.Migration migrateAll = do { let defs_a9oM = [Database.Persist.Types.Base.EntityDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "Manufacturer")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "manufacturer")) (Database.Persist.Types.Base.FieldDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "Id")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "id")) (Database.Persist.Types.Base.FTTypeCon GHC.Base.Nothing (Database.Persist.TH.packPTH "ManufacturerId")) Database.Persist.Types.Base.SqlInt64 [] GHC.Types.True (Database.Persist.Types.Base.ForeignRef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "Manufacturer")) (Database.Persist.Types.Base.FTTypeCon (GHC.Base.Just (Database.Persist.TH.packPTH "Data.Int")) (Database.Persist.TH.packPTH "Int64")))) [Database.Persist.TH.packPTH "json"] [Database.Persist.Types.Base.FieldDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "name")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "name")) (Database.Persist.Types.Base.FTTypeCon GHC.Base.Nothing (Database.Persist.TH.packPTH "Text")) Database.Persist.Types.Base.SqlString [] GHC.Types.True Database.Persist.Types.Base.NoReference] [Database.Persist.Types.Base.UniqueDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "UniqueManufacturer")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "unique_manufacturer")) [(Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "name"), Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "name"))] []] [] [Database.Persist.TH.packPTH "Show", Database.Persist.TH.packPTH "Read", Database.Persist.TH.packPTH "Typeable"] (Data.Map.Base.fromList []) GHC.Types.False]; Database.Persist.Sql.Migration.migrate defs_a9oM (Database.Persist.Types.Base.EntityDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "Manufacturer")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "manufacturer")) (Database.Persist.Types.Base.FieldDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "Id")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "id")) (Database.Persist.Types.Base.FTTypeCon GHC.Base.Nothing (Database.Persist.TH.packPTH "ManufacturerId")) Database.Persist.Types.Base.SqlInt64 [] GHC.Types.True (Database.Persist.Types.Base.ForeignRef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "Manufacturer")) (Database.Persist.Types.Base.FTTypeCon (GHC.Base.Just (Database.Persist.TH.packPTH "Data.Int")) (Database.Persist.TH.packPTH "Int64")))) [Database.Persist.TH.packPTH "json"] [Database.Persist.Types.Base.FieldDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "name")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "name")) (Database.Persist.Types.Base.FTTypeCon GHC.Base.Nothing (Database.Persist.TH.packPTH "Text")) Database.Persist.Types.Base.SqlString [] GHC.Types.True Database.Persist.Types.Base.NoReference] [Database.Persist.Types.Base.UniqueDef (Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "UniqueManufacturer")) (Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "unique_manufacturer")) [(Database.Persist.Types.Base.HaskellName (Database.Persist.TH.packPTH "name"), Database.Persist.Types.Base.DBName (Database.Persist.TH.packPTH "name"))] []] [] [Database.Persist.TH.packPTH "Show", Database.Persist.TH.packPTH "Read", Database.Persist.TH.packPTH "Typeable"] (Data.Map.Base.fromList []) GHC.Types.False) } Error message reported parse error at -> on line starting with GHC.Base.Nothing -> (\ name_a9oy -> case Data.HashMap.Base.lookup (Data.Text.pack name_a9oy) columns_a9ox of { GHC.Base.Just v_a9oz -> v_a9oz GHC.Base.Nothing -> Database.Persist.Types.Base.PersistNull })) A: EDIT: You can't directly reuse code generated in a ghc build, but you can simply use the module containing your Persistent database model in your ghcjs code. This will generate and build the database stuff with GHCJS and it is then available to your GHCJS code.
Q: JavaScript - manipulate with a few ID of svg via one variable I have a few SVG and each contains a few ID's. My goal is manipulate with the several ID's inside the SVG via one javascript variable. What I have tried, but doesn't works: var svg = document.getElementById("svg"); //this ID has each SVG file and is loaded separately var svgElement = svg.contentDocument; //get the inner DOM .svg var t10open = new Array(); t10open.push(svgElement.getElementById("door-open-T10")); t10open.push(svgElement.getElementById("door-opened-big-right-T10")); t10open.push(svgElement.getElementById("door-opened-small-right-T10")); t10open.push(svgElement.getElementById("door-opened-big-left-T10")); t10open.push(svgElement.getElementById("door-opened-small-left-T10")); in HTML I have checkbox with ID #T10 and here is the js function where I want to manipulate via one variable: if ($("#T10").is(":checked")) { t10open.setAttribute("display" , "visible"); } Unhandled Error: 't10open.setAttribute' is not a function A: t10open refers to an array. Arrays don't have a setAttribute function. If you want to set the attribute on each element in the array, use a loop. For instance: t10open.forEach(function(entry) { entry.setAttribute("display", "block"); // Note that "visible" is not a valid `display` value }); My answer here talks about the variety of ways you can loop through arrays; the above is just one of them. A: thanx now it works (jQuery record): if ($("#T10").is(":checked")) { $.each(t10open, function(i,element) { $(t10open).attr("display" , "none")}); }
Q: Bitmap is not being drawn after setting BitmapFactory.options Im trying to load bitmap more efficiently, as per: https://developer.android.com/topic/performance/graphics/load-bitmap However when I calculate the sample size & pass that recommendation to BitmapFactory.Options the bitmap is no longer drawn? The sample size being passed is 1 therefore no scaling is required. Here is my AsyncTask that attempts to download an image via inputstream & return a bitmap: package com.xyz.InboxManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.widget.ImageView; import java.io.IOException; import java.io.InputStream; import com.xyz.helpers.ImageUtility; public class GetBitmapDataFromInputStreamTask extends AsyncTask<InputStream,Void,Bitmap> { ImageView imageView = null; public GetBitmapDataFromInputStreamTask(ImageView _imageView) { super(); imageView = _imageView; } @Override protected Bitmap doInBackground(InputStream... inputStreams) { InputStream is = inputStreams[0]; Bitmap bitmap = null; if (is != null) { ImageUtility.ImageScalingData imageScalingData = ImageUtility.optimalDimension(ImageUtility.bitmapWidthAndHeight(is).outWidth,ImageUtility.bitmapWidthAndHeight(is).outHeight,ImageUtility.dpScreenWidth(),ImageUtility.dpScreenHeight()); final BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = imageScalingData.getSampleSize(); bitmap = BitmapFactory.decodeStream(is); if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return bitmap; } @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); if (bitmap!=null && imageView!=null) { imageView.setImageBitmap(bitmap); } } } This class ImageUtility is used to calculate the Image Scaling factor for a Bitmap, based on https://developer.android.com/topic/performance/graphics/load-bitmap: package com.xyz.helpers; import android.graphics.BitmapFactory; import android.util.DisplayMetrics; import android.util.Log; import java.io.InputStream; import com.xyz.Application.NgfrApp; public class ImageUtility { private static final String TAG = "ImageUtility"; public static float dpScreenHeight() { DisplayMetrics displayMetrics = NgfrApp.getContext().getResources().getDisplayMetrics(); return displayMetrics.heightPixels / displayMetrics.density; } public static float dpScreenWidth() { DisplayMetrics displayMetrics = NgfrApp.getContext().getResources().getDisplayMetrics(); return displayMetrics.widthPixels / displayMetrics.density; } public static BitmapFactory.Options bitmapWidthAndHeight (InputStream is) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is); //set back to false options.inJustDecodeBounds = false; return options; } public static ImageScalingData optimalDimension(double imageWidth, double imageHeight, double screenWidth, double screenHeight, float imageToScreenScaleFactor) { Log.i(TAG,"imageWidth: "+imageWidth+",imageHeight:"+imageHeight+",screenWidth:"+screenWidth+",screenHeight:"+screenHeight); ImageScalingData imageScalingData = null; double imageFrameHeight = screenHeight * imageToScreenScaleFactor; double imageFrameWidth = screenWidth * imageToScreenScaleFactor; int counter = 1; //image is larger than frame , decrease dimension if (imageHeight > screenHeight || imageWidth > screenWidth) { while (imageHeight > screenHeight || imageWidth > screenWidth) { imageHeight = imageHeight / 2; imageWidth = imageWidth / 2; counter *= 2; } imageScalingData = new ImageScalingData(imageWidth,imageHeight,counter); } else { //same size do nothing imageScalingData = new ImageScalingData(imageWidth,imageHeight,counter); } return imageScalingData; } public static class ImageScalingData { private double width; private double height; private int sampleSize; private ImageScalingData(double _width, double _height, int _sampleSize) { width = _width; height = _height; sampleSize = _sampleSize; } public double getWidth() { return width; } public double getHeight() { return height; } public int getSampleSize() { return sampleSize; } } } I also noticed my logs , were showing image height & width has 0 , which doesn't make sense. I/ImageUtility: imageWidth: 0.0,imageHeight:0.0,screenWidth:360.0,screenHeight:640.0 When I removed the code in async class GetBitmapDataFromInputStreamTask, everthing works however Im not down sampling & that degrades performance when you have 100 messages in the : inbox. ImageUtility.ImageScalingData imageScalingData = ImageUtility.optimalDimension(ImageUtility.bitmapWidthAndHeight(is).outWidth,ImageUtility.bitmapWidthAndHeight(is).outHeight,ImageUtility.dpScreenWidth(),ImageUtility.dpScreenHeight()); final BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = imageScalingData.getSampleSize(); Much appreciated.
Q: Changing java heapsizes for a websphere server using websphere and wsadminlib.py Im trying to call a command from wsadminlib.py to change the initialHeapSize and the maximumHeapSize in a script. But unfortunately my jython (and general scripting knowledge) is still total newbie. Im using the call #Change Java Heap Size setJvmProperty(nodeName,serverName,maximumHeapsize -2048 ,initialHeapSize -2048) Which should relate to the command in the wsadminlib.py library def setJvmProperty(nodename,servername,propertyname,value): """Set a particular JVM property for the named server Some useful examples: 'maximumHeapSize': 512 , 'initialHeapSize':512, 'verboseModeGarbageCollection':"true", 'genericJvmArguments':"-Xgcpolicy:gencon -Xdump:heap:events=user -Xgc:noAdaptiveTenure,tenureAge=8,stdGlobalCompactToSatisfyAllocate -Xconcurrentlevel1 -Xtgc:parallel", """ jvm = getServerJvm(nodename,servername) AdminConfig.modify(jvm, [[propertyname, value]]) But I'm met with this issue when i run the script WASX7017E: Exception received while running file "/etc/was-scripts/administrateservertest.py"; exception information: com.ibm.bsf.BSFException: exception from Jython: Traceback (innermost last): File "", line 14, in ? NameError: maximumHeapsize Any suggestions would be appreciated as I'm tearing my hair out trying to work this out A: this was answered by a friend on face book I think you might need to make two calls, one for each property you want to set. e.g. setJvmProperty(nodeName,serverName,'maximumHeapsize',2048) A: For others looking for a more specific answer, try this: AdminConfig.modify(jvmId,[['genericJvmArguments',arguments],["maximumHeapSize", str(1536)]])
Q: sending multiple data rows to firebase on clicking one button Guys <3 This is my first project with firebase and I wanna send a quite bunch of data to the database, the problem is when I click the button only the last line of code get send, I also tried to but every row in a function and call them one by one, and the same happens, only the last function work and send it's data, here's the button on click code @IBAction func Send(_ sender: Any) { apperfun(); dnamefun(); docfun(); servfun(); pnamefun(); pnumfun(); } and here's the functions func apperfun() { if ap == "1" {self.ref.child("fullinfo").child(pname).setValue(["apperance": "Excellent"])} else if ap == "2" {self.ref.child("fullinfo").child(pname).setValue(["apperance": "Good"])} else if ap == "3" {self.ref.child("fullinfo").child(pname).setValue(["apperance": "Bad"])} } func dnamefun() { self.ref.child("fullinfo").child(pname).setValue(["dname":dname]) } func docfun() { if doc == "1" {self.ref.child("fullinfo").child(pname).setValue(["level": "Excellent"])} else if doc == "2" {self.ref.child("fullinfo").child(pname).setValue(["level": "Good"])} else if doc == "3" {self.ref.child("fullinfo").child(pname).setValue(["level": "Bad"]) self.ref.child("bad").child(pname+phone).setValue(["level": "Bad"])} } func servfun() { if serv == "1" {self.ref.child("fullinfo").child(pname).setValue(["performance": "Excellent"])} else if serv == "2" {self.ref.child("fullinfo").child(pname).setValue(["performance": "Good"])} else if serv == "3" {self.ref.child("fullinfo").child(pname).setValue(["performance": "Bad"])} } func pnamefun() { self.ref.child("fullinfo").child(pname).setValue(["pname":pname]); } func pnumfun() { self.ref.child("fullinfo").child(pname).setValue(["pnum":phone]); } func receptionfun() { if recep == "1" {self.ref.child("fullinfo").child(pname).setValue(["reception": "Excellent"])} else if recep == "2" {self.ref.child("fullinfo").child(pname).setValue(["reception": "Good"])} else if recep == "3" {self.ref.child("fullinfo").child(pname).setValue(["reception": "Bad"])} } A: setValue will replace any data in that node to your data you are setting. You want to use an update. An update will replace the key if it exists, or add it to your database if it not exists. You have this: if ap == "1" {self.ref.child("fullinfo").child(pname).setValue(["apperance": "Excellent"])} It should be: if ap == "1" {self.ref.child("fullinfo").child(pname).updateChildValues(["apperance": "Excellent"])}
Q: How to send data from iOS to c# web service I've developed a c# rest web service to comunicate with my iPad app and so far I've been using it with no problem. It's a very simple thing, with a couple of query's and GET method has worked very well for me so far. The problem is now I'm trying to send data from my app to the web service, to insert into my database. NSString *query = [NSString stringWithFormat:@"http:mywebsite.com"]; _theURL = [[NSURL alloc]initWithString:query]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:_theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15.0]; [request setHTTPMethod:@"POST"]; [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request addValue:@"application/json" forHTTPHeaderField:@"Accept"]; NSData *requestData = [NSData dataWithBytes:[json UTF8String] length:[json length]]; [request setHTTPBody:requestData]; NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES]; This is basically my objective-C code, where I try to establish the connection, set the http method to post and encode the NSData which I want to send. This NSData is just a json string already good to go. Now in my web service, I try to get this NSData with a Byte[] to decode to string, get my json and on and on. The thing is I'm not being able to do it. My web service method code is: [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)] public bool submitResults(Byte[] data) { String jsonString = System.Text.Encoding.UTF8.GetString(data); try{ JavaScriptSerializer json = new JavaScriptSerializer(); var resultado = json.Deserialize<Pergunta[]>(jsonString); ... and it goes on. Resuming all this: I can't send the data to the web service so I can insert it in my DB. Any help would be much, much appreciated. Btw, the error I'm getting is this horrible thing: {"Message":"Type \u0027System.Collections.Generic.IDictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]\u0027 is not supported for deserialization of an array.","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, Boolean throwOnError, IList& convertedList)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"} So, trying to help you to help me, here's my json: =) [ { "categoriaID" : 1, "cursoID" : "601", "perguntaID" : "1", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 1, "cursoID" : "601", "perguntaID" : "2", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 1, "cursoID" : "601", "perguntaID" : "3", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 1, "cursoID" : "601", "perguntaID" : "21", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 2, "cursoID" : "601", "perguntaID" : "4", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 2, "cursoID" : "601", "perguntaID" : "5", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 3, "cursoID" : "601", "perguntaID" : "6", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 3, "cursoID" : "601", "perguntaID" : "7", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 3, "cursoID" : "601", "perguntaID" : "8", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 4, "cursoID" : "601", "perguntaID" : "9", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 4, "cursoID" : "601", "perguntaID" : "10", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 4, "cursoID" : "601", "perguntaID" : "11", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 4, "cursoID" : "601", "perguntaID" : "12", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 4, "cursoID" : "601", "perguntaID" : "13", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 5, "cursoID" : "601", "perguntaID" : "14", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 5, "cursoID" : "601", "perguntaID" : "15", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 5, "cursoID" : "601", "perguntaID" : "16", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 6, "cursoID" : "601", "perguntaID" : "17", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 6, "cursoID" : "601", "perguntaID" : "18", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 6, "cursoID" : "601", "perguntaID" : "19", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 6, "cursoID" : "601", "perguntaID" : "20", "nb" : 19574, "respostaTipo" : "Bom" }, { "categoriaID" : 7, "cursoID" : "601", "perguntaID" : 22, "respostaTexto" : "Adorei!", "nb" : 19574 } ] UPDATE: After a lot of research, I think it has to do with me serialization in Xcode. It goes like this: _arrayPerguntas = [[NSMutableArray alloc]init]; for (int i = 0; i < _conteudoProgramatico.count; i++) { InqueritosResposta *resp = [[InqueritosResposta alloc]init]; [resp setNb:[NSNumber numberWithInt:_nb]]; [resp setCursoID:[self indiceSessao:_nomeSessao]]; [resp setCategoriaID:[NSNumber numberWithInt:1]]; [resp setPerguntaID:[_idConteudoProgramatico objectAtIndex:i]]; [resp setRespostaTipo:[self codeToString:[_respostasConteudoProgramatico objectAtIndex:i]]]; [_arrayPerguntas addObject:resp]; } for (int i = 0; i < _sessoesPraticas.count; i++) { InqueritosResposta *resp = [[InqueritosResposta alloc]init]; [resp setNb:[NSNumber numberWithInt:_nb]]; [resp setCursoID:[self indiceSessao:_nomeSessao]]; [resp setCategoriaID:[NSNumber numberWithInt:2]]; [resp setPerguntaID:[_idSessoesPraticas objectAtIndex:i]]; [resp setRespostaTipo:[self codeToString:[_respostasSessoesPraticas objectAtIndex:i]]]; [_arrayPerguntas addObject:resp]; } for (int i = 0; i < _materiaisSuporte.count; i++) { InqueritosResposta *resp = [[InqueritosResposta alloc]init]; [resp setNb:[NSNumber numberWithInt:_nb]]; [resp setCursoID:[self indiceSessao:_nomeSessao]]; [resp setCategoriaID:[NSNumber numberWithInt:3]]; [resp setPerguntaID:[_idMateriaisSuporte objectAtIndex:i]]; [resp setRespostaTipo:[self codeToString:[_respostasMateriaisSuporte objectAtIndex:i]]]; [_arrayPerguntas addObject:resp]; } for (int i = 0; i < _apresentacao.count; i++) { InqueritosResposta *resp = [[InqueritosResposta alloc]init]; [resp setNb:[NSNumber numberWithInt:_nb]]; [resp setCursoID:[self indiceSessao:_nomeSessao]]; [resp setCategoriaID:[NSNumber numberWithInt:4]]; [resp setPerguntaID:[_idApresentacao objectAtIndex:i]]; [resp setRespostaTipo:[self codeToString:[_respostasApresentacao objectAtIndex:i]]]; [_arrayPerguntas addObject:resp]; } for (int i = 0; i < _expectativas.count; i++) { InqueritosResposta *resp = [[InqueritosResposta alloc]init]; [resp setNb:[NSNumber numberWithInt:_nb]]; [resp setCursoID:[self indiceSessao:_nomeSessao]]; [resp setCategoriaID:[NSNumber numberWithInt:5]]; [resp setPerguntaID:[_idExpectativas objectAtIndex:i]]; [resp setRespostaTipo:[self codeToString:[_respostasExpectativas objectAtIndex:i]]]; [_arrayPerguntas addObject:resp]; } for (int i = 0; i < _feedBack.count; i++) { InqueritosResposta *resp = [[InqueritosResposta alloc]init]; [resp setNb:[NSNumber numberWithInt:_nb]]; [resp setCursoID:[self indiceSessao:_nomeSessao]]; [resp setCategoriaID:[NSNumber numberWithInt:6]]; [resp setPerguntaID:[_idFeedback objectAtIndex:i]]; [resp setRespostaTipo:[self codeToString:[_respostasFeedback objectAtIndex:i]]]; [_arrayPerguntas addObject:resp]; } InqueritosResposta *resp = [[InqueritosResposta alloc]init]; [resp setNb:[NSNumber numberWithInt:_nb]]; [resp setCursoID:[self indiceSessao:_nomeSessao]]; [resp setCategoriaID:[NSNumber numberWithInt:7]]; [resp setPerguntaID:[NSNumber numberWithInt:22]]; [resp setRespostaTexto:_respostaObservacoes]; [_arrayPerguntas addObject:resp]; NSError *writeError = nil; NSMutableArray *jsonRespostas = [[NSMutableArray alloc]init]; for(InqueritosResposta *resp in _arrayPerguntas) { NSMutableDictionary *jAnswer = [[NSMutableDictionary alloc] init]; [jAnswer setObject:resp.nb forKey:@"nb"]; [jAnswer setObject:resp.cursoID forKey:@"cursoID"]; [jAnswer setObject:resp.categoriaID forKey:@"categoriaID"]; [jAnswer setObject:resp.perguntaID forKey:@"perguntaID"]; if (resp.respostaTipo != nil) { [jAnswer setObject:resp.respostaTipo forKey:@"respostaTipo"]; } if (resp.respostaTexto != nil) { [jAnswer setObject:resp.respostaTexto forKey:@"respostaTexto"]; } [jsonRespostas addObject: jAnswer]; } NSArray *final = [NSArray arrayWithArray:jsonRespostas]; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:final options:NSJSONWritingPrettyPrinted error:&writeError]; [self submitData:jsonData]; Basically I put all my objects in _arrayPerguntas from different sources. Then I use a dictionary to put them all correctly in another array (final array). The submitData method is the one I entered above with connection setup. Thanks in advance, Happy Coding, ruitex23 A: Don't do this. Don't use Microsoft's convoluted approach to web services that really only offer a benefit if you're using Microsoft technology to connect to them. Even then it's... shaky at best. Look into JSONResult MVC Controller Methods. These offer you the most platform independent control over your application's behavior and you won't get any obscure errors like the one you're experiencing. It's pure JSON both ways and there's no guesswork. A: I think it's failing in the de-serialization. Please validate your json object (jsonString). A really good online json validator is jsonlint.com
Q: How to block input of numbers from list? FirstNumber = int(input('Input first odd number smaller than17:')) SecondNumber = int(input('Input second odd number smaller than 17:')) SumOfBoth = FirstNumber + SecondNumber listN = [0, 2, 4, 6, 8, 10, 12, 14, 16] if int(FirstNumber or SecondNumber) <= 17: print(SumOfBoth) elif (FirstNumber or SecondNumber) > 17: print('Error') As you can see in my program I created a list called "ListN", can u help me, when user writes a number and press enter, to make the program not accept the numbers from the list. A: You can use: if FirstNumber not in listN: print("Correct") else: print("Wrong Input")
Q: Crontab opens on blank page, cannot save I am really not familiar with Linux, and only started using it recently, so be patient with me. I am trying to control a camera on regular intervals through a script that is called upon in the crontab. When I start up the computer, I can open the crontab file, edit and save, and everything is executed correctly. So my script is fine. (btw, I use gedit as editor) However, I can never open crontab a second time, unless I reboot the computer first. This is what happens: I type crontab -e in terminal and I get a blank page. (Usually, crontab shows first a whole explanation as comments, after which you type your actual commands.) When I then type my commands and try to save the file (/tmp/crontab.something), I get the following message: could not find the file /tmp/crontqb.something/crontab. Please check that you typed the location correctly and try again. After I then closed the file without saving, terminal says "no modification made", which is fair enough.. When I try: crontab -l, I do get the correct content of crontab in terminal. I don't know if this is relevant, but when I try sudo crontab -e, I get " no crontab for root. Using an empty one. 888" But he doesn't open anything and I get no new input line in the terminal. After I reboot the computer, crontab -e works fine again, but only once.. Any help is really appreciated! Sarah
Q: Re-render the react component based on onclick event assoicated with button created as part of innerHTML in vanilla javascript Primary Objective: Re-render the react component based on onclick event assoicated with button created as part of innerHTML in vanilla javascript. Additional Details: An AJAX request is made after the onclick event.This request can be made either in vanilla javascript or from the react component. Based on the fetched results, the react component has to re-render itself. What is already tried?: * *Just importing the results into react component file. As expected, the results are not updating as per the event. *Accessing the react method from vanilla javascript. Please check the details below. myReactComponent code: const myReactComponent = () => { const [attribute,setAttribute] = useState([]); const assignValueToAttribute = function assignValue(results){ attribute = results; setAttribute(attribute); } } export default myReactComponent; myjavascript code: import myReactComponent from './React/components/myReactComponent' let getResults=[]; let getResultsUrl="https://myresultspath.com"; function updateResults(){ $.ajax({ url: getResultsUrl, type: "get", contentType: "application/json", success: function (data) { getResults.push(data); }, error: function (jqXHR, textStatus) { console.log(textStatus); }, myReactComponent.assignValueToAttribute(getResults); } Error message: assignValueToAttribute is not a function. The above solution is based on one of the four methods suggested here:http://www.primaryobjects.com/2017/05/08/integrating-react-with-an-existing-jquery-web-application/ I have chosen the above method since it involved less code refactoring. If the above approach is correct in principle, please let me know where did I commit mistake. Otherwise, kindly suggest the right approach to achieve the primary objective based on the details provided. Thank you for your support. A: You can do like this const myReactComponent = (results) => { const [attribute,setAttribute] = useState([]); const assignValueToAttribute = function assignValue(results){ attribute = results; setAttribute(attribute); } } export default myReactComponent; myjavascript code: import myReactComponent from './React/components/myReactComponent' let getResults=[]; let getResultsUrl="https://myresultspath.com"; function updateResults(){ $.ajax({ url: getResultsUrl, type: "get", contentType: "application/json", success: function (data) { getResults.push(data); }, error: function (jqXHR, textStatus) { console.log(textStatus); }, myReactComponent.assignValueToAttribute(getResults); } A: I could achieve my primary objective by using the "Event Driven method" suggested at communicating with a functional component outside of react Steps I followed: 1.Dispatched global Custom event after I fetched details from the backend through AJAX request as shown below. function updateResults(){ let getResults; var someEvent = new Event("someEvent") $.ajax({ url: getResultsUrl, type: "get", contentType: "application/json", success: function (data) { getResults = data; window.dispatchEvent(someEvent) }, error: function (jqXHR, textStatus) { console.log(textStatus); }, } *Insdide the react component file React.useEffect(() => { window.addEventListener( "someEvent", "functionToBeCalled" , false ); }, []); *You can get the fetched details from ajax request in either of the two ways. i. Importing the fetched details from the vanilla js file into react component file (OR) ii.Making it part of the event dispatch var someEvent = new CustomEvent("someEvent", {detail: "SomeAdditionalData"}); if you need more clarity on second approach please refer the above link. *Assign the data to the state variable using "setState" of "useState" hook in the function to be called. import fetchedData from "vanillaFile.js" [variableToBeChanged, setVariableToBeChanged] = useState(); //initially inside the component functionTobeCalled() { setVariableToBeChanged(fetchedData); } I am thankful to the members @95faf8e76605e973 and @Guerilla
Q: secure scripting within a nodejs application I want to build a nodejs application that allows users to enter their own JavaScript scripts to interact with my applications API for extensibility purposes. I want this to be secure; I only want a specific set of objects exposed to the scripts. Is there a secure way of doing this in node? A: The sandbox module spawns a child process and runs user scripts in a new context provided by vm module. No global variables or node.js methods are accessible in user scripts because the global variable is redefined( see line 28, 45-47, file shovel.js). If you want to expose some objects and functions, e.g., var myobj = { x:12, y:12}; var add = function(a, b) { return a + b; }; to the user script, e.g., var b = 100; myobj.x = add(myobj.x, b); , prepend the object and the function to the user script and run it by sandbox like this: var Sandbox = require('sandbox'); var s = new Sandbox(); s.run('myobj=' + JSON.stringify(myobj) + ';' + 'add=' + add.toString() + ';' + userscript + '; print(myobj);', function( output ) { console.log(output); }); The output includes the new value of myobj: { result: 'null', console: [ { x: 112, y: 12 } ] } There is a relative discussion: How restrict access to apis in node.js javascript?. But this method is against the rule: 'To prevent accidental global variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code requires a separate process.' (see http://nodejs.org/api/vm.html)
Q: Using .hasClass() in if condition is not works I am having a div when user hover on it will insert a div child div. But the problem is on every hover it added the same div repeatably. so i tried the below script for check if child div availabe in MotherDiv do nothing. else add the Child div. These all are happen on hover. So, What is the wrong with the below code? Am i missing something? if ($('.MotherDiv').hasClass('Child')) { alert('alerady a div there!');//DO NOTHING } else { var Details= "<div class='MotherDiv'><table class='Special'><tr><td>Offers</td></tr><tr><td>CheckOut Now</td></tr></table></div>"; $(Child).insertAfter($(this));//This is insert the child div on hover } A: Your JavaScript snipplet you shown above is invalid. You can not have line breaks in it like that. You can add a \ at the end of the line to denote that it is continued, but it is normally frowned upon as a bad practice. if ($('.MotherDiv').hasClass('Child')) { alert('alerady a div there!');//DO NOTHING } else { var Details= "<div class='MotherDiv'>\ <table class='Special'>\ <tr><td>Offers</td></tr>\ <tr><td>CheckOut Now</td></tr>\ </table>\ </div>"; $(Child).insertAfter($(this));//This is insert the child div on hover } Note, there can not be any characters after the \ or it will error out. A: Are you looking for something like this. Simply adds new Child class if the div doesn't have. If you need to add new child div inside mother div then you just have to customize the code a bit. http://jsfiddle.net/ETuZB/3/ A: The issue may be that you have a string that spans multiple lines. JavaScript does not handle strings that way. You need to either break the string into parts and concatenate them "..." + "...", or use a line termination escape \ to preserve the newline and following whitespace. var Details= "<div class='MotherDiv'> <table class='Special'> <tr><td>Offers</td></tr> <tr><td>CheckOut Now</td></tr> </table> </div>"; To: var Details = "<div class='MotherDiv'>" + "<table class='Special'>" + "<tr><td>Offers</td></tr>" + "<tr><td>CheckOut Now</td></tr>" + "</table> + "</div>"; Or: var Details = "<div class='MotherDiv'> \ <table class='Special'> \ <tr><td>Offers</td></tr> \ <tr><td>CheckOut Now</td></tr> \ </table> \ </div>"; A: Assuming this is the HTML structure you want to generate: <div class="Mother"> Mother Div Content <div class="Child"> Child Div to be generated dynamically </div> </div> jQuery Script: $(".Mother").hover(function(){ var motherDiv = $(this); if(motherDiv.find(".Child").length == 0) { var childDiv = $("<div class='Child'>Child Div Content</div>"); motherDiv.append(childDiv); } }); A: $(function(){ var $motherDiv=$('.MotherDiv'); $motherDiv.bind('mouseenter', function(){ if($motherDiv.find('.ChildDiv').length==0){ $('<div></div>',{class:'ChildDiv',text:'Child Data Text'}).appendTo($motherDiv); } });}); A: Where is .MotherDiv being added to the document? You don't seem to be inserting $(Details).
Q: Point-free style in Template Haskell Consider the following Template Haskell function: composeQ :: ExpQ -> ExpQ -> ExpQ composeQ = \x y -> [| $(x) . $(y) |] Is it possible to eliminate the lambda expression from the right hand side of the equation and write composeQ using point-free style? A: There's no generic way to splice expressions into any quotation in point-free style, but this particular case could be implemented like this: composeQ :: ExpQ -> ExpQ -> ExpQ composeQ = flip infixApp [|(.)|] Here were flip infixApp which usually takes parameters in the order left op right into op left right and then supply it with the composition operator. Now we have a point-free function that's equivalent to the original composeQ.
Q: Hydrogen: Whether it's a metal or non-metal I know hydrogen is a non metal, but when I just study about some introductory elementary band theory I find the band structure of hydrogen has a half filled valence band just like alkali metals, and this should make it conductive. Is there some thing more complex about it or is my understanding is wrong? How can the non metallic nature of hydrogen be explained using band theory? A: Solid hydrogen is not made up from hydrogen atoms. It contains hydrogen molecules held together by relatively weak Van der Waals forces. In the hydrogen molecule the two $1s$ levels of the atoms form a bonding $\sigma$ molecular orbital that is full and an antibonding $\sigma^*$ orbital that is empty: In the solid the $\sigma$ level broadens to form a full valence band and the $\sigma^*$ level broadens to form an empty conduction band, with a gap of around 15eV between the two bands. That is why solid hydrogen is an insulator. A: In solid hydrogen the electrons are localised in H2 bonds. There are various crystal structures. The band structure of course depends on this. Upon very strong compression the crystal structure should change to a high coordination characteristic of a metal. The H2 bonds then disappear. So the behaviour is more complex than just a shift of bands. It is a structural and electronic phase transition. Search for metal-insulator transition.
Q: Connecting PowerBI to Microsoft Graph or Azure AD My customer needs to connect their users and groups within Office 365 & Azure AD to Power BI, so they can show a report of the amount of users with certain licenties, the amount of RDS users and what type mailbox the users are using. The whole proces needs to go automatically, so when PowerBI is opened the data is already ready for them and up to date. My solution was the following: * *Source,Office 365 & Azure AD), send the data to an API(Microsoft Graph) *Microsoft Graph exposes a webendpoint which another application can get the data from, IF they provide the correct OAuth2 bearer token-. *Access the webendpoint with Power BI and get the data when Power BI get's opened. PROBLEM I don't know how to refresh an OAuth2 token in Power BI, can someone help me? A: Connecting to Microsoft Graph REST APIs from Power Query isn't recommended or supported. Read more here: https://learn.microsoft.com/en-us/power-query/connecting-to-graph
Q: Tomcat 7.0.47 keeps throwing errors why? Dear Tomcat master out there, I use tomcat 7.0.47 in my laptop, inside a VM, it runs well at first ... but after sometimes it shutsdown. I checked on the catalina.yyyy-MM-dd.log, and I found errors on two things: * *Errors regarding JDBC connection pool, in which I'm using ormlite JdbcPooledConnectionSource *Errors regarding access log, this error caused by access log is the most of all, I found around 10 times in a row, than the server seems dead afterwards. The error regarding Ormlite jdbc conn pool is: java.lang.IllegalStateException at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1588) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547) at com.mysql.jdbc.Connection.realClose(Connection.java:4060) at com.mysql.jdbc.Connection.close(Connection.java:1398) at com.j256.ormlite.jdbc.JdbcDatabaseConnection.close(JdbcDatabaseConnection.java:144) at com.j256.ormlite.jdbc.JdbcPooledConnectionSource.closeConnection(JdbcPooledConnectionSource.java:330) at com.j256.ormlite.jdbc.JdbcPooledConnectionSource.closeConnectionQuietly(JdbcPooledConnectionSource.java:341) at com.j256.ormlite.jdbc.JdbcPooledConnectionSource$ConnectionTester.testConnections(JdbcPooledConnectionSource.java:494) at com.j256.ormlite.jdbc.JdbcPooledConnectionSource$ConnectionTester.run(JdbcPooledConnectionSource.java:439) While error regarding access log is like this: WARNING: Exception while attempting to add an entry to the access log java.lang.NullPointerException at org.apache.catalina.connector.CoyoteAdapter.log(CoyoteAdapter.java:512) at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:191) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) It seems that there are some kind of memory leak or something ... but the Tomcat suddenly drop. Can anybody help? Thanks in advanced. A: Ok, frankly speaking I gave up on my old codings ... What I did to fix this are: * *I'm not using 3rd party DB Connection pool lib anymore, I changed it to use built-in Tomcat db connection pool and access it from my codes using JNDI lookup. (I hope this way, tomcat will handle it better) --> I followed my Tomcat db pool config according to this site, thanks to that guy :). *I commented the access logging in server.xml, so tomcat will no longer log any access (its not recommended by some postings, but what the heck!), I use Apache log instead, since I'm using Apache as my reverse proxy to my java web app in tomcat. But I'm still open to any suggestion. Thanks Bromo
Q: Exporting data from Excel sheet into XML file I am dealing with a large number of records. I have around 5,50,000 records in an excel sheet. I need to export that data in an XML file. I tried using the inbuilt functions in Excel but it has a limitation. A max of only 65,000 records can be exported into XML file using Excel. Can you please suggest something on how can this be done? Thanks. A: * *Make sure your file is saved in the XLSX format. *In File Explorer, right click the XLSX file > Unzip. *Browse unzipped contents, you should see an XML file with your data. In my version of Excel, the data is in the \xl\worksheets folder.
Q: how to perform two operations on the same flux I have a project reactor Flux. I want to perform two different operation on the same flux. I thought of doing the below way. But this is happening in sequential way. Is there any better way I can get this two operation to happen in parallel as they are independent operations myFlux.reduce(this::operationOne).subscribe(System.out::println); myFlux.reduce(this::operationTwo).subscribe(System.out::println);
Q: How to use onSavedInstance? One quick question: Why does my onSavedInstance not work? I want to save last state of user activity (current workout session etc.) but in some particular reason it keeps turning me back to the mainActivity when I press the home or overview button and then I return to the application. It should return me the last saved state of activity but something seems to be bugged. I have been struggling with this problem for two weeks. I searched all over the forum but I still can't find the answer. Hope someone can help: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_workout); if (savedInstanceState != null) { // What should I call here? } else { // And here? } } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); } A: onSaveInstanceState(Bundle savedInstanceState) is called when the user leaves your app.It provides a Bundle object that you can pass values you want to save as key value pairs. static final String WORKOUT_STATE = "state"; @Override public void onSaveInstanceState(Bundle savedInstanceState) { // Save the user's current workout state savedInstanceState.putInt(WORKOUT_STATE, currentState); super.onSaveInstanceState(savedInstanceState); } There are two options for where you can restore the current state when the activity is recreated. It can be done in onCreate(Bundle savedInstanceState) method or onRestoreInstanceState(Bundle savedInstanceState). If you should do it in onCreate, you should check if the savedInstanceState is not null. If savedInstanceState is not null then the activity is being recreated and this is where you extract the values. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { currentState = savedInstanceState.getInt(WORKOUT_STATE); } else { // Initialize members with default values for a new instance } } Instead of extracting the values in the onCreate method, you can optionally use the onRestoreInstanceState(Bundle savedInstanceState) method. This method is called if there is a state to restore so you don't need to check if savedInstanceState is null. public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Restore state currentScore = savedInstanceState.getInt(WORKOUT_STATE); } You can read more about saving UI states here: https://developer.android.com/topic/libraries/architecture/saving-states.html A: SOLVED! I fixed my problem, believe it or not the problem was in FLAG_ACTIVITY_NO_HISTORY in my intent service. Thanks for trying to help!
Q: How to wrap a table in a scrollable container? (coding the Game of Life) first of all I apologize if I use imprecise terminology but I' m still a beginner. I' m trying to code my version of Conway's game of life using what I learned at my web dev class but I' m a little bit stuck. I' m using vanilla Javascript, HTML and CSS. The game logic it's fully implemented and working as intended. Basically I' m rendering the game as a huge table and it looks like this: Code is available here: https://github.com/lfmvit/GameOfLife Now what I'm trying to achieve is instead something like this one: https://playgameoflife.com/ I want my table, that has a fixed dimension (potentially big), standing inside a container that allows me to grab and scroll around the game field, just like you scroll a map in a Google Map viewer. Finally I would like to add a control bar to add some buttons and slider, but I think I already know how to do that.(any advice will still be appreciated).
Q: How do you access another UIViewController in appDelegate when login using facebook-ios-sdk? answer: Finally I use Notifications that I think is a elegant way to do it. Thanks you Alan. I have a facebook login (through facebook-ios-sdk) in my tab based app. I initial "Facebook" in my appDelegate. I have a "Connect Facebook" UIButton in settingViewController Tab. I can login facebook through clicking the "Connect Facebook" UIButton (in settingViewController Tab), and then "- (void)fbDidLogin" (in appDelegate) get called. Everything is fine. But my question is how to update "Connect Facebook" UIButton (in settingViewController Tab) to "Facebook connected"? Can I do something like this in appDelegate: - (void)fbDidLogin { NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:[self.facebook accessToken] forKey:@"FBAccessTokenKey"]; [userDefaults setObject:[self.facebook expirationDate] forKey:@"FBExpirationDateKey"]; [userDefaults synchronize]; if (settingViewController) { settingViewController.facebookButton.text = @"facebook connected"; } } Thanks you. What I have tried: I put this in settingViewController Tab, but this was not called when the app return from the facebook login screen. So I guess I may have to use delegate in "- (void)fbDidLogin" in appDelegate? - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self checkAccStatusAndUpdateButton]; } A: There are several ways you could deal with this. Here are a couple: NSUserDefaults You could store a flag in NSUserDefaults when Facebook is connected. In the viewDidLoad method of SettingViewController you could check that flag and make the appropriate change in your UIButton title. Notifications In the fbDidLogin method, you could fire an NSNotification; and your SettingViewController could observe that notification and change the button title. That approach assumes SettingViewController instance exists and can observe the notification.
Q: How to center a pgfplot? I am trying to center a graph made with pgfplots with \centering. If I put \centering within a group to limit its scope, the graph does not get centered. If I don't limit the scope of \centering, then everything gets centered. \documentclass{minimal} \usepackage{pgfplots} \begin{document} This text should not be centered, but the graph should be. % \begingroup \centering \begin{tikzpicture} \begin{axis} \addplot coordinates { (0, 0) (1, 1)}; \end{axis} \end{tikzpicture} % \endgroup This text should not be centered. \end{document} A: There is nothing special about tikzpicture here you would see the same with {\centering X} \centering works by setting the paragraph parameters, so if you close the group before the paragraph ends then nothing happens. You can use {\centering X } To centre an X (or a tikzpicture). Or more naturally use \begin{center} X \end{center} which also adds some vertical space.
Q: How to split a string on consecutive amounts of only letter or nonletter characters I'm looking to specially split a string based on certain criteria. I'd like for any words (that is, consecutive amounts of only letter characters) to each be returned, as well as any non-words. To illustrate what I mean, let's say I have the string "Each of the past 20 nights, John has gone to bed at 11:00 pm." (without quotes). I'd like this split to return an array of strings = { "Each", " ", "of", " ", "the", " ", "past", " 20 ", "nights", ", ", "John", " ", "has", " ", "gone", " ", "to", " " "bed", " ", "at", " 11:00 ", "pm", "." } I'm not very familiar with regular expressions, but I'm hoping there might be a solution here! A: it's easy with a regular expression: Dim s = "Each of the past 20 nights, John has gone to bed at 11:00 pm." Dim result = Regex.Split(s, "(\p{L}+)").Skip(1).ToArray() \p{L} matches any unicode code point belonging to the "letter" category, so (\p{L}+) means: match any one or consecutive letters and keep them in the result. Regex.Split does, well, split the string on that pattern. Here's the same without LINQ: Dim s = "Each of the past 20 nights, John has gone to bed at 11:00 pm." Dim tmp = Regex.Split(s, "(\p{L}+)") Dim result(tmp.Length - 2) As String Array.Copy(tmp, 1, result, 0, tmp.Length - 1)
Q: Hibernate Mapping I have an issue in performing Hibernate Mapping. The scenario is as follows: * *There is a User class which has username, name, dateofbirth, image and other information pertaining to a user with username as the primary key. *Second class is Product class which has product id and other information related to a product with primary key as product key. *The third class is Order class which has OrderId, OrderDate, Username- should be foriegn key-referring to the User class username and finally a Set of type Product- because one order can have many products. Now I want the primary key of the Order class as a composite key (OrderId, ProductID) and this productID should be reference from Product Class. The relationships that I want to create are as follows: 1. One order can belong to only one User 2. One order can have many products Can someone lead me on how to go about it? Any kind of help will be great. A: I think most likely you are thinking similar relationship. Difference in your requirement is you need One to Many mapping from Order/PurchaseOrder to Product/Item and you don't want Shipment. My suggestion would be: * *Create bi-directional one-to-many relationship b/w User and Order. Benefit for bidirectional is you can access User Object from Order Object, if not required, you can keep it unidirectional from User to Order. *Create one-to-many relationship b/w Order and Product. *Instead of composite key in order, keep the primary key as just OrderID. You can still fetch list of products from your order object and order object from user object. The whole point in making this decision is from which object you derive remaining objects. With ORMs you should know from which object you would derive rest and so my suggestion is based on assumption that you will have User object available as attached entity, so you can get list of orders (defined as set) and from a particular order find out list/set of Products. In case you have Order object available first, then create a bidirectional with User. So that you can find list/set of Products at one end, and Customer associated at other. For ORM mappings refer Hibernate Mapping Examples. Hope this clarifies.
Q: Wordpress custom endpoints (WP_REST_Controller) 404 only on mobile I currently have a working controller that extends WP_REST_Controller in a file under the current theme. These are being called using jQuery ajax. (all code below) The issue I am facing is that I receive this error ONLY when accessing with a mobile device. {"code": "rest_no_route", "message": "No route was found matching the URL and request method" "data": {"status": 404}} * *settings -> permalinks -> save changes *tried using controller namespace "api/v1" and "wp/v2" javascript function getAllClients() { jQuery.ajax({ url: "http://myurl.com/index.php/wp-json/wp/v2/get_all_clients", type: "GET", data: { /*data object*/}, success: function (clientList) { // success stuff here }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.statusText); } }) } api/base.php <?php class ApiBaseController extends WP_REST_Controller { //The namespace and version for the REST SERVER var $my_namespace = 'wp/v'; var $my_version = '2'; public function register_routes() { $namespace = $this->my_namespace . $this->my_version; register_rest_route( $namespace, '/get_all_clients', array( array( 'methods' => 'GET', 'callback' => array(new ApiDefaultController('getAllClients'), 'init'), ) ) ); $ApiBaseController = new ApiBaseController(); $ApiBaseController->hook_rest_server(); api/func.php <?php class ApiDefaultController extends ApiBaseController { public $method; public $response; public function __construct($method) { $this->method = $method; $this->response = array( // 'Status' => false, // 'StatusCode' => 0, // 'StatusMessage' => 'Default' // ); } private $status_codes = array( 'success' => true, 'failure' => 0, 'missing_param' => 150, ); public function init(WP_REST_Request $request) { try { if (!method_exists($this, $this->method)) { throw new Exception('No method exists', 500); } $data = $this->{$this->method}($request); $this->response['Status'] = $this->status_codes['success']; $this->response['StatusMessage'] = 'success'; $this->response['Data'] = $data; } catch (Exception $e) { $this->response['Status'] = false; $this->response['StatusCode'] = $e->getCode(); $this->response['StatusMessage'] = $e->getMessage(); } return $this->response['Data']; } public function getAllClients() { // db calls here return json_encode($stringArr,true); } } These are registered in the Functions.php file require get_parent_theme_file_path('api/base.php'); require get_parent_theme_file_path('api/func.php'); A: Turns out the issue was a plugin my client installed called "oBox mobile framework" that was doing some weird routing behind the scenes. Disabling it resolved the issue, though there is probably a way to hack around this and get both to play together.
Q: how to detect change of actual value not just OnChange nuxt vuetify As a result of export default { name: "Details", async asyncData({ redirect, params, store }) { if ( !store I am returning a few values in which one of them is return { camera: c, thumbnail_url: thumbnail_url, camera, and then in my form fields where I am populating a Vuetify dialog, Text Field inputs such as <v-dialog v-model="dialog" max-width="600px"> <v-card> <v-card-text> <v-layout class="model-container"> <v-row> <v-col cols="12" lg="7" md="7" sm="12" xs="12"> <v-text-field v-model="camera.name" class="caption bottom-padding" required > <template v-slot:label> <div class="caption"> Name </div> </template> </v-text-field> my issue is, I have a button as <v-btn color="primary" text @click="updateCamera"> Save </v-btn> which I only want to make disable false, only if there is an actual change occurs to, this.camera, in updateCamera method, I can use the updated values as async updateCamera() { let payload = { name: this.camera.name, but I want to enable or disable the button on when change occurs, I had tried @input, I have also tried to watch camera object <v-text-field v-model="camera.name" class="caption bottom-padding" required @input="up($event, camera)" > This way I tried to get some info about event, such as which text field it is, so I can compare, but in up method it only passes input value. in watch camera: function() { this.$nextTick(() => { console.log(this.camera) }) } camera: { handler: function(val) { this.$nextTick(() => { console.log(val) }) /* ... */ }, immediate: true } I have tried this but nothing worked. Of course, we can enable or disable a button on change but not just if the user places an A and then deletes it, not such change. Any help would be wonderful Update: Even after using this camera: { handler: function(newValue) { if (newValue === this.dumpyCamera) { console.log(this.dumpyCamera) console.log(newValue) console.log("here") this.updateButton = true } else { this.updateButton = false } }, deep: true } both new and old values are the same. I have tried to add new variable dumyCamera and on mount I have assigned this.camera value to this.dumyCamera but when something changes in camera, it changes this.dumyCamera as well? why is this the case? A: You should be able to recognize any changes made to this.camera by using a watcher watch: { camera: { handler (newValue, oldValue) { // do something here because your this.camera changed }, deep: true } }
Q: Organising a big project - how is it done? I understand that for smaller projects keeping methods in the main view controller (namely viewDidLoad) is the way forward, but for bigger projects im thinking this cant be the way apps are organised - the m file would be chuffing huge! also there would be thousands of declarations at the top! Im nowhere near building an app that big but i'm intrigued, would you put them in a separate file and call them when they're needed? or is it just a case of scroll past the declarations and use pragma marks to find what your looking for? A: Basically this is not a specific question for developing iOS applications, it's more of a software architecture problem and requires more knowledge that can't be put in a single answer. But to get hold of how things usually work, the project has to be planned by pen and paper first, since those are the developer's best tool, then when you've got the main parts of your project planned in a good manner, you start by plotting some ERD of your main components, and decide what will each part be responsible of, then start coding from there a prototype version. when you have a simple project up and running, you start cleaning up the code, planning even further, and start testing your code, I can't describe how important testing is ! You'll also need software to manage your project (not the source code, but the project itself), something like asana maybe to keep track of tasks and who does what. In order to keep your code safe against overwriting by other people who are working with you, and to keep things managed across versions, you'll need to setup a revision control repository of some king, Git is supported out of the box by XCode ! Now for the part of code writing, you need to learn some kind of pattern and follow it, iOS projects and most others now follow the MVC structure, which answers your question of how big the classes will get and how things will communicate together without turning into a mess ! Yes, you'll need pragmas and code trickery here and there, but you should always follow the patterns and conventions in order to keep things maintainable when projects grow ! again as I said, this is not anywhere near a good start, you need lots of experience and knowledge before you can actually work on huge projects, but it's something ! Keep up the good work, and always remember that you always have to ask questions, never be intimidated :) Edit 1 Forgot to add a tip on reading about Agile software development that's probably my last tip :)
Q: Set default Status bar style to .lightContent but and also allow for a dark override on some view controllers I working on a huge app loads of view controllers, the app currently sets in status bar style in the plist using: Status bar style = UIStatusBarStyleLightContent View controller-based status bar appearance = NO New features require me to have some status bars in the dark default style. So to summarize I need all the app with a default .lightContent and about 10VCs with an override to .default/dark To start with I need to set the plist to: View controller-based status bar appearance = YES but once I do this many of the status bars in the app change to the .default / dark style. I can change this style in every VC using: override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } but in an app this big, this would be impractical. I've tried quite a few extensions to override behavior, but since these are instance methods they can't be overriden like this: extension UIViewController { override open var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } You can use this extension: extension UINavigationController { override open var preferredStatusBarStyle : UIStatusBarStyle { return topViewController?.preferredStatusBarStyle ?? .default } } But it only works on VC's in NavControllers and you need to set every single rootVC to .lightContent A: The extension you provided should work. extension UINavigationController { open override var preferredStatusBarStyle: UIStatusBarStyle { switch topViewController { case is DarkContentVC1, is DarkContentVC2, is DarkContentVC3: return .default default: return .lightContent } } } A: After much research it turns out that setting View controller-based status bar appearance to YES changes the paradigm of how the status bar is manipulated. It set's it to default which automatically configures it to the expected style, it also allows for overriding within individual VC's. To obtain the goal of setting the whole app to lightContent as the default style, the best solution would be to create a subclass of UIViewController for all VC's in your app with that functionality. A second solution would be to manually change all the root view controllers.
Q: Inflated Fragment not consuming all the space So i have recently been working on switching my application over to using Fragments to make it a bit more flexible. One thing I have noticed is that when I inflate my fragment view, it is not taking up the entire screen, there is still a gap at the top (below actionbar) that is actually part of my activity_main.xml here are my view and where i inflate. activity_main.xml <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_container" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:background="@color/mainBlue" android:orientation="vertical" > <TextView android:id="@+id/appTitle" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/app_name" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="@color/white" android:gravity="center_horizontal" android:textSize="75sp" android:layout_weight="2"/> <TextView android:id="@+id/newRecord" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/newRecord" android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center_horizontal" android:textSize="50sp" android:textColor="@color/white" android:layout_weight="1" /> <TextView android:id="@+id/pastRecords" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/pastRecords" android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center_horizontal" android:textSize="50sp" android:textColor="@color/white" android:layout_weight="1" /> <TextView android:id="@+id/statistics" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/statistics" android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center_horizontal" android:textSize="50sp" android:textColor="@color/white" android:layout_weight="1" /> <TextView android:id="@+id/settings" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/settings" android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center_horizontal" android:textSize="50sp" android:textColor="@color/white" android:layout_weight="1" /> </LinearLayout> <!-- The navigation drawer --> <ListView android:id="@+id/list_slidermenu" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="start" android:choiceMode="singleChoice" android:divider="@color/list_divider" android:dividerHeight="1dp" android:listSelector="@drawable/list_selector" android:background="@color/list_background"/> </android.support.v4.widget.DrawerLayout> new_record.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:background="@color/mainBlue"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_weight="1" > <EditText android:id="@+id/pricePerGallon" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="@string/pricePerGallon" android:inputType="numberDecimal" android:textSize="30sp" android:textColor="@color/white" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_weight="1"> <requestFocus /> </EditText> <EditText android:id="@+id/gallons" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="@string/gallons" android:inputType="numberDecimal" android:textSize="30sp" android:textColor="@color/white" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_weight="1"/> <EditText android:id="@+id/odometer" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="@string/odometer" android:inputType="numberDecimal" android:textSize="30sp" android:textColor="@color/white" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_weight="1"/> <EditText android:id="@+id/date" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="date" android:textSize="30sp" android:textColor="@color/white" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_weight="1"/> <EditText android:id="@+id/comments" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:textSize="30sp" android:textColor="@color/white" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:hint="@string/comments" android:layout_weight="1"/> <CheckBox android:id="@+id/completeFill" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/notCompleteFill" android:textColor="@color/white" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:background="@color/mainBlue" android:gravity="center_horizontal" > <TextView android:id="@+id/save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/save" android:textSize="50sp" android:textColor="@color/white" android:layout_weight="1" android:gravity="center_horizontal"/> <TextView android:id="@+id/reset" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/reset" android:textSize="50sp" android:textColor="@color/white" android:layout_weight="1" android:gravity="center_horizontal" /> </LinearLayout> </LinearLayout> MainActivity.java (inflating fragment here) if (fragment != null) { FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.main_container, fragment).commit(); // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); mDrawerList.setSelection(position); setTitle(navMenuTitles[position]); mDrawerLayout.closeDrawer(mDrawerList); } else { // error in creating fragment Log.e("MainActivity", "Error in creating fragment"); } Funny thing is, if I use an intent and call my NewRecord.java class the view works just fine. If I inflate my NewRecordFragment.java which is replacing NewRecord.java, is when I have the issue. Any ideas? A: The reason for the space is because your container layout (the layout into which the Fragment is inflated) has paddings applied: <LinearLayout xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_container" android:layout_width="fill_parent" android:layout_height="fill_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:background="@color/mainBlue" android:orientation="vertical" > Remove the paddings at top, bottom, left and right and your Fragment will take up all the space. A: I would remove these lines: android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"
Q: Macro to match cells across worksheets and then copy and paste relevant cells I'm trying to make a macro that matches values in column A of Sheet("Company"), to those in Column E of "Current". If there is a match, and the cell 28 ("Current") to the right of this is empty, then I want to copy the cell to the right of the respective cell in "Company" and paste it. It should loop through all values in column A of Sheet("Company"). For added difficulty, I'd love if I could implement a kind of ActiveSheet utility, so that I can apply it to other sheets rather than just "Company". Here's what I have... Option Explicit Sub CopyPaster() InvestorName As String InvestorName = ActiveCell.Value With Sheets("Current") For i = 11 To 500: If i = InvestorName And Cells(i, 27) = 0 Then Sheets("Company").ActiveCell.Offset(0, 3).Copy Sheets("Current").Cells(i, 28).PasteSpecial Next i End Sub First shows the Current Sheet, and the second image is an example of one of the Company sheets I want to copy from. A: Based on the information given, I think this is what you are after. Please double check that I chose the right columns, it was difficult to guess what you were referring to without data to look at. Sub StackExchangeVlookup() Dim Company As Worksheet Dim Current As Worksheet 'set worksheets with the names of the sheets to compare Set Company = Sheets("Company") Set Current = Sheets("Current") Dim myRange As range Dim myCell As range 'Set the range to the column you want to replace empty cells in. I think I counted 'correctly, but maybe not. If AF is not correct, will also need to change the 32 Set myRange = range("AF1", Cells(Rows.count, 32).End(xlUp)) 'if the cell is empty in the column AF (or whichever is the one you want, then use 'the VLOOKUP function. For Each myCell In myRange If Len(myCell) = 0 Then 'VLOOKUP will get the cell in column E of the row of the blank space in AF, compare 'it to Column A in Company, and then return the value to the right of the cell found 'in the Company sheet. myCell.Value = _ "=VLOOKUP(" & Current.Name & "!E" & myCell.Row & "," & Company.Name & "!A:B, 2, FALSE)" End If Next myCell End Sub
Q: Evaluating time with python I need to write a program that reads in seconds as input, and outputs the time in hours, minutes, and seconds using python. seconds = int(input()) minutes = seconds // 60 hours = minutes // 3600 seconds_left = + (seconds - hours) print(f'Hours: {hours}') print(f'Minutes: {minutes}') print(f'Seconds: {seconds_left}') This is what I'm currently running and it's not getting the desired output. Question in mind uses 4000 as an input and outputs 1 hour, 6 min, and 40 seconds A: When you divide to get (e.g.) the hours, you should also take the mod in order to just carry forward the remainder: >>> seconds = 4000 >>> hours = seconds // 3600 >>> seconds = seconds % 3600 >>> minutes = seconds // 60 >>> seconds = seconds % 60 >>> hours, minutes, seconds (1, 6, 40) This is equivalent to multiplying the int quotient by the divisor and subtracting: >>> seconds = 4000 >>> hours = seconds // 3600 >>> seconds -= hours * 3600 >>> minutes = seconds // 60 >>> seconds -= minutes * 60 >>> hours, minutes, seconds (1, 6, 40)
Q: Why does nested fadeToggle fire twice? The nested fadeToggle on '#hero-text' in this jQuery fires twice when I click the 'hero' ID and I'm trying to figure out why, and how to fix this behavior. $(document).ready(function() { $('#hero').click(function() { $('.non-hero').fadeToggle(800, function() { $('#hero-text').fadeToggle(); }); }); }); A: I've encountered this from time to time. You can spend time trying to figure out why, but if you want a quick solution, here you go: $(document).ready(function() { $('#hero').off().click(function() { $('.non-hero').fadeToggle(800, function() { $('#hero-text').fadeToggle(); }); }); }); The above answer will solve the case in which '#hero' is getting an extra bind. However, another case you might be running into is if '.non-hero' is used in more than one spot. That function is going to fire for each instance of it, and then cause separate events to trigger fadeToggle on '#hero-text'. Based on your jsfiddle, try this: $(document).ready(function() { $('#hero').click(function() { $('.non-hero').fadeToggle(800); setTimeout(function() { $('#hero-text').fadeToggle(); }, 800); }); $('#primary').click(function() { $('.non-primary').fadeToggle(800); setTimeout(function() { $('#primary-text').fadeToggle(); }, 800); }); $('#secondary').click(function() { $('.non-secondary').fadeToggle(800); setTimeout(function() { $('#secondary-text').fadeToggle(); }, 800); }); }); And for giggles I posted an alternative jsfiddle for you to consider: http://jsfiddle.net/GbgvH/3/
Q: strcpy when dest buffer is smaller than src buffer I am trying to understand the difference/disadvantages of strcpy and strncpy. Can somebody please help: void main() { char src[] = "this is a long string"; char dest[5]; strcpy(dest,src) ; printf("%s \n", dest); printf("%s \n", src); } The output is: this is a long string a long string QUESTION: I dont understand, how the source sting got modified. As per explanation, strcpy should keep copying till it encounters a '\0', so it does, but how come "src' string got modified. Please explain. A: This is a buffer overflow, and undefined behavior. In your case, it appears that the compiler has placed dest and src sequentially in memory. When you copy from src to dest, it continues copying past the end of dest and overwrites part of src. A: The easy answer is that you have (with that strcpy() call) done something outside the specifications of the system, and thus deservedly suffer from undefined behaviour. The more difficult answer involves examining the concrete memory layout on your system, and how strcpy() works internally. It probably goes something like this: N+28 "g0PP" N+24 "trin" N+20 "ng s" N+16 "a lo" N+12 " is " src N+08 "this" N+04 "DPPP" dest N+00 "DDDD" The letters D stand for bytes in dest, the letters P are padding bytes, the 0 characters are ASCII NUL characters used as string terminators. Now strcpy(dest,src) will change the memory content somewhat (presuming it correctly handles the overlapping memory areas): N+28 "g0PP" N+24 "trin" N+20 "g0 s" N+16 "trin" N+12 "ng s" src N+08 "a lo" N+04 " is " dest N+00 "this" I.e. while dest now "contains" the full string "this is a long string" (if you count the overflowed memory), src now contains a completely different NUL-terminated string "a long string". A: with high likliness the string are exact neighbours. So in your case you may have this picture dst | | | | |src | | | | | | so you start writing and it happens that the fields of src are overwritten. Howerver you can surely not rely on it. Everything could happen what you have is undefined behaviour. So something else can happen on another computer another time and/or other options. Regards Friedrich A: Your code caused a buffer overflow - copying to dest more characters than it can hold. The additional characters were written on another place on the stack, in your case, where src was pointing to. You need to use strncpy() function. A: As an additional note, please keep in mind that strncpy function is not the right function to use when you need to perform copying with buffer overrun protection. This function is not intended for that purpose and has never been intended for that purpose. strncpy is a function that was created long time ago to perform some very application-specific string copying within some very specific filesystem in some old version of UNIX. Unfortunately, the authors of the library managed to "highjack" the generic-sounding name strncpy to use for that very narrow and specific purpose. It was then preserved for backward compatibility purposes. And now, we have a generation or two of programmers who make ther assumptions about strncpy's purpose based solely on its name, and consequently use it improperly. In reality, strncpy has very little or no meaningful uses at all. C standard library (at least its C89/90 version) offers no string copying function with buffer overrrun protection. In order to perform such protected copying, you have to use either some platform-specific function, like strlcpy, strcpy_s or write one yourself. P.S. This thread on StackOverflow contains a good discussion about the real purpose strncpy was developed for. See this post specifically for the precise explanation of its role in UNIX file system. Also, see here for a good article on how strncpy came to be. Once again, strncpy is a function for copying a completely different kind of string - fixed length string. It is not even intended to be used with traditional C-style null-terminated strings. A: I suggest a quick read of: http://en.wikipedia.org/wiki/Strncpy#strncpy which shows you the differences. Essentially strncpy lets you specify a number of bytes to copy, which means the resultant string isn't necessarily nullterminated. Now when you use strcpy to copy one string over another, it doesn't check the resultant area of memory to see if it's big enough - it doesn't hold your hand in that regard. It checks up to the null character in the src string. Of course, dst in this example is only 5 bytes. So what happens? It keeps on writing, to the end of dest and onwards past it in memory. And in this case, the next part of memory on the stack is your src string. So while your code isn't intentionally copying it, the layout of bytes in memory coupled with the writing past the end of dst has caused this. Hope that helps! A: Either I'm misunderstanding your question, or you're misunderstanding strcpy: QUESTION: I dont understand, how the source sting got modified. As per explanation, strcpy should keep copying till it encounters a '\0', so it does, but how come "src' string got modified. It sounds to me like you're expecting strcpy to stop copying into dest when it reaches the end of dest, based on seeing a \0 character. This isn't what it does. strcpy copies into the destination until it reaches the end of the source string, delimited by a \0 character. It assumes you allocated enough memory for the copy. Before the copy the dest buffer could have anything in it, including all nulls. strncpy solves this by having you actually tell it how big the buffer you're copying into is, so you can avoid cases where it copies more than can fit.
Q: Viewpager with footer I am trying to setup a layout but somehow the viewpager is overlapping with the footer. I could see the viewpager's image below the footer. The layout structure I am trying is (with no overlapping) | ViewPager | | Footer | | Admob Footer | I haven't mentioned the actionbar on the top. My code so far: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="fill_parent" android:id="@+id/home_layout" android:orientation="vertical" android:layout_height="wrap_content" android:layout_alignTop="@+id/home_layout"> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/background"> </android.support.v4.view.ViewPager> </LinearLayout> <LinearLayout android:id="@+id/feature_add_confirm_buttons" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignBottom="@+id/home_layout" android:gravity="bottom" android:layout_alignParentBottom="true" android:orientation="horizontal"> <Button android:id="@+id/add" android:text="Add" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:background="@color/background" android:textColor="#FFFFFF"/> <TextView android:id="@+id/num" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="@dimen/num" android:textStyle="bold" /> <Button android:id="@+id/delete" android:text="Del" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:background="@color/background" android:textColor="#FFFFFF" /> </LinearLayout> <com.google.ads.AdView android:layout_alignParentBottom="true"> </com.google.ads.AdView> Am I missing anything? Any help will be appreciated. A: You are making mistakes in using android:layout_alignParentBottom and android:layout_alignTop, I guess. You can try this way: Firstly, put a AdView at bottom, Place the layout for feature_add_confirm_buttons above that, and finally fill the remaining space with your ViewPager placing it abve feature_add_confirm_buttons. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.google.ads.AdView android:id="@+id/adView" android:layout_alignParentBottom="true"> </com.google.ads.AdView> <LinearLayout android:id="@+id/feature_add_confirm_buttons" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="adView" android:orientation="horizontal"> <Button android:id="@+id/add" android:text="Left" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:background="@color/background" android:textColor="#FFFFFF"/> <TextView android:id="@+id/num" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="@dimen/num" android:textStyle="bold" /> <Button android:id="@+id/delete" android:text="Right" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:background="@color/background" android:textColor="#FFFFFF" /> </LinearLayout> <LinearLayout android:layout_width="fill_parent" android:id="@+id/home_layout" android:orientation="vertical" android:layout_height="wrap_content" android:layout_above="@+id/feature_add_confirm_buttons"> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/background"> </android.support.v4.view.ViewPager> <TextView android:id="@+id/sometext" android:layout_width="match_parent" android:layout_height="wrap_content" android:visibility="gone" /> </LinearLayout> </RelativeLayout> Hope it helps.
Q: Sonal lint : change this condition so that it does not always evaluate to true I am trying to consume Data JPA Repository from From Java Service which is something like below: @Service public class APIKeyServiceImpl implements APIKeyService { private APIKeyRepo apiKeyRepo; @Autowired public APIKeyServiceImpl(APIKeyRepo apiKeyRepo) { this.apiKeyRepo = apiKeyRepo; } @Override public String save(String apiKeyInput) { APIKEY apikey = new APIKEY(); apikey.setApikey(apiKeyInput); APIKEY savedKey = apiKeyRepo.save(apikey); return null != savedKey ? savedKey.getApikey() : null; } } Now Short Repo Code is below: public interface APIKeyRepo extends JpaRepository<APIKEY, String> { } Problem is whenever I run Sonarlint Report then I am getting below major issue: change this condition so that it does not always evaluate to true Which is occurring at ternary operator code which is : return null != savedKey ? savedKey.getApikey() : null; I havn't much understand which part of this will always evaluate true. A: As you save an entity save method will return you the saved entity, which can never be null. Source: Method Doc.