id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23531300
Each FILE belongs to a single COMPANY via its "COMPANY_ID" field. We would like to join each USER with every one of the FILEs that its connected to via any of the COMPANIES its associated to. This naive solution: SELECT u._id as user_id, z._id as file_id, z.SENT_ON FROM users u, LATERAL (SELECT f._id, f.SENT_ON from FILES f where ( ARRAY_CONTAINS(TO_VARIANT(f.COMPANY_ID), TO_ARRAY(u.COMPANY_IDS)))) z Takes forever and never finishes. A more convoluted solution that avoids the "ARRAY_CONTAINS" function - finishes in a second and a half: SELECT u._id as user_id, max(files.sent_on) FROM users u LEFT JOIN ( select * FROM companies c, lateral (select flt.value as cid , us._id as uid from users us, lateral flatten ( company_ids) as flt where cid = c._id) ccc ) x on (x.uid = u._id) LEFT JOIN files on x.cid = files.company_id GROUP BY u._id Is there something preventing ARRAY_CONTAINS from being used properly in "ON" clauses or as part of the "WHERE" clause of correlated lateral sub-queries?
doc_23531301
This is my test : /** * Test used to deconnect user */ public void testDeconnexion() { // revoque publish permissions on facebook FacebookManager.RevoqueAllPermissions(this.getActivity()); // wait for authorization deleted solo.waitForLogMessage(this.getActivity().getResources().getString(R.string.log_facebook_revoque_publish_action), 5000); // disconnect solo.clickOnMenuItem(this.getActivity().getString(R.string.menu_item_logout)); // give it time to change activity solo.sleep(1000); // click on log out button solo.clickOnButton("Log out"); // give it time to change activity solo.sleep(1000); // click on log out button solo.clickOnButton("Log out"); // give it time to change activity solo.sleep(1000); // log in solo.clickOnButton("Log in with Facebook"); // give it time for to see popup confirm solo.sleep(1000); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !!!!!!! My Screenshot here !!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! //click on ok button solo.clickOnButton("OK"); // <-- Doesn't Work... solo.sleep(5000); } My problem is when Facebook dialog with authorization is displayed, Robotium does not want to click on "OK" button. How to fix this? Ty A: I've had a lot of trouble using the specific "clickOn" methods. Try not specifying that it's a button you want to click by using solo.clickOnText("OK") instead. Also, avoid using solo.sleep() because it will slow down your tests significantly even if it's not required. Make use of solo.waitFor-methods. For example waitForText("text"), waitForActivity(YourActivity.class) etc. Those methods return a boolean you can use in assert-statements. See the Solo Javadoc for the available methods.
doc_23531302
https://verificacfdi.facturaelectronica.sat.gob.mx, if I'm correct those two inputs have the id of: * *ctl00_MainContent_TxtRfcEmisor *ctl00_MainContent_TxtRfcReceptor I already tried this but it didn't work: https://verificacfdi.facturaelectronica.sat.gob.mx/&ctl00_MainContent_TxtRfcEmisor=123456789&ctl00_MainContent_TxtRfcReceptor=123456789 there is a way to achieve what I want? A: The short answer is no. The browser won't automatically detect the URL parameter and pre-populate any form fields. A back-end PHP / ASP.NET page can read the value from the request and generate the HTML fields with the specified values. Alternatively, the page could use JavaScript to set the field values when the document finishes loading. But all of this depends on changes to the target web page. If you do not have the ability to modify that page, I'm afraid there's very little you could do. You might be able to duplicate the form on your own page, and send the form data to the target—effectively bypassing the form on the other page and 'faking' your own, but if the target system does some kind of validation to prevent posting forms across domain names, this probably won't work either. You may have create the form and process it yourself, replicating the entire form interaction programmatically when a user submits a form to your server. In any case, none of these options are particularly graceful.
doc_23531303
I added the eclipse plugin for auto-complete during coding. Buts its a trial version just like the sencha architect. Am really confused on how the sencha app should be developed. I want to know the tools that sencha developers are using so that I can deploy and debug effeciently. Thanks in advance. A: The workflow / tools choice when developing an application is a subjective matter so I'm going to talk about my experience, having been a Sencha Touch developer for the last year. I find it really hard to find typo and errors in my code. ... Am really confused on how the sencha app should be developed. This is not a matter of tools in my opinion. Sencha Touch has an unavoidable steep learning curve. You should start with simple examples, and you could ask here when you have specific programming issues (I personally found Sencha Touch forums less useful than stackoverflow). The most important thing is understanding the basics concepts: * *Sencha Touch class system (http://www.sencha.com/learn/sencha-class-system), *How Sencha implements MVC (http://docs.sencha.com/touch/2.2.1/#!/guide/controllers) (http://docs.sencha.com/touch/2.2.1/#!/guide/views), *Sencha Touch Layouts (http://docs.sencha.com/touch/2.2.1/#!/guide/layouts), *Sencha Touch Components (http://docs.sencha.com/touch/2.2.1/#!/guide/components) Also all of these guides will be very useful, make sure you understand them and learn to use Sencha Docs, which definetely has some obscure, non explained properties, but should still be your main resource when developing a Sencha Touch app. Debugging will always be tricky, unfortunately sometimes setting the wrong property on a Component, or misunderstanding how a Component is meant to work, ends up with some obscure var is not defined error. Do not fear to check Sencha Touch source code when this happens, code is well written and usually easy to understand. Here the tools to use are again Sencha Touch Docs (when hovering on a class title you can examine directly its source code, plus your browser debugging console. Use frequent console.debug() messages, and when something weird happens inside framework classes stop execution with debugger; and step inside source code). Now back to your question: I have been using the following tools: * *NetBeans, *Chrome DevTools, *Chrome Ripple Extension, *Sencha Command (optional) *Compass CSS authoring framework *a couple shell scripts The IDE is a matter of personal choice, Netbeans has some nice Javascript suggestions: it highlights variables when they are used but not defined in the current scope, or defined but not used, which really helps a lot against typos. It is very heavy in terms of memory usage. I guess Eclipse, or even a lighter one could be equally good. Chrome is kinda a forced choice if you are on Windows, their DevTools are excellent, make sure you master them, they will be your main working tools. Once again: lot of RAM helps. Ripple is an invaluable extension that allows you to test your mobile app on different devices and if you are using Phonegap for native deployment it emulates a part of its API on the browser. Compass is the tool suggested by Sencha to compile their sass files. There is a detailed tutorial on how to setup compass on Sencha Docs. I have been using Sencha Command but it's not strictly necessary, if you don't care about resources minification (but you should) you will not miss much about it. If you are developing a native app you can make up for the lack of Sencha Command deploy function with a simple shell script that copies html/js/css resources to the assets folder of your Phonegap project. Another script activates automatically compass watch on the /resources/sass folder at startup, to avoid having to manually do that each time. Just my two cents, hope it helps. A: Anubis covered majority of the bee knees in hand coding Sencha Touch. I'd like to add a couple more cents into the kitty. My personal preference for IDE is Sublime Text. Searching through entire projects of code for anything, I've not seen an equal for effectiveness and speed. You can customise everything - especially colours and keybindings. It also has a ludicrous wealth of plugins, including working in correlation to Chrome, as well as Github. SENCHA GUIDES Miami Coder Tutorials - great collection of practical tutorials which will help you understand development patterns faster than most other guides. Great for starters. Figleaf Training can be a little unconventional, but a great free means of learning Sencha Touch and almost everything it is capable of. Great for starters too. Druck IT - solid collection of guides and ST information. Has links to many other useful sites such as these listed. Mitchell Simoens - Mitchell is Sencha staff, a quality coder, and his site has some great advice and snippets to help learn. This is where you'll truly learn how to code ST well. Helps towards getting a grasp, but mainly for mid+ knowledge. Ladysign - one of the Sencha Trainers. Has content that clears up "how to" in many facets other sites and books never even mention. Quality information. This info will get you above basic and flesh out your knowledge and understanding. Modus Create - Jay Garcia is one of the devs of ST. Modus Create is his enterprise, which contains some useful guides within the blog. Custom Font Icons - complete guide for 2.2. Very useful. There's a few other sites that were incredible sources of tidbits through to information on how to code ST professionally. These links above will help immensely though. Above all, read the source code. It is very well documented, as well as being an example in itself of how to use the code. I have learnt ludicrous amounts this way. GRUNT (with NPM/Node.js)! Use Grunt! This will automate the vast majority of what you want to do. For example, typing "grunt" in the command line could jshint/jslint your code, concatenate all .js files together, all css files together (including all the compass joy), obfuscate, compress, run a comprehensive set of unit tests (especially Phantom), output to desired location, then add a cherry on top by refreshing your browser window. Add in the grunt watch plugin, and it'll do that every time a file is saved in defined directories. Any bugs in your code - you get accurate specific line numbers where it is broken. The beauty of grunt is extended by optional alternate commandlines for different tasks. Also, you can specify in the package.json file of a few kB the precise list of plugins you wish to use with the gruntfile you've created, saving megabytes of file transfer. NPM can process that file, and download and install all that is required to operate. Makes for fast setup on another computer. Side note: Touch Node has come of age. This permits all ST's class structure to develop your serverside javascript. Want to include Sencha Cmd? Sencha Cmd (finally) does do a decent job of collecting only the dependent classes from the full library. grunt-sencha-build grunt-senchacmd Alternative for Sencha Cmd Extend Grunt with Matt Goldspink's grunt-sencha-dependencies which works for both ST and ExtJS, or use grunt-sencha-resolver - this latter one I haven't used.
doc_23531304
I am running on windows which I understand is not officially supported yet. Has any one managed to get this up and running with some success? I have followed some tutorials on line relating to the subject however I think they are out dated. I managed to install yeoman without any additional steps and no errors as far as I can tell. Grunt File being Used A: Oh no... Git was not on the system path. Adding it caused me to run into another small error with a solution found here http://wingkaiwan.com/2012/11/25/bower-errors-on-windows/ Thank you Mr Ricky Wan
doc_23531305
So, how am I supposed to reset the values of a model form before the form is displayed. Definitely, the model belonging to that form is updated with the new values everytime. But I need to reset them when rendered again for edit. Let me pinpoint what I actually need. I need to override the field values during edit. So if a model was saved with field A having value 'value1'. I need to change this field's value to 'specified value' during edit. So even if the user then changes it to value 2 and saves it. During edit, I again want to have the value set to 'specified value' in the rendered form. It is independent of the values in the database A: You can set form values using initial value: form = MyForm(initial={'field1': value1, 'field2': value2, 'field3': value3})
doc_23531306
I've tried to google preprocess scripting in Unity. Did I understand correctly that I need to use something like BuildPipeline? Are there any simple examples to understand how does it work? A: Well, finally I managed to do it myself. If someone will handle same problem, here is my code: class MyBuilder : Editor { private static string[] FillLevels () { return (from scene in EditorBuildSettings.scenes where scene.enabled select scene.path).ToArray (); } [MenuItem ("MyTool/BuildGame")] public static void buildGame() { string[] levels = FillLevels (); foreach (string level in levels) { EditorApplication.OpenScene (level); object[] allObjects = Resources.FindObjectsOfTypeAll (typeof(UnityEngine.GameObject)); foreach (object thisObject in allObjects) { /* my gameObjects changing before compilation */ } EditorApplication.SaveScene (); } BuildPipeline.BuildPlayer (levels, Path.GetFullPath (Application.dataPath + "/../game.exe"), BuildTarget.StandaloneWindows, BuildOptions.None); } } A: You want to create an Editor Script. With the API reference link you should be able to do what ever you want to the scene. The script below will allow you to save those changes. This is an example of an Editor script that will allow you to save a change done to a scene, here: import UnityEditor; class SimpleAutoSave extends EditorWindow { var saveTime : float = 300; var nextSave : float = 0; @MenuItem("Example/Simple autoSave") static function Init() { var window : SimpleAutoSave = EditorWindow.GetWindowWithRect(SimpleAutoSave, Rect(0,0,165,40)); window.Show(); } function OnGUI() { EditorGUILayout.LabelField("Save Each:", saveTime + " Secs"); var timeToSave : int = nextSave - EditorApplication.timeSinceStartup; EditorGUILayout.LabelField("Next Save:", timeToSave.ToString() + " Sec"); this.Repaint(); if(EditorApplication.timeSinceStartup > nextSave) { var path : String [] = EditorApplication.currentScene.Split(char.Parse("/")); path[path.Length -1] = "AutoSave_" + path[path.Length-1]; EditorApplication.SaveScene(String.Join("/",path), true); Debug.Log("Saved Scene"); nextSave = EditorApplication.timeSinceStartup + saveTime; } } }
doc_23531307
I override DefaultDelegate and handleNotification(cHandle, data), and get data from handleNotification(cHandle, data). Then I convert type of data from byte to hex, and I can only get 20 bytes of data. Here is my code: dev = btle.Peripheral(address, 'random') dev.setMTU(244) My BLE peripheral device is "Nordic NRF52832". How can I get more than 20 bytes of data? A: Adding delay worked for me : dev = btle.Peripheral(address, 'random') import time time.sleep(1) dev.setMTU(244) source: https://github.com/IanHarvey/bluepy/issues/325 A: I think I find the reason of it. Library bluepy supports BLE4.0 but don't support BLE4.2. BLE4.0 and BLE4.1 can get the payload for only 20 bytes.
doc_23531308
I have a YAML file, which executes a bash code: bash ./deploy_eventhubs.sh In deploy.eventhubs.sh I execute the command: az deployment group create --resource-group myresourcegroup --templatefile armtemp/eventhubs.json --parameters @eventhubs-params.json Inside my two templates: * *eventhubs.json *eventhubs-params.json I have different parameters, such as {"value": "${LOCATION}"}, that I would like to change runtime. Location is different per use-case so I am curious how is it possible to predefine this parameter that these two JSON files use, in the YAML or Bash? Useful resource: https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/transforms-variable-substitution?view=azure-devops&tabs=yaml#json-variable-substitution-notes A: The documentation suggest that you could use a parameters JSON file (as you use above), and then override it at runtime: az deployment group create --resource-group testrg --name rollout01 \ --template-file azuredeploy.json --parameters @params.json \ --parameters https://mysite/params.json --parameters MyValue=This MyArray=@array.json so, you could conceivably do a couple of ways: construct a JSON file or literal JSON string with the expanded variable values you wish to use, and tack it on as an additional --parameters item, OR dynamically construct the entire command as a string, with $(variable) references embedded, and execute it (which has some shell injection risk).
doc_23531309
Imagine if I wanted users of the application to see each other's application specific data - at minimum I would need a list of users that are licensed to use the application. Is this possible? I want to be able to add code to the package that can be used to make decisions based on whether users have been granted a license seat through the LMA's "Manage Licenses" process. Update: I've discovered that you can tell if the currently logged in user is licensed via the UserInfo.isCurrentUserLicensed(namespace) method - but so far no way to get a list of all licensed users. A: UserInfo.isCurrentUserLicensed(namespace) is the only method related to licensing from apex sadly, there is currently no way to get all licensed users of an application programmatically. There's an idea for this on the appexchange which it can't hurt to vote for: https://sites.secure.force.com/success/ideaView?id=08730000000bj7xAAA
doc_23531310
Project's package.json { "name": "Your Cool Project", "version": "0.0.0", "dependencies": { "myModule" : "git+ssh://git@github.com:user/myModule.git", /* All your other dependencies */ } ... } Module's .npmignore file .git* gulpfile.js index.html tests.js README.md When I run npm update myModule these files are still being downloaded into my project. Am I missing something? Does .npmignore work for privately hosted modules? Thanks in advance. A: Since you're specifying the dependency myModule as a Git repository, npm is probably just cloning the repo. Therefore your .npmignore files isn't being used. .npmignore seems to be used when "making modules" eg: pack or publish not consuming modules (like in your example). A: Be careful when using .npmignore If you haven't been using .npmignore, it defaults to .gitignore with a few additional sane defaults. What many don't realize that once you add a .npmignore file to your project the .gitignore rules are (ironically) ignored. The result is you will need to audit the two ignore files in sync to prevent sensitive leaks when publishing. Still, I think is missing put the /node_modules in your .npmignore. Set the attribute private: true in package.json file as below: { "name": "project-name", "version": "0.0.0", "license": "MIT", "scripts": { }, "private": true, "dependencies": { }, "devDependencies": { } } Generate the build into /public folder to publish it to NPM repository with .npmignore into that folder.
doc_23531311
I went through the doc link https://www.elastic.co/guide/en/elasticsearch/reference/current/removal-of-types.html mentioned by elastic search but still not able to get why is it. I think types were helpful in searching faster through documents as similar documents are grouped together. A: what you are suggesting there, "searching faster through documents as similar documents are grouped together", is no different from using a field called filter_field and using that (which that link talks about) however, types as they were implemented, were a bit more than just a data filtering field. and the implementation approach caused a number of issues with the way that users interacted with Elasticsearch, and the flexibility of Elasticsearch as it scales this section goes into those technical details, and if that's not clear then it'd be great to understand why as we can make changes to it :)
doc_23531312
I have tried the following code: var htmlBody=htmlOutput.evaluate().getContent(); var blob = Utilities.newBlob(htmlBody, MimeType.HTML, name).getAs(MimeType.PDF); Bootstrap classes and css formatting is lost while converting to pdf.
doc_23531313
printf("Enter name and salary of 'Employee 1':\n"); scanf("%49[^\n]%*c,%d", name1,&salary1); And I input the value as: Harry Wilson 12000 the next code to echo those values: puts(name1); printf("%d",salary1); The output was: Harry Wilson 118592 The output of name1 was fine but there was a garbage value inside salary1. Suggest me the way to prevent this error!! I want the similar input to employee2 but when I tried to do the same it was not even able to take input. A: scanf reads input and try to match it with the format string passed to scanf. It will keep on reading as long as the input can match the format string and stop as soon as something doesn't match. Let's take a close look at your format string. Format string: %49[^\n]%*c,%d %49[^\n] means: Keep reading characters until a newline is found or 49 characters has been read %*c means: Read the next character an discard it , means: Read a comma %d means: Read any number of white spaces (incl. zero) followed by an integer Your input is `"Harry Wilson\n12000\n" which means: input is: Harry Wilson\n12000\n Format %49[^\n] will match the Harry Wilson and then input is: "\n12000\n" Format %*c will match the first \n and then input is: "12000\n" Format , will not match and scanf will return leaving 12000\n in the input stream So your problem is the comma. Either remove it from the format string or change your input to include a comma at the correct position. Also notice that %*c is unnecessary as %d will also read (and discard) the newline before the integer value. If the "comma" problem is solved a new problem will pop-up. After successful scan of the integer value there will be a \n in the input stream. This may interfere with any following scanf calls. Consider adding a space as first character of the format string to remove initial white spaces in the input stream. Notes: Consider using fgets together with sscanf (or similar parser) instead of scanf. It will give you a much better control when parsing user input. As an example: Consider what will happen with your current code if a user inputs a 100 character long name. For both sscanf and scanf always check the return value as it tells how many input items that were matched. A: You can prevent the error by giving the input in the right syntax: Harry Wilson ,12000 Gets you successful scanning and echo: Harry Wilson 12000 This is because the code requires first one "any character" "%c*" which has to be a newline (because of the ^\n in the previous "%49[^\n]") and gets ignored, i.e. not written to any receiving variable. Then it requires a specific ",". Doing a check on the return value of scanf() will help you to get it right. As long as the return value is not as expected, the scanning did fail and any further scan attempts meet unexpected input which probably makes them fail. Alternatively you can change the code to match the input. Either by tinkering with the scanf formatting. Or, as recommended in the comments already, by reading error-prone input (i.e. anything a human types in) with fgets() and parsing it with non-destructive sscanf() attempts. (scanf() consumes the input...).
doc_23531314
I have this Index ST   ID   time 0     1      12:04 1     1     12:00 0     2     12:02 1     2     11:58 0     2     11:22 1     3     12:33 0     3     12:20 In Kibana, I'm trying to get a table with the top hit from ID when ST = 0 to have results as ST    ID    time 0     1      12:04 0     2     12:02 As you could see ID = 3 has top hit with ST = 1, so it shouldn't appear in the table Could someone help me with this? BR BR
doc_23531315
I have a ListA and an ENUM. I would like to iterate over ListA and for each element from ListA apply a method get(value) where value is an ENUM. All this processing should return an object of type T. What I have now is: default void processLists(P<?, ?, T> p) { T allData = (T) Stream.of(Vvalues.values()) .map(c -> p.get(c.name())) .flatMap(optionalData -> optionalData.map(data -> ((List<T>) data).stream()).orElse(Stream.empty())) .collect(Collectors.toList()); save(allData); } .... getListA().stream().forEach(p->processLists(p)); The code (as posted in the comments): getUrls().stream().forEach(url->processUrl(url)); default void processUrl(Url<?, ?, T> url) { T allData = (T) Stream.of(Location.values()) .map(location -> url.get(location.name())) .flatMap(optionalData -> optionalData .map(data -> ((List<T>) data).stream()) .orElse(Stream.empty())) .collect(Collectors.toList()); save(allData); } This is not ok as I would like to call save just ONCE. A: As I understand correctly you problem, you have an Enum and some other class, i.e. Data: enum Enum {} class Data { public String get(Enum value) { return value.name(); } } All you need, is just call Data.get(Enum) with all available constants from Enum. As result for each item from source list, you get list of results and you want to retrieve all these data as simple list. public static List<String> process(List<Data> data) { return data.stream() .map(d -> Arrays.stream(Enum.values()).map(d::get).collect(Collectors.toList())) // .map(d -> Arrays.stream(Enum.values()).map(e -> d.get(e.name())).collect(Collectors.toList())) .flatMap(List::stream) .collect(Collectors.toList()); } This is example of the client code: List<String> res = process(new ArrayList<>());
doc_23531316
axios.post(url, { email: this.email, }) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); I get the error from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. The problem is not at the server level, I have done tests from Postman or directly with CURL and it does not generate an error. Solution: Thanks to Shrinivas Bendkhale's comments. I managed to solve the problem. At first it did not work, so it was necessary to add the "logLevel" and "pathRewrite" options to the proxy. * *logLevel: It allows to see in the terminal how the proxy is working *pathRewrite: Add the rest of the path to the proxy // vue.config.js module.exports = { devServer: { proxy: { '^/rp': { target: process.env.API_OLD_SERVER, secure: false, logLevel: 'debug', pathRewrite: { '^/rp': '/' } }, }, }, } So my call was as follows axios.post('/rp/full-path', { usermail: this.email, }) .then((response) => { console.log(response.data); }) .catch((error) => { console.log(error); }); A: Inside vue.config.js file add following lines: // vue.config.js module.exports = { // options... devServer: { proxy: 'https://mywebsite/', } }
doc_23531317
On the desktop (being log out of facebook) there is the following situation: * *Click on like *A popup appears with a form for login *After login the popup is closed and the like count is raised However, using it on my iphone in chrome browser and being logged out of facebook the following happens: * *Click on the like button *Redirect to the facebook login page *After login I'm redirected to a blank page. The screenshot below shows the problem: Is there a possibility to avoid this? EDIT: The same happens when I try this in an iOS app using a UIWebView. A: Okay, I found a solution for doing this in my iOS app for an integrated UIWebView. When someone is not logged in to facebook a popup opens and requests a login. After logging in the user is redirected back to the page from where he hit the like button. However in the UIWebView this redirect URL leaves the user with a blank page. The solution to the problem is to intercept the redirect URL and reload the page with the like button. So, with UIWebView one can intercept the requests before the actual webpage is loaded and react on certain URLs. The code for this look like this: - (void)viewDidLoad { [super viewDidLoad]; self.webview.delegate = self; [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/facebook_like_box.html"]]]; } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if( [[request.URL description] rangeOfString:@"lugins/close_popup.php"].location != NSNotFound) { // We intercepted the redirect URL of facebook after logging in. Instead of loading a blank page recall the URL of the like box // manually on the uiwebview. [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/facebook_like_box.html"]]]; //returning NO indicates the the page is not further loaded. return NO; } //Any other page should be loaded return YES; }
doc_23531318
function hello(name, callback) { var hello1 = "Hello There " + name; callback(hello1); } hello("John", function(hello1) { alert(hello1); }); I can get "Hello There John" in an alert box. How do I make it such that I can have a hello2 variable so that there are two variables in the callback? I essentially want to do something like: function hello(name, callback) { var hello1 = "Hello There " + name; var hello2 = "Greetings " + name; callback(hello1, hello2); } hello("John", function(hello1, hello2) { alert(hello1 + " " + hello2); }); A: if you got only strings values, the best will be create a array: var someArray = new Array(); then in the function you can put the values in the array: someArray[someArray.length]= "HELLO USER WITH NAME: " + name; someArray[someArray.length]= "HELLO USER WITH NAME: " + name2; and after that return the array: callback(someArray); // or maybe will be better?: return someArray; and in the callback function you can get the values with: function callback(var retArray){ for(int i=0,i<retArray.length,i++){ console.log(retArray[i]); } or you can put make your own object (function) with some strings inside..and then return this function..But if you have only string values, better will be the Array.
doc_23531319
CommUtil.showCAlertDialog( act = this, msg = getString(R.string.network_error_app_fake_msg), dialogFinishType = DialogFinishType.APP_PROCESS_KILL) return But When I Reset My Computer And Download Android Studio Set My Code Style Like this CommUtil.showCAlertDialog(act = this, msg = getString(R.string.network_error_app_fake_msg), dialogFinishType = DialogFinishType.APP_PROCESS_KILL) return What options should I set to return to the previous code style? A: Settings -> Editor -> Code Sytle -> Kotlin -> Wrapping and Braces -> Function Call Arguments Set it to "Chop down if long" or "Wrap always".
doc_23531320
My question is, how can I log in to the rest of the subdomain that I log in? The bigger problem I have is that it does not log in to the site but it runs online? And that I send a request, it is sent, but the answer does not come for Ajax to show, but it comes in the network thanks. A: Perhaps you could make a database table that checks the user logins that will also expire. So when a user enters your sub domains it checks via ip(not recommended) or other things if that user is logged in.
doc_23531321
<input type="range" id="slider" min="0" max="100" value="50" /> at runtime like the following : $( "#slider" ).slider( "option", "min", 40 ); $( "#slider" ).slider( "option", "max", 90 ); But its not working, Kindly help . No error . Also tried destroy() and refresh() , but no change. A: Use .prop() to change min and max and then .slider("refresh") to apply changes. $("#slider").prop({ min: 40, max: 90 }).slider("refresh"); Demo
doc_23531322
script.js ---------- $(function() { var myData = { requests: [ {id: "1", firstname: "Roger", lastname: "Jones", age: 24}, {id: "2", firstname: "Phillip", lastname: "Green", age: 44} ]}; $.ajax({ url: 'templates/requests.html', dataType: 'html', cache: false, success: function(data, status, response) { var template = Handlebars.compile(response.responseText); var context = myData; $('#InjectTemplate_Requests').html(template(context)); } }); }); index.html ------------- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Handlebars</title> </head> <body> <div id="InjectTemplate_Requests"> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script> <script src="script.js"></script> </body> </html> requests.html (template file inside the 'templates' directory) -------------- <table> <thead> <th>Name</th> <th>Status</th> <th>Type</th> </thead> <tbody> {{#requests}} <tr> <td>{{firstname}} {{lastname}}</td> <td>{{age}}</td> </tr> {{/requests}} </tbody> </table> File Structure -------------- index.html | script.js | | |---templates | | |---requests.html I seem to be getting this error on the console: Failed to load resource: The requested URL was not found on this server. However, when I add the template to Index.html (and remove ajax call from the script file), the template renders just fine. Can anybody shed some light as to why this is happening and how I can fix this? Thanks in advance. A: I managed to fix the issue by changing this: <script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script> to this: <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script> Thanks for all the suggestions though. A: This isn't an issue with Handlebars; it's an issue with your URL (as the error notes); I noticed you're using a relative path templates/requests.html in the AJAX request. If you use an absolute URL instead (/templates/requests.html), does that fix the problem? Likewise, is whatever backend server you're using configured to serve that directory?
doc_23531323
I want to write a function which receives component as parameter and removes it like that: function removeComponent(component) if component then component:removeSelf() end component = nil end Well, it works but my parameter does not get nil after using this function. Probably I have to pass it by reference, but I'm not sure it is possible with Corona. A: This does not really make sense as presented in your example. What exactly are you trying to accomplish? Is component a global ? Or a key in a table? In your example, component is the name of a local variable in your function. Your component = nil only removes the value from the local variable, and thus will be lost. If you want to have global effects, you'd need to pass the name of the variable you'd want to eliminate as string: function removeComponent(component) if _G[component] then -- exists globally? _G[component]:removeSelf() end _G[component] = nil end Note that this style of programming (using the global table for this kind of things) is generally not a good idea. In the best case it can surprise you, in the worst case you end up zapping things like standard functions as print. Therefore I'd recommend puttign things in their own table, and passing it on to the function. A: Its not different really than any other language. Passing by a value by reference (in C++ for example) would not stop any program from holding another copy of this same value elsewhere. I know nothing of Corona, but this isn't really a Corona question so much as a Lua style question. However, if I had wrote it, I would ensure that the 'component' userdata or underlying value would clear itself up. If the userdata was accessed again, it should throw an error complaining about re-using a dead userdata. A: I have written this code: local component = display.newCircle(100, 100, 100); local function removeComponent(c) if component then component:removeSelf() end component = nil end removeComponent(component) if component == nil then print("Component is nil") else print("Component is not nil") end And it prints "Component is nil". Perhaps you have a copy of your component somewere else or may be you forget to call function removeComponent or something else. Need to see more of your code A: Lua doesn't support passing by reference, but since it does support return values you can always achieve what you want using this idiomatic approach: function removeComponent(component) if component then component:removeSelf() end return nil end And then call it like this: a = removeComponent(a) Edit: It's worth pointing out too that since Lua supports multiple return values and multiple assignments, you never actually need pass-by-reference. If you need several items updated, pass them in and return them and then do the call as a,b = myFunction(a,b)
doc_23531324
Here is my Access Class: public partial class Access { public Access() { this.Rights = new HashSet<Right>(); } public int AccessId { get; set; } public string Name { get; set; } public string Type { get; set; } public virtual ICollection<Right> Rights { get; set; } } } Here is my DBContext: public partial class UserManEntities : DbContext { public UserManEntities() : base("name=UserManEntities") { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public DbSet<Access> Accesses { get; set; } public DbSet<Right> Rights { get; set; } } Now my database has a one to many relationship ACCESS to RIGHT using (var db = new UserManEntities()) { Access newObject = new Access(){name=newUser, type="user"}; db.Accesses.Add(newObject); db.SaveChanges(); } My results are that I have two rows in the Access table with the exact same name. I don't understand why it is adding double. Can someone please steer me in the right direciton?
doc_23531325
data['demands_oranges'] = [0, 1, 1, 2, 4, 2, 4, 1, 8, 1, 2, 1, 2, 4, 4, 8, 8] data['demands_apples'] = [0, 1, 1, 2, 4, 2, 4, 1, 8, 1, 2, 1, 2, 4, 4, 8, 8] data['vehicle_capacities_oranges'] = [0, 0, 40, 40] data['vehicle_capacities_apples'] = [40, 40, 0, 0] Also, I Defined two dimensions for each capacity: # Add Capacity constraint. def demand_callback_apples(from_index): """Returns the demand of the node.""" # Convert from routing variable Index to demands NodeIndex. from_node = manager.IndexToNode(from_index) return data['demands_apples'][from_node] demand_callback_index_apples = routing.RegisterUnaryTransitCallback( demand_callback_apples) routing.AddDimensionWithVehicleCapacity( demand_callback_index_apples, 0, # null capacity slack data['vehicle_capacities_apples'], # vehicle maximum capacities True, # start cumul to zero 'Capacity_apples') def demand_callback_oranges(from_index): """Returns the demand of the node.""" # Convert from routing variable Index to demands NodeIndex. from_node = manager.IndexToNode(from_index) return data['demands_oranges'][from_node] demand_callback_index_oranges = routing.RegisterUnaryTransitCallback( demand_callback_oranges) routing.AddDimensionWithVehicleCapacity( demand_callback_index_oranges, 0, # null capacity slack data['vehicle_capacities_oranges'], # vehicle maximum capacities True, # start cumul to zero 'Capacity_oranges') The Probem is, that no solution is returned for this input data. Despite the fact that the vehicle capacity is not even close to be exceeded. The Model works for some reason when I use: data['vehicle_capacities_oranges'] = [0, 0, 40, 40] data['vehicle_capacities_apples'] = [0, 0, 40, 40] But that's not what I need. What is the reason for that? Code: """Capacited Vehicles Routing Problem (CVRP).""" from ortools.constraint_solver import routing_enums_pb2 from ortools.constraint_solver import pywrapcp def create_data_model(): """Stores the data for the problem.""" data = {} data['distance_matrix'] = [ [ 0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354, 468, 776, 662 ], [ 548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674, 1016, 868, 1210 ], [ 776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164, 1130, 788, 1552, 754 ], [ 696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822, 1164, 560, 1358 ], [ 582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708, 1050, 674, 1244 ], [ 274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628, 514, 1050, 708 ], [ 502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856, 514, 1278, 480 ], [ 194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320, 662, 742, 856 ], [ 308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662, 320, 1084, 514 ], [ 194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388, 274, 810, 468 ], [ 536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764, 730, 388, 1152, 354 ], [ 502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114, 308, 650, 274, 844 ], [ 388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194, 536, 388, 730 ], [ 354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0, 342, 422, 536 ], [ 468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536, 342, 0, 764, 194 ], [ 776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274, 388, 422, 764, 0, 798 ], [ 662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730, 536, 194, 798, 0 ], ] data['demands_oranges'] = [0, 1, 1, 2, 4, 2, 4, 1, 8, 1, 2, 1, 2, 4, 4, 8, 8] data['demands_apples'] = [0, 1, 1, 2, 4, 2, 4, 1, 8, 1, 2, 1, 2, 4, 4, 8, 8] data['vehicle_capacities_oranges'] = [0, 0, 40, 40] data['vehicle_capacities_apples'] = [0, 0, 40, 40] data['price_per_km'] = [1, 1, 1, 1] data["price_per_stop"] = [1, 1, 1, 1] data['num_vehicles'] = 4 data['depot'] = 0 return data def print_solution(data, manager, routing, solution): """Prints solution on console.""" for capacity_ID in ['demands_oranges','demands_apples']: print("____Capacity_{}_____".format(capacity_ID)) total_distance = 0 total_load = 0 for vehicle_id in range(data['num_vehicles']): index = routing.Start(vehicle_id) plan_output = 'Route for vehicle {}:\n'.format(vehicle_id) route_distance = 0 route_load = 0 while not routing.IsEnd(index): node_index = manager.IndexToNode(index) route_load += data[str(capacity_ID)][node_index] plan_output += ' {0} Load({1}) -> '.format(node_index, route_load) previous_index = index index = solution.Value(routing.NextVar(index)) route_distance += routing.GetArcCostForVehicle( previous_index, index, vehicle_id) plan_output += ' {0} Load({1})\n'.format(manager.IndexToNode(index), route_load) plan_output += 'Distance of the route: {}m\n'.format(route_distance) plan_output += 'Load of the route: {}\n'.format(route_load) print(plan_output) total_distance += route_distance total_load += route_load print('Total distance of all routes: {}m'.format(total_distance)) print('Total load of all routes: {}'.format(total_load)) def main(): """Solve the CVRP problem.""" # Instantiate the data problem. data = create_data_model() # Create the routing index manager. manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']), data['num_vehicles'], data['depot']) # Create Routing Model. routing = pywrapcp.RoutingModel(manager) ### Kosten festlegen ### def create_cost_callback(dist_matrix, km_costs, stop_costs): # Create a callback to calculate distances between cities. def distance_callback(from_index, to_index): from_node = manager.IndexToNode(from_index) to_node = manager.IndexToNode(to_index) return int(dist_matrix[from_node][to_node]) * (km_costs) + (stop_costs) return distance_callback for i in range(data['num_vehicles']): cost_callback = create_cost_callback(data['distance_matrix'], data["price_per_km"][i], data["price_per_stop"][i]) # Callbackfunktion erstellen cost_callback_index = routing.RegisterTransitCallback(cost_callback) # registrieren routing.SetArcCostEvaluatorOfVehicle(cost_callback_index, i) # Vehicle zuordnen # Add Capacity constraint. def demand_callback_apples(from_index): """Returns the demand of the node.""" # Convert from routing variable Index to demands NodeIndex. from_node = manager.IndexToNode(from_index) return data['demands_apples'][from_node] demand_callback_index_apples = routing.RegisterUnaryTransitCallback( demand_callback_apples) routing.AddDimensionWithVehicleCapacity( demand_callback_index_apples, 0, # null capacity slack data['vehicle_capacities_apples'], # vehicle maximum capacities True, # start cumul to zero 'Capacity_apples') def demand_callback_oranges(from_index): """Returns the demand of the node.""" # Convert from routing variable Index to demands NodeIndex. from_node = manager.IndexToNode(from_index) return data['demands_oranges'][from_node] demand_callback_index_oranges = routing.RegisterUnaryTransitCallback( demand_callback_oranges) routing.AddDimensionWithVehicleCapacity( demand_callback_index_oranges, 0, # null capacity slack data['vehicle_capacities_oranges'], # vehicle maximum capacities True, # start cumul to zero 'Capacity_oranges') # Setting first solution heuristic. search_parameters = pywrapcp.DefaultRoutingSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC) search_parameters.local_search_metaheuristic = ( routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH) search_parameters.time_limit.FromSeconds(10) # Solve the problem. solution = routing.SolveWithParameters(search_parameters) # Print solution on console. if solution: print_solution(data, manager, routing, solution) print(solution) if __name__ == '__main__': main() A: All location can only be visited once So if you have apples and oranges you should duplicate the location instead, so one will be visited by one vehicle and one by an other vehicle... note: When you change your capacity so a vehicle can carry both types then it works
doc_23531326
captureOutput = [[AVCapturePhotoOutput alloc]init]; AVCapturePhotoSettings* hots = [AVCapturePhotoSettings photoSettingsWithFormat:@{AVVideoCodecKey:AVVideoCodecTypeJPEG}]; [captureOutput setPreparedPhotoSettingsArray:hots completionHandler:nil]; I am trying to make a barcode scanner A: Use this instead: [captureOutput setPreparedPhotoSettingsArray:@[hots] completionHandler:nil];
doc_23531327
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) { String url = "jdbc:mysql://localhost:3306/joebdd"; String driver = "com.mysql.jdbc.Driver"; String user = "root"; String pass = "12345"; String value=(jComboBox1.getSelectedItem().toString()); try { Class.forName(driver).newInstance(); Connection con = (Connection)DriverManager.getConnection(url,user,pass); String sql1 = "select Price from Produit where ProductName='"+value+"'"; PreparedStatement pst = con.prepareStatement(sql1); ResultSet rs = (ResultSet) pst.executeQuery(sql1); jTextField3.setText(rs.getString(1)); } catch( ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e){ JOptionPane.showMessageDialog(null, e); }} A: Check that ResultSet has any value or not, by rs.next(). String pass = "12345"; String value=(jComboBox1.getSelectedItem().toString()); try { Class.forName(driver).newInstance(); Connection con = (Connection)DriverManager.getConnection(url,user,pass); String sql1 = "select Price from Produit where ProductName='"+value+"'"; PreparedStatement pst = con.prepareStatement(sql1); ResultSet rs = (ResultSet) pst.executeQuery(sql1); if(rs.next()) { jTextField3.setText(rs.getString(1)); } else { jTextField3.setText(""); } } catch( ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) { JOptionPane.showMessageDialog(null, e); }
doc_23531328
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); HANDLE hCom = CreateFile(com_name, GENERIC_READ | GENERIC_WRITE, NULL, NULL, OPEN_EXISTING, 0, NULL); /* check for errors opening the serial port, configure, set timeouts, etc */ HANDLE hWaitHandles[2]; hWaitHandles[0] = hStdin; hWaitHandles[1] = hCom; DWORD dwWaitResult = 0; for (;;) { dwWaitResult = WaitForMultipleObjects(2, hWaitHandles, FALSE, INFINITE); if(dwWaitResult == WAIT_OBJECT_0) { DWORD bytesWritten; int c = _getch(); WriteFile(hCom, &c, 1, &bytesWritten, NULL); FlushConsoleInputBuffer( hStdin); } else if (dwWaitResult == WAIT_OBJECT_0+1) { char byte; ReadFile(hCom, &byte, 1, &bytesRead, NULL); if (bytesRead) printf("%c",byte); } } Any ideas what I'm doing wrong here? A: If I remember correctly, you need to do serial port access using overlapped I/O for everything to work properly. This generally means that you need to create a separate thread to handle the serial port input. I don't remember why exactly, but using WaitForMultipleObjects has problems with serial ports. A: The docs for WaitForMultiplObjects says that the following are waitable: * Change notification * Console input * Event * Memory resource notification * Mutex * Process * Semaphore * Thread * Waitable timer Notice that files and comms ports are not mentioned.
doc_23531329
We have jobs that run for between a minute and many hours. Given that we assign them resource values that afford them QOS Guaranteed status, how could we minimize resource waste across the nodes? The problem is that downscaling rarely happens, because each node eventually gets assigned one of the long running jobs. They are not common, but the keep all of the nodes running, even when we do not have need for them. The dumb strategy that seems to avoid this would be a depth first scheduling algorithm, wherein among nodes that have capacity, the one most filled already will be assigned. In other words, if we have two total nodes running at 90% cpu/memory usage and 10% cpu/memory assigned, the 90% would always be assigned first provided it has sufficient capacity. Open to any input here and/or ideas. Thanks kindly. A: As of now there seems to be this kube-sheduler profile plugin: NodeResourcesMostAllocated: Favors nodes that have a high allocation of resources. But it is in alpha stage since k8s v1.18+, so probably not safe to use it for produciton. There is also this parameter you can set for kube-scheduler that I have found here: MostRequestedPriority: Favors nodes with most requested resources. This policy will fit the scheduled Pods onto the smallest number of Nodes needed to run your overall set of workloads. and here is an example on how to configure it. One last thing that comes to my mind is using node affinity. Using nodeAffinity on long running pods, (more specificaly with preferredDuringSchedulingIgnoredDuringExecution), will prefer to schedule these pods on the nodes that run all the time, and prefer to not schedule them on nodes that are being autoscaled. This approach requires excluding some nodes from autoscaling and labeling approprietly so that scheduler can make use of node-affinity.
doc_23531330
I want to use brave to trace the system by injecting Zipkin headers before sending messages and extracting Zipkin headers right after receiving messages. The problem is In step3 of the following scenario, how can I get span1 before sending message? Scenario: step1, app -> mq (new created span1, root span, client) step2, mq -> app (receive span1, server) step3, app -> mq (**new created span2, child span of span1, client**) step4, mq -> app (receive span2, server) Code snippet before sending message: try{ Span currentSpan = tracer.currentSpan(); Span newSpan = null; if(currentSpan == null){ newSpan = tracer.newTrace(); }else{ newSpan = tracer.newChild(currentSpan.context()); } Map<String, String> strHeaders = new HashMap<String, String>(); tracing.propagation().injector(Map<String, String>::put).inject(newSpan.context(),strHeaders); messageProperties.setHeader("zipkin.brave.tracing.headers", strHeaders); newSpan.name("send").kind(Kind.CLIENT).start().flush(); }catch(Exception e){ logger.warn("zipkin problem", e); } In the above code, Span currentSpan = tracer.currentSpan(); , the currentSpan is always null. Code snippet after receiving message: try{ Map<String, Object> msgHeaders = messageProperties.getHeaders(); Object headersObj = msgHeaders.get("zipkin.brave.tracing.headers"); Map<String, String> strHeaders = null; if(headersObj != null){ strHeaders = (HashMap<String, String>)headersObj; } TraceContextOrSamplingFlags result = tracing.propagation().extractor(Map<String, String>::get).extract(strHeaders); if(result.context() != null){ Span clientSpan = tracer.joinSpan(result.context()); clientSpan.name("receive").kind(Kind.SERVER).start().flush(); } }catch(Exception e){ logger.warn("zipkin problem", e); } Brave configuration code: @Configuration public class BraveSpringConfiguration { private static final Logger logger = LoggerFactory.getLogger(BraveSpringConfiguration.class); /** Configuration for how to send spans to Zipkin */ @Bean public Sender sender() { logger.debug("okhttpsender"); return OkHttpSender.create("http://127.0.0.1:9411/api/v1/spans"); } /** Configuration for how to buffer spans into messages for Zipkin */ @Bean public Reporter<Span> reporter() { logger.debug("asyncreporter"); return AsyncReporter.builder(sender()).build(); } /** Controls aspects of tracing such as the name that shows up in the UI */ @Bean public Tracing tracing() { logger.debug("one tracing"); return Tracing.newBuilder() .localServiceName("spring-rabbitmq-brave") //// log4j2, import brave.context.log4j2.ThreadContextCurrentTraceContext; //.currentTraceContext(ThreadContextCurrentTraceContext.create()) // puts trace IDs into logs .currentTraceContext(MDCCurrentTraceContext.create()) // puts trace IDs into logs .sampler(Sampler.ALWAYS_SAMPLE) // always sampler .reporter(reporter()) .build(); } /** Controls aspects of tracing such as the name that shows up in the UI */ @Bean public Tracer tracer() { logger.debug("one tracer"); return tracing().tracer(); } } Following are my references: * *https://github.com/openzipkin/brave/tree/master/brave#one-way-tracing *https://github.com/openzipkin/brave/blob/master/brave/src/test/java/brave/features/async/OneWaySpanTest.java *https://gist.github.com/adriancole/76d94054b77e3be338bd75424ca8ba30 A: Problem solved. tracer.withSpanInScope(clientSpan) would do the work. Note that, withSpanInScope(...) has not been called before sending messages .
doc_23531331
CREATE OR REPLACE FUNCTION public.buscarexamen(visit anyelement) RETURNS anyelement LANGUAGE plpgsql AS $function$ BEGIN return array(SELECT fn_folio_paciente(vi.clave_unilabor, vi.fecha, vi.consec) AS folio_paciente, vi.cve_visita, gp.nombre AS nombre_grupo, gp.cve_grupo, -- vp.cve_visita_prueba, p.cve_prueba, p.nombre AS nombre_prueba, me.nombre AS nombre_metodo, -- gcf.visible AS visible_grupo, cf.cve_grupo_campo_formato, gc.nombre_grupo_campo AS grupo_parametro, cf.nombre AS nombre_parametro, cf.orden, cf.tipo_dato, cf.solo_lectura AS tipo_titulo, cf.cve_seccion_padre, cf.tiene_elementos_seccion, cf.observacion AS observacion_parametro, -- pr.cve_prueba_resultado, pr.tipo_formato_prueba AS tipo_formato, pr.cantidad_resultado AS cantidad_parametro, pr.observaciones AS observacion_analista, pr.observaciones_prueba, CASE WHEN (TRIM(pr.observaciones) <> '') OR (TRIM(pr.observaciones_prueba) <> '') THEN 1 ELSE 0 END AS prueba_tiene_observacion, -- rc.cve_resultado_campo, rc.resultado, rc.observacion AS observacion_resultado, rc.signo, rc.decimales, cf.xleft as cursiva, vr.valor_referencia_min, vr.valor_referencia_max, un.nombre AS nombre_unidad, cf.tiene_valores_referencia FROM visitas vi JOIN corporativo.unilabor_unidades uu ON (vi.cve_unilabor_unidad = uu.cve_unilabor_unidad) JOIN visita_pruebas vp ON (vi.cve_visita = vp.cve_visita) JOIN prueba_resultados pr ON (vp.cve_visita_prueba = pr.cve_visita_prueba) JOIN prueba_metodo pm ON (pr.cve_prueba_metodo = pm.cve_prueba_metodo) JOIN metodos me ON (pm.cve_metodo = me.cve_metodo) JOIN pruebas p ON (pr.cve_prueba = p.cve_prueba) JOIN grupos gh ON (p.cve_grupo = gh.cve_grupo) JOIN grupos gp ON (gh.cve_grupo_padre = gp.cve_grupo) JOIN pacientes pa ON (vi.cve_paciente = pa.cve_paciente) JOIN contratos co ON (vi.cve_contrato = co.cve_contrato AND co.contrato_cerrado = 0) JOIN resultados_campos rc ON (pr.cve_prueba_resultado = rc.cve_prueba_resultado) JOIN unidades un ON (rc.cve_unidad = un.cve_unidad) LEFT JOIN valor_referencia_resultado vr ON (rc.cve_resultado_campo = vr.cve_resultado_campo) JOIN campos_formatos cf ON (rc.cve_campo_formato = cf.cve_campo_formato) JOIN grupos_campos_formato gcf ON (cf.cve_grupo_campo_formato = gcf.cve_grupo_campo_formato) JOIN grupos_campos gc ON (gcf.cve_grupo_campo = gc.cve_grupo_campo) WHERE vi.cve_visita = 696787 AND cf.solo_lectura = 0 ORDER BY p.orden_prueba, pr.cve_prueba_resultado, gcf.orden_grupo, rc.orden_local, vr.orden_valor); END; $function$ ; I try to use: select * from buscarexamen(123123); On SQL Script return this: SQL Error [42601]: ERROR: subquery must return only one column Where: PL/pgSQL function buscarexamen(anyelement) line 3 at RETURN Really I spend a lot of time finding solutions but until now isn't working. Any help is really apreciated. Regards. A: Your objective sounds like strange. However you should be able to achieve it by creating a composite type your_composite_type : CREATE TYPE your_composite_type AS ( folio_paciente folio_paciente_data_type , cve_visita cve_visita_data_type , nombre_grupo nombre_grupo_data_type , cve_grupo cve_grupo_data_type , cve_visita_prueba cve_visita_prueba_data_type , cve_prueba cve_prueba_data_type , nombre_prueba nombre_prueba_data_type , nombre_metodo nombre_metodo_data_type , visible_grupo visible_grupo_data_type , [...] , nombre_unidad nombre_unidad_data_type , tiene_valores_referencia tiene_valores_referencia_data_type ) ; Then the function public.buscarexamen() can return an array of data type your_composite_type : CREATE OR REPLACE FUNCTION public.buscarexamen(visit anyelement) RETURNS your_composite_type[] -- instead of anyarray LANGUAGE plpgsql AS $function$ BEGIN return array(SELECT row( fn_folio_paciente(...) , vi.cve_visita, gp.nombre, gp.cve_grupo , [...] , vr.valor_referencia_min, vr.valor_referencia_max, un.nombre , cf.tiene_valores_referencia ) :: your_composite_type FROM visitas vi JOIN [...] WHERE [...] ORDER BY p.orden_prueba, pr.cve_prueba_resultado, gcf.orden_grupo, rc.orden_local, vr.orden_valor) ) ; END; $function$ ;
doc_23531332
<script> function fillin(entire,name,id,key) { if (entire.checked == true) { var split_info = new Array(); split_info = name.split(":"); var div = $("#Inputfields"+id); var till = (div.children("input").length)/4; var current_count = 0; for (var j=0;j<till;j++) { if (document.getElementById("insertname_"+j+"_"+id).value == "" && document.getElementById("insertnumber_"+j+"_"+id).value == "") { document.getElementById("insertname_"+j+"_"+id).value = split_info[0]; document.getElementById("insertnumber_"+j+"_"+id).value = split_info[1]; break; } else current_count = current_count+1; if (current_count == till) { var x= addnew(id); x =x+1; $("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0]; alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value); document.getElementById("insertname_"+x+"_"+id).text = split_info[0]; //alert(document.getElementById("insertname_"+x+"_"+id).value); //document.getElementById("insertnumber_"+x+"_"+id).value = split_info[1]; } } } else { } } </script> <script> function addnew(n) { //var id = $(this).attr("id"); var div = $("#Inputfields"+n); var howManyInputs = (div.children("input").length)/4; alert(howManyInputs); var val = $("div").data("addedCount"); var a = '<input type="search" id="insertinstitute_'+(howManyInputs)+'_'+n+'" placeholder="Institute" class="span3">'; var b = '<input type="search" id="insertname_'+(howManyInputs)+'_'+n+'" placeholder="name" class="span3">'; var c = '<input type="search" name="" id="insertnumber_'+(howManyInputs)+'_'+n+'" placeholder="number" class="span3">'; var d = '<input type="search" name="" id="insertarea_'+(howManyInputs)+'_'+n+'" placeholder="area" class="span3">'; var fin = a+b+d+c; $(fin).appendTo(div); div.data("addedCount", div.data("addedCount") + 1); return howManyInputs; } </script> UPDATED: Thank you all. I was able to find the bug. The culprit was x =x+1;. It should have been x A: The problem is probably here: document.getElementById("insertname_"+x+"_"+id).text There's no text property in elements. There's textContent (not in IE8-), innerText (in IE) and innerHTML. There's the text method in jQuery, though. So you can either do: document.getElementById("insertname_"+x+"_"+id).innerHTML = ... or $("#insertname_"+x+"_"+id).text(...); Also, these lines: $("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0]; alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value); .value there should be replaced with .val(), because those are jQuery objects. A: I have reworked a lot of your code for a lot of reasons. Compare the two. function fillin(entire, name, id, key) { if (entire.checked) { var split_info = []; split_info = name.split(":"); var div = $("#Inputfields" + id); var till = (div.children("input").length) / 4; var current_count = 0; var j = 0; for (j = 0; j < till; j++) { var myj = j + "_" + id; if ($("#insertname_" + myj).val() === "" && $("#insertnumber_" + myj).val() === "") { $("#insertname_" + myj).val(split_info[0]); $("#insertnumber_" + myj).val(split_info[1]); break; } else { current_count = current_count + 1; } if (current_count === till) { var x = addnew(id) + 1; div.find("#insertname_" + x + "_" + id).val(split_info[0]); alert(div.find("#insertname_" + x + "_" + id).val()); $("#insertname_" + x + "_" + id).val(split_info[0]); } } } } function addnew(n) { var div = $("#Inputfields" + n); var howManyInputs = (div.children("input").length) / 4; alert(howManyInputs); var myi = (howManyInputs) + '_' + n + '"'; var val = div.data("addedCount"); var a = '<input type="search" id="insertinstitute_' + myi + ' placeholder="Institute" class="span3">'; var b = '<input type="search" id="insertname_' + myi + ' placeholder="name" class="span3">'; var c = '<input type="search" name="" id="insertnumber_' + myi + ' placeholder="number" class="span3">'; var d = '<input type="search" name="" id="insertarea_' + myi + ' placeholder="area" class="span3">'; var fin = a + b + d + c; $(fin).appendTo(div); div.data("addedCount", val + 1); return howManyInputs; }
doc_23531333
ssh -i ~/.ssh/company.pem -o StrictHostKeyChecking=no user@$hostname "supervisorctl start company-$app ; awk -v app=$app '$0 ~ "program:company-"app {p=NR} p && NR==p+6 && /^autostart/ {$0="autostart=true" ; p=0} 1' /etc/supervisord.conf > $$.tmp && sudo mv $$.tmp /etc/supervisord.conf” This is one of the last steps of a job which creates a CloudFormation stack. Running the command from the target server's terminal works properly. In this step, I'd like to ssh to each one of the servers (members of ASG's within the new stack) and search and replace a specific line as shown above in the /etc/supervisord.conf, basically setting one specific service to autostart. When I run the command I get the following error: Usage: awk [POSIX or GNU style options] -f progfile [--] file ... Usage: awk [POSIX or GNU style options] [--] 'program' file ... I've tried escaping the double quotes but got the same error, any idea what I'm doing wrong? A: You are running in to this issue due to the way the shell handles nested quotes. This is a use case for a HERE DOCUMENT or heredoc - A HERE DOCUMENT allows you to write multi-line commands passed through bash without worrying about quotes. The structure is as follows: $ ssh -t user@server.com <<'END' command |\ command2 |\ END <--- Oh yeah, the -t is important to the ssh command as it lets the shell know to behave as if being used interactively, and will avoid warnings and unexpected results. In your specific case, you should try something like: $ ssh -t -i ~/.ssh/company.pem -o StrictHostKeyChecking=no user@$hostname <<'END' supervisorctl start company-$app |\ awk -v app=$app '$0 ~ \"program:company-\"app {p=NR} p && NR==p+6 \ && /^autostart/ {$0="autostart=true" ; p=0} 1' \ /etc/supervisord.conf > $$.tmp && sudo mv $$.tmp /etc/supervisord.conf END Just a note, since I can't be sure about your desired output of the command you are running, be advised to keep track of your own " and ' marks, and to escape them accordingly in your awk command as you would at an interactive terminal. I notice the "'s around program:company and I am confused a bit by them If they are a part of the pattern in the string being searched they will need to be escaped accordingly. P.S.
doc_23531334
Currently when a user adds an item, it's added to the site through create.js.erb now I also add the ability to destroy the item. If they click on delete the method is deleted, however I'm not able to remove it from the site. The reason is that if I run $('item-13') f.ex in my console, it's not found in the DOM because it was added through AJAX. So the issue I'm having is that in my destroy.js.erb I have: $("#item-<%= @current_item %>").remove(); with my destroy action: def destroy @line_item = @cart.line_items.find(params[:id]) respond_to do |format| format.js { @current_item = @line_item.id } end end how can I make it so that I'm able to find the id I've attached to the div that displays the item when it's created? After I reload the page I'm able to delete the div based on AJAX. A: A jQuery select will look at the CURRENT dom, ie it will include objects that have been added with Ajax. I think the problem is that you have defined the block to handle the js request in the controller, in this line: format.js { @current_item = @line_item.id } This means that it won't go on to render destroy.js.erb - this is the default action if nothing else is defined. I would fix this by moving everything into destroy.js.erb: #controller def destroy @line_item = @cart.line_items.find(params[:id]) respond_to do |format| format.js end end #destroy.js.erb $("#item-<%= @line_item.id %>").remove();
doc_23531335
I understand what's a REST API but what I do not understand is how does the frontend gets served to the user? Do I need to have 2 Rails projects, one for the API, from which we get JSON data (like users etc) and one for the View Layer which will return an HTML with plenty of javascript ? And what if I create only a simple rails app (not API), which has controllers for the view-layer (to render html/javascript) and controllers for json data (which would be "API") ? Would that be a good practice or not? All I want to create is an app that: you visit a page, say /users/1, get the HTML content (which would be mostly referencing scripts and that's it) and another route responsible for json data from which we pull data, let's say /api/users/1.json (which would be a namespace route to match the api folder in controllers). A: What you want to do here is to use react-rails. It also allows server side rendering (no REST API). https://github.com/reactjs/react-rails Just run gem 'react-rails' , bundle install, and rails g react:install Then you just list components to your application.js file like below and can start using react components from automatically created folder at app/assets/javascripts/components/ //= require react //= require react_ujs //= require components
doc_23531336
CodeSandBox :- My React App Codesandbox App.js function Card({ item }) { return ( <div> <Col sm className="grid-view lrg-view" > <h5 style={{ textAlign: "center" }}>{item.name}</h5> <hr /> </Col> <br /> <br /> <br /> <br /> </div> ); } function App() { const [thirdGroup, setThirdGroup] = useState([ { name: "Box 1", id: "1" }, { name: "Box 2", id: "2" }, { name: "Box 3", id: "3" }, { name: "Box 4", id: "4" } ]); return ( <Container> <Row> <ReactSortable list={thirdGroup} setList={setThirdGroup} animation={250} > {thirdGroup.map((item) => ( <Card key={item.id} item={item} /> ))} </ReactSortable> </Row> </Container> ) I have also tried by putting Row inside ReactSortable then It is showing grid but not sorting. I am trying for hours and looked into many issues but it is still not working. What I am trying to do I am trying to put two boxes side by side in one row and then same for the second row. Like Grid Row in Bootstrap A: There are several problems in your snippet. * *The react-bootstrap Col component is required to be a direct child of the Row component for the grid layout to work. Since the direct child of the Row component in your snippet is the ReactSortable component, then it doesn't satisfy this requirement. *Your Card component should be the Col component instead of a div. This satisfies the requirement mentioned above. To resolve the problem, we need the ReactSortable component to act as a Row component, using the tag property. You may refer to this part of the documentation for more info. A working example on codesandbox: import "./styles.css"; import { ReactSortable } from "react-sortablejs"; import { useState } from "react"; import Container from "react-bootstrap/Container"; import Row from "react-bootstrap/Row"; import Col from "react-bootstrap/Col"; function Card({ item }) { let backgroundColor = "#dad9f3"; return ( <Col sm className="grid-view lrg-view" style={Object.assign({}, { backgroundColor })} > <h5 style={{ textAlign: "center" }}>{item.name}</h5> <hr /> </Col> ); } export default function App() { const [thirdGroup, setThirdGroup] = useState([ { name: "Box 1", id: "1" }, { name: "Box 2", id: "2" }, { name: "Box 3", id: "3" }, { name: "Box 4", id: "4" } ]); return ( <Container> <ReactSortable tag={Row} list={thirdGroup} setList={setThirdGroup} animation={250} > {thirdGroup.map((item) => ( <Card key={item.id} item={item} /> ))} </ReactSortable> </Container> ); }
doc_23531337
Model definition - hyperparameter_space = {"gru_up": 64, "up_dropout": 0.2, "learning_rate": 0.004} def many_to_one_model(params): input_1 = tf.keras.Input(shape = (1, 53), name = 'input_1') input_2 = tf.keras.Input(shape = (1, 19), name = 'input_2') input_3 = tf.keras.Input(shape = (1, 130), name = 'input_3') input_3_flatten = Flatten()(input_3) input_3_flatten = RepeatVector(1)(input_3_flatten) concat_outputs = Concatenate()([input_1, input_2, input_3_flatten]) output_1 = GRU(units = int(params['gru_up']), kernel_initializer = tf.keras.initializers.he_uniform(), activation = 'relu')(concat_outputs) output_1 = Dropout(rate = float(params['up_dropout']))(output_1) output_1 = Dense(units = 1, activation = 'linear', name = 'output_1')(output_1) model = tf.keras.models.Model(inputs = [input_1, input_2, input_3], outputs = [output_1], name = 'many_to_one_model') return model many_to_one_model(hyperparameter_space) Model summary - ''' Model: "many_to_one_model" ______________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ______________________________________________________________________________________________ input_3 (InputLayer) [(None, 1, 130)] 0 flatten_5 (Flatten) (None, 130) 0 input_3[0][0] input_1 (InputLayer) [(None, 1, 53)] 0 input_2 (InputLayer) [(None, 1, 19)] 0 repeat_vector_5 (RepeatVector) (None, 1, 130) 0 flatten_5[0][0] concatenate_5 (Concatenate) (None, 1, 202) 0 input_1[0][0] input_2[0][0] repeat_vector_5[0][0] gru_5 (GRU) (None, 64) 51456 concatenate_5[0][0] dropout_5 (Dropout) (None, 64) 0 gru_5[0][0] output_1 (Dense) (None, 1) 65 dropout_5[0][0] _____________________________________________________________________________________________ Total params: 51,521 Trainable params: 51,521 Non-trainable params: 0 ''' Adaptive loss implementation - import robust_loss.general import robust_loss.adaptive model = many_to_one_model(hyperparameter_space) adaptive_lossfun = robust_loss.adaptive.AdaptiveLossFunction(num_channels = 1, float_dtype = np.float32) variables = (list(model.trainable_variables) + list(adaptive_lossfun.trainable_variables)) optimizer_call = getattr(tf.keras.optimizers, "Adam") optimizer = optimizer_call(learning_rate = hyperparameter_space["learning_rate"], amsgrad = True) mlflow_callback = LambdaCallback() for epoch in range(750): def lossfun(): # Stealthily unsqueeze to an (n,1) matrix, and then compute the loss. # A matrix with this shape corresponds to a loss where there's one shape # and scale parameter per dimension (and there's only one dimension for # this data). aa = y_train_up - model([train_cat_ip, train_num_ip, ex_train_num_ip]) mean_calc = tf.reduce_mean(adaptive_lossfun(aa)) return mean_calc optimizer.minimize(lossfun, variables) loss = lossfun() alpha = adaptive_lossfun.alpha()[0, 0] scale = adaptive_lossfun.scale()[0, 0] print('{:<4}: loss={:+0.5f} alpha={:0.5f} scale={:0.5f}'.format(epoch, loss, alpha, scale)) mlflow_callback.on_batch_end(epoch, mlflow.log_metrics({"loss":loss.numpy(), "alpha":alpha.numpy(), "scale":scale.numpy()}, epoch)) Loss, alpha and scale vs epochs graph - loss against epochs Here is the github repo for robust adaptive loss: https://github.com/google-research/google-research/tree/5b4f2d4637b6adbddc5e3261647414e9bdc8010c/robust_loss
doc_23531338
Here's a list of what I already know or know how to find: * *The X and Y coordinates of the ball's center during the frame when a collision is detected *The X and Y components of the ball's velocity *The X and Y coordinates of the corner *The angle between the ball's center and the corner *The angle in which the ball is traveling just before the collision *The amount that the ball is overlapping the corner when the collision is detected I'm guessing that it's best to pretend that the corner is an infinitely small circle, so I can treat a collision between the ball and that circle as if the ball were colliding with a wall that runs tangent to the circles at the point of collision. It seems to me that all I need to do is rotate the coordinate system to line up with this imaginary wall, reverse the X component of the ball's velocity under this system, and rotate the coordinates back to the original system. The problem is that I have no idea how to program this. By the way, this is an ideal simulation. I'm not taking anything like friction or the ball's rotation into account. I'm using Objective-C, but I'd really just like a general algorithm or some advice. A: As you say you can treat the corner as a circle with infinitely small radius. The normal of the collision plane in this case is given by a unit vector from the contact point to the center of the ball: float nx = ballX - cornerX; float ny = ballY - cornerY; const float length = sqrt(nx * nx + ny * ny); nx /= length; ny /= length; to reflect the velocity vector you do this: const float projection = velocityX * nx + velocityY * ny; velocityX = velocityX - 2 * projection * nx; velocityY = velocityY - 2 * projection * ny; A: If it's a sharp (without any fillet) right-angled corner it will act as a retroreflector and bounce it back along the path it came in on.
doc_23531339
<%# IfEmpty(Eval("Link1URL"), "", "<a href="<%#Eval("Link1URL")%>" class="btn"> <%#Eval("Link1Title")%> </a>")) %> What I am trying to say here is, If the field Link1Url is empty, then display nothing. Otherwise, display an <a> tag with the Link1URL field as the href. This doesn't work as the inner macro: <a href="<%#Eval("Link1URL")%> messes things up for the outer IfEmpty macro. How can I fix this issue? A: I used .Net string.IsNullOrEmpty in the macro to help me next the logic: <%# !string.IsNullOrEmpty((string)Eval("Link2URL")) ? "<a href='" + Eval("Link2URL") + "'>" + Eval("Link2Title") + "</a>" : null %> A: For more advanced scenarios you could use asp:Placeholder Here's an example: <asp:Placeholder runat="server" visible='<%# !String.IsNullOrEmpty(Eval("Foo").ToString()) %>' > <div class="foo-structure"> ... </div> </asp:Placeholder> Conditional layout changes within transformations are discussed here. Spoiler All of those approaches are hacky.
doc_23531340
old xml file: <Root> <Chatter Name="Dat" ID="1"> <Content Time="06/05/2014 2:00:08 PM">Send Content</Content> <Content Time="06/05/2014 2:00:50 PM">Recieve Content</Content> </Chatter> <Chatter Name="Khang" ID="2"> <Content Time="06/05/2014 2:01:40 PM">Send Content</Content> <Content Time="06/05/2014 2:02:00 PM">Recieve Content</Content> </Chatter> <Chatter Name="Khanh" ID="12"> <Content Time="06/05/2014 2:03:10 PM">them moi</Content> </Chatter> </Root> i want to add a new element to node which has attribute Name="Khang" if it exist ,so here is new xml file <Root> <Chatter Name="Dat" ID="1"> <Content Time="06/05/2014 2:00:08 PM">Send Content</Content> <Content Time="06/05/2014 2:00:50 PM">Recieve Content</Content> </Chatter> <Chatter Name="Khang" ID="2"> <Content Time="06/05/2014 2:01:40 PM">Send Content</Content> <Content Time="06/05/2014 2:02:00 PM">Recieve Content</Content> <Content Time="06/05/2014 2:20:40 PM">Send Content</Content> </Chatter> <Chatter Name="Khanh" ID="12"> <Content Time="06/05/2014 2:03:10 PM">them moi</Content> </Chatter> </Root> Thank you very much! and my code public static bool SaveMessage(string name, string content) { XmlDocument xmldoc = new XmlDocument(); XmlNodeList xmlnode,xmlOldNode; xmldoc.Load(_fileXmlPath); xmlnode =xmlOldNode= xmldoc.GetElementsByTagName("Chatter"); for (int i = 0; i < xmlnode.Count;i++ ) { if (xmlnode[i].Attributes["Name"].Value == name) { XmlElement elem = xmldoc.CreateElement("Name", "Content", name); elem.SetAttribute("Time", DateTime.Now.ToString()); elem.InnerText = content; xmldoc.DocumentElement.AppendChild(elem); return true; } } return false; } but it not add to xml file A: As a rough example, the following should work for you; //First load the xml into a XDocument (can be a string or file for example) var doc = XDocument.Load(xml); //Then try and retrieve the Khang node XElement khang = (from xml2 in doc.Descendants("Chatter") where xml2.Attribute("Name").Value == "Khang" select xml2).FirstOrDefault(); //If the Khang node exists, create a new Element and add it to the Khang node if(khang != null) { XElement newNode = new XElement("Node"); khang.Add(newNode); } In detail: * *First load the xml into a XDocument var doc = XDocument.Load(xml); *Then try and retrieve the Khang node using Linq To Xml to select the Khang node XElement khang = (from xml2 in doc.Descendants("Chatter") where xml2.Attribute("Name").Value == "Khang" select xml2).FirstOrDefault(); *Create a new XElement and Add it to the Khang node (if it exists) if(khang != null) { XElement newNode = new XElement("Node"); khang.Add(newNode); }
doc_23531341
I am returning a user and would like to access it from within my controller. I tried the principal object but i can not reach to the companyId field of my ESecurityUser object. Any help would be appreciated.. @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { ESecurityUser user = new ESecurityUser(); user.setUsername("hello"); user.setPassword("world"); user.setCompanyId(199); Set<EAuthority> authorities = new HashSet<EAuthority>(); EAuthority authority = new EAuthority(); authority.setAuthority("ROLE_ADMIN"); authorities.add(authority); user.setAuthorities(authorities);; return user; } Sample Controller Code @RequestMapping("") public String toPeriodicAdReport(@ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper, Model model,Principal principal) { //What to write here so that i can access to authenticated user`s companyId field.. return "Test"; } A: You can use the annotation @AuthenticationPrincipal to directly access ESecurityUser. @RequestMapping("") public String toPeriodicAdReport(@ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper, Model model, @AuthenticationPrincipal ESecurityUser principal) { principal.getCompanyId(); return "Test"; } A: You were not far... The Principal that the SpringMVC machinery passed to a controller method is the Authentication token that identifies the user. You must use its getDetails() method to extract the ESecurityUser that you returned from your loadUserByUsername Your code could become: @RequestMapping("") public String toPeriodicAdReport(@ModelAttribute("advertFormHelper") AdvertFormHelper advertFormHelper, Model model,Principal principal) { ESecurityUser user = (ESecurityUser) ((Authentication) principal).getDetails(); // stuff... return "Test"; } A: ESecurityUser e = (ESecurityUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal(); This is working for me..
doc_23531342
Hi, I add my progress bar to my element "myID" and I can see it on the page so it works $("#myID").progressbar({ value: 99 }); Why wont this return true. the documentaion says it should as the progress bar is added to it var s = $('#myID').is( ":data( 'ui-progressbar' )" ); console.log(s); // returns false but should return true why A: I think the spaces are causing the problem var s = $('#myID').is(":data(ui-progressbar)"); Demo: Fiddle
doc_23531343
SELECT table1.*, table2.* FROM `Table1` AS table1, `Table2` AS table2, `Table3` WHERE table1.col1 = table2.col1 AND table1.col1 = Table3.col1 AND table1.col1 != '0' AND table1.col1 NOT IN (1,2) table1.col2 LIKE 'A' AND (table1.col3 LIKE 'A' OR table1.col3 LIKE 'B') AND Table3.col4 = 0 AND Table3.col5 = 0 AND Table3.col6 = 0 ORDER BY table1.col10 ASC LIMIT 0, 5 Without the ORDER BY statement, it executes in 0.002 seconds. With the ORDER BY statement, it executes in 2 seconds. I saw this answer which seemed to work for the OP, but when I tried it on mine I got a Duplicate column name 'col1' error. Any ideas on how I can speed this up with the ORDER BY ? EDIT: As requested, below is the modified Query that I tried based on the link above which gave me the Duplicate column name 'col1' error: SELECT * FROM ( SELECT table1.*, table2.* FROM `Table1` AS table1, `Table2` AS table2, `Table3` WHERE table1.col1 = table2.col1 AND table1.col1 = Table3.col1 AND table1.col1 != '0' AND table1.col1 NOT IN (1,2) table1.col2 LIKE 'A' AND (table1.col3 LIKE 'A' OR table1.col3 LIKE 'B') AND Table3.col4 = 0 AND Table3.col5 = 0 AND Table3.col6 = 0 ) AS t1 ORDER BY table1.col10 ASC LIMIT 0, 5 Apparently, this is supposed to ensure the ORDER BY is only done after the final result set is determined. A: Try adding an index on table1 and col10 . A: You can also explore to use temp table SELECT table1.*, table2.* INTO #temp FROM `Table1` AS table1, `Table2` AS table2, `Table3` WHERE table1.col1 = table2.col1 AND table1.col1 = Table3.col1 AND table1.col1 != '0' AND table1.col1 NOT IN (1,2) table1.col2 LIKE 'A' AND (table1.col3 LIKE 'A' OR table1.col3 LIKE 'B') AND Table3.col4 = 0 AND Table3.col5 = 0 AND Table3.col6 = 0 SELECT * FROM #temp ORDER BY col10 ASC LIMIT 0, 5
doc_23531344
PNG files are failed to load in my project, Some of the SlickGrid plugin uses url() function to load PNG files as given below, But I'm getting following error on my browser console, Here is my webpack file, /* eslint-env node */ module.exports = { context: __dirname + '/xyz/static', entry: { reactComponents: './bundle/components.js', history: './js/history/index.js', slickgrid: './bundle/slickgrid.js', }, output: { libraryTarget: 'amd', path: __dirname + '/xyz/static/js/generated', filename: '[name].js', }, module: { rules: [{ test: /\.jsx?$/, exclude: [/node_modules/, /vendor/], use: { loader: 'babel-loader', options: { presets: ['es2015', 'react'], }, }, }, { test: /\.css$/, use: ['style-loader', 'raw-loader'], }], }, resolve: { extensions: ['.js', '.jsx'], }, }; Please let me know what I'm missing here. A: You need to make use of a url-loader in your webpack config to load images like module: { rules: [{ test: /\.jsx?$/, exclude: [/node_modules/, /vendor/], use: { loader: 'babel-loader', options: { presets: ['es2015', 'react'], }, }, }, { test: /\.css$/, use: ['style-loader', 'raw-loader'], },{ test: /\.(jpe?g|png|gif|svg)$/, use:['url-loader'] }], } and then in your code you can import images like import img from 'path/to/image.png'; and use it as a source in the image tag like <img src={img} />
doc_23531345
// $tags = 'first, second, third'; How can i add a tag to this php code through a form. I want to enter a value in the form and then it will be added to the $tags then it has to redirect me to another page? A: On form action page $next_value = $_POST['fildvalue']; $tags .=','.$next_value; header('location:url') ; A: <?php $tags=array(); $tags[]="first"; $tags[]="second"; $tags[]="third"; array_push($tags,$_GET["tag"]); $nTags=implode(",",$tags); $nTags=urlencode($nTags); header("Location : http://example.com/?tags=$nTags"); ?>
doc_23531346
The game supposed to choose a number from the range 50-100. There are 2 people in the game. Player and computer take turns the numbers until one of them guesses correctly. Guess of each player supposed to be save as a hash where key is the guess number and the value is the number which user entered. For example User puts 56,53,67 and 67 is a match. so it suppose to looks like this : my %guesses = (1 => 56, 2 => 53, 3 => 67 ) I just started to learn Perl and I can not understand the hashes. Could you help me how to implement this part in code? (I think there is also a mistake in a loop, cause it's not working correctly? ) Here is my code: use warnings; use strict; sub loot{ $lower_limit = 50; $upper_limit = 100; my $random_number = int(rand($upper_limit-$lower_limit)) + $lower_limit; return $random_number; } my $number = loot; my $counter = 0; print $number; print "\n"; my $state = false; while( $state == true ){ ++$counter; print "Pick number: \n"; my $variable = <STDIN>; chomp($variable); if($variable == $number){ print "You have won"; print "\n"; $state = true; printf "You made : $counter guesses."; exit; } else{ print "--------- \n"; my $a = loot; print "Computer guess it: $a "; print "\n"; if($a == $number){ $state = true; print "Computer won"; print "\n"; printf "Computer made : $counter guesses."; exit; } } A: First, some feedback because you are just beginning to learn Perl. * *Give meaningful names to things. Instead of loot, the subroutine picking the random number should be something like rand_int_between. The lower and upper bounds should be parameters to the function, not hard-coded in the body of the function. sub rand_int_between { my ($lo, $hi) = @_; return int(rand($hi - $lo) + $lo); } *Don't call the state variable $state. Instead, use something like $keep_guessing so conditions read more naturally. The clarity of your code is a reflection on the clarity of your thinking. *There are no builtin values true and false in Perl. Therefore, I suspect you slapped the use strict just for show, and your real code does not have it. Don't do that. It is there to help you. *Don't use a variable name like $variable. Instead use something meaningful like $picked. *If you are mapping a strictly increasing sequence of integers with no gaps to data, the correct structure to use is an array not a hash. *Hashes have no inherent order. That means, if you want to list all the moves the player made in order, you will have to waste cycles sorting those keys, whereas if you had just kept the moves in an array, it would naturally be sorted in play order. *Regardless, there is no hash in your script. You do not save the moves at all. You also do not specify what purpose the hash serves. So, one has to imagine what you might want to do with it. With those points in mind, this is how one might write such a game: #!/usr/bin/env perl use strict; use warnings; use constant DEBUG => !!$ENV{DEBUG_GUESSING_GAME}; play( 50, 100 ); sub play { my ($lo, $hi) = @_; my $secret = rand_int_between($lo, $hi + 1); DEBUG and warn "Secret number is $secret\n"; my %human_moves; my $turn; while ( 1 ) { ++ $turn; my $picked = human_picks($lo, $hi); $human_moves{ $turn } = $picked; if ( $secret == $picked ) { printf "You won after %d guesses\n", $turn; last; } $picked = computer_picks($lo, $hi); if ( $secret == $picked ) { printf "The computer won after %d turns\n", $turn; last; } } print "Your guesses were:\n"; print "\t$human_moves{$_}\n" for sort { $a <=> $b } keys %human_moves; return; } sub computer_picks { return rand_int_between(@_); } sub human_picks { my ($lo, $hi) = @_; printf "Pick a number between %d and %d\n", $lo, $hi; my $input = <STDIN>; trim( $input ); return $input; } sub trim { $_[0] =~ s/^\s+//; $_[0] =~ s/\s+\z//; return; } sub rand_int_between { my ($lo, $hi) = @_; return int(rand($hi - $lo) + $lo); } The line $human_moves{ $turn } = $picked; associates the current value of $turn with the number the human player picked. sort { $a <=> $b } keys %human_moves sorts the keys of the %human_moves hash in numerical order, from the smallest to the largest (see perldoc -f sort). Thus, the loop print "\t$human_moves{$_}\n" for sort { $a <=> $b } keys %human_moves; prints each number guessed in move order. If you had saved the moves in an array, just print "\t$_\n" for @human_moves; would have sufficed.
doc_23531347
FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory Aborted (core dumped) var connection = mongoose.createConnection("mongodb://localhost/entity"); var entitySchema = new mongoose.Schema({ name: String , date: Date , close : Number , volume: Number , adjClose: Number }); var Entity = connection.model('entity', entitySchema) var mongoobjs =["2.2 Millions obejcts here populating in code"] // works completely fine till here async.map(mongoobjs, function(object, next){ Obj = new Entity({ name : object.name , date: object.date , close : object.close , volume: object.volume , adjClose: object.adjClose }); Obj.save(next); }, function(){console.log("Saved")}); A: Thanks cdbajorin This seem to be much better way and a little faster batch approach for for doing this. So what I learned was that in my earlier approach, "new Entity(....)" was taking time and causing memory overflow. Still not sure why. So, What I did was rather than using this line Obj = new Entity({ name : object.name , date: object.date , close : object.close , volume: object.volume , adjClose: object.adjClose }); I just created JSON objects and stored in an array. stockObj ={ name : object.name , date: object.date , close : object.close , volume: object.volume , adjClose: object.adjClose }; mongoobjs.push(stockObj); //array of objs. and used this command... and Voila It worked !!! Entity.collection.insert(mongoobjs, function(){ console.log("Saved succesfully")}); A: nodejs uses v8 which has the unfortunate property, from the perspective of developers coming from other interpreted languages, of severely restricting the amount of memory you can use to something like 1.7GB regardless of available system memory. There is really only one way, afaik, to get around this - use streams. Precisely how you do this is up to you. For example, you can simply stream data in continuously, process it as it's coming in, and let the processed objects get garbage collected. This has the downside of being difficult to balance input to output. The approach we've been favoring lately is to have an input stream bring work and save it to a queue (e.g. an array). In parallel you can write a function that is always trying to pull work off the queue. This makes it easy to separate logic and throttle the input stream in case work is coming in (or going out) too quickly. Say for example, to avoid memory issues, you want to stay below 50k objects in the queue. Then your stream-in function could pause the stream or skip the get() call if the output queue has > 50k entries. Similarly, you might want to batch writes to improve server efficiency. So your output processor could avoid writing unless there are at least 500 objects in the queue or if it's been over 1 second since the last write. This works because javascript uses an event loop which means that it will switch between asynchronous tasks automatically. Node will stream data in for some period of time then switch to another task. You can use setTimeout() or setInterval() to ensure that there is some delay between function calls, thereby allowing another asynchronous task to resume. Specifically addressing your problem, it looks like you are individually saving each object. This will take a long time for 2.2 million objects. Instead, there must be a way to batch writes. A: As an addition to answers provided in this thread, I was successful with * *Bulk Insert (or batch insertion of ) 20.000+ documents (or objects) *Using low memory (250 MB) available within cheap offerings of Heroku *Using one instance, without any parallel processing The Bulk operation as specified with MongoDB native driver was used, and the following is the code-ish that worked for me: var counter = 0; var entity= {}, entities = [];// Initialize Entities from a source such as a file, external database etc var bulk = Entity.collection.initializeOrderedBulkOp(); var size = MAX_ENTITIES; //or `entities.length` Defined in config, mine was 20.0000 //while and -- constructs is deemed faster than other loops available in JavaScript ecosystem while(size--){ entity = entities[size]; if( entity && entity.id){ // Add `{upsert:true}` parameter to create if object doesn't exist bulk.find({id: entity.id}).update({$set:{value:entity.value}}); } console.log('processing --- ', entity, size); } bulk.execute(function (error) { if(error) return next(error); return next(null, {message: 'Synced vector data'}); }); Entity is a mongoose model. Old versions of mongodb may not support Entity type as it was made available from version 3+. I hope this answer helps someone. Thanks.
doc_23531348
I am having a designer that is working with sketch. And designers love to work pixel perfect. So far so goot. So he is creating dozens of screen designs for each iphone / ipad with absolute positions/dimensions. This lead to the question, How should I implement this? I mean i can create one storyboard file for iPhone and another one for iPad. But i cannot create storyboards for each iPhone device. I mean even if I could it would be hell wouldn't it? Now I thought working with relative constraints would lead to the situation the he and me will have to work with 2 designs only (one for iPad one for iPhone), well then I found out the plugin "Fluid" for SketchApp which allows working like in XCode. Now he is wondering how to change his workflow, because he cant work pixel perfect with absolute positions. Whats your best practice to handle the designers workflow in sketch. Do you ask them to work with relative values? Do you convert the absolute px values by yourself? Did I miss something? A: I assume you're a developer? What exactly are you trying to implement this file into? The designer shouldn't be worrying about absolute positioning. The designer should simply know what your designing for and what assets you need output as deliverables. I use sketch it one of two ways... * *My file is always live on InVision where my developers can go in a view it in developer mode to get the full color palette, font listing, and some CSS-translated code for reference use during the development process. *I export sections of the design as SVG for use in things like XCode or Android Studio. So really the best practice depends on what your end goal is. It's very unclear from your OP however.
doc_23531349
public static function getImage ($imagePath) { if(Storage::exists($imagePath)) { return Storage::disk('s3')->get($imagePath); }else { return 'No Image'; } } I'm sure that those image is exist on the aws, so there is no problem with that. And then I use above method as the src in my blade view like this : {!!Html::image(getImage($myPath),'logo',['width'=>60,'height'=>55])!!} $myPath here already point to the specific file on aws for example : bucket/file.jgp. But when I run my webpage, this Html::Image gives a view like this : What's going on here ? Why Html::image can't render my image file ? :( A: Works on Laravel 6.x <img src="{{Storage::disk('s3')->url($imagePath)}}"> A: You can use Storage::url($imagePath). Please see Filesystem / Cloud storage on laravel docs A: {!!Html::image(<Your S3 bucket URL>.$myPath),'logo',['width'=>60,'height'=>55])!!} You can save the S3 URL in a config file and use the config value instead of writing actual value everytime. A: I had the same issue. This code snippet solved it <img src="{!! url(<path to your image>) !!}" /> A: First, you need to give it public promotion in the controller $path = Storage::disk('s3')->put('profileImages/', $request->file('profile_image'), 'public'); //save image name in database $user->profile_image = basename($path); In blade file <img src="{{Storage::disk('s3')->url('profileImages/' . $user->profile_image)}}" /> A: You can add an accessor like follow to get Image URL It returns URL to the image and you can access it by $profile->image public function getImageAttribute($value) { if ($value) { return Storage::disk('s3')->url($value); } return "https://source.unsplash.com/96x96/daily"; } I assume you save image as follow $path = $request->file('image')->store('images', 's3'); Storage::disk('s3')->setVisibility($path, 'public'); $profile->update([ 'image' => $path ]); You can check this commit for more detail https://github.com/itxshakil/ediary/commit/23cb4b1cb7b8a4eac68f534e8c5b6897abc6421a A: I have read every solution and no one has pointed it directly. So I thought to write my answers. For this problem I just required to add this simple line and boom, it starts working. But I got access denied alert you should check that problem too. <img class="img-responsive" src="{!! Storage::disk('s3')->url('thumbs/' . $business->image->path) !!}" alt="thumb"> A: This works Storage::disk('s3')->url($imagePath) and also from your Minio Browser. You have to Add a policy to Read and Write A: I think that private visibility of images is an important security feature. I found a solution :-) Method in Controller: /** * @param string $name : image name on bucket * ( stored if you want into database ) */ public function show( $name ) { $path = config('filesystems.disks.s3.base_directory') . '/' . $name; $type = pathinfo($path, PATHINFO_EXTENSION); $data = Storage::get( $path ); $base64 = 'data:image/' . $type . ';base64,' . base64_encode( $data ); return view( 'show', [ 'src' => $base64 ]); } The view: ... <div class="panel panel-primary"> <div class="panel-heading"><h2>Laravel File Retrive with Amazon S3 </h2></div> <div class="panel-body"> **<img src="{{ $src }}"/>** </div> </div> ...
doc_23531350
A: OSX supports modern GL only in core profile (which is the only profile required to be supported, by the GL specification). You have to explicitely request this when creating the context, otherwise it will fall back to a legacy context implementing GL 2.1 (for compatibility with old applications which do not know about profiles or moder GL versions at all). This means that on OSX, you never can mix old, deprecated GL featuers with modern features (as you could do with a compatibility profile). If this is a good or a bad thing depends on the point of view, though. For GLFW, you will have to use glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE) and request a GL version >= 3.2.
doc_23531351
<script language="JavaScript"> <!-- var txt_minute = "Min"; var txt_second = "s"; var time_left = 1111; var temp=timeleft; houres = Math.floor(temp / 3600); temp %= 3600; minutes = Math.floor(temp / 60)"; temp %= 60; seconds= temp; function display() { time_left -= 1; if (seconds <= 0) { seconds = 59; minutes -= 1; } else { seconds -= 1; } if (minutes <= 0){ minutes=59; houres-=1; } if (time_left <= 0) { seconds = 0; } if (time_left > 0) { document.getElementById("timeframe").innerHTML = houres +" hours" + minutes + " " + txt_minute + " " + seconds + " " + txt_second; } else { window.location.reload(); } setTimeout("display()",1000); } display(); //--> </script> A: There are some smaller mistakes: * *minutes = Math.floor(temp / 60)"; There is a trailing quotation mark that shouldn't be there. *var temp=timeleft; That should be time_left. *Also you should use setTimeout with a reference to the function instead of requiring it to parse the text as code: setTimeout(display,1000); edit: I wrote a small, clearer countdown script. function startCountdown ( timeLeft ) { var interval = setInterval( countdown, 1000 ); update(); function countdown () { if ( --timeLeft > 0 ) update(); else { clearInterval( interval ); update(); completed(); } } function update () { hours = Math.floor( timeLeft / 3600 ); minutes = Math.floor( ( timeLeft % 3600 ) / 60 ); seconds = timeLeft % 60; alert( '' + hours + ':' + minutes + ':' + seconds ); } function completed () { alert( 'completed' ); } } startCountdown( 1234 ); Just alter the update and completed function to your needs and start the countdown with your desired value. And btw. if you want to change some innerHTML of an element in your code, you should save the reference somewhere, instead of getting it via DOM every call. A: minutes = Math.floor(temp / 60)"; ? A: All the typos that have been mentioned above and one logic flaw .. If the code is in the head section of the html then the first time you call the display() the timeframe element has not been created yet.. instead of display(); use window.onload=display; to run it for the first time, after the dom has loaded.. here is a fixed working version of your code.. http://jsbin.com/orege/edit A: One thing that jumps out at me is that your calculation at the top (starting with var temp...) should be inside the display function (which probably wants a new name). Where it is, it's only done once. (I'm also not convinced that the actual calcuation is correct. In fact, the code overall is not really ideal, you might not want to get more code from wherever you got this. But I'm not going to rewrite it for this answer.) See also n00b32's answer, there seems to be a syntax error near the top. Also (OT): You can change your setTimeout to: setTimeout(display, 1000). No need for the quotes and parens. A: As an additional improvement (but first get the basic version working by reading everyone else's comments), I like to replace this line setTimeout(display, 1000); with this: var next = 1010 - (new Date()).getTime() % 1000; setTimeout(display, next); The first version will never run exactly every second (due to other processes running and other inaccuracies in setTimeout). This can make your display jump 2 seconds at once when one call of display() happens at the end of second n and the next call only happens at the beginning of n+2. The second version looks at the current time (down to the millisecond), and tries to schedule the next call of display() just after the start of each second, which results in a much smoother display.
doc_23531352
Installing linecache19 (0.5.11) with native extensions Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension. /home/raza/.rvm/rubies/ruby-1.9.3-p362/bin/ruby extconf.rb checking for vm_core.h... no /home/raza/.rvm/gems/ruby-1.9.3-p362@holla/gems/ruby_core_source-0.1.4/lib/ruby_core_source.rb:39: Use RbConfig instead of obsolete and deprecated Config. checking for vm_core.h... yes checking for version.h... yes checking for RUBY_VERSION_MAJOR in version.h... no Requesting http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p362.tar.gz Downloading http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p362.tar.gz checking for vm_core.h... yes checking for version.h... yes checking for RUBY_VERSION_MAJOR in version.h... no Makefile creation failed ************************************************************* NOTE: For Ruby 1.9 installation instructions, please see: http://wiki.github.com/mark-moseley/ruby-debug ************************************************************* *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/home/raza/.rvm/rubies/ruby-1.9.3-p362/bin/ruby --with-ruby-dir --without-ruby-dir --with-ruby-include --without-ruby-include=${ruby-dir}/include --with-ruby-lib --without-ruby-lib=${ruby-dir}/lib Gem files will remain installed in /home/raza/.rvm/gems/ruby-1.9.3-p362@holla/gems/linecache19-0.5.11 for inspection. Results logged to /home/raza/.rvm/gems/ruby-1.9.3-p362@holla/gems/linecache19-0.5.11/ext/trace_nums/gem_make.out An error occurred while installing linecache19 (0.5.11), and Bundler cannot continue. Make sure that `gem install linecache19 -v '0.5.11'` succeeds before bundling. I then tried running gem install linecache19 -v '0.5.11' as well as gem install linecache19 -v '0.5.11' -- --with-ruby-include=$rvm_path/src/ruby-1.9.3-p362 but still facing same problem. My mkmf.log located at ~/.rvm/gems/ruby-1.9.3-p362@holla/gems/linecache19-0.5.11/ext/trace_nums is as follows : have_header: checking for vm_core.h... -------------------- no "gcc -o conftest -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/x86_64-linux -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby/backward -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1 -I. -I/home/raza/.rvm/usr/include -O3 -ggdb -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wimplicit-function-declaration -fPIC conftest.c -L. -L/home/raza/.rvm/rubies/ruby-1.9.3-p362/lib -Wl,-R/home/raza/.rvm/rubies/ruby-1.9.3-p362/lib -L/home/raza/.rvm/usr/lib -Wl,-R/home/raza/.rvm/usr/lib -L. -rdynamic -Wl,-export-dynamic -L/home/raza/.rvm/usr/lib -Wl,-R/home/raza/.rvm/usr/lib -Wl,-R -Wl,/home/raza/.rvm/rubies/ruby-1.9.3-p362/lib -L/home/raza/.rvm/rubies/ruby-1.9.3-p362/lib -lruby -lpthread -lrt -ldl -lcrypt -lm -lc" checked program was: /* begin */ 1: #include "ruby.h" 2: 3: int main() {return 0;} /* end */ "gcc -E -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/x86_64-linux -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby/backward -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1 -I. -I/home/raza/.rvm/usr/include -O3 -ggdb -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wimplicit-function-declaration -fPIC conftest.c -o conftest.i" conftest.c:3:21: fatal error: vm_core.h: No such file or directory compilation terminated. checked program was: /* begin */ 1: #include "ruby.h" 2: 3: #include <vm_core.h> /* end */ -------------------- have_header: checking for vm_core.h... -------------------- yes "gcc -E -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/x86_64-linux -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby/backward -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1 -I. -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby-1.9.3-p362 -O3 -ggdb -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wimplicit-function-declaration -fPIC conftest.c -o conftest.i" checked program was: /* begin */ 1: #include "ruby.h" 2: 3: #include <vm_core.h> /* end */ -------------------- have_header: checking for version.h... -------------------- yes "gcc -E -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/x86_64-linux -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby/backward -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1 -I. -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby-1.9.3-p362 -O3 -ggdb -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wimplicit-function-declaration -fPIC conftest.c -o conftest.i" checked program was: /* begin */ 1: #include "ruby.h" 2: 3: #include <version.h> /* end */ -------------------- have_macro: checking for RUBY_VERSION_MAJOR in version.h... -------------------- no "gcc -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/x86_64-linux -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby/backward -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1 -I. -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby-1.9.3-p362 -O3 -ggdb -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wimplicit-function-declaration -fPIC -c conftest.c" conftest.c:6:3: error: #error conftest.c:7:1: error: expected identifier or ‘(’ before ‘>>’ token checked program was: /* begin */ 1: #include "ruby.h" 2: 3: #include <version.h> 4: /*top*/ 5: #ifndef RUBY_VERSION_MAJOR 6: # error 7: >>>>>> RUBY_VERSION_MAJOR undefined <<<<<< 8: #endif /* end */ -------------------- have_header: checking for vm_core.h... -------------------- yes "gcc -E -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/x86_64-linux -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby/backward -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1 -I. -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby-1.9.3-p362 -O3 -ggdb -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wimplicit-function-declaration -fPIC conftest.c -o conftest.i" checked program was: /* begin */ 1: #include "ruby.h" 2: 3: #include <vm_core.h> /* end */ -------------------- have_header: checking for version.h... -------------------- yes "gcc -E -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/x86_64-linux -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby/backward -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1 -I. -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby-1.9.3-p362 -O3 -ggdb -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wimplicit-function-declaration -fPIC conftest.c -o conftest.i" checked program was: /* begin */ 1: #include "ruby.h" 2: 3: #include <version.h> /* end */ -------------------- have_macro: checking for RUBY_VERSION_MAJOR in version.h... -------------------- no "gcc -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/x86_64-linux -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby/backward -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1 -I. -I/home/raza/.rvm/rubies/ruby-1.9.3-p362/include/ruby-1.9.1/ruby-1.9.3-p362 -O3 -ggdb -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wimplicit-function-declaration -fPIC -c conftest.c" conftest.c:6:3: error: #error conftest.c:7:1: error: expected identifier or ‘(’ before ‘>>’ token checked program was: /* begin */ 1: #include "ruby.h" 2: 3: #include <version.h> 4: /*top*/ 5: #ifndef RUBY_VERSION_MAJOR 6: # error 7: >>>>>> RUBY_VERSION_MAJOR undefined <<<<<< 8: #endif /* end */ -------------------- Im on a machine running Ubuntu 12.10. How can i fix this problem ? Thank You A: You need to install ruby-debug first passing the include directory. gem install ruby-debug19 -- --with-ruby-include=$rvm_path/src/ruby-1.9.3-p362
doc_23531353
Here's two pictures to explain what is exactly the problem... If anyone could explain what's going on and what to do to solve this issue would be respected. Here's my class which contains printpreviewcontrol code: Private mRow As Integer = 0 Private newpage As Boolean = True Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage Try Dim font36 = New Font("Playball", 36, FontStyle.Regular) Dim font8 = New Font("Lora", 8, FontStyle.Regular) Dim font20 = New Font("Lora", 20, FontStyle.Underline) Dim font16 = New Font("Lora", 16, FontStyle.Regular) e.Graphics.DrawString("Riviera Beach Chalets", font36, Brushes.Black, New Rectangle(150, 25, 800, 100)) e.Graphics.DrawString("Accounting Reports", font20, Brushes.Black, New Rectangle(650, 45, 300, 50)) e.Graphics.FillRectangle(Brushes.MistyRose, New Rectangle(101, 741, 19, 19)) e.Graphics.DrawString("Accommondation Revenue or Beach Revenue or CoffeeShop Revenue is 0", font8, Brushes.Black, New Rectangle(125, 745, 500, 30)) e.Graphics.DrawString("Amount Received Total :", font16, Brushes.Black, New Rectangle(570, 735, 500, 50)) e.Graphics.DrawString(Report_Database.reporttot, font16, Brushes.Black, New Rectangle(850, 735, 500, 50)) ' sets it to show '...' for long text Dim fmt As StringFormat = New StringFormat(StringFormatFlags.LineLimit) fmt.LineAlignment = StringAlignment.Center fmt.Trimming = StringTrimming.EllipsisCharacter Dim y As Int32 = e.MarginBounds.Top Dim rc As Rectangle Dim x As Int32 Dim h As Int32 = 0 Dim row As DataGridViewRow ' print the header text for a new page ' use a grey bg just like the control If newpage Then row = Report_Database.DataGridView1.Rows(mRow) x = 50 For Each cell As DataGridViewCell In row.Cells ' since we are printing the control's view, ' skip invidible columns If cell.Visible Then rc = New Rectangle(x, y, cell.Size.Width, cell.Size.Height) e.Graphics.FillRectangle(Brushes.LightGray, rc) e.Graphics.DrawRectangle(Pens.Black, rc) ' reused in the data pront - should be a function Select Case Report_Database.DataGridView1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment Case DataGridViewContentAlignment.BottomRight, DataGridViewContentAlignment.MiddleRight fmt.Alignment = StringAlignment.Far rc.Offset(-1, 0) Case DataGridViewContentAlignment.BottomCenter, DataGridViewContentAlignment.MiddleCenter fmt.Alignment = StringAlignment.Center Case Else fmt.Alignment = StringAlignment.Near rc.Offset(2, 0) End Select e.Graphics.DrawString(Report_Database.DataGridView1.Columns(cell.ColumnIndex).HeaderText, Report_Database.DataGridView1.Font, Brushes.Black, rc, fmt) x += rc.Width h = Math.Max(h, rc.Height) End If Next y += h End If newpage = False ' now print the data for each row Dim thisNDX As Int32 For thisNDX = mRow To Report_Database.DataGridView1.RowCount - 1 ' no need to try to print the new row If Report_Database.DataGridView1.Rows(thisNDX).IsNewRow Then Exit For row = Report_Database.DataGridView1.Rows(thisNDX) h = 0 ' reset X for data x = 50 ' print the data For Each cell As DataGridViewCell In row.Cells If cell.Visible Then rc = New Rectangle(x, y, cell.Size.Width, cell.Size.Height) ' SAMPLE CODE: How To ' up a RowPrePaint rule If Val(row.Cells(2).Value) = 0 Or Val(row.Cells(3).Value) = 0 Or Val(row.Cells(4).Value) = 0 Then Using br As New SolidBrush(Color.MistyRose) e.Graphics.FillRectangle(br, rc) End Using End If e.Graphics.DrawRectangle(Pens.Black, rc) Select Case Report_Database.DataGridView1.Columns(cell.ColumnIndex).DefaultCellStyle.Alignment Case DataGridViewContentAlignment.BottomRight, DataGridViewContentAlignment.MiddleRight fmt.Alignment = StringAlignment.Far rc.Offset(-1, 0) Case DataGridViewContentAlignment.BottomCenter, DataGridViewContentAlignment.MiddleCenter fmt.Alignment = StringAlignment.Center Case Else fmt.Alignment = StringAlignment.Near rc.Offset(2, 0) End Select e.Graphics.DrawString(cell.FormattedValue.ToString(), Report_Database.DataGridView1.Font, Brushes.Black, rc, fmt) x += rc.Width h = Math.Max(h, rc.Height) End If Next y += h ' next row to print mRow = thisNDX + 1 If y + h > e.MarginBounds.Bottom Then e.HasMorePages = True ' mRow -= 1 causes last row to rePrint on next page newpage = True Button1.Enabled = True Button4.Enabled = True If mRow = Report_Database.DataGridView1.RowCount Then e.HasMorePages = False Exit Sub End If Return End If Next Catch ex As Exception MsgBox(ex.ToString, MsgBoxStyle.Critical) End Try
doc_23531354
"You may not use reference operators (such as unions, intersections, and ranges) or array constants for Data Validation criteria" My formula is =INDIRECT("IQ!"&LEFT($T28, 2)&"11"):INDIRECT("IQ!"&LEFT($T28, 2)&11+$V28) I had to do the formula like this, as the business users cannot update the formula themselves. I have a dropdown list in another sheet within Excel, which this refers to. A: I'm curious why Excel doesn't accept the current format of Indirect range.. However, one workaround could be to create a named range: And then refer to the named range (test1) in your data validation list:
doc_23531355
Here's the code: @interface PEXViewController () @property (strong, nonatomic) IBOutlet UIView *redSquare; @property (strong, nonatomic) IBOutlet UIView *greenSquare; @property (strong, nonatomic) IBOutlet UIView *yellowSquareBlueSquare; @end @implementation PEXViewController #define TILT_AMOUNT 0.65 -(void)tiltView:(UIView *)slave{ CATransform3D rotateX = CATransform3DIdentity; rotateX.m34 = -1 / 500.0; rotateX = CATransform3DRotate(rotateX, TILT_AMOUNT * M_PI_2, 1, 0, 0); slave.layer.transform = rotateX; } - (void)viewDidLoad { [super viewDidLoad]; [self tiltView:self.greenSquare]; [self tiltView:self.redSquare]; [self tiltView:self.yellowSquareBlueSquare]; } @end 1) Is there a simple way to apply a transform(s) to the separate red/green UIViews and achieve the same effect as the "grouped" yellow and blue UIViews? I prefer to keep the views separate, as this is a universal app and the UIViews are not side-by-side in (e.g.) the iPad layout. 2) If #1 is not possible, I am guessing the best thing to do is simply create a parent view that is present in say iPhone, but not present in iPad. Any other alternatives? A: I opted for solution #2. I created a short routine that calculates a bounding box based on an array of UIViews, creates a new parent view from the bounding box, then adds the arrayed views as children. I then can apply the transform to the parent view for the desired effect. Here's the code for gathering and adopting children subviews. -(UIView *)makeParentWithSubviews:(NSArray *)arrayOfViews{ // Creating a bounding box UIView and add the passed UIViews as subview // "in-place". CGFloat xMax = -HUGE_VALF; CGFloat xMin = HUGE_VALF; CGFloat yMax = -HUGE_VALF; CGFloat yMin = HUGE_VALF; for (UIView *myView in arrayOfViews) { xMin = MIN(xMin, myView.frame.origin.x); xMax = MAX(xMax, myView.frame.origin.x + myView.frame.size.width); yMin = MIN(yMin, myView.frame.origin.y); yMax = MAX(yMax, myView.frame.origin.y + myView.frame.size.height); } CGFloat parentWidth = xMax - xMin; CGFloat parentHeight = yMax - yMin; CGRect parentFrame = CGRectMake(xMin, yMin, parentWidth, parentHeight); UIView *parentView = [[UIView alloc] initWithFrame:parentFrame]; // Replace each child's frame for (UIView *myView in arrayOfViews){ myView.frame = [[myView superview] convertRect:myView.frame toView:parentView]; [myView removeFromSuperview]; [parentView addSubview:myView]; } parentView.backgroundColor = [UIColor clearColor]; [self.view addSubview:parentView]; return parentView; }
doc_23531356
declare rec p_schema_table; BEGIN .... How to use function parameter p_schema_table as composite_type_name e.g. rec public.customer. I tested create function, but error return ERROR: type "p_schema_table" does not exist Why plpgsql language don't understand p_schema_table is passing function parameter, It's should treat to table name e.g public.customer A: You can't declare variable, which type is passed as parameter. In such case you should declare it using RECORD type.
doc_23531357
Here is a sample of what we are doing: jsFiddle. Note that is does not have the export buttons enabled - see item 3 below. We are allowing the user to export the chart. Testing this we have found 2 issues (and a third just came up while trying to make a jsFiddle for this post): 1) Upon changing the range via the rangeSelector buttons it renders corectly but upon export the "highlighted" range selection is the one in that is the default selection when the chart initially loads. Solved this by removing the rangeSelector from the export. Which is not really an ideal solution but it hides the bug. Here is how we did it: exporting: { chartOptions: { rangeSelector: { enabled: false } }, buttons: { enabled: false }, filename: 'UnempRate', width: 590 } 2) When changing what the series is that is visible we also set the navigator series to it and update the chart title (which we have at the bottom of the graph). When a user exports the data the main graph has the correct series listed but the navigator goes back to the original "loaded" series and so does the chart title. 3) When trying to create a jsFiddle of this I get errors on the events: legendItemClick that the chartTrend is not defined only if I set the export buttons to be enabled: navigation: { buttonOptions: { enabled: false } } So I am not sure how to let you guys see the issue here. Basically we want the navigator series and the chart title to match what the user has selected via the legendItemClick when they choose to export the chart. A: these issues are the result of how the exporting module works. Basically it creates a completely new chart in a hidden element. This new chart always uses SVG renderer (so browsers without SVG support, like old IE or Androids 2.x generates code that it can't display). Then Highcharts get generated SVG code and sends it to the exportin server. However, this new chart is created from options, so almost everything you changed in a runtime is gone. If you don't have to support Androids 2.x or IE<9, you can call chart.getSVG and send POST request directly to the exporting server. Here is the sample request payload: ------WebKitFormBoundaryiBhRpBiiTfKjcspB Content-Disposition: form-data; name="filename" UnempRate ------WebKitFormBoundaryiBhRpBiiTfKjcspB Content-Disposition: form-data; name="type" image/png ------WebKitFormBoundaryiBhRpBiiTfKjcspB Content-Disposition: form-data; name="width" 590 ------WebKitFormBoundaryiBhRpBiiTfKjcspB Content-Disposition: form-data; name="scale" 2 ------WebKitFormBoundaryiBhRpBiiTfKjcspB Content-Disposition: form-data; name="svg" <svg xmlns:xlink="http://www.w3.org/1999/xlink" ...and so on to the end of SVG code ------WebKitFormBoundaryiBhRpBiiTfKjcspB-- But if you have to support as many browsers as possible, you should store informations like navigator series, active range selector button, etc. and pass them as a second parameter in exportChart method: http://api.highcharts.com/highcharts#Chart.exportChart()
doc_23531358
Log.e("size of:"," size listStudent(listview)--"+number); for (int i=0;i<number;i++) { View view = listStudent.getChildAt(i); if(view !=null){ Log.e("size of:","counter"+i); studentIdTxt = (TextView) view.findViewById(R.id.student_id_ls); obtainedTxt = (EditText) view.findViewById(R.id.obtained); maxTxt = (TextView) view.findViewById(R.id.max); student = studentIdTxt.getText().toString().trim(); obtained_value = obtainedTxt.getText().toString().trim(); max_value = maxTxt.getText().toString().trim(); //updating the new mark list array HashMap<String,String>studentMark=new HashMap<String,String>(); studentMark.put(TAG_STUDENT_ID,student); studentMark.put(TAG_MARKS_OBTAINED,obtained_value); studentMark.put(TAG_MARKS_MAX, max_value); studentMarksList.add(studentMark); } } //start of calling the JSON transmitter JSONTransmitter transmitter=new JSONTransmitter(); //set the url String url=domain+"/app/caller.php"; //transform studentMarksList to json String studentList=gson.toJson(studentMarksList); transmitter.setUrl(url); Everything works fine, it's only that I can't get those item visible when you scroll. "number" is equal to 29 but the counter only iterates up to 4. Any help please! A: listStudent.getChildAt(i); A child view can only be retrieved from listview if it is visible on the screen. Use a setOnFocusChangeListener for each EditText in the adapter (I assume you're using a custom adapter). When the user is done putting data, retrieve the text and update the list accordingly. This is a tutorial if you need one.
doc_23531359
array 0 => array 'cid' => string '18427' (length=5) 1 => array 'cid' => string '17004' (length=5) 2 => array 'cid' => string '19331' (length=5) I want to join the values so I can get a string like this: 18427,17004,19331 I tried the implode PHP function, But I get an error: A PHP Error was encountered How can join only the values which are in cid? A: You have to map the array values first: echo join(',', array_map(function($item) { return $item['cid']; }, $arr)); Without closures it would look like this: function get_cid($item) { return $item['cid']; } echo join(',', array_map('get_cid', $arr)); See also: array_map() A: You can loop through each element $result = ''; foreach($array as $sub_array){ $result .= $sub_array['cid'] . ','; } $result = substr($result, -2); A: // set a new variable for their the value of cid $cid = array(); // then loop to call them one by one. foreach($css as $style){ foreach($style as $row){ array_push($cid,$row); } } // then the new $cid array would contain the values of your cid array $cid = array('1','2','3'); note:then you can now implode or watever you want to get the data set you want..
doc_23531360
mapView.cameraMovementMode = .followGpsPositionWithAutozoom I didn't know if there is an other setting that I should follow the user position after starting the navigation A: It should work the way you are using it. Did you try move camera somewhere out of your position and then call mapView.cameraMovementMode = .followGpsPositionWithAutozoom? It should set camera to your position and following your gps. * *Are you initializing SYMapView after SDK is initialized? *Do you call SYPositioning.shared().startUpdatingPosition() after SDK is initialized? So SDK will start updating your location You can register your class to SYPositioningDelegate and implement -(void)positioning:(nonnull SYPositioning*)positioning didUpdatePosition:(nonnull SYPosition*)position; method, so you can print your position.
doc_23531361
<input type="checkbox" id="cb"+{{data.id}} /> <label for="cb"+{{data.id}}> <img class="card-image" [src]="imgUrl"/> </label> The data is a component object that has string id property: @Input() data: Constructor; But I get this error: ERROR DOMException: Failed to execute 'setAttribute' on 'Element': '+{{data.id}}' is not a valid attribute name.** My question is how can I concatenate string in the template with property object defined in the component? A: Alternative to the solution in the other question, you could also do the following * *The interpolation must be inside the quotes. *The plus symbol isn't required. <input type="checkbox" id="cb{{data.id}}" /> <label for="cb{{data.id}}"> <img class="card-image" [src]="imgUrl"/> </label> Working example: Stackblitz A: Use property binding <input type="checkbox" [id]="'cb' + data.id" /> <label [for]="'cb'+ data.id"> <img class="card-image" [src]="imgUrl"/> </label> Working example: StackBlitz A: Did you try something like that. <input type="checkbox" id="{{'cb' + data.id}}" /> <label for="{{'cb' + data.id}}"> <img class="card-image" [src]="imgUrl"/> </label> I have added at the label some '' maybe it will help A: You set dynamic id like below for your checkbox <input type="checkbox" [id]="'cb'+name">
doc_23531362
<div id='green'> <div id="orange"></div> </div> #green{ border: 20px solid #3D3; } #orange{ width :100px; height: 100px; border: 10px solid orange; float: left; } A: and if you don't want to float your outer div to left you can set it to display:table this will make the outer div wrap around the inner one. A: Try adding float:left and display:block to the outer div see updated example - http://jsfiddle.net/jordanlewis/gDtSZ/1/ A: <div id='green'> <div id="orange"></div> <div style="clear:both"></div> </div> A: Elements do not expand to contain floated children by default. There are a number of workarounds, such as floating the parent, using a clearfix or adding overflow: hidden to the parent. Personally, I try and use the latter. Here is your jsFiddle working. A: The green box is not a floated element. You need to either clear your float after the nested div or float both. A: you could just add display:inline-block to the orange box.
doc_23531363
I have been tearing my hair out trying to figure out how to to stop a Kendo UI dropdown from sorting alphabetically ? <select id="ddlArtworkStatuses" onlyPreparedValues="true" readOnlyInput="true" data-bind="idNameOptions: artworkStatuses, comboboxSelectedValue: artworkStatusId"></select> For some reason this sorts althabetically but I want it to keep the order in the datasource. I have double checked to make sure it is in the order I want. It doesn't use the standard way of using Kendo UI and I can't find any examples anywhere of using it this way? It binds the view to the model with this line at the top of the view I believe? <!-- ko with: fabricationModel --> The vm.fabrication file is this: (function (app) { app.namespace("models"); var resources = { unableToDeleteArtworkMessage: "This artwork cannot be deleted because it is linked to one or more of the following: Movements, Shows, POs. Or it has Imported Costs, Sales or Restoration Cases.", unableToBlankArtworkFullyMessage: "This artwork has some data that will not be blanked if you continue. This could be one or more of the following: Movements, Shows, POs, Imported Costs, Sales or Restoration Cases. Do you want to continue?", deleteArtworkTitle: "Delete artwork", blankArtworkTitle: "Blank Artwork", duplicateTitle: "New artwork form is pre-populated", duplicateMessage: "You can make changes to Fabrication form fields. Record will be created after you press save button", saveError: 'An error occured during artwork saving. Changes were not saved.' }; app.models.FabricationModel = function (datasource) { var emitter = new app.events.EventEmitter(), self = this, duplicateArtwork = ko.observable(false); this.isNewArtwork = ko.observable(false); this.isActivated = ko.observable(false); this.showCreationInformation = ko.observable(true); this.wipeArtworkModel = new app.models.WipeArtworkDialogModel(datasource); this.internalArtworkModel = ko.observable(); this.editCategoryModel = new app.models.EditDhCategoryModel(); // alert("data=" + this.artworkStatuses); this.isReadOnly = ko.computed(function () { if (!self.internalArtworkModel()) { return true; } return self.internalArtworkModel().isReadOnly(); }); this.canSaveStudioStatusOnly = ko.computed(function () { if (!self.internalArtworkModel()) { return false; } return self.internalArtworkModel().isUnblockStatusActive() && self.internalArtworkModel().isReadOnly() && self.internalArtworkModel().isStudioStatusVisible(); }); this.canSaveCatRaisOnly = ko.computed(function () { if (!self.internalArtworkModel()) { return false; } return self.internalArtworkModel().isReadOnly() && self.internalArtworkModel().isArchiveProvenanceWriter(); }); this.isNewOrDuplicating = ko.computed(function () { return self.isNewArtwork() || duplicateArtwork(); }); this.activate = function (params) { var id = params.id || 0; self.isNewArtwork(!id); return self.loadArtworkDetails(id); }; this.isValid = function () { return self.internalArtworkModel() && self.internalArtworkModel().errors().length == 0; }; this.loadArtworkDetails = function (id) { var action = self.isNewArtwork() ? datasource.artworks.getEmpty : datasource.artworks.getById; return action(id) .done(function (result) { var mapper = app.mappers["fabrication"], model = mapper.map(result.data); self.internalArtworkModel(model); self.editCategoryModel.categoryId(model.defaultDhCategoryId); self.editCategoryModel.setModeAsCategoryChanging(); if (self.isNewArtwork()) { self.editCategoryModel.setModeAsCreation(); self.editCategoryModel.show(); } self.isActivated(true); duplicateArtwork(false); $("a#science-link").attr("href", window.location.href); triggerLoadEvent(); }); }; this.saveArtwork = function () { if (self.isValid()) { return saveInternal($.noop); } }; this.editCategory = function () { self.editCategoryModel.show(); }; this.onLoad = function (callback) { emitter.subscribe("load", callback); }; this.onCategoryChanged = function (callback) { emitter.subscribe("category-changed", callback); }; this.onDelete = function (callback) { emitter.subscribe("delete", callback); }; this.onCreated = function (callback) { emitter.subscribe("artwork-created", callback); }; this.onUpdated = function (callback) { emitter.subscribe("artwork-updated", callback); }; this.onBlanked = function (callback) { emitter.subscribe("blanked", callback); }; this.saveStudioStatusInt = function () { return saveStudioStatusInternal($.noop); }; this.saveCatRaisInt = function () { return saveCatRaisInternal($.noop); }; this.saveStudioStatus = ko.asyncCommand({ execute: function (complete) { saveStudioStatusInternal(complete); }, canExecute: function (isExecuting) { return !isExecuting && self.canSaveStudioStatusOnly(); } }); this.saveCatRais = ko.asyncCommand({ execute: function (complete) { saveCatRaisInternal(complete); }, canExecute: function (isExecuting) { return !isExecuting && self.canSaveCatRaisOnly(); } }); this.save = ko.asyncCommand({ execute: function (complete) { return saveInternal(complete); }, canExecute: function (isExecuting) { if (!self.isValid()) { showErrors(); } return !isExecuting && self.isValid(); } }); function saveStudioStatusInternal(completeCallback) { var model = self.internalArtworkModel(); triggerSaveStudioStatusEvent(); datasource.artworks.saveStudioStatus(model.artworkId(), model.artworkStatusId(), model.studioStatusId).always(completeCallback); } function saveCatRaisInternal(completeCallback) { var model = self.internalArtworkModel(); triggerSaveStudioStatusEvent(); datasource.artworks.saveCatRais(model.artworkId(), model.inclusion(), model.image(), model.details(), model.crReady(), model.selectedVolume.selected.value).always(completeCallback); } this.onSaveStudioStatus = function (callback) { emitter.subscribe("saveStudioStatus", callback); }; function triggerSaveStudioStatusEvent() { emitter.publish("saveStudioStatus"); } this.beginArtworkDeletion = function () { if (!self.internalArtworkModel().canBeBlanked) { jAlert(resources.unableToDeleteArtworkMessage, resources.deleteArtworkTitle); return; } self.wipeArtworkModel.beginArtworkDeletion(self.internalArtworkModel().artworkId()); }; this.beginArtworkBlanking = function () { if (!self.internalArtworkModel().canBeBlanked) { //jAlert(resources.unableToBlankArtworkMessage, resources.blankArtworkTitle); app.alerts.appConfirm(resources.unableToBlankArtworkFullyMessage, resources.blankArtworkTitle, function (ok) { if (ok) { self.wipeArtworkModel.beginArtworkBlanking(self.internalArtworkModel().artworkId()); } }); return; } self.wipeArtworkModel.beginArtworkBlanking(self.internalArtworkModel().artworkId()); }; this.duplicateArtwork = function () { if (!self.internalArtworkModel()) { return; } duplicateArtwork(true); resetModelBeforeDuplication(); if (self.isValid()) { showErrors(); } jAlert(resources.duplicateMessage, resources.duplicateTitle); }; function saveInternal(completeCallback) { var mapper = app.mappers["fabrication"]; //alert("saving now..."); var unmappedModel = mapper.toJS(self.internalArtworkModel()); if (duplicateArtwork()) { return saveDuplicatedArtwork(unmappedModel, completeCallback); } if (unmappedModel.artworkId) { return updateArtwork(unmappedModel, completeCallback); } return createArtwork(unmappedModel, completeCallback); } function saveDuplicatedArtwork(model, completeCallback) { return datasource.artworks.duplicate(model) .always(completeCallback) .fail(function (response) { jAlert(resources.saveError); }) .done(function (id) { triggerArtworkCreatedEvent(id); duplicateArtwork(false); self.showCreationInformation(true); }); } function updateArtwork(model, completeCallback) { return datasource.artworks.save(model) .always(completeCallback) .fail(function (response) { jAlert(resources.saveError); }) .done(function (result) { if (!result) { return; } var mapper = app.mappers["fabrication"], mappedModel = mapper.map(result.data); triggerUpdateEvent( { dhCategory: mappedModel.dhCategory(), refNumber: mappedModel.refNumber(), computedTitle: mappedModel.computedTitle() }); self.internalArtworkModel(mappedModel); }); } function createArtwork(model, completeCallback) { return datasource.artworks.save(model) .always(completeCallback) .fail(function (response) { jAlert(resources.saveError); }) .done(function (id) { if (id) { triggerArtworkCreatedEvent(id); } }); } function triggerLoadEvent() { var model = self.internalArtworkModel(); emitter.publish("load", { artworkId: model.artworkId() || 0, dhCategory: model.dhCategory() || "", refNumber: model.refNumber() || "", computedTitle: model.computedTitle() || "", isForSale: model.isForSale }); } function triggerArtworkCreatedEvent(artworkId) { emitter.publish("artwork-created", artworkId); } function triggerCategoryChangedEvent() { emitter.publish("category-changed", { name: self.internalArtworkModel().dhCategoryName(), id: self.internalArtworkModel().dhCategoryId() }); } function triggerDeleteEvent(e, artworkId) { emitter.publish("delete", artworkId); } function triggerUpdateEvent(data) { var model = self.internalArtworkModel(); data.isCategoryChanged = model.initialCategoryId !== model.dhCategoryId(); emitter.publish("artwork-updated", data); } function showErrors() { var model = self.internalArtworkModel(); if (model) { model.errors.showAllMessages(); } } function resetModelBeforeDuplication() { var model = self.internalArtworkModel(); model.refNumber(""); model.computedTitle(""); model.isOnDisplay(false); model.isOnRestoration(false); model.salesStatus("Not set"); model.creationDate(""); model.creatorName(""); model.isFramed(false); model.framedDate(""); model.framedUserName(""); model.framedUserInitials(""); model.framedUserId(null); model.locations(null); model.isInsuranceComponent(false); model.dateWebsiteWork(""); model.dateWebsiteReady(""); model.dateWebsiteUploaded(""); model.dateRemovedFromWebsite(""); model.collectionListing(""); model.salesStatusChangedDate(""); model.salesStatusChangerUserInitials(""); model.salesStatusChangerUserName(""); self.showCreationInformation(false); } function triggerBlanked(artworkId) { emitter.publish("blanked", { artworkId: artworkId, flag: true }); } (function () { self.editCategoryModel.onChanged(function (e, categoryId) { self.internalArtworkModel().dhCategoryId(categoryId); triggerCategoryChangedEvent(); }); self.editCategoryModel.onCancel(function () { if (self.isNewArtwork()) { self.isNewArtwork(false); app.router.back(); } }); self.wipeArtworkModel.onDelete(triggerDeleteEvent); self.wipeArtworkModel.onBlank(function (e, artworkId) { self.loadArtworkDetails(artworkId); triggerBlanked(artworkId); }); })(); }; })(app); It also uses a mapper: (function (app, ko) { app.namespace("mappers"); var s = app.urls.shared, datasource = app.datasource; var mapSettings = { selectedMedium: { create: function (options) { return new ListModel({ isRemoteSource: true, url: s.get('dictionaryUrl'), listType: datasource.dictionaryTypes.get("medium"), currentValue: options.data, nobutton: true, templateName: "textAreaTemplate" }); } }, artist: { create: function (options) { return new ListModel({ isRemoteSource: true, url: s.get('dictionaryUrl'), listType: datasource.dictionaryTypes.get("artist"), currentValue: options.data, onlyPreparedValues: false }); } }, manager: { create: function (options) { return new ListModel({ isRemoteSource: true, url: s.get('dictionaryUrl'), listType: datasource.dictionaryTypes.get("manager"), currentValue: options.data, onlyPreparedValues: false }); } }, managerStatus: { create: function (options) { return new ListModel({ isRemoteSource: true, url: s.get('dictionaryUrl'), listType: datasource.dictionaryTypes.get("managerStatus"), currentValue: options.data, onlyPreparedValues: false }); } }, selectedVolume: { create: function (options) { return new ListModel({ isRemoteSource: true, url: s.get('dictionaryUrl'), listType: datasource.dictionaryTypes.get("volume"), currentValue: options.data, onlyPreparedValues: false, readonly: !options.parent.isArchiveProvenanceWriter(), editable: options.parent.isArchiveProvenanceWriter() }); } }, salesStatus: { create: function (options) { var value = options.data || "Not set"; return ko.observable(value); } }, oldReferences: { create: function (options) { return ko.observable(options.data); } }, copy: ['defaultDhCategoryId', "canBeDeleted", "canBeBlanked", "isForSale"], ignore: ["dimensions", "dimensionUnits", "selectedMediumTypes", "selectedSeries", "selectedSubSeries", "selectedAkaNames", "selectedWebSiteMediumTypes", 'selectedWebSiteCategoryIds', "locations", "hasInTransitLocations"] }, unmapSettings = { ignore: ["selectedMedium", "artist", "manager", "managerStatus", "mediumTypesModel", "dimensionModel", "seriesModel", "subSeriesModel", "akaModel", "webSiteMediumTypesModel", "webSiteCategoriesModel", "selectedVolume"] }, map = function (json) { var convertedObject = ko.utils.parseJson(json); var model = ko.mapping.fromJS(convertedObject, mapSettings); model.artworkStatusesModel = new ListModel({ isRemoteSource: false, currentValue: convertedObject.selectedArtworkStatus, data: convertedObject.artworkStatuses, //data: filteredSalesStatuses, onlyPreparedValues: true, allowNull: false, readonly: true }); alert("mooo=" + model.artworkStatuses()[0].name()); alert("mooo=" + model.artworkStatuses()[1].name()); alert("mooo=" + model.artworkStatuses()[2].name()); //alert("mooo=" + model.artworkStatuses()[3].name()); //alert("mooo=" + model.artworkStatuses()[4].name()); model.dhCategoryName = ko.computed(function () { var categories = model.dhCategories(); for (var i = 0; i < categories.length; i++) { var category = categories[i]; if (category.id() == model.dhCategoryId()) { return category.name(); } } return ""; }); model.initialCategoryId = convertedObject.dhCategoryId; model.dimensionModel = new app.models.DimensionModel(convertedObject.dimensions); ko.utils.arrayForEach(convertedObject.dimensionUnits, function (unit) { model.dimensionModel.units.push(unit); }); model.locations = ko.observable(convertedObject.locations ? { archivedLocations: $.map(convertedObject.locations, function (elem) { return elem.isArchived ? elem : null; }), activeLocations: $.map(convertedObject.locations, function (elem) { return elem.isArchived ? null : elem; }), hasInTransitLocations: convertedObject.hasInTransitLocations } : convertedObject.locations); model.mediumTypesModel = new app.models.MultilistModel(convertedObject.selectedMediumTypes, { url: s.get("mediumTypesUrl") }); model.seriesModel = new app.models.MultilistModel(convertedObject.selectedSeries, { url: s.get("seriesUrl") }); model.subSeriesModel = new app.models.MultilistModel(convertedObject.selectedSubSeries, { url: s.get("subSeriesUrl") }); model.akaModel = new app.models.MultilistModel(convertedObject.selectedAkaNames, { url: s.get("akaUrl") }); model.webSiteMediumTypesModel = new app.models.MultilistModel(convertedObject.selectedWebSiteMediumTypes, { url: s.get("webSiteMediumTypeUrl") }); model.webSiteCategoriesModel = new app.models.MultilistModel(convertedObject.selectedWebSiteCategories, { url: s.get("webSiteCategoryUrl") }); model.isStudioStatusVisible = ko.computed(function () { var foundStatuses = ko.utils.arrayFilter(model.artworkStatuses(), function (status) { return status.id() == model.artworkStatusId(); }); var currentStatus = foundStatuses[0]; if (currentStatus) { return currentStatus.name().toLowerCase() == "in progress"; } return false; }); addValidationOptions(model); return model; }, toJS = function (artwork) { var result = ko.mapping.toJS(artwork, unmapSettings); result.artist = artwork.artist.toJS(); result.manager = artwork.manager.toJS(); result.managerStatus = artwork.managerStatus.toJS(); result.selectedMedium = artwork.selectedMedium.toJS(); result.selectedVolume = artwork.selectedVolume.toJS(); result.dimensions = artwork.dimensionModel.toJS(); result.selectedMediumTypes = artwork.mediumTypesModel.toJS(); result.selectedSeries = artwork.seriesModel.toJS(); result.selectedSubSeries = artwork.subSeriesModel.toJS(); result.selectedAkaNames = artwork.akaModel.toJS(); result.selectedWebSiteMediumTypes = artwork.webSiteMediumTypesModel.toJS(); result.selectedWebSiteCategories = artwork.webSiteCategoriesModel.toJS(); return result; }; function isValidationRequired(model) { var artworkStatus = ko.utils.unwrapObservable(model.artworkStatusId); var dhCategory = ko.utils.unwrapObservable(model.dhCategoryId); return artworkStatus == app.global.dictionary.get("compiteArtworkStatus") && dhCategory != app.global.dictionary.get("ignoreDHCatigory"); } function addValidationOptions(model) { model.artworkStatusId.extend({ required: true }); model.title.extend({ required: true }); model.artist.selected.value.extend({ required: true }); model.startYear.extend({ lessEqualThan: { params: model.endYear, onlyIf: function () { return (model.endYear() != undefined && model.endYear() != null); }, message: 'From Date should be less or equal than a To Date' } }); model.endYear.extend({ required: { params: true, onlyIf: function () { return isValidationRequired(model); }, message: "To Date field is required" } }); model.selectedMedium.selected.value.extend({ required: { params: true, onlyIf: function () { return isValidationRequired(model); }, message: "Medium is required" } }); model.mediumTypesModel.hasValue.extend({ equal: { params: true, onlyIf: function () { return isValidationRequired(model); }, message: "Medium Type is required" } }); model.akaModel.hasValue.extend({ equal: { params: true, onlyIf: function () { return isValidationRequired(model); }, message: "Aka is required" } }); model.isInsuranceComponent.extend({ equal: { params: true, onlyIf: function () { return isValidationRequired(model); }, message: "At least 1 Insurance component should be chosen" } }); model.dimensionModel.hasDimensions.extend({ equal: { params: true, onlyIf: function () { return isValidationRequired(model); }, message: "The Dimension fields should be filled" } }); model.errors = ko.validation.group(model, { deep: true }); } app.mappers.fabrication = { settings: mapSettings, map: map, toJS: toJS }; })(app, ko); Where I have the alerts, the items are in the right order, so somewhere they are getting sorted but cant find out where?! I hope someone can help? It would be really appreciated. Many thanks, David.
doc_23531364
When window.cordova.plugins.activity.getExtras is called, I get the error TypeError: Cannot read property 'activity' of undefined". How to fix it? The following code is my plugin configuration: activity.js cordova.define("com.zlzkj.cordova.activity.activity", function(require, exports, module) { var exec = require('cordova/exec'); function Activity() { }; Activity.prototype={ start : function(activityClassName,jsonData,successCallback) { exec(successCallback, errorCallback, "ActivityPlugin", "start", [activityClassName,jsonData]); }, getExtras : function(successCallback) { exec(successCallback, errorCallback, "ActivityPlugin", "getExtras", []); } }; var errorCallback = function(message) { alert("Error:" + message); }; module.exports = new Activity(); }); config.xml <feature name="ActivityPlugin"> <param name="android-package" value="com.zlzkj.cordova.ActivityPlugin" /> </feature> cordova_plugins.js module.exports = [ { "file": "plugins/cordova-plugin-whitelist/whitelist.js", "id": "cordova-plugin-whitelist.whitelist", "runs": true }, { "file": "plugins/com.zlzkj.cordova.activity/www/activity.js", "id": "com.zlzkj.cordova.activity.activity", "clobbers": [ "cordova.plugins.activity" ] } ]; The window.cordova.plugins.activity.getExtras and window.cordova.plugins.activity.start are called as follows: .controller('AppCtrl', function($scope, $ionicModal, $ionicPopover, $timeout, $location) { // Form data for the login modal var loginData = $scope.loginData = { userName:"", privName:"", funcIdStr:"" }; //'window.cordova.plugins.activity.getExtras' make error messages window.cordova.plugins.activity.getExtras(function(data){ loginData.userName=date.userName; loginData.privName=data.privName; loginData.funcIdStr=data.funcIdStr; $scope.$apply(); }); } .controller('HomeCtrl', function($scope, $stateParams) { var activityDate = $scope.activityDate = { flag:false, name:"" } $scope.goActivity = function(){ var sendData = { id:10001, name:"Simon", age:28 }; //'window.cordova.plugins.activity.start' is called correctly window.cordova.plugins.activity.start("com.haiwei.ar_oaapp.activity.AdditionActivity",sendData,function(data){ $scope.activityDate.flag=true; activityDate.name=data.name; $scope.$apply(); }); } }) Part of the code in app.js .run(function($ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); } if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } }); } A: Cordova will fire the event. You should listen to the event. No Plugin will be available before the event was fired.
doc_23531365
public static List<FichierCTAF> getXmlFCtaf(string pathXml) { var doc = XDocument.Load(pathXml); ... } But it throws me the exception " Root element is missing" when calling the load method. Help please A: Every xml file has to have a Root Element, in your case it seems your xml doesn't have any. See this for more info: Do you always have to have a root node with xml/xsd?
doc_23531366
I have the following code, and now I want to display all items (circles) always (depends on screen size) in one row, but the last item should be always in place (on desktop, tablet, mobile). <body ng-controller="MainCtrl"> <button class="btn-select-user" ng-repeat="item in items | limitTo: limit as result"> <span> <img ng-class="{}" ng-src="https://graph.facebook.com/4/picture?height=46&amp;type=square&amp;width=46" width="40" height="40" src="https://graph.facebook.com/4/picture?height=46&amp;type=square&amp;width=46"> </span> </button> <span class="badge pull-right" ng-click="limit = items.length" ng-hide="limit == items.length">Show all</span> </body> Any suggestions? A: You can do this with a custom directive. Working plunker: http://plnkr.co/edit/4m3xU5JQqL4R5YPrYIdC?p=preview <span ng-repeat="item in items | limitTo:numDisplay"> <span class="huge" ng-class="{'last':$last}">{{item}}</span> </span> You'll need to add this directive to the body tag: <body resizable> The directive: app.directive("resizable", ["$window", function($window){ return function($scope) { $scope.initializeWindowSize = function() { //do the screen width check if($window.innerWidth < 641) $scope.numDisplay = 3; else if($window.innerWidth > 640 && $window.innerWidth < 800) $scope.numDisplay = 5; else $scope.numDisplay = 10; //check console see if it's correct console.log($window.innerWidth, $scope.numDisplay); //return the inner width return $scope.windowWidth = $window.innerWidth; }; $scope.initializeWindowSize(); return angular.element($window).bind('resize', function() { $scope.initializeWindowSize(); return $scope.$apply(); //run digest }); }; }]) A: You could add new parent div for buttons with fixed height and overflow so they are hidden until div is bigger or resized. Something like this: .buttons { width: calc(100% - 40px); height: 40px; overflow: hidden; float: left; } Here is example of it http://plnkr.co/edit/LGYdQszYtxtMXB7fxpDs?p=preview Then on click of that last circle you just remove fixed height. A: Right now you're outputting 10 circles + 1 circle that is a solid color on the end. For usability sake, I would stick to a fixed number of circles and change the dimensions of those circles depending on the screen size.
doc_23531367
I don't want to manually filter a huge result set. A: At the time of my answer (Facebook Graph API v2.8) there seems to be no way of filtering by from.id.
doc_23531368
I wonder if there is any source code for this. A: There is a way to check this since API level 21 and it has recently changed in API level 26. These are the correct backwards compatible ways to do this. Java: public static boolean packageIsGame(Context context, String packageName) { try { ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, 0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { return info.category == ApplicationInfo.CATEGORY_GAME; } else { // We are suppressing deprecation since there are no other options in this API Level //noinspection deprecation return (info.flags & ApplicationInfo.FLAG_IS_GAME) == ApplicationInfo.FLAG_IS_GAME; } } catch (PackageManager.NameNotFoundException e) { Log.e("Util", "Package info not found for name: " + packageName, e); // Or throw an exception if you want return false; } } Kotlin: fun packageIsGame(context: Context, packageName: String): Boolean { return try { val info: ApplicationInfo = context.packageManager.getApplicationInfo(packageName, 0) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { info.category == ApplicationInfo.CATEGORY_GAME } else { // We are suppressing deprecation since there are no other options in this API Level @Suppress("DEPRECATION") (info.flags and ApplicationInfo.FLAG_IS_GAME) == ApplicationInfo.FLAG_IS_GAME } } catch (e: PackageManager.NameNotFoundException) { Log.e("Util", "Package info not found for name: " + packageName, e) // Or throw an exception if you want false } } Source: Android Documentation
doc_23531369
For that I am using ExecutorService for multi-threading to check status of each and every url. Code of class which check response code for url is given below public class ConnectionTester implements Callable<Object> { private URL url; private Map<String,Integer> map; private static final Log LOGGER = LogFactoryUtil.getLog(ConnectionTester.class); public ConnectionTester(String url,Map<String,Integer> map) { try { this.url = new URL(url); this.map = map; } catch (MalformedURLException e) { LOGGER.error(e.getMessage(), e); } } /** * Get status code of url * @return */ public void getStatuscode(URL url) { HttpURLConnection http = null; try { http = (HttpURLConnection)url.openConnection(); http.setConnectTimeout(0); http.setReadTimeout(0); http.setRequestMethod("HEAD"); http.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); http.connect(); map.put(url.toString(), http.getResponseCode()); } catch (IOException e) { map.put(url.toString(), 500 ); }finally{ if(http !=null)http.disconnect(); } } @Override public Object call() throws Exception { getStatuscode(url); return null; } } And I use following code to check response code for each and every url ExecutorService service = Executors.newFixedThreadPool(urls.size()); List<ConnectionTester> connectionTesters = new ArrayList<ConnectionTester>(urls.size()); Map<String,Integer> map = new HashMap<String, Integer>(); for (String string : urls) { if(Validator.isNotNull(string) && !string.contains("mailto")) connectionTesters.add(new ConnectionTester(string, map)); } service.invokeAll(connectionTesters); Now problem is when I don't use multi-threading I get proper response code of each and every URL but when I use multi-threading I am getting connection timeout exception. So far I have checked and tried below things. * *My internet speed is high *I have set http.setConnectTimeout(0); http.setReadTimeout(0); to set infinite time out. *Response time of url I am checking is also less and working fine. What am I missing here ? A: You are overloading the server. When a Unix/Linux TCP server's listen(2) backlog queue fills, it starts ignoring incoming connect requests, which causes connect timeouts at the clients. Solution: don't. Cut the number of threads, and when a thread gets a connect timeout, don't create any more.
doc_23531370
What I want is, before running the Tests, it checks the configuration file where there is an option to have separeLogFile=true/false. If the option is true, the Test should generate separate log file for each Test, and if the option is false it will generate just one log file for all five Tests. I am using logback.xml and SL4J logger for logging. Currently it generates just one log file for all Tests. I am confused how do I programmatically specify which/where should the log file generated depending on the option ? Is there any way I can specify two file names and locations and make logback.xml choose from them depending on the option in configuration file? I have used logback.xml for the first time. Currently my logback.xml looks like following: <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n </pattern> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>INFO</level> </filter> </encoder> </appender> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- Daily rollover --> <fileNamePattern>target/logs/Log_Test_%d{yyyy-MM-dd}.log </fileNamePattern> <!-- Keep 7 days' worth of history --> <maxHistory>7</maxHistory> </rollingPolicy> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n </pattern> </encoder> </appender> <!-- Configure so that it outputs to both console and log file --> <root level="INFO"> <appender-ref ref="FILE"/> <appender-ref ref="STDOUT"/> </root> A: You could use Logback's SiftingAppender to direct logs to specific log files. Here's an example: <?xml version="1.0" encoding="UTF-8"?> <configuration debug="true"> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern> %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n </Pattern> </layout> </appender> <appender name="SIFTER" class="ch.qos.logback.classic.sift.SiftingAppender"> <discriminator> <key>testName</key> <defaultValue>ALL</defaultValue> </discriminator> <sift> <appender name="FILE-${testName}" class="ch.qos.logback.core.FileAppender"> <file>target/logs/Log_Test_${testName}.log</file> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n </pattern> </encoder> </appender> </sift> </appender> <root level="INFO"> <appender-ref ref="STDOUT"/> <appender-ref ref="SIFTER"/> </root> </configuration> With this Logback configuration the following code ... String[] testNames = new String[] { "one", "two"}; for (String testName : testNames) { MDC.put("testName", testName); logger.info("This message should go into the log file for {}", testName); } ... will cause two log files to be populated: ~/dev/code/stackoverflow/target/logs$ cat Log_Test_one.log 09:04:19.922 [main] INFO SomeClassTest - This message should go into the log file for one ~/dev/code/stackoverflow/target/logs$ cat Log_Test_two.log 09:04:19.938 [main] INFO SomeClassTest - This message should go into the log file for two And the following code ... String[] testNames = new String[] { "one", "two"}; for (String testName : testNames) { logger.info("This message should go into the log file for {}", testName); } ... will cause one log file to be populated: ~/dev/code/stackoverflow/target/logs$ cat Log_Test_ALL.log 09:06:54.009 [main] INFO SomeClassTest - This message should go into the log file for one 09:06:54.022 [main] INFO SomeClassTest - This message should go into the log file for two So, if you populate the testName MDC attribute before invoking logger.xxx() then the log events wil be sifted i.e. directed to a log file which is named for that MDC value. If you do not populate the testName MDC attribute then all log events will be directed to an 'ALL' log file. Update 1 in response to this comment: well I replcaed whole block of my original File Appender with the one you provided, but it is not producing log file at all..Something is going wrong. It's difficult to diagnose what's going wrong without seeing all of your configuration so I have updated this answer to include a complete logback.xml and this configuration has debug enabled so you should see output like ... 09:59:32,268 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [SIFTER] 09:59:32,281 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.sift.MDCBasedDiscriminator] for [discriminator] property 09:59:32,298 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to INFO 09:59:32,298 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT] 09:59:32,304 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [SIFTER] to Logger[ROOT] ... 09:59:34,725 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.FileAppender] 09:59:34,730 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [FILE-one] ... 09:59:34,732 |-INFO in ch.qos.logback.core.FileAppender[FILE-one] - File property is set to [target/logs/Log_Test_one.log] ... which shows the sifting appender in action.
doc_23531371
I'm doing so with this: page.click('@btn_submit'); page.expect.element('@validation_label_required').to.be.visible; where @validation_label_required is represented by the CSS selector: input[required] ~ p.error-message-required However, this test passes if ANY of the validation labels are visible. The test should only pass if they ALL are. How can I achieve this? A: You will need to create a custom assertion for that where you locate all elements by selenium commands and then loop to verify condition. It should look something like this var util = require('util'); exports.assertion = function (elementSelector, expectedValue, msg) { this.message = msg || util.format('Testing if elements located by "%s" are visible', elementSelector); this.expected = expectedValue; this.pass = function (value) { return value === this.expected; }; this.value = function (result) { return result; }; this.command = function (callback) { var that = this.api; this.api.elements('css selector',elementSelector, function (elements) { elements.value.forEach(function(element){ that.elementIdDisplayed(element.ELEMENT,function(result){ if(!result.value){ callback(false); } }); }); callback(true); }); return this; }; }; A: I've just ended up with another custom assertion that check how many elements are visible by given css selector. /** * Check how many elements are visible by given css selector. * */ var util = require('util'); exports.assertion = function(elementSelector, expectedCount, msg) { this.message = msg || util.format('Asserting %s elements located by css selector "%s" are visible', expectedCount, elementSelector); this.expected = expectedCount; this.count = 0; this.pass = function(value) { return value === this.expected; }; this.value = function(result) { return this.count; }; this.command = function(callback) { var me = this, elcount = 0; this.count = 0; this.api.elements('css selector', elementSelector, function(elements) { if(elements.value && elements.value.length > 0){ elcount = elements.value.length; }else{ return callback(false); } elements.value.forEach(function(element) { me.api.elementIdDisplayed(element.ELEMENT, function(result) { if (result.value) { me.count++; } elcount--; if (elcount === 0) { callback(me.count); } }); }); }); }; };
doc_23531372
I've followed this to create a selector. I've used following cdn links CSS <link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" /> JS <script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script> HTML <div class="col-md-4"> <label>Assign Projects</label> <select class="form-control input-md" name="projects[]" id="projects" multiple="multiple"> @foreach($projects as $project) <option value="{{$project->id}}" selected>{{$project->name}}</option> @endforeach </select> @if ($errors->has('projects')) <span class="help-block"> <strong>{{ $errors->first('projects') }}</strong> </span> @endif </div> This is working perfectly in terms of functionality but appearance is not as expected. This is current view, Can someone give me idea what's going wrong here ? Any help is appreciated. A: I think you missed up this part: <script type="text/javascript"> $(document).ready(function() { $('.input-md').multiselect(); }); A: You can use bellow code in jquery. setTimeout(function(){ $('#projects').multiselect(); }, 800); This may help you ! A: <script type="text/javascript"> $(function() { $('.multiselect-ui').multiselect({ includeSelectAllOption: true }); }); </script> Include this script and check(replace the class "input-md" with "multiselect-ui")
doc_23531373
Here is my forms.py from flask_wtf import FlaskForm from flask_wtf.csrf import CSRFProtect from wtforms import StringField, TextAreaField, DateField, IntegerField from wtforms.validators import DataRequired csrf = CSRFProtect() class NewAccount(FlaskForm): account_field = StringField("Dealership Name:", validators=[DataRequired()]) rep_field = StringField("Sales Rep:", validators=[DataRequired()]) group_field = StringField("Group:", default ="n/a") price_field = IntegerField("Price:", validators=[DataRequired()]) setup_field = IntegerField("Setup:", validators=[DataRequired()]) signed_field = DateField("Signed Date(MM/DD/YYYY):", format='%m/%d/%Y',validators=[DataRequired()]) commitment_field = StringField("Commitment:", validators=[DataRequired()]) payment_field = StringField("Payment Type:", validators=[DataRequired()]) vertical_field = StringField("Vertical:",validators=[DataRequired()]) Here is my validate on submit: @app.route('/new_account', methods=('GET', 'POST')) def add(): """create new account""" form = forms.NewAccount() if form.validate_on_submit(): models.MasterLog.create(account_name=form.account_field.data, sales_rep=form.rep_field.data,dealer_group=form.group_field.data, price=form.price_field.data,setup=form.setup_field.data, signed_on=form.signed_field.data,commitment=form.commitment_field.data, payment_type=form.payment_field.data,vertical=form.vertical_field.data) flash("Account Added! Thanks!", "success") return redirect(url_for('active')) else: print("An error occured") return render_template('new.html', form=form) Here is the HTML Form: {% extends "layout.html" %} {% from 'macros.html' import render_field %} {% block content %} <div class="new-entry"> <div class="form-style-8"> <h2>New Account</h2> <form method='POST' action=''> {% for field in form %} {{ form.hidden_tag() }} {% if field.name != 'csrf_token' %} {{ field.label() }} {% endif %} {% if field.name == 'rep_field' %} <select id="reps" name="reps"> <option value="Dan">Dan</option> <option value="Danielle">Danielle</option> <option value="Hal">Hal</option> <option value="Hessam">Hessam</option> <option value="Jessica">Jessica</option> <option value="Travis">Travis</option> </select> {% elif field.name == 'commitment_field' %} <select id="commitment" name="commitment"> <option value="Anually">Anually</option> <option value="Quarterly">Quarterly</option> <option value="6 Months">6 Months</option> <option value="Monthly">Monthly</option> </select> {% elif field.name == 'payment_field' %} <select id="payment" name="payment"> <option value="Pay As You Go">Pay As You Go</option> <option value="Advanced Payment">Advanced Payment</option> </select> {% elif field.name == 'vertical_field' %} <select id="vertical" name="vertical"> <option value="Franchise">Franchise</option> <option value="Independent">Independent</option> <option value="Sokal">Sokal</option> <option value="PowerSport">Powersport</option> </select> {% elif field.name =='price_field' %} {{field(value='$')}} {% elif field.name =='setup_field' %} {{field(value='$')}} {% elif field.name =='signed_field' %} {{field(type='date')}} {% else %} {{ render_field(field) }} {% endif %} {% endfor %} <div class="button-section"> <button type="submit" id="submit" class="button">Add</button> <button class="button" onclick="document.location='active'">Cancel</button> </div> </form> </div> </div> </div> {% endblock %} Here is my Models: from peewee import * import csv import datetime DATABASE = SqliteDatabase('Master.db') class MasterLog(Model): id = AutoField() timestamp = DateTimeField(default=datetime.datetime.now, null=True) account_name = CharField(max_length=200, unique=True) sales_rep = CharField(max_length=200, unique=False) dealer_group = CharField(max_length=200, unique=False) price = IntegerField(null=True) setup = IntegerField(null=True) signed_on = DateTimeField(null=True) integrated_on = DateTimeField(null=True) billable_on = DateTimeField(null=True) commitment = CharField(max_length=200, unique=False) payment_type = CharField(max_length=200, unique=False) billing_method = CharField(max_length=200, unique=False, null=True) kick_off = CharField(max_length=200, unique=False, null=True) last_visit = DateTimeField(null=True) vertical = CharField(max_length=200, unique=False) notes = CharField(max_length=200, unique=False, null=True) cancelled_on = DateTimeField(null=True) class Meta: database = DATABASE A: Change {{ form.hidden_tag() }} to {{ form.csrf_token }} A: I had the same issue, i did two things to resolve this. First, i added an Optional() validator to the form fields i was leaving blank, like this field = StringField('string', validators=[Optional()]) And then change the line if form.validate_on_submit(): to if form.validate_on_submit: without the ()
doc_23531374
9000_1.txt 9000_2.txt 7000_1.txt 7000_2.txt 7000_3.txt I would like to save the contents of the files according to: 9000.txt as sum files 9000_1.txt and 9000_2.txt 7000.txt as sum files 7000_1.txt and 7000_2.txt and 7000_3.txt and ect Now I'm at moment where I have: import os import re folderPath = r'C:/Users/a/Desktop/OD' if os.path.exists(folderPath): files = [] for name in os.listdir(folderPath): if os.path.isfile(os.path.join(folderPath, name)): files.append(os.path.join(folderPath, name)) print(files) for ii in files: current = os.path.basename(ii).split("_")[0] could anyone advise on a simple way to go about it? A: Sure - use glob.glob to conveniently find all matching files and our good friend collections.defaultdict to group the files up, and loop over those groups: import glob import os import shutil from collections import defaultdict folder_path = os.path.expanduser("~/Desktop/OD") # Gather files into groups groups = defaultdict(set) for filename in glob.glob(os.path.join(folder_path, "*.txt")): # Since `filename` will also contain the path segment, # we'll need `basename` to just take the filename, # and then we split it by the underscore and take the first part. prefix = os.path.basename(filename).split("_")[0] # Defaultdict takes care of "hydrating" sets, so we can just groups[prefix].add(filename) # Process each group, in sorted order for sanity's sake. for group_name, filenames in sorted(groups.items()): # Concoct a destination name based on the group name. dest_name = os.path.join(folder_path, f"{group_name}.joined") with open(dest_name, "wb") as outf: # Similarly, sort the filenames here so we always get the # same result. for filename in sorted(filenames): print(f"Adding {filename} to {dest_name}") with open(filename, "rb") as inf: # You might want to do something else such as # write line-by-line, but this will do a straight up # merge in sorted order. shutil.copyfileobj(inf, outf) This outputs Adding C:\Users\X/Desktop/OD\7000_1.txt to C:\Users\X/Desktop/OD\7000.joined Adding C:\Users\X/Desktop/OD\7000_2.txt to C:\Users\X/Desktop/OD\7000.joined Adding C:\Users\X/Desktop/OD\7000_3.txt to C:\Users\X/Desktop/OD\7000.joined === Adding C:\Users\X/Desktop/OD\9000_1.txt to C:\Users\X/Desktop/OD\9000.joined Adding C:\Users\X/Desktop/OD\9000_2.txt to C:\Users\X/Desktop/OD\9000.joined
doc_23531375
Here is the full stack trace. /Users/rakesh.kumar/.virtualenvs/wpToConfluence.py/lib/python2.7/site-packages/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning. SNIMissingWarning /Users/rakesh.kumar/.virtualenvs/wpToConfluence.py/lib/python2.7/site-packages/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Traceback (most recent call last): File "wpToConfluence.py", line 15, in <module> main() File "wpToConfluence.py", line 11, in main headers={'content-type': 'application/json'}) File "/Users/rakesh.kumar/.virtualenvs/wpToConfluence.py/lib/python2.7/site-packages/requests/api.py", line 71, in get return request('get', url, params=params, **kwargs) File "/Users/rakesh.kumar/.virtualenvs/wpToConfluence.py/lib/python2.7/site-packages/requests/api.py", line 57, in request return session.request(method=method, url=url, **kwargs) File "/Users/rakesh.kumar/.virtualenvs/wpToConfluence.py/lib/python2.7/site-packages/requests/sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "/Users/rakesh.kumar/.virtualenvs/wpToConfluence.py/lib/python2.7/site-packages/requests/sessions.py", line 585, in send r = adapter.send(request, **kwargs) File "/Users/rakesh.kumar/.virtualenvs/wpToConfluence.py/lib/python2.7/site-packages/requests/adapters.py", line 453, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', error(54, 'Connection reset by peer')) Here is my client code: import requests def main(): auth = open('/tmp/confluence', 'r').readline().strip() username = 'rakesh.kumar' response = requests.get("https://<HOST-NAME>/rest/api/content/", auth=(username, auth), headers={'content-type': 'application/json'}) print response if __name__ == "__main__": main() I am running this script in a virtual environment and following packages are installed on that environment: (wpToConfluence.py)➜ Python pip list You are using pip version 6.1.1, however version 8.1.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. appnope (0.1.0) backports.shutil-get-terminal-size (1.0.0) decorator (4.0.10) ipdb (0.10.1) ipython (5.0.0) ipython-genutils (0.1.0) pathlib2 (2.1.0) pexpect (4.2.0) pickleshare (0.7.3) pip (6.1.1) prompt-toolkit (1.0.5) ptyprocess (0.5.1) Pygments (2.1.3) requests (2.10.0) setuptools (25.1.6) simplegeneric (0.8.1) six (1.10.0) traitlets (4.2.2) urllib3 (1.16) wcwidth (0.1.7) It does complain about the python version number but I am not sure how to update my Mac/Virtual environment python. I have tried to curl command and Postman both of them work fine for the given parameters. A: While installing requests library it skips few of optional security packages ('pyOpenSSL', 'ndg-httpsclient', and 'pyasn1') which are required for the SSL/Https connection. You can fix it by either running this command pip install "requests[security]" or pip install pyopenssl ndg-httpsclient pyasn1 A: I tried installing all the optional security packages provided in the answer above. But nothing seemed to work. One important GOTCHA : Check if your url end-point actively prevents programmatic access. Take a look at the robots.txt file in the root directory of a website: http://myweburl.com/robots.txt. If it contains text that looks like this : User-agent: * Disallow: / This site doesn’t like and want scraping. This gives you the same dreaded error 54, connection reset by the peer. Here is a snapshot : https://www.aclibrary.org/robots.txt User-agent: discobot Disallow: / User-agent: AddThis.com Disallow: / User-agent: Yandex Disallow: / User-agent: Baiduspider Disallow: / User-agent: Baiduspider-video Disallow: / User-agent: Baiduspider-image Disallow: / User-agent: SemrushBot Disallow: / User-agent: SemrushBot-SA Disallow: / User-Agent: W3C-checklink Crawl-delay: 0 User-agent: Twitterbot Disallow: User-agent: * Crawl-delay: 10 Disallow: /er.php Disallow: /err.php Disallow: /go.php Disallow: /friendly.php Disallow: /ld.php Disallow: /srch.php Sitemap: https://aclibrary.org/sitemap.xml A: I had the same problem, but installing the optional security packages did not work for me too. I had to downgrade requests version from 2.25.1 to 2.21.0 A: Installing the optional security packages did not work for me, just in case someone as the same error message, check that the url you are trying to use is correct. For instance if the server expects a connection on a different port, it is possible you find this error.
doc_23531376
I am trying to implement SOLR with Delta import queries to make my category pages faster. And my concern is about performance of page while getting data from SOLR and accuracy of real time data like Stock and Price. actually my database queries to get product data are little bit complicated and have several joins, so i have to make several related entities in SOLR database. So due to this data upload to SOLR is slow. that makes difficult to upload data (even with delta import query) frequently, so my application lacking real time data like stock of products. basically i want to know best practice approach to implement SOLR. I am confused with 1. Should i export my all data to SOLR and then get all details from SOLR? (I am worried about performance and real time data) 2. should i get only index data (say id of products) from SOLR and then get othere details from my SQL database? (not sure about this approach perfomance). So please help me and suggest me that how can i implement SOLR for my app in best way. all help is appretiated!! A: You can set up a database trigger or data access layer event to send data to Solr whenever there's a change, and configure autoCommit to control freshness. See also: * *http://wiki.apache.org/solr/NearRealtimeSearch *http://java.dzone.com/articles/tuning-solr-near-real-time A: One good case practice I encountered while developing e-commerce solution and SOLR as the search provider is to retrieve from SOLR only the IDs and get the data from SQL server. I created a single schema that was updating every time some new products were added in the database.(In my case products were added by a user in an admin console, in your case you can use the @Mauricio Scheffer comment to have latest updates) One field in the schema was the ID - representing the ID of the product in the database. After querying SOLR I was receiving N documents suiting the query and with the ID field I was getting all the information from my database and display it to the user. So the good part is that the user will always get the data from your database ( real time data), and will have his search results displayed very fast because of SOLR. You can add to the schema different fields that you can use to filter your results such as * *category *date *price *size *etc... And also differnet fields that you need to query upon: * *headline *description *name *etc... And also add the product ID. So after making the query to SOLR you have a list of product IDs, now the only thing you need to do is to implement a function that will get the products from database based on the ID and display it on the search results page. This approach performance is pretty good because selecting from database elements based on primary key is the fastest way to retrieve data from sql. I worked on a website with 1.000.000 products and searching time was always under 0.2 seconds and page loading time in the browser was under 0.6 seconds on single user queries. ( the server where SOLR and SQL was running was 8Gb ram and quad core 1.8 gb as I remember) Hope this type of implementation is useful for you.
doc_23531377
For that I followed instructions from this link: https://learn.microsoft.com/en-us/azure/aks/ingress-internal-ip I defined YAML file for helm install controller: service: annotations: service.beta.kubernetes.io/azure-load-balancer-internal: "true" I configured nginx: helm install nginx-ingress ingress-nginx/ingress-nginx \ -f internal-ingress.yaml \ --set controller.nodeSelector."beta\.kubernetes\.io/os"=linux \ --set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux \ --set controller.admissionWebhooks.patch.nodeSelector."beta\.kubernetes\.io/os"=linux NGINX configuration after that is that it has Ports 80 and 443: kubectl get services -o wide NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) nginx-ingress-ingress-ngingx controller LoadBalancer 10.0.36.81 10.33.27.35 80:31312/TCP,443:30653/TCP After that I run the helm upgrade to ensure my tcp port 9000 is being configured helm upgrade nginx-ingress ingress-nginx/ingress-nginx -f internal-ingress.yaml --set tcp.9000="default/frontarena-ads-aks-test:9000" This gave me the ConfigMap setting automatically when I check with "kubectl get configmaps": apiVersion: v1 data: "9000": default/frontarena-ads-aks-test:9000 kind: ConfigMap I have also edited my nginx Service: spec: clusterIP: 10.0.36.81 externalTrafficPolicy: Cluster ports: - name: http nodePort: 31312 port: 80 protocol: TCP targetPort: http - name: https nodePort: 30653 port: 443 protocol: TCP targetPort: https - name: 9000-tcp nodePort: 30758 port: 9000 protocol: TCP targetPort: 9000 I have my deployed App Pod : apiVersion: apps/v1 kind: Deployment metadata: name: frontarena-ads-deployment labels: app: frontarena-ads-deployment spec: replicas: 1 template: metadata: name: frontarena-ads-aks-test labels: app: frontarena-ads-aks-test spec: nodeSelector: "beta.kubernetes.io/os": linux restartPolicy: Always containers: - name: frontarena-ads-aks-test image: fa.dev/:test1 ports: - containerPort: 9000 selector: matchLabels: app: frontarena-ads-aks-test --- apiVersion: v1 kind: Service metadata: name: frontarena-ads-aks-test spec: type: ClusterIP ports: - protocol: TCP port: 9000 selector: app: frontarena-ads-aks-test I configured and deployed Ingress Controller YAML in same default namespace as well to connect my Ingress with above Service (I suppose it can connect through it based on the ClusterIP ): apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: ads-ingress annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/ssl-redirect: "false" spec: rules: - http: paths: - path: / backend: serviceName: frontarena-ads-aks-test servicePort: 9000 Now this issue is the following: if I try to target from my VM app deployed outside the AKS cluster in different virtual network with Ingress Controller IP or its DNS name configured by Azure Admins and the Port 9000 - I do not get any response which brings the conclusion that Ingress Controller is not propagating the network connection to my service which targets the app running on Port 9000 on my Pod. I can't find the reason why Ingress Controller will not forward the traffic to my service which Targets the Port 9000 which is the Port on which My App Pod is being run. Thank you!!! A: you have only one pod, change the matadata of the deployment to match the metadata of the pod: .... kind: Deployment metadata: name: frontarena-ads-aks-test labels: app: frontarena-ads-aks-test spec: replicas: 1 template: metadata: name: frontarena-ads-aks-test labels: app: frontarena-ads-aks-test ....
doc_23531378
public class FileUploader { private static readonly Dictionary FileStreams = new Dictionary(StringComparer.InvariantCultureIgnoreCase); public void SaveChunk(String storagePath, File file, Int64 currentPos, Byte[] chunk) { using (var writer = new BinaryWriter(OpenFileStream(storagePath))) { try { SaveChunk(writer, currentPos, chunk); } finally { writer.Close(); RemoveLock(storagePath); } } } private Stream OpenFileStream(String fullFileName) { Stream result = null; lock (FileStreams) { while (FileStreams.ContainsKey(fullFileName)) { Monitor.Wait(FileStreams); } result = System.IO.File.Open(fullFileName, FileMode.OpenOrCreate, FileAccess.Write); FileStreams[fullFileName] = true; } return result; } private void RemoveLock(String fileName) { lock (FileStreams) { FileStreams.Remove(fileName); Monitor.Pulse(FileStreams); } } Somehow we spmetime got an error message: The process cannot access the file '\ourstorage\folder\a_file_name.zip' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) But we cannot see why. It seems the code is correct, and wont access two threads same file same time. Any idea? A: You write with different threads in the same file. You have to check in every thread, if you are already writing in this file.
doc_23531379
id_A id_B 1 1 2 1 2 1 3 1 3 3 3 3 And I need a sql command that puts the table like this: id_A id_B 1 1 2 1 3 3 A: Technically, this is called the "mode" of (the distribution of) the values. If you only want one, then use can use the ANSI standard function row_number() with conditional aggregation: select id_A, id_B as mode_id_B from (select id_A, id_B, count(*) as cnt, row_number() over (partition by id_A order by count(*) desc) as seqnum from t group by id_A, id_B ) ab where seqnum = 1;
doc_23531380
When ever i try to save the document. it prompt me the msg "Error saving the document..: The object cannot be created in directory."webdav://server/webdav/filedemo/1AE86876842E2B4DC‌​1258018004E4710/doc.‌​odt any idea how to go about it or do i need any extension or plugin for Microsoft Office or open office as well?
doc_23531381
In CSS, I'm using this within classes: overflow-x: scroll -webkit-overflow-scrolling touch; overflow: hidden -webkit-transform translate3d (0,0,0); The curious thing is that on Android is normal... Why is this happening? What should I do? A: The keyboard on iOS behaves in a very special way, here's a quote from a great article on this topic The Eccentric Ways of iOS Safari with the Keyboard: The fundamental problem is that when the soft keyboard appears due to a user tap on a text input box near the bottom of the screen, Safari doesn’t resize the browser window but instead moves it upward such that it is partially offscreen You're likely preventing the body to move up, so make sure there's no code that would interfere with that.
doc_23531382
If I try to change to a background color, it works fine! I have also tried to change css class with a background-image and it works, but in my case I can't do that because I don't know which image to show from the css. HTML <div id="test" ondrop="drop(event)" ondragenter="enter(event)"></div> JavaScript function enter(event) { $('#test').css('background', '#333 url("test.png")'); event.preventDefault(); } In my code example the div will get the color #333 when the mouse enters and then get the background image when I let the mouse button up. I'm developing this in spotify which is webkit-based. Does anyone have a clue how I can solve this problem? Thank you! A: On http://musicmachinery.com/2011/12/02/building-a-spotify-app/, it says: Developing a Spotify App is just like developing a modern HTML5 app. You have a rich toolkit: CSS, HTML and Javascript. You can use jQuery, you can use the many Javascript libraries. Your app can connect to 3rd party web services like The Echo Nest. The Spotify Apps supports just about everything your Chrome browser supports with some exceptions: no web audio, no video, no geolocation and no Flash (thank god). That being said, I recommend that you use Jquery. Not only is it easy to learn, but you have have access to JQuery UI (visit http://jqueryui.com/demos/ for demos). As for your drag-enter/drop problem, I've made you an example using jquery. The demo can be found on HERE or http://jsfiddle.net/H8fPL/12/. I've also provided the code I used below. Let me know if you need anything else! Happy coding! CSS: div{ width:200px; height:220px; border:1px solid black; } #div1{ background-color:orange; margin-left:20px; } .NC{ background:url("http://www.dreadcentral.com/img/news/jun11/niccage.jpg") no-repeat; } .surprised{ background:url('http://rlv.zcache.ca/smiley_oh_sticker-p217194901605792400envb3_400.jpg'); background-size:80px 60px; background-repeat:no-repeat; background-position:center; } JAVASCRIPT: //needed for jquery, //CALL THIS SCRIPT BEFORE USING $ syntax <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> //query UI script <script type="text/javascript" src="http://code.jquery.com/ui/1.8.18/jquery-ui.min.js"></script> HTML: <div id='div1'> Come Hither... </div> <div id="dropme"> DRAG ME OVER AND WATCH ME CHANGE </div> IMPORTANT REFERENCES: * *http://docs.jquery.com/Main_Page (Obviously) *http://jqueryui.com/demos/ (UI DEMOS) *http://jqueryui.com/demos/droppable/ (METHODS/EVENTS/OPTIONS ESSENTIAL!) *http://jqueryui.com/demos/draggable/#event-drag (METHODS/EVENTS/OPTIONS ESSENTIAL!) *http://oscarotero.com/jquery/ (jquery cheatsheet)
doc_23531383
import pandas as pd df = pd.DataFrame(data= {"x": [1,2,3,4],"y":[5,6,7,8],"i":["a.0","a.1","a.0","a.1"]}).set_index("i") df Out: x y i a.0 1 5 a.1 2 6 a.0 3 7 a.1 4 8 and I want to rename the index based on a column condition: df.loc[df["y"]>6].rename(index=lambda x: x+ ">6" ) what gives me: x y i a.0>6 3 7 a.1>6 4 8 I tried it with inplace=True, but it does not work df.loc[df["y"]>6].rename(index=lambda x: x+ ">6" , inplace=True ) I only could get it done by resetting the index, changing the i-column-values via apply and set the index again: df1 = df.reset_index() df1.loc[df1["y"]>6, "i"] = df1.loc[df1["y"]>6, "i"].apply(lambda x: x+ ">6" ) df1.set_index("i", inplace=True) df1 Out: x y i a.0 1 5 a.1 2 6 a.0>6 3 7 a.1>6 4 8 But this is so complicated. Do you know if there is an easier way? A: How about trying this? import numpy as np df.index=np.where(df['y']>6, df.index+'>6', df.index)
doc_23531384
I think everything turned out, but I can not figure out how to work with the data of the current_user. If I write in controller: user = conn.assigns.current_user IO.inspect user I get: {:ok, %Myfiles.User{__meta__: #Ecto.Schema.Metadata<:loaded, "users">, encrypted_password: "$2b$12$KLDREZ08084BhHXrJR8EAuQinHn.X2X9OlfylelYiK5KSinlxfTii", id: 1, inserted_at: #Ecto.DateTime<2016-10-07 21:28:51>, password: "123456", password_confirmation: "123456", updated_at: #Ecto.DateTime<2016-10-07 21:28:51>, username: "test"}} this is not a map? how to get out of here id? A: Your current_user is a tuple that containing :ok and a user struct.You can get id out like this: {:ok, user} = conn.assigns.current_user IO.inspect user.id You can read more about struct here
doc_23531385
'internal/modules/cjs/loader.js:58\n' + "const internalModuleStat = function (f) { return require('fs').internalModuleStat(f); };\n" + ' ^\n' + '\n' + 'TypeError: require(...).internalModuleStat is not a function\n' + ' at internalModuleStat (internal/modules/cjs/loader.js:58:64)\n' + ' at stat (internal/modules/cjs/loader.js:137:18)\n' + ' at Function.Module._findPath (internal/modules/cjs/loader.js:667:16)\n' + ' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:967:27)\n' + ' at Function.Module._load (internal/modules/cjs/loader.js:862:27)\n' + ' at Module.require (internal/modules/cjs/loader.js:1042:19)\n' + ' at Module._preloadModules (internal/modules/cjs/loader.js:1296:12)\n' + ' at loadPreloadModules (internal/bootstrap/pre_execution.js:449:5)\n' + ' at prepareMainThreadExecution (internal/bootstrap/pre_execution.js:73:3)\n' + ' at internal/bootstrap/pkg.js:7:1\n' What can be going on here? A: This can happen for many reasons. Here is a common root cause of similar problems: Something may be messing up with the values of the NODE_OPTIONS variable. The problem can be something else, but I would check the value NODE_OPTIONS as a possible culprit. To understand why here is a... Case study Here, we use both nyc (the test coverage tool) and pkg. nyc sets an environment variable called NODE_OPTIONS; pkg, also, checks the value of this variable. So when we run coverage, the variable is changed by nyc. The value nyc sets, though, does not make sense to pkg. pkg gets lost then. How we solve it Our solution was to reset the variable before running the tests. In our case, we use Mocha, so we had a line like this in our package.json: "scripts": { "coverage": "nyc --reporter=lcov --include='src/**/*.js' npm test", "test": "./node_modules/.bin/mocha --require @babel/register --recursive --exit", } We just added NODE_OPTIONS='' before calling mocha: "scripts": { "coverage": "nyc --reporter=lcov --include='src/**/*.js' npm test", "test": "NODE_OPTIONS='' ./node_modules/.bin/mocha --require @babel/register --recursive --exit", } Now, npm run coverage runs nyc, which sets the variable as needed. nyc then calls npm run test, whose script cleans up the variable. Your mileage may vary Maybe your problem is not the same as the one above, or NODE_OPTIONS is messed up somewhere else. I hope, though, this answer can help you to figure out what is going on then.
doc_23531386
This is the function I have now: function spamcheck($field) { if(eregi("to:",$field) || eregi("cc:",$field) || eregi("Content-Type:",$field) || eregi("bcc:",$field) || eregi("%0D",$field) || eregi("\r",$field) || eregi("\n",$field) || eregi("%0A",$field)){ $possiblespam = TRUE; }else $possiblespam = FALSE; if ($possiblespam) { die("Possible spam attempt detected. If this is not the case, please edit the content of the contact form and try again."); return 1; } } Now, I'm not sure if I could just replace eregi with preg_match like so: if(preg_match("/to:/i",$field) // and so on for each string I want to catch I have read here that preg_match needs delimiters, not sure if I've used them right. Also, should be case sensitive, so I added the i flag (without confidence). Still, no real idea if above would actually be correct. Does that seem secure? Again, apologies for my lack of PHP knowledge. This kind of function is quite common in online tutorials, but using eregi rather than preg_match. A: Just checking for line breaks should be enough: $possiblespam = (0 !== preg_match("~(\r|\n)~", $field));
doc_23531387
I few days back I got an error message that said I had a merge conflict. I didn't know what this meant so I stopped trying to commit. Now whenever I go onto the git terminal I see (master|MERGING). And whenever I try to commit (even when it's not on the same remote) I get a lengthy error: It says to fix the error but I'm not sure how to go about that. What exactly do I need to do? A: Try running git reset --merge or git merge --abort (they are equivalent)
doc_23531388
'User' object has no attribute 'phone' What I did in models.py is: class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) ... phone = models.CharField(max_length=17, null=True, unique=True) ... def __str__(self): return str(self.user) and I have forms.py class CreatUserForm(UserCreationForm): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") first_name = forms.CharField() last_name = forms.CharField() email = forms.EmailField() phone = forms.CharField(validators=[phone_regex], max_length=17) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'phone', 'password1', 'password2'] and finally in views.py I have the following function: @unauthenticated_user def registerPage(request): form = CreatUserForm() if request.method == 'POST': form = CreatUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') group = Group.objects.get(name='customers') user.groups.add(group) first_name = user.first_name last_name = user.last_name email = user.email phone = user.phone Customer.objects.create( user=user, first_name=first_name, last_name=last_name, email=email, phone=phone, ) messages.success(request, username + ' created!') return redirect('login') context = {'form': form} return render(request, 'main/page-register.html', context) But I can't get phone from my users! A: It is likely better to work with two forms here, one for the User, and one for the Customer, and then "link" the two at the view level: class CustomerForm(ModelForm): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message='Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.') phone = forms.CharField(validators=[phone_regex], max_length=17) class Meta: model = Customer fields = ['phone'] then we can combine both forms with: @unauthenticated_user def registerPage(request): if request.method == 'POST': form = UserCreationForm(request.POST, request.FILES) form2 = CustomerForm(request.POST, request.FILES) if form.is_valid() and form2.is_valid(): user = form.save() form2.instance.user = user form2.save() group = Group.objects.get(name='customers') user.groups.add(group) messages.success(request, username + ' created!') return redirect('login') else: form = UserCreationForm() form2 = CustomerForm() context = {'form': form, 'form2': forom2} return render(request, 'main/page-register.html', context) in the template, then both forms are rendered: <form action="…" method="post"> {% csrf_token %} {{ form1 }} {{ form2 }} Create customer </form> Your customer should not have the same fields as the user: you are then duplicating data, and it is hard to keep data in sync.
doc_23531389
I'm able to display all the unique movies using this: Movies.distinct(:Tags).each {|x| puts x } I've tried Movies.distinct(:Tags).each {|x| puts x._id }, this came up with an error. Now how do I extract the ID value from x? EDIT: The document is structured like so [ _id: Integer, movie: String, tags: Array ] UPDATE: Maybe a simpler question... if i have Movies.any_of(:Tags => /comedy/i) how can I get the value of _id? Movies.any_of(:Tags => /comedy/i).only(:_id) returns a document that I'm not able to get id from individually.. it just sets the other fields to nil. A: Ended up using .only(:id) and saving that to a variable then going through it with .each and pushing it to an empty array
doc_23531390
What is the best way to create this dependency? The library doesn't have ant, maven or even gradle support. Some options that came to my mind: 1) Fork the repo and add gradle support. 2) Clone the repo and add maven support then add it to the local maven repo. What do the experts think how to handle such dependencies? A: If the library only publish sources, not binaries, you don't have any other option rather than build it yourself. Once you did that, you can host the binary in binary repository (like Artifactory) for sharing it with your colleagues, or even publish it on a distribution platform (like Bintray) for anyone who want to use it. For the later, you'll be able to pass the ownership (and the maintenance burden) to the original author in any moment.
doc_23531391
A: Download Nexus for free from Sonatype, or Artifactory, or any of the other repository managers. The alternative is to learn about install:install-file to shove jars into your personal local repo. However, having a full repo as above has so many advantages (not the least speed via caching) that it's easier to just install one. A: You can use a Maven2 repository implementation such as Nexus, Artifactory, or Archiva. You can create a simple POM for the non-maven dependency you are working with and use the deploy:deploy-file goal to deploy it to the repository. If you just need the dependency locally you can use the install:install-file to install the dependency in your local repository. This approach requires nothing more than maven be installed on your machine. If you just want to add libraries to the path of your build without worrying about repositories you can declare them as system dependencies. I do not recommend this approach but it should work fine.
doc_23531392
In the system a User has 0..n roles. Based on which role the user is at the moment the system will return a specific set of data to that user. The user will be able to perform certain actions but not others etc. public class User {     public bool HasRole(string roleName)     {         return this.UserRoles.Any(r => r.Name == roleName);     }     public string Username { get; set; }     public long? CurrentRoleId { get; set; }     public Role CurrentRole { get; set; }     public virtual IList<Role> UserRoles { get; set; } } public class Role {     public Role() { }     public string Name { get; set; } } public class GetEventsQuery : IQuery<List<Event>> {     public List<Event> Query()     {         switch (this.user.CurrentRole.Name)         {             case "Administrator":                 UserIsNotInAdministratorRole();                 return repository.All.ToList();             case "Supervisor":                 UserIsNotInSupervisorRole();                 return repository.All.Where(evnt => evnt.SupervisorId == this.user.RecordId).ToList();             case "User":                 UserIsNotInUserRole();                 return repository.All.Where(evnt => evnt.UserId == this.user.RecordId).ToList();             default:                 throw new Exception("GetEventsQuery Unknow exception.");         }     }     private void UserIsNotInUserRole()     {         if (!this.user.HasRole("User"))         {             throw new NoUserRoleException("User does not have user role!");         }     }     private void UserIsNotInSupervisorRole()     {         if (!this.user.HasRole("Supervisor"))         {             throw new NoSupervisorRoleException("User does not have supervisor role!");         }     }     private void UserIsNotInAdministratorRole()     {         if (!this.user.HasRole("Administrator"))         {             throw new NoAdministratorRoleException("User does not have administrator role!");         }     }     public GetEventsQuery(string username, IUserRepository userRepository, IEventRepository repository)     {         this.repository = repository;         var userQuery = new GetUserQuery(username, userRepository);         this.user = userQuery.Query();     }     private readonly User user;     private readonly IEventRepository repository; } This switch statement will show up in all parts of the system. If there was a way to re-factor it out into a class and have it in a single location I don't mind keeping it but having it repeated over and over again is definitely a code smell. I am just starting this project out so if there is a better way to design the object hierarchy or make major changes to eliminate this issue I am open to it. A: The Strategy Pattern is often a good pattern to use when replacing non-OO switch statements. A: Role should be a common base class (or interface) inherited by each role (e.g Administrator, Supervisor, User.) Each implementation of Role should have them information on what is or is not allowed for that particular role. A: Can you use polymorphism to avoid your switch? You would use an abstraction to contain your behaviour as necessary. And then create concrete implementations of that which encapsulate the logic specific to them - these then replace your switch statement. It would be the Role that needed to be refactored out, so possibly something like public interface IRole { // whatever you need here } public class Administrator : IRole { // your implementation } There's a good post on lostechies.com on polymorphism-part-2-refactoring-to-polymorphic-behavior A: Interface IRole: GetRole(); //You can use it to self-define the role IsUserInRole(Role roleType) //Check if user in specific role GetList(); //Query Define specific Roles: SuperVisor implements IRole {...} Administrator implements IRole {...} Advantage here is that you can rely on IRole to maintain your transaction instead of dealing with direct Role objects (AdministratorObject) and cast it to appropriate class when you need to call any specific method inside that class's definition. A: What you want in this case is a combination of the Factory and Strategy patterns. The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from the clients that use it. The Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. When the above are used together you will be able to create a fully extensible class that will provide all the functionality you want... I hope this helps.
doc_23531393
Dim strComputer, objFSO, ObjShell, strDisplayName, objList, strObject Dim objReg, arrSubKeys, strProduct, strVersion, strReqVersion Const For_Writing = 2 Const ForReading = 1 const ForAppending = 3 Const HKLM = &H80000002 Const strKeyPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" strReqVersion = "8.2.1 MP2" Set objFSO = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("WScript.Shell") Set objList = objFSO.OpenTextFile("c:\test\test.txt",ForReading) Do While Not objList.AtEndOfStream strComputer = objList.ReadLine If HostOnline(strComputer) = True Then Inventory(strComputer) End If Loop Function Inventory(strComputer) Set objTextFile = objFSO.OpenTextFile("c:\test\inventory.txt",2,true) 'creating a dictionary object Set objDictionary = CreateObject("Scripting.Dictionary") Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _ strComputer & "\root\default:StdRegProv") ' Enumerate the subkeys of the Uninstall key objReg.EnumKey HKLM, strKeyPath, arrSubKeys For Each strProduct In arrSubKeys ' Get the product's display name objReg.GetStringValue HKLM, strKeyPath & "\" & strProduct, "DisplayName", strDisplayName ' Process only products whose name contain 'symantec' If InStr(1, strDisplayName, "Symantec", vbTextCompare) > 0 Then ' Get the product's display version objReg.GetStringValue HKLM, strKeyPath & "\" & strProduct, "DisplayVersion", strVersion If strReqVersion <> strVersion Then WScript.Echo strObject objDictionary.Add strComputer, strVersion For Each strObject In objDictionary WScript.Echo strObject objTextFile.WriteLine(strObject) Next objTextFile.Close End If End If Next End Function Function HostOnline(strComputername) '---------- Test to see if host or url alive through ping ----------------- ' Returns True if Host responds to ping ' ' strComputername is a hostname or IP Const OpenAsASCII = 0 Const FailIfNotExist = 0 Const ForReading = 1 Dim objShell, objFSO, sTempFile, fFile Set objShell = CreateObject("WScript.Shell") Set objFSO = CreateObject("Scripting.FileSystemObject") sTempFile = objFSO.GetSpecialFolder(2).ShortPath & "\" & objFSO.GetTempName objShell.Run "cmd /c ping -n 2 -l 8 " & strComputername & ">" & sTempFile, 0 , True Set fFile = objFSO.OpenTextFile(sTempFile, ForReading, FailIfNotExist, OpenAsASCII) Select Case InStr(fFile.ReadAll, "TTL=") Case 0 HostOnline = False Case Else HostOnline = True End Select ffile.close objFSO.DeleteFile(sTempFile) Set objFSO = Nothing Set objShell = Nothing End Function can some one help me please thanks A: Why not use the system's event log? I described how in this answer It means most of the work is done for you and you don't need to worry about where to put your log file A: There are several ways to do this. The simplest way, without any modification to your script, would be to call the script with cscript.exe (in a command prompt) and redirect the output to a file: cscript your.vbs > output.log However, if you want a log to be created even when users double-click your script you'll have to change your script so that it writes to a file instead of echoing the output. Open the log file at the beginning of the script: Set myLog = objFSO.OpenTextFile("C:\my.log", For_Writing, True) replace WScript.Echo ... with myLog.WriteLine ..., and close the file before you exit from the script: myLog.Close A somewhat more sophisticated approach would be to create a set of logging functions, which will allow you create log lines depending on certain conditions, e.g. LogInfo() for informational log messages and LogError() for errors. Shameless plug: Some time ago I got fed up with writing the same boilerplate logging functions over and over again, so I wrote a logger class that encapsulates the usual logging facilities (interactive console, files, eventlog) and provides logging methods for 4 log levels (Error, Warning, Information, Debug). The class can be used for logging to a file like this: Set myLog = New CLogger myLog.LogToConsole = False myLog.LogFile = "C:\my.log" myLog.LogInfo "info message" ... myLog.LogError "an error occurred" The log file is automatically closed when the object is released.
doc_23531394
import 'package:path/path.dart'; import 'package:async/async.dart'; import 'dart:io'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; upload(File imageFile) async { // open a bytestream var stream = new http.ByteStream(DelegatingStream(imageFile.openRead())); // get file length var length = await imageFile.length(); // string to uri var uri = Uri.parse("http://192.168.43.76/soledesign/wp-json/wp/v2/media"); // create multipart request var request = new http.MultipartRequest("POST", uri); // multipart that takes file var multipartFile = new http.MultipartFile('file', stream, length, filename: basename(imageFile.path)); // add file to multipart request.files.add(multipartFile); //multipart that take headers Map<String, String> headers = { "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xOTIuMTY4LjQzLjc2XC9zb2xlZGVzaWduIiwiaWF0IjoxNTg5Nzg0MDE2LCJuYmYiOjE1ODk3ODQwMTYsImV4cCI6MTU5MDM4ODgxNiwiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMTAzIn19fQ.ST-Ts_GnziJLJEIRLHvnZMW3xcs7f5ARk0ZeKTvMyFo", "Content-Disposition": "attachment;filename=1.png", "Content-Type": "image/png" }; // add header to multipart request.headers.addAll(headers); // send var response = await request.send(); print(response.statusCode); // listen for response response.stream.transform(utf8.decoder).listen((value) { print(value); }); } class PickImgGallery extends StatefulWidget { @override _PickImgGalleryState createState() => _PickImgGalleryState(); } class _PickImgGalleryState extends State<PickImgGallery> { File _image; Future getImage() async { var image = await ImagePicker.pickImage(source: ImageSource.gallery); setState(() { _image = image; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Builder(builder: (context) { return Column( children: <Widget>[ Center( child: _image == null ? Text('No image selected.') : Image.file(_image), ), RaisedButton( onPressed: () { upload(_image); Scaffold.of(context) .showSnackBar(SnackBar(content: Text('Uploading'))); }, child: Text('Image Upload'), ), ], ); }), floatingActionButton: FloatingActionButton( onPressed: () { getImage(); }, tooltip: 'Pick Image', child: Icon(Icons.add_a_photo), ), ); } } A: To receive data after a MultipartRequest, rather than this // send var response = await request.send(); print(response.statusCode); // listen for response response.stream.transform(utf8.decoder).listen((value) { print(value); }); try this: http.Response response = await http.Response.fromStream(await request.send()); print("Result: ${response.statusCode}"); return response.body;
doc_23531395
A: ttk.treeview.focus() returns the current focus item. That means the item that was last selected. The function you are looking for is ttk.treeview.selection(). This returns a tuple of the selected items. A: Use ttk.treeview.selection(). It gives the selected items. See also other Treeview methods with selection prefix such as, selection_add selection_remove selection_toggle See the example below: import tkinter as tk from tkinter import ttk, Tk def insert(tree, value): tree.insert('', tk.END, value, text=value) root = Tk() tree = ttk.Treeview(root) insert(tree, '1') insert(tree, '2') insert(tree, '3') tree.pack() children = tree.get_children() tree.selection_set(children) tree.selection_toggle(children[1]) # uncomment line by line to see the change #tree.selection_toggle(children) #tree.selection_remove(children[1]) print(tree.selection()) root.mainloop()
doc_23531396
I wanted to check the version using mysql --version and the following error ocurred: mysql: [ERROR] unknown variable 'pid-file=/var/run/mysqld/mysqld.pid'. I have also tried starting mysql with sudo service mysql start and I get the following warning: su: warning: cannot change directory to /nonexistent: No such file or directory I haven't been able to use mysql and do not have access to the console. I haven't yet found a clear solution on other sites so I am asking here. Thank you in advance for your help! A: Did you try to desintall mysql and purge ?
doc_23531397
Access – <a href="http://extratorrent.cc/search/?search=Cotent">Torrent Search</a> – <a href="http://link1.com/Text">Link 1</a> – <a href="http://link2.com/Text">Link 2</a> – <a href="http://link3.com/Text">Link 3</a> – <a href="http://link4.com/Text">Link 4</a> I want use regex to make it like this Access – <a href="http://extratorrent.cc/search/?search=Cotent">Torrent Search</a> – AAABBBCCC I just know </?a(|\s+[^>]+)>to remove url link but don't know how to regex like content above. A: Something like this? <?php $input = 'Access – <a href="http://extratorrent.cc/search/?search=Cotent">Torrent Search</a> – <a href="http://link1.com/Text">Link 1</a> – <a href="http://link2.com/Text">Link 2</a> – <a href="http://link3.com/Text">Link 3</a> – <a href="http://link4.com/Text">Link 4</a>'; $output = preg_replace("/<a href=\"http:\/\/(?!extratorrent.cc)[^\"]+\">([^<]+)<\/a>/", '$1', $input); // remove all links $output = preg_replace("/\ –? Link [0-9]+/", '', $output); // CONCAT TEXT $output.= " AABBCCDD"; echo $output; /* output: Access – <a href="http://extratorrent.cc/search/?search=Cotent">Torrent Search</a> AABBCCDD */
doc_23531398
sent="Hi please help me to <e1>solve, this problem please</e1> Thank you." What I need (the desired output): [5, 6, 7, 8, 9] If you count each word from the beginning of the sentence, I need the index of the sequence between two markers: solve -> 5 , -> 6 this -> 7 problem -> 8 please -> 9 I tried these two solutions: Solution 1: sent="Hi please help me to <e1>solve, this problem please</e1> Thank you." E1 = re.search('<e1>(.*)</e1>', sent).group(1) sent = sent.replace('<e1>', '') sent = sent.replace('</e1>', '') sent = word_tokenize(sent) E1_indx = [] E1_lis = word_tokenize(E1) print(E1_lis) for item in E1_lis: E1_indx.append(sent.index(item)) print(E1_indx) But the output is: [5, 6, 7, 8, 1] Solution 2: sent="Hi please help me to <e1>solve, this problem please</e1> Thank you." e1_st = re.findall(r'<e1>\w+', sent) e1_end = re.findall(r'\w+</e1>', sent) e1_st=(''.join(str(x) for x in e1_st)) e1_end=(''.join(str(x) for x in e1_end)) e1_st = e1_st.replace('<e1>', '') e1_end = e1_end.replace('</e1>', '') sent = sent.replace('<e1>', '') sent = sent.replace('</e1>', '') sent = word_tokenize(sent) print(list(range(sent.index(e1_st), sent.index(e1_end)+1))) Output: [] The problem arises when there is a repetitive word of sequence before it (here "please"). Is there any straightforward solution? A: It looks like this question. If you compute the offsets as following and remove the markers you should have the expected results. sub_b = sent.find('<e1>') sent = sent.replace('<e1>') sub_e = sent.find('</e1>') sent = sent.replace('</e1>')
doc_23531399
Now it works smoothly in debug mode However after I sign it and convert it to release mode when i try to install it on phone it shows the problem Application not installed My config.xml <?xml version="1.0" encoding="UTF-8"?> <widget xmlns = "http://www.w3.org/ns/widgets" xmlns:gap = "http://phonegap.com/ns/1.0" id = "com.brilliantapp.seb7a2015" versionCode="5" version = "1.0"> <name>Seb7a</name> <description> seb7a app helps u calculate zekr </description> <author href="www.fb.com/DrOs96" email="Drusama2@gmail.com"> Osama Soliman </author> <preference name="phonegap-version" value="3.7.0" /> <preference name="orientation" value="default" /> <preference name="fullscreen" value="false" /> <preference name="target-device" value="universal" /> <preference name="webviewbounce" value="true" /> <preference name="prerendered-icon" value="true" /> <preference name="stay-in-webview" value="true" /> <preference name="ios-statusbarstyle" value="default" /> <preference name="detect-data-types" value="true" /> <preference name="exit-on-suspend" value="false" /> <preference name="show-splash-screen-spinner" value="true" /> <preference name="auto-hide-splash-screen" value="true" /> <preference name="EnableViewportScale" value="true" /> <preference name="MediaPlaybackRequiresUserAction" value="false" /> <preference name="AllowInlineMediaPlayback" value="false" /> <preference name="BackupWebStorage" value="cloud" /> <preference name="TopActivityIndicator" value="gray" /> <preference name="KeyboardDisplayRequiresUserAction" value="false" /> <preference name="HideKeyboardFormAccessoryBar" value="false" /> <preference name="SuppressesIncrementalRendering" value="false" /> <preference name="android-minSdkVersion" value="10" /> <preference name="android-installLocation" value="auto" /> <preference name="SplashScreenDelay" value="5000" /> <preference name="ErrorUrl" value=""/> <preference name="BackgroundColor" value="0x000000"/> <preference name="KeepRunning" value="true"/> <preference name="DisallowOverscroll" value="false"/> <preference name="LoadingDialog" value=","/> <preference name="LoadUrlTimeoutValue" value="20000" /> <preference name="disable-cursor" value="false" /> <gap:platform name="android" /> <feature name="http://api.phonegap.com/1.0/notification"/> <icon src="res/icon/android/icon-36-ldpi.png" gap:platform="android" gap:density="ldpi" /> <icon src="res/icon/android/icon-48-mdpi.png" gap:platform="android" gap:density="mdpi" /> <icon src="res/icon/android/icon-72-hdpi.png" gap:platform="android" gap:density="hdpi" /> <icon src="res/icon/android/icon-96-xhdpi.png" gap:platform="android" gap:density="xhdpi" /> <icon src="res/icon/android/144.png" gap:platform="android" gap:density="xxhdpi" /> <icon src="res/icon/android/192.png" gap:platform="android" gap:density="xxxhdpi" /> <icon src="res/icon/android/64.png" /> </widget> And My key.keystore Please can Someone tell me Where the problem ? A: You can't install the same version of your app twice on an Android phone ! That's simple ! You have two options: * *Delete the debug/current version installed *change the version of your app from config.xml file A: Try signing it using the Jarsinger method. once you have run the release command place your keystore file in your ant-build folder, rename the unsigned app file to what you want then CD to ant-build and run: jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore seb7a1.keystore [yourAppName].apk [yourAppName] A: First off - don't show your keystore like that. This happens when you try to install the same package named app as a debug and a release. Uninstall the debug version, reinstall the release version and it should be fine. This happened to me a few times before I realised what the problem was.