qid
int64
1
74.7M
question
stringlengths
16
65.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
117k
response_k
stringlengths
3
61.5k
57,883,619
I have already installed the MySQL workbench before. Now I want to install the MySQL Server to my local, I download the MySQL Installer 8.0.17 msi file in [dev.mysql.com](https://dev.mysql.com/downloads/windows/installer/8.0.html) . But open the msi file always show upgrading products , not adding products. [![MySQL Installer community ](https://i.stack.imgur.com/bxTHn.png)](https://i.stack.imgur.com/bxTHn.png) [![Show Upgrading ](https://i.stack.imgur.com/7b7A1.png)](https://i.stack.imgur.com/7b7A1.png) How to adding MySQL Server to Windows 10 instead of upgrade?
2019/09/11
[ "https://Stackoverflow.com/questions/57883619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5338465/" ]
Set environment variable for Gunicorn (Airflow uses Gunicorn for webserver): For **TLS 1.2**: ``` GUNICORN_CMD_ARGS="--ssl-version=5" ``` If you want to change ciphers too, you can add them in the above environment variable. Example: ``` GUNICORN_CMD_ARGS="--ssl-version=5 --ciphers=TLSv1.2" ``` Docs: <https://docs.gunicorn.org/en/stable/settings.html> We used `--ciphers=EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH:DHE+RSA+AES` in one of our projects.
Setting the GUNICORN variable in the environment file of systemd unit service can also be handy. example for airflow environment file `/opt/airflow/airflow_env` ```html PATH=/opt/airflow/.local/bin:/usr/bin:/usr/local/bin:/bin:$PATH AIRFLOW_HOME=/opt/airflow/airflow PYTHONPATH=/opt/rh/rh-python36 AIRFLOW_GPL_UNIDECODE=yes GUNICORN_CMD_ARGS="--ssl-version=5 --ciphers=TLSv1.2" ``` example for systemd unit service, here we are using airflow-webserver unit service created at `/etc/systemd/system/multi-user.target.wants/airflow-webserver.service` :- ```html [Unit] Description=Airflow webserver daemon After=network.target mysqld.service redis.service Wants=mysqld.service redis.service [Service] EnvironmentFile=/opt/airflow/airflow_env User=airflow Group=airflow Type=simple PermissionsStartOnly=true ExecStartPre=/bin/mkdir -p /run/airflow/ ExecStartPre=/bin/chown -R airflow:airflow /run/airflow/ ExecStart=/opt/airflow/.local/bin/airflow webserver --pid /run/airflow/webserver.pid -l /var/log/airflow Restart=on-failure RestartSec=10s PrivateTmp=true [Install] WantedBy=multi-user.target ```
57,072,874
We're trying to embed a GDS private report in our customer portal and we hope to filter the data using the email of the person connected to our customer portal . some of our users are no google users (they dont have an account gmail) and they're connected to this portal with an email and password form of authentification. Our data is stored in Google Storage and we use Bigquery for querying and we use BQ connector to connect BQ and Google Data Studio. There is any solution to do this ? parameters in GDS report URL ? Through API? Any help will be appreciated. Taoufiq.
2019/07/17
[ "https://Stackoverflow.com/questions/57072874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11796792/" ]
This is possible to do using Community Connectors and some minor development work in your portal. You will need to pass a short lived unique token as a parameter for the embedded report and then have an API or some other way to tie that token to a user identity. This [solution guide](http://developers.google.com/datastudio/solution/viewers-cred-with-3p-credentials) has instructions for this specific use case.
The [documentation](https://support.google.com/datastudio/answer/7450249?hl=en&ref_topic=7442437) states that the only sharing options are: a) Making the report public, or b) Have the user authenticate with a google account. Unfortunately, it neither has an API, nor support for parameters through URL yet.
39,139,834
I have this simple code here about the input type email. I have some reference about validating an email when user clicks the button. Here's the reference [http://stackoverflow.com/questions/46155/validate-email-address-in-javascript](http://Validate%20email%20address%20in%20JavaScript?) **HTML code** ``` <html> <body> <div class="form-group"> <input class="form-control" placeholder="Email" name="email" id="email" type="email" required> <span id="checkEmail"></span> </div> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <html> ``` I tried the script to validate and display a message in the span tag id="checkEmail" using keyup event function but it doesn't seem to work. Does my syntax is incorrect? Please help. Its **Script** ``` <script> //Email Regular Expression function function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } //Email Validate function function validate() { $("#email").keyup(function() { var email = $("#email").val(); if (validateEmail(email)) { $("#checkEmail").text(email + " is valid :)"); $("#checkEmail").css("color", "green"); } else { $("#checkEmail").text(email + " is not valid :("); $("#checkEmail").css("color", "red"); } }); //UPDATE $(document).ready(function() { $("#checkEmail").keyup(validate); }); } </script> ```
2016/08/25
[ "https://Stackoverflow.com/questions/39139834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3144998/" ]
Your code works for me, all I needed to do is to call ``` validate(); ``` anywhere on document load to actually bind the events. (which means you might want to move the binding outside the validate function, to not re-bind it anytime you click/use the function) edit: I have prepared a fiddle for you: <https://jsfiddle.net/caz9o53e/>
I think you can use this fiddle link, does the work. <http://jsfiddle.net/o6d86xtw/1/> HTML ``` <label for="email" id="email">Hey!</label> <input id="email" name="email" type="email" class="required" /> <span class="msg error">You shall not pass!</span> <span class="msg success">You can pass!</span> ``` JQuery ``` var component = { input : $('input[name="email"]'), mensage : { fields : $('.msg'), success : $('.success'), error : $('.error') } }, regex = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/; component.input.blur(function () { component.mensage.fields.hide(); regex.test(component.input.val()) ? component.mensage.success.show() : component.mensage.error.show(); }); ``` Note : I forked someone else's fiddle.
59,516,851
I can't get the Java / Javascript bridge to work on Java11 and Java13. The bridge seems to work fine i Java8 and Java10. Here is essentially the same code as <https://stackoverflow.com/a/34840552/11329518>, which again works for me on Java8 and Java10: ```java import java.io.File; import java.net.MalformedURLException; import java.net.URL; import javafx.application.Application; import javafx.concurrent.Worker.State; import javafx.scene.control.ButtonType; import javafx.scene.web.WebEngine; import javafx.scene.web.WebEvent; import javafx.scene.web.WebView; import javafx.stage.Stage; import netscape.javascript.JSObject; public class Main extends Application { public static void main(String[] args) { launch(args); } JavaBridge bridge; WebEngine webEngine; @Override public void start(Stage primaryStage) throws MalformedURLException { final URL url = new File("C:/test.html").toURI().toURL(); WebView webView = new javafx.scene.web.WebView(); webEngine = webView.getEngine(); webEngine.load(url.toExternalForm()); webEngine.setJavaScriptEnabled(true); webEngine.setOnAlert(Main::showAlert); webEngine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> { if (newState == State.SUCCEEDED) { System.out.println("READY"); JSObject jsobj = (JSObject) webEngine.executeScript("window"); bridge = new JavaBridge(); jsobj.setMember("bridge", bridge); } }); primaryStage.setScene(new javafx.scene.Scene(webView, 300, 300)); primaryStage.show(); } // Shows the alert, used in JS catch statement private static void showAlert(WebEvent<String> event) { javafx.scene.control.Dialog<ButtonType> alert = new javafx.scene.control.Dialog<>(); alert.getDialogPane().setContentText(event.getData()); alert.getDialogPane().getButtonTypes().add(ButtonType.OK); alert.showAndWait(); } public class JavaBridge { public void hello() { System.out.println("hello"); } } } ``` with `test.html` containing the Javascript: ```js <button onclick="try{bridge.hello();}catch(err){alert(err.message);}">call java</button> ``` What's going on? I get the following error when clicking the button: `bridge.hello is not a function. (In 'bridge.hello()', 'bridge.hello' is undefined)`
2019/12/29
[ "https://Stackoverflow.com/questions/59516851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11329518/" ]
I can't reproduce your issue with JavaFX 13 or 14-ea+6, using Java 11 (OpenJDK 11.0.2) or Java 13 (OpenJDK 13). However I can reproduce the issue, if I remove the strong reference to `JavaBridge` and I use Java 11. This: ``` jsobj.setMember("bridge", new JavaBridge()); ``` fails with the same error you have posted, with Java 11. But when using Java 13 (OpenJDK 13), that works fine (and also with Java 12). Are you using other Java vendors? Can you try with OpenJDK <https://jdk.java.net/13/>?
There are two things that resolved this issue with OpenJDK 14 and JavaFx 14 1. Hard Reference to Bridge Object ``` bridge = new JavaBridge(); // create Bridge before hand webEngine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> { if (newState == State.SUCCEEDED) { System.out.println("READY"); JSObject jsobj = (JSObject) webEngine.executeScript("window"); jsobj.setMember("bridge", bridge); } }); ``` 2. Use Bridge in Javascript/HTML page after the page is loaded ``` window.onload = function() { bridge.hello(); } ```
38,705,126
I've been able to set up a toy app with the following code taken from YouTube's sample ruby [projects](https://github.com/youtube/api-samples/blob/master/ruby/search.rb). I'm looking to use YouTube to search for artists channels, playlists, videos. No issues with the sample toy app but can't get the same code working in Rails. After successfully searching YouTube's API and manipulating the response, I've tried importing some of this code into an existing rails app. I initially put the following code into a new initializer in my `config` directory but when trying to load rails console to play with the query, I'm receiving the following error: "NameError: uninitialized constant Google" ``` require 'google/api_client client = Google::APIClient.new( :key => "XXXXXXXXXXX", :authorization => nil, :application_name => $PROGRAM_NAME, :application_version => '1.0.0' ) ``` Gemfile: ``` gem 'google-api-client', '0.9' ``` I know there's been some updates to the API but having trouble tracking down exactly what I need to do.
2016/08/01
[ "https://Stackoverflow.com/questions/38705126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3505369/" ]
`[System.Net.ServicePointManager]::DefaultConnectionLimit = 1024` before the request creation solved the problem.
[The timeout property that you're setting to `100` is in milliseconds](https://msdn.microsoft.com/en-us/library/system.net.webrequest.timeout%28v=vs.110%29.aspx). That's pretty short. Might want to set it to a few seconds. It happens because the server side took longer than that amount of time to actually send the data. It may have sent a 200 response but the entire request did not complete in the time allotted. Definitely possible if you're sending a lot of requests at once.
43,544,299
I'm using this : ``` string url = string.Format("https://maps.googleapis.com/maps/api/timezone/json?location={0},{1}&timestamp=1374868635&sensor=false", lat, lon); using (HttpClient cl = new HttpClient()) { string json = await cl.GetStringAsync(url).ConfigureAwait(false); TimeZoneModel timezone = new JavaScriptSerializer().Deserialize<TimeZoneModel>(json); } ``` To get user timezone. This works fine. I want to convert this : ``` "timeZoneName" : "Central European Summer Time" ``` To .net timezone ? In .net Timezone that timezone does not exists. I tried to get proper timezone with : ``` TimeZoneInfo tzf = TimeZoneInfo.FindSystemTimeZoneById("Central European Summer Time"); ``` Any idea how to convert google timezone to .net timezone ? Is that possible ? Thank you guys in advance !
2017/04/21
[ "https://Stackoverflow.com/questions/43544299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7739945/" ]
Instead of using `timeZoneName`, I'd suggest using `timeZoneId`, which will be an IANA ID such as `Europe/London`. You then have various options: * Find a mapping from that to Windows time zone IDs yourself, e.g. with [TimeZoneConverter](https://www.nuget.org/packages/TimeZoneConverter/) * Use [Noda Time](http://nodatime.org) and map the time zone to a Windows time zone using `TzdbDateTimeZoneSource`, e.g. with `TzdbDateTimeZoneSource.WindowsMapping`. See [this answer](https://stackoverflow.com/a/25092899/1774334) for sample code. * Use Noda Time and *don't* map it to a Windows time zone - just use the Noda Time `DateTimeZone` instead, and use Noda Time throughout your app, for a better date/time experience in general Obviously I favour the last option, but I'm biased as the main author of Noda Time...
" Find a mapping from that to Windows time zone IDs yourself, e.g. with TimeZoneConverter " The example usage from the docs: ``` string tz = TZConvert.IanaToWindows("America/New_York"); // Result: "Eastern Standard Time" ``` <https://github.com/mattjohnsonpint/TimeZoneConverter>
36,130,282
I am trying to set-up a workspace with Node, Express, Angular2 (Database,- MongoDB or SQL) But I am not sure how to correctly set it up combined. My file structure looks like this so far, and I intend to put the front-end under the public folder. ``` ── package.json ├── public ├── routes │   └── test.js ├── server.js └── views ``` So far my my **server.js** looks like this ``` var express = require('express'); var mysql = require('mysql'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var path = require('path'); var lel = require('./routes/test'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false})); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/api/', test); app.use(function(req, res, next) { // error handling }); var server = app.listen(3000, function() { // shows the connection etc }); module.exports = app; ``` My **test.js** is where I handle my API calls under /api/test. And this is how my **package.json** looks like, with a script for npm, that will start the server with `npm start` And all the required dependencies, that can be downloaded with `npm install` ``` { "name": "testing", "version": "0.1.0", "description": "-", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node server.js" }, "author": "-", "license": "-", "dependencies": { "body-parser": "^1.15.0", "cookie-parser": "^1.4.1", "ejs": "^2.4.1", "express": "^4.13.4", "morgan": "^1.7.0", "mysql": "^2.10.2", "path": "^0.12.7" } } ``` Now my question is how do I add Angular2 to work properly under public and so they start up together at `npm start`. I have been following the quickstart at Angulars documentation site, and noticed they use lite-server, but that shouldn't be necessary with node/express right? How should my **package.json** look like after Angular2 is added. For example like this: ``` ├── package.json ├── public │   ├── app │   │   ├── app.component.js │   │   └── main.js │   └── index.html ├── routes │   └── test.js ├── server.js └── views ``` If it is still too early with Angular2, then I have the same question but with Angular1.X, or perhaps is it better to use Angular2 with TS?
2016/03/21
[ "https://Stackoverflow.com/questions/36130282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1731280/" ]
I was curious about the same setup and was able to write a simple, using NG2 RC1, [example](https://github.com/CoolHandDev/ng2-express) on how to run NG2 on Express. Setup is not straightforward compared to NG1 and the key to NG2 on Express is making sure SystemJS knows where to find the libraries Here are the key things that you should look into. Please note that it is not recommended to expose node\_modules. I want my example to be simple so focus can be easily placed on learning basic setup. 1. Expose the location of static resources (index.html) and dependencies (node\_modules) ```js app.use(express.static(rootPath + '/client/app')) app.use('/node_modules', express.static(rootPath + '/node_modules')); ``` 2. Let SystemJS know where to find dependencies ```js System.config({ map: { "@angular": "node_modules/@angular", "rxjs": "node_modules/rxjs" }, packages: { '/': { //format: 'register', defaultExtension: 'js' }, 'node_modules/@angular/http': { //format: 'cjs', defaultExtension: 'js', main: 'http.js' }, 'node_modules/@angular/core': { //format: 'cjs', defaultExtension: 'js', main: 'index.js' }, 'node_modules/@angular/router': { //format: 'cjs', defaultExtension: 'js', main: 'index.js' }, 'node_modules/@angular/router-deprecated': { //format: 'cjs', defaultExtension: 'js', main: 'index.js' }, 'node_modules/@angular/platform-browser-dynamic': { //format: 'cjs', defaultExtension: 'js', main: 'index.js' }, 'node_modules/@angular/platform-browser': { //format: 'cjs', defaultExtension: 'js', main: 'index.js' }, 'node_modules/@angular/compiler': { //format: 'cjs', defaultExtension: 'js', main: 'compiler.js' }, 'node_modules/@angular/common': { //format: 'cjs', defaultExtension: 'js', main: 'index.js' }, 'rxjs' : { defaultExtension: 'js' } } }); System.import('./main').then(null, console.error.bind(console)); ``` [Please have a look at my example on GitHub](https://github.com/CoolHandDev/ng2-express)
You can use [a generator which will create the basic directories and files to get started](https://www.npmjs.com/package/generator-express-angular) Later any database can be used by installing its plugin from npm.
37,241
Got a scooter recently which I leave parked on the street while at work. A couple of days ago I was about to ride it home when I noticed a note saying that this person tried to parallel park near it and tipped it over. I know very little about scooters and what kind of damage is possible when something like this happens. Do you have any advice on what to check to make sure it's safe to ride both short and long term? I did basic things: minor cosmetic scratches, it starts fine, rode it slowly on residential street back home etc -- everything looks ok on the surface. But I would like to understand whether it's possible that there's some not obvious damage.
2016/10/10
[ "https://mechanics.stackexchange.com/questions/37241", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/2762/" ]
A scooter is quite rigid for its weight and size, and there shouldn't happen much more than some scratches, broken mirrors etc. There are just two issues I can think of: * If the scooter fell hard on a brake lever, this could have damaged the lever itself or for example one of the gaskets inside, when it's a hydraulic brake. Obvious signs would be a brake fluid leakage, usually at the lever or at the brake, or when you can just pull the lever onto the grip. At least, you should be able to say if the scooter acually did fell on the lever from the scratches. If not, don't worry. * Liquids. It's clear that oil and fuel could have leaked out, which is a mess, but usually not really a problem, except it got on the brakes. This can also lead to some starting problems, but that's it. But most scooters still have an old style, not sealed battery, which could have leaked. The acid is typically dumped to the street through a hose, so no problem for the scooter. But it's now missing in the battery, and you can't simply top it up with distilled water. I'd suggest you inspect the battery and the acid levels. However, liquids leak out slowly, so if the scooter was tipped over and put up directly after, this shouldn't be an issue. Your last question is a legal one and can't be answered without knowing the country, and this is also not the right place for it. But in general, an inspection is the first step of an repair, so it sounds reasonable that the guy has to pay for it.
Only thing you have to worry about is just make sure there’s no oil in your airbox if the bike wasn’t running then you don’t have much to worry about except top it off with some gas don’t start it immediately be patient most likely it will start like I said if it fell over when it wasn’t running shouldn’t be too bad except the damage otherwise be patient it will start again check oil in the airbox. If it fell over for a long period of time most likely the oil has drained into the head and into the air filter system so most likely you’re gonna need to change the oil and like I said in the beginning do not start the bike immediately be patient go over all the checking most important is the oil obviously you’re gonna need gas it will be all over the ground so you’ll notice it check your battery if it was drained out don’t try to fill it just get a new battery it’s not worth your eye damage or loss of your fingers and just be patient
6,073,910
For example, how can I use `System.Console.WriteLine` from clojure-clr? In general, what's the rule for exporting/importing functions/classes from other languages such as C#/F# from/to Clojure-clr?
2011/05/20
[ "https://Stackoverflow.com/questions/6073910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
System.Console is loaded by default. You can simply use: ``` (System.Console/WriteLine "Hello World!") ``` Another example, using a static class: ``` (import (System.IO Path)) (println (Path/GetFullPath ".")) ```
in Java, instantiating the *Date* object, then calls its *toString()* method, you have to write like the following, ``` user=> (. (new java.util.Date) (toString)) ```
58,768,736
Created an Azure SQL server machine and I am able to rdp as well as connect via the local SQL Server Mgt Studio client. However I cannot connect to the same instance via Java code using the connection string further below. * I am using the latest JDBC Driver (Microsoft JDBC Driver 7.4) * I am using SQL Server 2017 Express * I am able to connect manually via SQL Server Mgt Studio client on local machine Here is the error message: > > com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not > establish a secure connection to SQL Server by using Secure Sockets > Layer (SSL) encryption. Error: > "sun.security.validator.ValidatorException: PKIX path building failed: > sun.security.provider.certpath.SunCertPathBuilderException: unable to > find valid certification path to requested target". > ClientConnectionId:xxxxxxxxxxxxxxxxxx > > > Here is the connection string: > > jdbc:sqlserver://Server=nn.nnn.nnn.nnn;Integrated Security=false;User > ID=myusername;Password=mypassword > > > Thanks for your help!
2019/11/08
[ "https://Stackoverflow.com/questions/58768736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212412/" ]
I got this to work by changing in the connection string: ``` encrypt=true ``` **into** ``` encrypt=false ``` Not sure this is the best solution but at least I can carry on developement.
It seems to be caused by the driver not finding a certificate that it trusts. If you do have a relevant certificate installed and are working on your localhost (meaning that it's probably self-signed and therefore wouldn't be trusted otherwise), try adding this to the end of your connection string: `trustServerCertificate=true` If it's a different machine you're working on, you may need to take a look at the validity of the certificate that it should be using. Microsoft also now has more information about SSL connections to SQL Server [here](https://learn.microsoft.com/en-us/sql/connect/jdbc/connecting-with-ssl-encryption).
4,347,374
I've just started reading through [Core JavaServer Faces, 3rd Ed.](http://horstmann.com/corejsf/) and they say this (emphasis mine): > > It is a historical accident that there are two separate mechanisms, CDI beans > and JSF managed beans, for beans that can be used in JSF pages. **We suggest > that you use CDI beans** unless your application must work on a plain servlet > runner such as Tomcat. > > > Why? They don't provide **any** justification. I've been using `@ManagedBean` for all the beans in a prototype application running on GlassFish 3, and I haven't really noticed any issues with this. I don't especially mind migrating from `@ManagedBean` to `@Named`, but I want to know **why I should bother**.
2010/12/03
[ "https://Stackoverflow.com/questions/4347374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139010/" ]
Use CDI. ======== As per JSF 2.3, `@ManagedBean` is **deprecated**. See also [spec issue 1417](https://github.com/javaee/javaserverfaces-spec/issues/1417). This means that there's not anymore a reason to choose `@ManagedBean` over `@Named`. This was first implemented in Mojarra 2.3.0 beta version m06. [![enter image description here](https://i.stack.imgur.com/YdG3r.png)](https://i.stack.imgur.com/YdG3r.png) Since Faces 4.0, the `@ManagedBean` has been **removed** as per spec [issue 1547](https://github.com/jakartaee/faces/issues/1547). --- ### History The core difference is, [`@ManagedBean`](https://jakarta.ee/specifications/platform/8/apidocs/javax/faces/bean/managedbean) is managed by JSF framework and is only via [`@ManagedProperty`](https://jakarta.ee/specifications/platform/8/apidocs/javax/faces/bean/managedproperty) available to another JSF managed beans. [`@Named`](https://jakarta.ee/specifications/platform/8/apidocs/javax/inject/named) is managed by application server (the container) via CDI framework and is via [`@Inject`](https://jakarta.ee/specifications/platform/8/apidocs/javax/inject/inject) available to any kind of a container managed artifact like `@WebListener`, `@WebFilter`, `@WebServlet`, `@Path`, `@Stateless`, etc and even a JSF `@ManagedBean`. From the other side on, `@ManagedProperty` does **not** work inside a `@Named` or any other container managed artifact. It works really only inside `@ManagedBean`. Another difference is that CDI actually injects proxies delegating to the current instance in the target scope on a per-request/thread basis (like as how EJBs are been injected). This mechanism allows injecting a bean of a narrower scope in a bean of a broader scope, which isn't possible with JSF `@ManagedProperty`. JSF "injects" here the physical instance directly by invoking a setter (that's also exactly why a setter is required, while that is **not** required with `@Inject`). While not directly a disadvantage — there are other ways — the scope of `@ManagedBean` is simply limited. From the other perspective, if you don't want to expose "too much" for `@Inject`, you can also just keep your managed beans `@ManagedBean`. It's like `protected` versus `public`. But that doesn't really count. At least, in JSF 2.0/2.1, the major disadvantage of managing JSF backing beans by CDI is that there's no CDI equivalent of `@ViewScoped`. The `@ConversationScoped` comes close, but still requires manually starting and stopping and it appends an ugly `cid` request parameter to outcome URLs. MyFaces CODI makes it easier by fully transparently bridging JSF's `javax.faces.bean.ViewScoped` to CDI so you can just do `@Named @ViewScoped`, however that appends an ugly `windowId` request parameter to outcome URLs, also on plain vanilla page-to-page navigation. [OmniFaces](https://omnifaces.org) solves this all with a true CDI [`@ViewScoped`](https://showcase.omnifaces.org/cdi/ViewScoped) which really ties the bean's scope to JSF view state instead of to an arbitrary request parameter. JSF 2.2 (which is released 3 years after this question/answer) offers a new fully CDI compatible `@ViewScoped` annotation out the box in flavor of `javax.faces.view.ViewScoped`. JSF 2.2 even comes along with a CDI-only `@FlowScoped` which doesn't have a `@ManagedBean` equivalent, hereby pushing JSF users towards CDI. The expectation is that `@ManagedBean` and friends will be deprecated as per Java EE 8. If you're currently still using `@ManagedBean`, it's therefore strongly recommend to switch to CDI to be prepared for future upgrade paths. CDI is readily available in Java EE Web Profile compatible containers, such as WildFly, TomEE and GlassFish. For Tomcat, you have to install it separately, exactly as you already did for JSF. See also [How to install CDI in Tomcat?](https://balusc.omnifaces.org/2013/10/how-to-install-cdi-in-tomcat.html)
CDI is preferred over plain JSF because CDI allows for JavaEE-wide dependency injection. You can also inject POJOs and let them be managed. With JSF you can only inject a subset of what you can with CDI.
4,347,374
I've just started reading through [Core JavaServer Faces, 3rd Ed.](http://horstmann.com/corejsf/) and they say this (emphasis mine): > > It is a historical accident that there are two separate mechanisms, CDI beans > and JSF managed beans, for beans that can be used in JSF pages. **We suggest > that you use CDI beans** unless your application must work on a plain servlet > runner such as Tomcat. > > > Why? They don't provide **any** justification. I've been using `@ManagedBean` for all the beans in a prototype application running on GlassFish 3, and I haven't really noticed any issues with this. I don't especially mind migrating from `@ManagedBean` to `@Named`, but I want to know **why I should bother**.
2010/12/03
[ "https://Stackoverflow.com/questions/4347374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139010/" ]
Use CDI. ======== As per JSF 2.3, `@ManagedBean` is **deprecated**. See also [spec issue 1417](https://github.com/javaee/javaserverfaces-spec/issues/1417). This means that there's not anymore a reason to choose `@ManagedBean` over `@Named`. This was first implemented in Mojarra 2.3.0 beta version m06. [![enter image description here](https://i.stack.imgur.com/YdG3r.png)](https://i.stack.imgur.com/YdG3r.png) Since Faces 4.0, the `@ManagedBean` has been **removed** as per spec [issue 1547](https://github.com/jakartaee/faces/issues/1547). --- ### History The core difference is, [`@ManagedBean`](https://jakarta.ee/specifications/platform/8/apidocs/javax/faces/bean/managedbean) is managed by JSF framework and is only via [`@ManagedProperty`](https://jakarta.ee/specifications/platform/8/apidocs/javax/faces/bean/managedproperty) available to another JSF managed beans. [`@Named`](https://jakarta.ee/specifications/platform/8/apidocs/javax/inject/named) is managed by application server (the container) via CDI framework and is via [`@Inject`](https://jakarta.ee/specifications/platform/8/apidocs/javax/inject/inject) available to any kind of a container managed artifact like `@WebListener`, `@WebFilter`, `@WebServlet`, `@Path`, `@Stateless`, etc and even a JSF `@ManagedBean`. From the other side on, `@ManagedProperty` does **not** work inside a `@Named` or any other container managed artifact. It works really only inside `@ManagedBean`. Another difference is that CDI actually injects proxies delegating to the current instance in the target scope on a per-request/thread basis (like as how EJBs are been injected). This mechanism allows injecting a bean of a narrower scope in a bean of a broader scope, which isn't possible with JSF `@ManagedProperty`. JSF "injects" here the physical instance directly by invoking a setter (that's also exactly why a setter is required, while that is **not** required with `@Inject`). While not directly a disadvantage — there are other ways — the scope of `@ManagedBean` is simply limited. From the other perspective, if you don't want to expose "too much" for `@Inject`, you can also just keep your managed beans `@ManagedBean`. It's like `protected` versus `public`. But that doesn't really count. At least, in JSF 2.0/2.1, the major disadvantage of managing JSF backing beans by CDI is that there's no CDI equivalent of `@ViewScoped`. The `@ConversationScoped` comes close, but still requires manually starting and stopping and it appends an ugly `cid` request parameter to outcome URLs. MyFaces CODI makes it easier by fully transparently bridging JSF's `javax.faces.bean.ViewScoped` to CDI so you can just do `@Named @ViewScoped`, however that appends an ugly `windowId` request parameter to outcome URLs, also on plain vanilla page-to-page navigation. [OmniFaces](https://omnifaces.org) solves this all with a true CDI [`@ViewScoped`](https://showcase.omnifaces.org/cdi/ViewScoped) which really ties the bean's scope to JSF view state instead of to an arbitrary request parameter. JSF 2.2 (which is released 3 years after this question/answer) offers a new fully CDI compatible `@ViewScoped` annotation out the box in flavor of `javax.faces.view.ViewScoped`. JSF 2.2 even comes along with a CDI-only `@FlowScoped` which doesn't have a `@ManagedBean` equivalent, hereby pushing JSF users towards CDI. The expectation is that `@ManagedBean` and friends will be deprecated as per Java EE 8. If you're currently still using `@ManagedBean`, it's therefore strongly recommend to switch to CDI to be prepared for future upgrade paths. CDI is readily available in Java EE Web Profile compatible containers, such as WildFly, TomEE and GlassFish. For Tomcat, you have to install it separately, exactly as you already did for JSF. See also [How to install CDI in Tomcat?](https://balusc.omnifaces.org/2013/10/how-to-install-cdi-in-tomcat.html)
With Java EE 6 and CDI you have different option for Managed Beans * `@javax.faces.bean.ManagedBean` is refer to JSR 314 and was introduced with JSF 2.0. The main goal was to avoid the configuration in the faces-config.xml file to use the bean inside an JSF Page. * `@javax.annotation.ManagedBean(“myBean”)` is defined by JSR 316. It generalizes the JSF managed beans for use elsewhere in Java EE * `@javax.inject.Named(“myBean”)` are almost the same, as that one above, except you need a beans.xml file in the web/WEB-INF Folder to activate CDI.
4,347,374
I've just started reading through [Core JavaServer Faces, 3rd Ed.](http://horstmann.com/corejsf/) and they say this (emphasis mine): > > It is a historical accident that there are two separate mechanisms, CDI beans > and JSF managed beans, for beans that can be used in JSF pages. **We suggest > that you use CDI beans** unless your application must work on a plain servlet > runner such as Tomcat. > > > Why? They don't provide **any** justification. I've been using `@ManagedBean` for all the beans in a prototype application running on GlassFish 3, and I haven't really noticed any issues with this. I don't especially mind migrating from `@ManagedBean` to `@Named`, but I want to know **why I should bother**.
2010/12/03
[ "https://Stackoverflow.com/questions/4347374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139010/" ]
Use CDI. ======== As per JSF 2.3, `@ManagedBean` is **deprecated**. See also [spec issue 1417](https://github.com/javaee/javaserverfaces-spec/issues/1417). This means that there's not anymore a reason to choose `@ManagedBean` over `@Named`. This was first implemented in Mojarra 2.3.0 beta version m06. [![enter image description here](https://i.stack.imgur.com/YdG3r.png)](https://i.stack.imgur.com/YdG3r.png) Since Faces 4.0, the `@ManagedBean` has been **removed** as per spec [issue 1547](https://github.com/jakartaee/faces/issues/1547). --- ### History The core difference is, [`@ManagedBean`](https://jakarta.ee/specifications/platform/8/apidocs/javax/faces/bean/managedbean) is managed by JSF framework and is only via [`@ManagedProperty`](https://jakarta.ee/specifications/platform/8/apidocs/javax/faces/bean/managedproperty) available to another JSF managed beans. [`@Named`](https://jakarta.ee/specifications/platform/8/apidocs/javax/inject/named) is managed by application server (the container) via CDI framework and is via [`@Inject`](https://jakarta.ee/specifications/platform/8/apidocs/javax/inject/inject) available to any kind of a container managed artifact like `@WebListener`, `@WebFilter`, `@WebServlet`, `@Path`, `@Stateless`, etc and even a JSF `@ManagedBean`. From the other side on, `@ManagedProperty` does **not** work inside a `@Named` or any other container managed artifact. It works really only inside `@ManagedBean`. Another difference is that CDI actually injects proxies delegating to the current instance in the target scope on a per-request/thread basis (like as how EJBs are been injected). This mechanism allows injecting a bean of a narrower scope in a bean of a broader scope, which isn't possible with JSF `@ManagedProperty`. JSF "injects" here the physical instance directly by invoking a setter (that's also exactly why a setter is required, while that is **not** required with `@Inject`). While not directly a disadvantage — there are other ways — the scope of `@ManagedBean` is simply limited. From the other perspective, if you don't want to expose "too much" for `@Inject`, you can also just keep your managed beans `@ManagedBean`. It's like `protected` versus `public`. But that doesn't really count. At least, in JSF 2.0/2.1, the major disadvantage of managing JSF backing beans by CDI is that there's no CDI equivalent of `@ViewScoped`. The `@ConversationScoped` comes close, but still requires manually starting and stopping and it appends an ugly `cid` request parameter to outcome URLs. MyFaces CODI makes it easier by fully transparently bridging JSF's `javax.faces.bean.ViewScoped` to CDI so you can just do `@Named @ViewScoped`, however that appends an ugly `windowId` request parameter to outcome URLs, also on plain vanilla page-to-page navigation. [OmniFaces](https://omnifaces.org) solves this all with a true CDI [`@ViewScoped`](https://showcase.omnifaces.org/cdi/ViewScoped) which really ties the bean's scope to JSF view state instead of to an arbitrary request parameter. JSF 2.2 (which is released 3 years after this question/answer) offers a new fully CDI compatible `@ViewScoped` annotation out the box in flavor of `javax.faces.view.ViewScoped`. JSF 2.2 even comes along with a CDI-only `@FlowScoped` which doesn't have a `@ManagedBean` equivalent, hereby pushing JSF users towards CDI. The expectation is that `@ManagedBean` and friends will be deprecated as per Java EE 8. If you're currently still using `@ManagedBean`, it's therefore strongly recommend to switch to CDI to be prepared for future upgrade paths. CDI is readily available in Java EE Web Profile compatible containers, such as WildFly, TomEE and GlassFish. For Tomcat, you have to install it separately, exactly as you already did for JSF. See also [How to install CDI in Tomcat?](https://balusc.omnifaces.org/2013/10/how-to-install-cdi-in-tomcat.html)
I was using CDI in GlassFish 3.0.1, but to get it to work I had to import the Seam 3 framework (Weld). That worked pretty well. In GlassFish 3.1 CDI stopped working, and the Seam Weld stopped working with it. I opened a [bug on this](http://java.net/jira/browse/GLASSFISH-14841) but haven't seen it fixed yet. I had to convert all my code to using the javax.faces.\* annotations but I plan to move back to CDI once they get it working. I agree you should use CDI, but one issue that I haven't seen resolved yet is what to do with the @ViewScoped annotation. I have a lot of code that depends on it. It is not clear whether @ViewScoped works if you are not using @ManagedBean with it. If anyone can clarify this I would appreciate it.
4,347,374
I've just started reading through [Core JavaServer Faces, 3rd Ed.](http://horstmann.com/corejsf/) and they say this (emphasis mine): > > It is a historical accident that there are two separate mechanisms, CDI beans > and JSF managed beans, for beans that can be used in JSF pages. **We suggest > that you use CDI beans** unless your application must work on a plain servlet > runner such as Tomcat. > > > Why? They don't provide **any** justification. I've been using `@ManagedBean` for all the beans in a prototype application running on GlassFish 3, and I haven't really noticed any issues with this. I don't especially mind migrating from `@ManagedBean` to `@Named`, but I want to know **why I should bother**.
2010/12/03
[ "https://Stackoverflow.com/questions/4347374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139010/" ]
Use CDI. ======== As per JSF 2.3, `@ManagedBean` is **deprecated**. See also [spec issue 1417](https://github.com/javaee/javaserverfaces-spec/issues/1417). This means that there's not anymore a reason to choose `@ManagedBean` over `@Named`. This was first implemented in Mojarra 2.3.0 beta version m06. [![enter image description here](https://i.stack.imgur.com/YdG3r.png)](https://i.stack.imgur.com/YdG3r.png) Since Faces 4.0, the `@ManagedBean` has been **removed** as per spec [issue 1547](https://github.com/jakartaee/faces/issues/1547). --- ### History The core difference is, [`@ManagedBean`](https://jakarta.ee/specifications/platform/8/apidocs/javax/faces/bean/managedbean) is managed by JSF framework and is only via [`@ManagedProperty`](https://jakarta.ee/specifications/platform/8/apidocs/javax/faces/bean/managedproperty) available to another JSF managed beans. [`@Named`](https://jakarta.ee/specifications/platform/8/apidocs/javax/inject/named) is managed by application server (the container) via CDI framework and is via [`@Inject`](https://jakarta.ee/specifications/platform/8/apidocs/javax/inject/inject) available to any kind of a container managed artifact like `@WebListener`, `@WebFilter`, `@WebServlet`, `@Path`, `@Stateless`, etc and even a JSF `@ManagedBean`. From the other side on, `@ManagedProperty` does **not** work inside a `@Named` or any other container managed artifact. It works really only inside `@ManagedBean`. Another difference is that CDI actually injects proxies delegating to the current instance in the target scope on a per-request/thread basis (like as how EJBs are been injected). This mechanism allows injecting a bean of a narrower scope in a bean of a broader scope, which isn't possible with JSF `@ManagedProperty`. JSF "injects" here the physical instance directly by invoking a setter (that's also exactly why a setter is required, while that is **not** required with `@Inject`). While not directly a disadvantage — there are other ways — the scope of `@ManagedBean` is simply limited. From the other perspective, if you don't want to expose "too much" for `@Inject`, you can also just keep your managed beans `@ManagedBean`. It's like `protected` versus `public`. But that doesn't really count. At least, in JSF 2.0/2.1, the major disadvantage of managing JSF backing beans by CDI is that there's no CDI equivalent of `@ViewScoped`. The `@ConversationScoped` comes close, but still requires manually starting and stopping and it appends an ugly `cid` request parameter to outcome URLs. MyFaces CODI makes it easier by fully transparently bridging JSF's `javax.faces.bean.ViewScoped` to CDI so you can just do `@Named @ViewScoped`, however that appends an ugly `windowId` request parameter to outcome URLs, also on plain vanilla page-to-page navigation. [OmniFaces](https://omnifaces.org) solves this all with a true CDI [`@ViewScoped`](https://showcase.omnifaces.org/cdi/ViewScoped) which really ties the bean's scope to JSF view state instead of to an arbitrary request parameter. JSF 2.2 (which is released 3 years after this question/answer) offers a new fully CDI compatible `@ViewScoped` annotation out the box in flavor of `javax.faces.view.ViewScoped`. JSF 2.2 even comes along with a CDI-only `@FlowScoped` which doesn't have a `@ManagedBean` equivalent, hereby pushing JSF users towards CDI. The expectation is that `@ManagedBean` and friends will be deprecated as per Java EE 8. If you're currently still using `@ManagedBean`, it's therefore strongly recommend to switch to CDI to be prepared for future upgrade paths. CDI is readily available in Java EE Web Profile compatible containers, such as WildFly, TomEE and GlassFish. For Tomcat, you have to install it separately, exactly as you already did for JSF. See also [How to install CDI in Tomcat?](https://balusc.omnifaces.org/2013/10/how-to-install-cdi-in-tomcat.html)
One good reason to move to CDI: you could have a common session-scoped resource (user profile for example) `@Inject`'ed into both JSF managed beans and REST services (i.e., Jersey/JAX-RS). On the other hand, `@ViewScoped` is a compelling reason to stick with JSF `@ManagedBean` - especially for anything with significant AJAX. There is no standard replacement for this in CDI. Seems that it may have some support for a `@ViewScoped`-like annotation for CDI beans, but I haven't played with it personally. <http://seamframework.org/Seam3/FacesModule>
4,347,374
I've just started reading through [Core JavaServer Faces, 3rd Ed.](http://horstmann.com/corejsf/) and they say this (emphasis mine): > > It is a historical accident that there are two separate mechanisms, CDI beans > and JSF managed beans, for beans that can be used in JSF pages. **We suggest > that you use CDI beans** unless your application must work on a plain servlet > runner such as Tomcat. > > > Why? They don't provide **any** justification. I've been using `@ManagedBean` for all the beans in a prototype application running on GlassFish 3, and I haven't really noticed any issues with this. I don't especially mind migrating from `@ManagedBean` to `@Named`, but I want to know **why I should bother**.
2010/12/03
[ "https://Stackoverflow.com/questions/4347374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139010/" ]
CDI is preferred over plain JSF because CDI allows for JavaEE-wide dependency injection. You can also inject POJOs and let them be managed. With JSF you can only inject a subset of what you can with CDI.
With Java EE 6 and CDI you have different option for Managed Beans * `@javax.faces.bean.ManagedBean` is refer to JSR 314 and was introduced with JSF 2.0. The main goal was to avoid the configuration in the faces-config.xml file to use the bean inside an JSF Page. * `@javax.annotation.ManagedBean(“myBean”)` is defined by JSR 316. It generalizes the JSF managed beans for use elsewhere in Java EE * `@javax.inject.Named(“myBean”)` are almost the same, as that one above, except you need a beans.xml file in the web/WEB-INF Folder to activate CDI.
4,347,374
I've just started reading through [Core JavaServer Faces, 3rd Ed.](http://horstmann.com/corejsf/) and they say this (emphasis mine): > > It is a historical accident that there are two separate mechanisms, CDI beans > and JSF managed beans, for beans that can be used in JSF pages. **We suggest > that you use CDI beans** unless your application must work on a plain servlet > runner such as Tomcat. > > > Why? They don't provide **any** justification. I've been using `@ManagedBean` for all the beans in a prototype application running on GlassFish 3, and I haven't really noticed any issues with this. I don't especially mind migrating from `@ManagedBean` to `@Named`, but I want to know **why I should bother**.
2010/12/03
[ "https://Stackoverflow.com/questions/4347374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139010/" ]
CDI is preferred over plain JSF because CDI allows for JavaEE-wide dependency injection. You can also inject POJOs and let them be managed. With JSF you can only inject a subset of what you can with CDI.
I was using CDI in GlassFish 3.0.1, but to get it to work I had to import the Seam 3 framework (Weld). That worked pretty well. In GlassFish 3.1 CDI stopped working, and the Seam Weld stopped working with it. I opened a [bug on this](http://java.net/jira/browse/GLASSFISH-14841) but haven't seen it fixed yet. I had to convert all my code to using the javax.faces.\* annotations but I plan to move back to CDI once they get it working. I agree you should use CDI, but one issue that I haven't seen resolved yet is what to do with the @ViewScoped annotation. I have a lot of code that depends on it. It is not clear whether @ViewScoped works if you are not using @ManagedBean with it. If anyone can clarify this I would appreciate it.
4,347,374
I've just started reading through [Core JavaServer Faces, 3rd Ed.](http://horstmann.com/corejsf/) and they say this (emphasis mine): > > It is a historical accident that there are two separate mechanisms, CDI beans > and JSF managed beans, for beans that can be used in JSF pages. **We suggest > that you use CDI beans** unless your application must work on a plain servlet > runner such as Tomcat. > > > Why? They don't provide **any** justification. I've been using `@ManagedBean` for all the beans in a prototype application running on GlassFish 3, and I haven't really noticed any issues with this. I don't especially mind migrating from `@ManagedBean` to `@Named`, but I want to know **why I should bother**.
2010/12/03
[ "https://Stackoverflow.com/questions/4347374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139010/" ]
CDI is preferred over plain JSF because CDI allows for JavaEE-wide dependency injection. You can also inject POJOs and let them be managed. With JSF you can only inject a subset of what you can with CDI.
One good reason to move to CDI: you could have a common session-scoped resource (user profile for example) `@Inject`'ed into both JSF managed beans and REST services (i.e., Jersey/JAX-RS). On the other hand, `@ViewScoped` is a compelling reason to stick with JSF `@ManagedBean` - especially for anything with significant AJAX. There is no standard replacement for this in CDI. Seems that it may have some support for a `@ViewScoped`-like annotation for CDI beans, but I haven't played with it personally. <http://seamframework.org/Seam3/FacesModule>
4,347,374
I've just started reading through [Core JavaServer Faces, 3rd Ed.](http://horstmann.com/corejsf/) and they say this (emphasis mine): > > It is a historical accident that there are two separate mechanisms, CDI beans > and JSF managed beans, for beans that can be used in JSF pages. **We suggest > that you use CDI beans** unless your application must work on a plain servlet > runner such as Tomcat. > > > Why? They don't provide **any** justification. I've been using `@ManagedBean` for all the beans in a prototype application running on GlassFish 3, and I haven't really noticed any issues with this. I don't especially mind migrating from `@ManagedBean` to `@Named`, but I want to know **why I should bother**.
2010/12/03
[ "https://Stackoverflow.com/questions/4347374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139010/" ]
With Java EE 6 and CDI you have different option for Managed Beans * `@javax.faces.bean.ManagedBean` is refer to JSR 314 and was introduced with JSF 2.0. The main goal was to avoid the configuration in the faces-config.xml file to use the bean inside an JSF Page. * `@javax.annotation.ManagedBean(“myBean”)` is defined by JSR 316. It generalizes the JSF managed beans for use elsewhere in Java EE * `@javax.inject.Named(“myBean”)` are almost the same, as that one above, except you need a beans.xml file in the web/WEB-INF Folder to activate CDI.
I was using CDI in GlassFish 3.0.1, but to get it to work I had to import the Seam 3 framework (Weld). That worked pretty well. In GlassFish 3.1 CDI stopped working, and the Seam Weld stopped working with it. I opened a [bug on this](http://java.net/jira/browse/GLASSFISH-14841) but haven't seen it fixed yet. I had to convert all my code to using the javax.faces.\* annotations but I plan to move back to CDI once they get it working. I agree you should use CDI, but one issue that I haven't seen resolved yet is what to do with the @ViewScoped annotation. I have a lot of code that depends on it. It is not clear whether @ViewScoped works if you are not using @ManagedBean with it. If anyone can clarify this I would appreciate it.
4,347,374
I've just started reading through [Core JavaServer Faces, 3rd Ed.](http://horstmann.com/corejsf/) and they say this (emphasis mine): > > It is a historical accident that there are two separate mechanisms, CDI beans > and JSF managed beans, for beans that can be used in JSF pages. **We suggest > that you use CDI beans** unless your application must work on a plain servlet > runner such as Tomcat. > > > Why? They don't provide **any** justification. I've been using `@ManagedBean` for all the beans in a prototype application running on GlassFish 3, and I haven't really noticed any issues with this. I don't especially mind migrating from `@ManagedBean` to `@Named`, but I want to know **why I should bother**.
2010/12/03
[ "https://Stackoverflow.com/questions/4347374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139010/" ]
With Java EE 6 and CDI you have different option for Managed Beans * `@javax.faces.bean.ManagedBean` is refer to JSR 314 and was introduced with JSF 2.0. The main goal was to avoid the configuration in the faces-config.xml file to use the bean inside an JSF Page. * `@javax.annotation.ManagedBean(“myBean”)` is defined by JSR 316. It generalizes the JSF managed beans for use elsewhere in Java EE * `@javax.inject.Named(“myBean”)` are almost the same, as that one above, except you need a beans.xml file in the web/WEB-INF Folder to activate CDI.
One good reason to move to CDI: you could have a common session-scoped resource (user profile for example) `@Inject`'ed into both JSF managed beans and REST services (i.e., Jersey/JAX-RS). On the other hand, `@ViewScoped` is a compelling reason to stick with JSF `@ManagedBean` - especially for anything with significant AJAX. There is no standard replacement for this in CDI. Seems that it may have some support for a `@ViewScoped`-like annotation for CDI beans, but I haven't played with it personally. <http://seamframework.org/Seam3/FacesModule>
4,347,374
I've just started reading through [Core JavaServer Faces, 3rd Ed.](http://horstmann.com/corejsf/) and they say this (emphasis mine): > > It is a historical accident that there are two separate mechanisms, CDI beans > and JSF managed beans, for beans that can be used in JSF pages. **We suggest > that you use CDI beans** unless your application must work on a plain servlet > runner such as Tomcat. > > > Why? They don't provide **any** justification. I've been using `@ManagedBean` for all the beans in a prototype application running on GlassFish 3, and I haven't really noticed any issues with this. I don't especially mind migrating from `@ManagedBean` to `@Named`, but I want to know **why I should bother**.
2010/12/03
[ "https://Stackoverflow.com/questions/4347374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139010/" ]
I was using CDI in GlassFish 3.0.1, but to get it to work I had to import the Seam 3 framework (Weld). That worked pretty well. In GlassFish 3.1 CDI stopped working, and the Seam Weld stopped working with it. I opened a [bug on this](http://java.net/jira/browse/GLASSFISH-14841) but haven't seen it fixed yet. I had to convert all my code to using the javax.faces.\* annotations but I plan to move back to CDI once they get it working. I agree you should use CDI, but one issue that I haven't seen resolved yet is what to do with the @ViewScoped annotation. I have a lot of code that depends on it. It is not clear whether @ViewScoped works if you are not using @ManagedBean with it. If anyone can clarify this I would appreciate it.
One good reason to move to CDI: you could have a common session-scoped resource (user profile for example) `@Inject`'ed into both JSF managed beans and REST services (i.e., Jersey/JAX-RS). On the other hand, `@ViewScoped` is a compelling reason to stick with JSF `@ManagedBean` - especially for anything with significant AJAX. There is no standard replacement for this in CDI. Seems that it may have some support for a `@ViewScoped`-like annotation for CDI beans, but I haven't played with it personally. <http://seamframework.org/Seam3/FacesModule>
46,122,300
There is an example in docs of PHP MongoDB Driver(<http://php.net/manual/en/mongodb-driver-cursor.toarray.php>) , the example code as follow: ``` $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $bulk = new MongoDB\Driver\BulkWrite; $bulk->insert(['x' => 1]); $bulk->insert(['x' => 2]); $bulk->insert(['x' => 3]); $manager->executeBulkWrite('db.collection', $bulk); $query = new MongoDB\Driver\Query([]); $cursor = $manager->executeQuery('db.collection', $query); var_dump($cursor->toArray()); ``` **Question:** I want to insert `$cursor` into mysql,what should I do to it? `toArray()` can change it into an array,but the elements of the array are `BSONDocument`s,they can not be insert mysql.
2017/09/08
[ "https://Stackoverflow.com/questions/46122300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5305592/" ]
You'll want to loop over your array of BSON objects, and insert them to a MySQL table with the same fields. You can use a PDO prepared statement for this, and execute it with values from each respective BSON. ``` $pdoStmt = $pdo->prepare("INSERT INTO MyTable SET x = :x"); foreach ($cursor->toArray() as $bson) { $data = get_object_vars($bson); unset($data["_id"]); $pdoStmt->execute($data); } ``` But this assumes your MySQL table has exactly the same fields as your BSON document. It's likely that the best MySQL table design to be different from your MongoDB document design. These are two different paradigms for storing data. This also assumes your BSON document has simple name-value pairs, where all values are scalars. MySQL doesn't support arrays or anything as subdocuments. This also assumes all your BSON documents have identical structure, that is, the same set of named fields in all documents. You should learn something about relational database design before you attempt this.
Without using `toArray` u can use `iterator_to_array` as below: ``` $resultArray = iterator_to_array($cursor); ```
56,763,528
Assume that I have a database table with the following columns: **ProteinSequence** ``` id (Integer) AASequence (nvarchar(max)) ``` Also assume that this table only has one entry where AASequence = 'PLEINEQMMDLHSSLRTWCYFCYNAALHVPGNLTTQLMAKAMEPNAINIHCSEPTDYQQQGRSAASEWGLGIWQIVNLCHMCLGLYACVKTGSFNGCDGGGFQGIWCCWGSFTDYSLDDALGEKWCKEMRPYAHQINDVLIDMPLEFQHDSSIQWPQKACDNNQSTMTFWLAEKIFTFFQGLKQMDSTFQDNCPHATQNQKAMQVRAGSRATEAYCINTSDFMCLSKKWMAACKTKIVDGFQFSQFCWSNMDWATVYICANLTNWFYTGATSSKLVDQVWRESIVGQMFTHLYCPNVCIVPEYCEEMCFNRSQAQCMSADMCSLRSKQCTTELFCYICAGFLGGNVAWNGQRWWETDMYIEYWLIWTLQWHCNKHMHGCSTESRMHEYDDQQILELKNIHVWPFPGYEEYYTECRPEEMTVMQHTASMGSEAHNDLKNAWILDGSDMIADIWEVNICESQPQWWVNEWGKYLCSHKHDGLIDE' When I perform the following query on it: ``` SELECT TOP 1 AASequence, LOWER(CONVERT(VARCHAR(32), HashBytes('MD5', AASequence), 2)) AS noconvertvarcharmd5, LOWER(CONVERT(VARCHAR(32), HashBytes('MD5', CONVERT(VARCHAR, UPPER(AASequence))), 2)) AS uppermd5, FROM [EOI].[dbo].[ProteinSequence] WHERE AASequence = 'PLEINEQMMDLHSSLRTWCYFCYNAALHVPGNLTTQLMAKAMEPNAINIHCSEPTDYQQQGRSAASEWGLGIWQIVNLCHMCLGLYACVKTGSFNGCDGGGFQGIWCCWGSFTDYSLDDALGEKWCKEMRPYAHQINDVLIDMPLEFQHDSSIQWPQKACDNNQSTMTFWLAEKIFTFFQGLKQMDSTFQDNCPHATQNQKAMQVRAGSRATEAYCINTSDFMCLSKKWMAACKTKIVDGFQFSQFCWSNMDWATVYICANLTNWFYTGATSSKLVDQVWRESIVGQMFTHLYCPNVCIVPEYCEEMCFNRSQAQCMSADMCSLRSKQCTTELFCYICAGFLGGNVAWNGQRWWETDMYIEYWLIWTLQWHCNKHMHGCSTESRMHEYDDQQILELKNIHVWPFPGYEEYYTECRPEEMTVMQHTASMGSEAHNDLKNAWILDGSDMIADIWEVNICESQPQWWVNEWGKYLCSHKHDGLIDE'; ``` I get different hash encodings in SQL Server 2017 depending on whether I convert the input sequence or not. Here are the results No conversion: 76efbe0427aa717507930168758c664d With conversion: 85b592208da2d9a2415420009fe56ceb I also discovered that this discrepancy is also not happening on very short strings like "ATCG" Can someone help me understand why this is happening? Context: This behavior was identified during code reviews looking for causes of why we had duplicate entries in the database. Note: We were using MD5 checksums to determine the uniqueness of a string of letters.
2019/06/26
[ "https://Stackoverflow.com/questions/56763528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5848524/" ]
`CONVERT(varchar,upper(AASequence))` truncates to 30 characters, you need to explicitly provide the type length, eg `CONVERT(varchar(500),upper(AASequence))` References: * <https://learn.microsoft.com/en-us/sql/t-sql/data-types/char-and-varchar-transact-sql?view=sql-server-2017> Sqlfiddle: <http://sqlfiddle.com/#!18/b4c4b/5>
The following function calls produce different plaintexts. ``` AASequence CONVERT(varchar,upper(AASequence))) ``` Different plaintexts in = different hashes out. Let AASequence = The quick brown fox jumped over the lazy dog. Then, upper(AASequence) = THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.
8,662,390
I am trying to do the following PHP / MySQL query, and it works fine for the first two groups, but for everyone else I am getting a MySQL error, is this written correctly? ``` $user =& JFactory::getUser(); $N = $user->get('name'); $username = $user->get('username'); $groups = $user->get('groups'); foreach($groups as $groupName=>$groupId) { } $G=$groupName; if ($G=="Management Staff") $result = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addupdatelead"); elseif ($G=="Website Developers") $result = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addupdatelead"); else $result = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addupdatelead WHERE createdby=$N"); ``` When I login as anyone else I get : `Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in C:\server2go\server2go\htdocs\chandlers\components\com_jumi\views\application\view.html.php(38) : eval()'d code on line 87` `Warning: mysql_free_result() expects parameter 1 to be resource, boolean given in C:\server2go\server2go\htdocs\chandlers\components\com_jumi\views\application\view.html.php(38) : eval()'d code on line 132`
2011/12/28
[ "https://Stackoverflow.com/questions/8662390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1104785/" ]
The problem is that you are performing a LINQ-to-Object query when you query a child collection like that. EF will load the whole collection and perform the query in memory. If you are using EF 4 you can query like this ``` var pChildren = this.Children.CreateSourceQuery() .OrderBy(/* */).Skip(skipRelated).Take(takeRelated); ``` In EF 4.1 ``` var pChildren = context.Entry(this) .Collection(e => e.Children) .Query() .OrderBy(/* */).Skip(skipRelated).Take(takeRelated) .Load(); ```
Does it help if you call `Skip` on the result of `Take`? i.e. ``` table.Take(takeCount+skipCount).Skip(skipCount).ToList() ``` Also, see * [TOP/LIMIT Support for LINQ?](http://social.msdn.microsoft.com/forums/en-US/linqprojectgeneral/thread/214de9e9-52ba-412b-a27f-d35be7fbe059/)
36,597,318
I am pricing financial instruments, and each financial instrument object requires a day counter as a property. There are 4 kinds of day counters which have different implementations for each of their two methods, `year_fraction` and `day_count`. This day counter property on financial instruments is used in other classes when pricing, to know how to discount curves appropriately, etc. However, all of the day count methods are static, and doing nothing more than applying some formula. So despite everything I've read online telling me to not use static methods and just have module-level functions instead, I couldn't see a way to nicely pass around the correct DayCounter without implementing something like this ``` class DayCounter: __metaclass__ = abc.ABCMeta @abc.abstractstaticmethod def year_fraction(start_date, end_date): raise NotImplementedError("DayCounter subclass must define a year_fraction method to be valid.") @abc.abstractstaticmethod def day_count(start_date, end_date): raise NotImplementedError("DayCounter subclass must define a day_count method to be valid.") class Actual360(DayCounter): @staticmethod def day_count(start_date, end_date): # some unique formula @staticmethod def year_fraction(start_date, end_date): # some unique formula class Actual365(DayCounter): @staticmethod def day_count(start_date, end_date): # some unique formula @staticmethod def year_fraction(start_date, end_date): # some unique formula class Thirty360(DayCounter): @staticmethod def day_count(start_date, end_date): # some unique formula @staticmethod def year_fraction(start_date, end_date): # some unique formula class ActualActual(DayCounter): @staticmethod def day_count(start_date, end_date): # some unique formula @staticmethod def year_fraction(start_date, end_date): # some unique formula ``` So that in a pricing engine for some particular instrument that is passed an instrument as a parameter, I can use the instrument's day counter property as needed. Am I missing something more idiomatic / stylistically acceptable in Python or does this seem like appropriate use for static method-only classes? --- ***Example***: I have a class FxPricingEngine, which has an `__init__` method passed an FxInstrument and subsequent `underlying_instrument` property. Then in order to use the `Value` method of my pricing engine I need to discount a curve with a particular day counter. I have a `YieldCurve` class with a `discount` method to which I pass `self.underlying_instrument.day_counter.year_fraction` such that I can apply the correct formula. Really all that the classes are serving to do is provide some logical organization for the unique implementations.
2016/04/13
[ "https://Stackoverflow.com/questions/36597318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4450134/" ]
As it is, object orientation does not make any sense in your scenario: there is no data associated with an instance of your types, so any two objects of some type (e.g. `Thirty360`) are going to be equal (i.e. you only have singletons). It looks like you want to be able to parametrise client code on behaviour - the data which your methods operate on is not given in a constructor but rather via the arguments of the methods. In that case, plain free functions may be a much more straight forward solution. For instance, given some imaginary client code which operates on your counters like: ``` def f(counter): counter.day_count(a, b) # ... counter.year_fraction(x, y) ``` ...you could just as well imagine passing two functions as arguments right away instead of an object, e.g. have ``` def f(day_count, year_fraction): day_count(a, b) # ... year_fraction(x, y) ``` On the caller side, you would pass plain functions, e.g. ``` f(thirty360_day_count, thirty360_year_fraction) ``` If you like, you could also have different names for the functions, or you could define them in separate modules to get the namespacing. You could also easily pass special functions like way (for instance if you only need the day\_count to be correct but the year\_fraction could be a noop).
Well to be frank it doesn't make much sense in defining static methods this way. The only purpose static methods are serving in your case is providing a namespace to your function names i.e. you can call your method like `Actual365.day_count` making it more clear that day\_count belongs to `Actual365` functionality. But you can accomplish the same think by defining a module named `actual365`. ``` import actual365 actual365.day_count() ``` As far as Object Orientation is concerned, your code is not offering any advantage that OOP design offers. You have just wrapped your functions in a class. Now I noticed all your methods are using start\_date and end\_date, how about using them as instance variables. ``` class Actual365(object): def __init__(self, start_date, end_date): self.start_date, self.end_date = start_date, end_date def day_count(self): # your unique formula ... ``` Besides `AbstractClasses` don't make much sense in Duck-Typed languages like Python. As long as some object is providing a behavior it doesn't need to inherit from some abstract class. If that doesn't work for you, using just functions might be better approach.
36,597,318
I am pricing financial instruments, and each financial instrument object requires a day counter as a property. There are 4 kinds of day counters which have different implementations for each of their two methods, `year_fraction` and `day_count`. This day counter property on financial instruments is used in other classes when pricing, to know how to discount curves appropriately, etc. However, all of the day count methods are static, and doing nothing more than applying some formula. So despite everything I've read online telling me to not use static methods and just have module-level functions instead, I couldn't see a way to nicely pass around the correct DayCounter without implementing something like this ``` class DayCounter: __metaclass__ = abc.ABCMeta @abc.abstractstaticmethod def year_fraction(start_date, end_date): raise NotImplementedError("DayCounter subclass must define a year_fraction method to be valid.") @abc.abstractstaticmethod def day_count(start_date, end_date): raise NotImplementedError("DayCounter subclass must define a day_count method to be valid.") class Actual360(DayCounter): @staticmethod def day_count(start_date, end_date): # some unique formula @staticmethod def year_fraction(start_date, end_date): # some unique formula class Actual365(DayCounter): @staticmethod def day_count(start_date, end_date): # some unique formula @staticmethod def year_fraction(start_date, end_date): # some unique formula class Thirty360(DayCounter): @staticmethod def day_count(start_date, end_date): # some unique formula @staticmethod def year_fraction(start_date, end_date): # some unique formula class ActualActual(DayCounter): @staticmethod def day_count(start_date, end_date): # some unique formula @staticmethod def year_fraction(start_date, end_date): # some unique formula ``` So that in a pricing engine for some particular instrument that is passed an instrument as a parameter, I can use the instrument's day counter property as needed. Am I missing something more idiomatic / stylistically acceptable in Python or does this seem like appropriate use for static method-only classes? --- ***Example***: I have a class FxPricingEngine, which has an `__init__` method passed an FxInstrument and subsequent `underlying_instrument` property. Then in order to use the `Value` method of my pricing engine I need to discount a curve with a particular day counter. I have a `YieldCurve` class with a `discount` method to which I pass `self.underlying_instrument.day_counter.year_fraction` such that I can apply the correct formula. Really all that the classes are serving to do is provide some logical organization for the unique implementations.
2016/04/13
[ "https://Stackoverflow.com/questions/36597318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4450134/" ]
As it is, object orientation does not make any sense in your scenario: there is no data associated with an instance of your types, so any two objects of some type (e.g. `Thirty360`) are going to be equal (i.e. you only have singletons). It looks like you want to be able to parametrise client code on behaviour - the data which your methods operate on is not given in a constructor but rather via the arguments of the methods. In that case, plain free functions may be a much more straight forward solution. For instance, given some imaginary client code which operates on your counters like: ``` def f(counter): counter.day_count(a, b) # ... counter.year_fraction(x, y) ``` ...you could just as well imagine passing two functions as arguments right away instead of an object, e.g. have ``` def f(day_count, year_fraction): day_count(a, b) # ... year_fraction(x, y) ``` On the caller side, you would pass plain functions, e.g. ``` f(thirty360_day_count, thirty360_year_fraction) ``` If you like, you could also have different names for the functions, or you could define them in separate modules to get the namespacing. You could also easily pass special functions like way (for instance if you only need the day\_count to be correct but the year\_fraction could be a noop).
No == Not that I know of. In my opinion your design pattern is ok. Especially if there is the possibility of your code growing to more than 2 functions per class and if the functions inside a class are connected. If any combination of function is possible, use the **function passing** approach. The **modules** approach and your approach are quite similar. The advantage or disadvantage (it depends) of modules is that your code get split up into many files. Your approach allows you to use `isinstance`, but you probably won't need that. Passing functions directly -------------------------- If you had only one function, you could just pass this function directly instead of using a class. But as soon as you have **2 or more functions** with different implementations, classes seem fine to me. Just add a docstring to explain the usage. I assume that the two function implementation in one class are somewhat connected. Using modules ------------- You could use modules instead of classes (e.g. a module Actual365DayCounter and a module Actual360DayCounter) and use something like `if something: import Actual360DayCounter as daycounter` and `else: import Actual365ayCounter as daycounter`. Or you could import all modules and put them in a dictionary (thanks to the comment by @freakish) like `MODULES = { 'Actual360': Actual360, ... }` and simply use `MODULES[my_var]`. But I doubt this would be a better design pattern, as you would split up your source coude in many tiny modules. Another option: --------------- One way would be to use only one class: ``` class DayCounter: def __init__(self, daysOfTheYear = 360): self.days_of_the_year = daysOfTheYear ``` And make the functions using `self.days_of_the_year`. But this only works if `days_of_the_year` is actually a parameter of the function. If you would have to use a lot of `if ... elif .. elif ...` in your function implementation, this approach would be worse
55,648,350
Goodmorning to everyone, I have a df composed like that > > df=data.frame("Description"=c("Miriam","Miriam","Miriam","Trump","Trump","Trump","Right","Right","Right","Sara","Sara","Star","Star","Star","Sandra")) > > > I would like to creare a loop that create a new column in which is assigned a sample number to each sample with the same name, thus to obtain this result: ``` Description SampleID Miriam sample1 Miriam sample1 Miriam sample1 Trump sample2 Trump sample2 Trump sample2 Right sample3 Right sample3 Right sample3 Sara sample4 Sara sample4 Star sample5 Star sample5 Star sample5 Sandra sample6 ``` Does anyone know how to do that? Thanks a lot to everyone will help. Andrea
2019/04/12
[ "https://Stackoverflow.com/questions/55648350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8758423/" ]
I was able to achieve this by doing the following: ``` @plugin_pool.register_plugin class ArticlesPluginPublisher(CMSPluginBase): model = ArticlesPluginModel name = _("Articles") render_template = "article_plugin/articles.html" cache = False def render(self, context, instance, placeholder): context = super(ArticlesPluginPublisher, self).render( context, instance, placeholder ) context.update( { "articles": Article.objects.order_by( "-original_publication_date" ) } ) return context ``` The plugin model(`ArticlesPluginModel`) is just for storing the configurations for the instance of the plugin. Not the actual articles. Then the render will just add to the context the relevant articles from the external app(`Article`)
``` {% load cms_tags %} <h1>{{ instance.poll.question }}</h1> <form action="{% url polls.views.vote poll.id %}" method="post"> {% csrf_token %} {% for choice in instance.poll.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> ```
55,648,350
Goodmorning to everyone, I have a df composed like that > > df=data.frame("Description"=c("Miriam","Miriam","Miriam","Trump","Trump","Trump","Right","Right","Right","Sara","Sara","Star","Star","Star","Sandra")) > > > I would like to creare a loop that create a new column in which is assigned a sample number to each sample with the same name, thus to obtain this result: ``` Description SampleID Miriam sample1 Miriam sample1 Miriam sample1 Trump sample2 Trump sample2 Trump sample2 Right sample3 Right sample3 Right sample3 Sara sample4 Sara sample4 Star sample5 Star sample5 Star sample5 Sandra sample6 ``` Does anyone know how to do that? Thanks a lot to everyone will help. Andrea
2019/04/12
[ "https://Stackoverflow.com/questions/55648350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8758423/" ]
I was able to achieve this by doing the following: ``` @plugin_pool.register_plugin class ArticlesPluginPublisher(CMSPluginBase): model = ArticlesPluginModel name = _("Articles") render_template = "article_plugin/articles.html" cache = False def render(self, context, instance, placeholder): context = super(ArticlesPluginPublisher, self).render( context, instance, placeholder ) context.update( { "articles": Article.objects.order_by( "-original_publication_date" ) } ) return context ``` The plugin model(`ArticlesPluginModel`) is just for storing the configurations for the instance of the plugin. Not the actual articles. Then the render will just add to the context the relevant articles from the external app(`Article`)
You must somehow connect the `ExternalArticle` with a page object. For example * by defining the `ExternalArticle` as a [page extension](http://docs.django-cms.org/en/latest/how_to/extending_page_title.html) * or with an [`AppHook`](http://docs.django-cms.org/en/latest/topics/apphooks.html) * or - low-tech - with a [`PageField`](http://docs.django-cms.org/en/latest/reference/fields.html#model-fields) on the `ExternalArticle` model
10,920,656
### Using C#2.0 and VIsualStudio2005 I'm trying to access the "DisplayName" inside "MonitorResponseRecord" from an XML file like the one Below: ``` <Magellan xsi:schemaLocation="http://tempuri.org/XMLSchema.xsd ..\Schema\Configuration.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/XMLSchema.xsd"> <SchemaVersion>1.0</SchemaVersion> <MonitorScope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" id="CleanStationChemicalManifoldFeed5" xmlns="http://tempuri.org/XMLSchema.xsd"> <PersonalSafety> <MonitorResponseRecord Enabled="true" DisplayName="ChemicalManifoldFeed5ControllerFault"> <ExpressionMonitor> <Expression>(ChemicalManifold.Feed5.DispenseValve = Open) and ((ChemicalManifold.Feed5.ViolatedRegion = HighProcess) or (ChemicalManifold.Feed5.ViolatedRegion = LowProcess) or (ChemicalManifold.Feed5.ViolatedRegion = Minimum))</Expression> <TestInterval>0.1</TestInterval> <MinimumTimeBetweenResponses>5</MinimumTimeBetweenResponses> </ExpressionMonitor> <Response> <PostAlarm> <AlarmName>ChemicalManifold_Feed5_ControllerFault</AlarmName> <Parameter1 /> <Parameter2>Alarm Region = {ChemicalManifold.Feed5.ViolatedRegion}</Parameter2> <Parameter3>{RecipeName}-{StepName}</Parameter3> <Parameter4>FlowSetpoint = {ChemicalManifold.Feed5.Setpoint}-LPM, ActualFlow = {ChemicalManifold.Feed5.FlowMeter}-LPM</Parameter4> </PostAlarm> <ResponseEvent> <TargetResource /> <Event>PA</Event> <Reason>ChemicalSupply</Reason> </ResponseEvent> </Response> </MonitorResponseRecord> </PersonalSafety> <PersonalSafety> <MonitorResponseRecord Enabled="true" DisplayName = "PressureValveFailure"> ... ... ...and soon ``` My current C# attempt is as follows, BUT it always hangs up when I try to `XmlDocument.Load("");` ``` XmlDocument doc = new XmlDocument(); doc.Load("../UMC0009.Configuration.Root.xml"); string attrVal = doc.SelectSingleNode("MonitorResponseRecord/@DisplayName").Value; ``` BUUUUT won't work :/ any help out there? ### UPDATE: the exception I recieve is as follows, and occures at the doc.Load("...") line: `{"Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function."} System.Exception {System.Xml.XPath.XPathException}`
2012/06/06
[ "https://Stackoverflow.com/questions/10920656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1241199/" ]
Your XPath query will be relative to the document root: ``` doc.SelectSingleNode("MonitorResponseRecord/@DisplayName") ``` To make it search anywhere in the doc prefix it with double slash: ``` doc.SelectSingleNode("//MonitorResponseRecord/@DisplayName") ``` If that still doesn't work I would try the above example after stripping out all those namespace declarations on the two root nodes. Otherwise, with the namespace declarations you may find you need to define XML namespace mappings and use prefixes in your XPath like: ``` XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("x", "http://tempuri.org/XMLSchema.xsd"); doc.SelectSingleNode("//x:MonitorResponseRecord/@DisplayName") ```
What about: ``` XmlDocument doc = new XmlDocument(); doc.Load("UMC0009.Configuration.Root.xml"); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("ns", "http://tempuri.org/XMLSchema.xsd"); string attrVal = doc.SelectSingleNode("//ns:MonitorResponseRecord/@DisplayName", nsmgr).Value; ``` Using a namespace manager, specify your namespace URI and use it in your XPath. It works for me.
45,967,261
We have a very weird requirement to convert 11 digit hexadecimal number ( range from (A0000000001 ~ AFFFFFFFFFF) ) to 11 digit decimal number. And there should be 1:1 mapping between hexadecimal to integer. Is there a way to do this in Java ?
2017/08/30
[ "https://Stackoverflow.com/questions/45967261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3593170/" ]
This is not possible, in Java or in any other language or system. This impossibility is a fundamental property of numbers and set theory. Since the leading `0xA` does not change, what you actually have is a 10-hex digit value, or 40 bits worth of data. This encompasses about 1.1 x 1012 possible values, so it is not possible to map this to an 11-digit decimal number, which by definition has only 1011 possible values. Based on the comments I'm going to make this more explicit. Start with `0xA0000000000` and map that to decimal `00000000000`, then increment both by 1 to establish a one-to-one correspondence between members of the two sets and repeat: ``` 0xA0000000000 -> 00000000000 0xA0000000001 -> 00000000001 0xA0000000002 -> 00000000002 ... 0xA0000000010 -> 00000000016 ... 0xA0000000100 -> 00000000256 ... 0xA0000001000 -> 00000004096 ... 0xA174876E7FF -> 99999999999 ... 0xA174876E800 -> oops! overflow! too many digits ``` Put another way, the size of the set of all hex values between `0xA0000000000` and `0xAFFFFFFFFFF` is larger than the set of all decimal values between `00000000000` and `99999999999`.
``` String hexNumber = ... int decimal = Integer.parseInt(hexNumber, 16); ``` Not sure if you need to display ten characters or not. If so, here is some code to convert it into a string and pad leading zeros. ``` String decNumber = Integer.toString(decimal); public static String padLeadingZeros(String data, int requiredLength){ StringBuffer sb = new StringBuffer(); int numLeadingZeros = requiredLength - data.length(); for (int i=0; i < numLeadingZeros; i++){ sb.append("0"); } sb.append(data); return sb.toString(); } ```
20,387,427
I wrote an application in Visual Studio C# 2010, that I would like to import into another existing Visual Studio C# 2010 Application. How would I go about doing this? For instance, I'd like to import the project into another, and basically copy/paste the interface from the application into a tabpage on a tab control I have. Any assistance or advice on how to do this is greatly appreciated!
2013/12/04
[ "https://Stackoverflow.com/questions/20387427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2015033/" ]
I've found this tutorial <http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/remap/remap.html> very useful for understanding how to set map1, map2 parameters. In the end it's something like this: ``` for(int i=0; i< rows; i++){ for(int j=0; j<col; j++) { map_x.at<float>(i,j) = j + motion_vect.ptr<float>(i)[2*j+0]; map_y.at<float>(i,j) = i + motion_vect.ptr<float>(i)[2*j+1];; }} ``` To have the output image as the original : ``` map_x.at<float>(i,j) = j ; map_y.at<float>(i,j) = i ; ```
For your #2, you can do this to get float values from pointer into some Mat: ``` cv::Mat testMat = cv::Mat::zeros(2, 3, CV_32F); std::cout << "(1, 2) elem = " << testMat.at<float>(1, 2) << std::endl; float* pTestVal = new float; *pTestVal = 3.14F; testMat.at<float>(1, 2) = *pTestVal; delete pTestVal; std::cout << "(1, 2) elem = " << testMat.at<float>(1, 2) << std::endl; ```
67,950
After merging two sites, one with ~40 URLs and one with ~700 URLs (due to a forum) the result was that overall traffic decreased by ~50%. I want to get the traffic back, as it was organic and a helpful resource to the community. After finding [this answer](https://webmasters.stackexchange.com/questions/16947/lower-google-traffic-after-adding-more-pages?rq=1) I decided to try removing the ~700 forum pages from the index by using a robots.txt disallow, which didn't work. As [this FAQ](https://developers.google.com/webmasters/control-crawl-index/docs/faq#h17) and [this answer](https://webmasters.stackexchange.com/questions/51628/how-long-does-it-take-for-google-to-remove-page-from-index-or-why-arent-these) point out, the robots.txt must *allow* the pages and meta noindex must be used. After applying noindex tags to all forum pages, removing the disallows from robots.txt and waiting a week, still there are 700+ URLs in the index according to Google webmaster tools. However, if I view the advanced index status and check all the boxes, it shows 795 URLs indexed and 200+ blocked by robots. The blocked by robots graph line is increasing steadily (~30 URLs per week). Note that average crawl rate is ~125 pages per day. My question is this: How can I tell that the URLs have successfully been removed? Looking at Google webmaster tools' graph of index status is what I thought was a good indicator, but I am wondering what should actually happen in the results there. Should the blue graph line of total indexed drop back down to a low URL count (as I am expecting), or will the total indexed remain high and the blocked by robots and/or removed URLs increase? This [answer from Google](https://support.google.com/webmasters/answer/2642366?hl=en) seems to indicate that the total indexed (blue line) should drop. Why then has it not dropped at all after applying the noindex tags and waiting a week?
2014/08/11
[ "https://webmasters.stackexchange.com/questions/67950", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/43832/" ]
Google Webmaster Tools index count will fluctuate constantly especially with dynamic sites or those using common platforms such as forum software. The best way to tell how many of these URL's Google are dropping from their index is to use the `site` operator in Google's web search, for example:- ``` site: example.com/forum ``` This will show you all indexed URL's at `/forum/*` - if you perform this search every few days and see how many URL's are indexed, this will give you an idea if they are being dropped from the index as you intend. As these URL's start getting dropped from the index, you should expect to see the total indexed count in Google Webmaster Tools also decrease accordingly, although as I mentioned above, there will also probably be plenty of new URL's Google are indexing (and dropping) from your site each day.
Unfortunately, the fastest way to remove pages from the Google index, you abandoned. There is nothing wrong with using the robots.txt file to remove pages from the Google index. Having switched to `noindex`, it will take some time for the spider to fetch all of the pages and update the index. The speed will depend upon the freshness of your site in the past. Part of what may slow this process down is changing the game. I strongly suggest staying the course. The more you change things around, the more you confuse the machine and the slower it will be to get what you want. Be patient. It will take some weeks before the page are removed. Search engines are notoriously slow. Unfortunately, there is no really good way to check your progress except for that the graph you already mentioned. Sometimes the numbers may not make sense. Google seems to use Microsoft for calculations sometimes. When the graph has leveled off for a period, it is likely that all the pages are de-listed. One thing you can do is to take a sample of the page titles and do a `site:` search using the unique titles in quotes. Taking a sample can give you an idea of what is going on.
42,424,166
I have a curious question about the graph LineChart JavaFX. I have this graph: [![Grapg](https://i.stack.imgur.com/Ui7Sf.png)](https://i.stack.imgur.com/Ui7Sf.png) dots forming a "jump" on the X axis (as shown by the two red points I scored) and therefore JavaFX draws me the line between these two points. How do I remove that line between each "jump"? I post the code: ``` public class ControllerIndividua { public static void plotIndividuaFull(String path, Stage stage, String name) { final NumberAxis xAxisIntensity = new NumberAxis(); //Dichiarazione asseX final NumberAxis yAxisIntensity = new NumberAxis();//Dichiarazione asseY DetectionS1.countS1(); //Dichiarazione del tipo di grafico final LineChart<Number, Number> lineChartIntensity = new LineChart<Number, Number>(xAxisIntensity,yAxisIntensity); ArrayList<Double> extractedData; //Lista dei valori dello dell' intensità ArrayList<Double> extractedTime; //Lista del tempo ArrayList<Double> extractedS1; //Lista del tempo ArrayList<Double> extractedS1Time; //Lista del tempo //Gestione e settaggio del grafico lineChartIntensity.getData().clear(); try { //Popolamento delle liste extractedTime = IntensityExtractor.pointsTime(); extractedData = IntensityExtractor.pointsIntensity(); extractedS1 = DetectionS1.S1pitch(); extractedS1Time = DetectionS1.pointsS1Time(); XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>(); XYChart.Series<Number, Number> seriesS1 = new XYChart.Series<Number, Number>(); //Creazione seconda serie series.setName("Intensità di:\t" + name.toUpperCase()); for (int j = 0; j < extractedS1.size(); j++) { seriesS1.getData().add(new XYChart.Data<Number, Number>(extractedS1Time.get(j), extractedS1.get(j))); lineChartIntensity.getStyleClass().add("CSSintensity"); } //Creazione finestra e stampa del grafico Scene scene = new Scene(lineChartIntensity, 1000, 600); lineChartIntensity.getData().addAll(series,seriesS1); scene.getStylesheets().add("application/application.css"); stage.setScene(scene); stage.show(); } catch (java.lang.Exception e) { e.printStackTrace(); } } } ``` Someone also has a little idea on how I could do? Thank you all in advance.
2017/02/23
[ "https://Stackoverflow.com/questions/42424166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7142695/" ]
This is an old question with an accepted answer but I came across it and was curious. I wanted to know if it was possible to put a gap in a `LineChart` (at least without having to create a custom chart implementation). It turns out that there is. The solution is kind of hacky and brittle. It involves getting the [`Path`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/Path.html) by using [`XYChart.Series.getNode()`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/chart/XYChart.Series.html#nodeProperty) and manipulating the list of [`PathElement`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/PathElement.html)s. The following code gives an example: ``` import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.layout.StackPane; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) { LineChart<Number, Number> chart = new LineChart<>(new NumberAxis(), new NumberAxis()); chart.getXAxis().setLabel("X"); chart.getYAxis().setLabel("Y"); chart.setLegendVisible(false); chart.getData().add(new XYChart.Series<>()); for (int x = 0; x <= 10; x++) { chart.getData().get(0).getData().add(new XYChart.Data<>(x, Math.pow(x, 2))); } /* * Had to wrap the call in a Platform.runLater otherwise the Path was * redrawn after the modifications are made. */ primaryStage.setOnShown(we -> Platform.runLater(() -> { Path path = (Path) chart.getData().get(0).getNode(); LineTo lineTo = (LineTo) path.getElements().get(8); path.getElements().set(8, new MoveTo(lineTo.getX(), lineTo.getY())); })); primaryStage.setScene(new Scene(new StackPane(chart), 500, 300)); primaryStage.setTitle("LineChart Gap"); primaryStage.show(); } } ``` This code results in the following: [![Screenshot of LineChart with gap in the line](https://i.stack.imgur.com/bOk6e.png)](https://i.stack.imgur.com/bOk6e.png) This is possible because the `ObservableList` of `PathElement`s seems to be a [`MoveTo`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/MoveTo.html) followed by a bunch of [`LineTo`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/LineTo.html)s. I simply picked a `LineTo` and replaced it with a `MoveTo` to the same coordinates. I haven't quite figured out which index of `LineTo` matches with which `XYChart.Data`, however, and picked `8` for the example randomly. There are a couple of issues with this solution. The first and obvious one is that this relies on the internal implementation of `LineChart`. The second is where the real brittleness comes from though. Any change to the data, either axes' value ranges, the chart's width or height, or pretty much *anything* that causes the chart to redraw itself will cause the `Path` to be recomputed and redrawn. This means if you use this solution you'll have to reapply the modification *every time* the chart redraws itself.
I checked it. It is not possible to change only one part of this line. Because this is one long Path and you can't change one element of Path. I think the only way is add each "jump" in different series.
42,424,166
I have a curious question about the graph LineChart JavaFX. I have this graph: [![Grapg](https://i.stack.imgur.com/Ui7Sf.png)](https://i.stack.imgur.com/Ui7Sf.png) dots forming a "jump" on the X axis (as shown by the two red points I scored) and therefore JavaFX draws me the line between these two points. How do I remove that line between each "jump"? I post the code: ``` public class ControllerIndividua { public static void plotIndividuaFull(String path, Stage stage, String name) { final NumberAxis xAxisIntensity = new NumberAxis(); //Dichiarazione asseX final NumberAxis yAxisIntensity = new NumberAxis();//Dichiarazione asseY DetectionS1.countS1(); //Dichiarazione del tipo di grafico final LineChart<Number, Number> lineChartIntensity = new LineChart<Number, Number>(xAxisIntensity,yAxisIntensity); ArrayList<Double> extractedData; //Lista dei valori dello dell' intensità ArrayList<Double> extractedTime; //Lista del tempo ArrayList<Double> extractedS1; //Lista del tempo ArrayList<Double> extractedS1Time; //Lista del tempo //Gestione e settaggio del grafico lineChartIntensity.getData().clear(); try { //Popolamento delle liste extractedTime = IntensityExtractor.pointsTime(); extractedData = IntensityExtractor.pointsIntensity(); extractedS1 = DetectionS1.S1pitch(); extractedS1Time = DetectionS1.pointsS1Time(); XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>(); XYChart.Series<Number, Number> seriesS1 = new XYChart.Series<Number, Number>(); //Creazione seconda serie series.setName("Intensità di:\t" + name.toUpperCase()); for (int j = 0; j < extractedS1.size(); j++) { seriesS1.getData().add(new XYChart.Data<Number, Number>(extractedS1Time.get(j), extractedS1.get(j))); lineChartIntensity.getStyleClass().add("CSSintensity"); } //Creazione finestra e stampa del grafico Scene scene = new Scene(lineChartIntensity, 1000, 600); lineChartIntensity.getData().addAll(series,seriesS1); scene.getStylesheets().add("application/application.css"); stage.setScene(scene); stage.show(); } catch (java.lang.Exception e) { e.printStackTrace(); } } } ``` Someone also has a little idea on how I could do? Thank you all in advance.
2017/02/23
[ "https://Stackoverflow.com/questions/42424166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7142695/" ]
I made a GapLineChart that automatically sets a MoveTo like Slaw pointed it whenever it sees a Double.NaN. You can find it here <https://gist.github.com/sirolf2009/ae8a7897b57dcf902b4ed747b05641f9>. Check the first comment for an example
I checked it. It is not possible to change only one part of this line. Because this is one long Path and you can't change one element of Path. I think the only way is add each "jump" in different series.
42,424,166
I have a curious question about the graph LineChart JavaFX. I have this graph: [![Grapg](https://i.stack.imgur.com/Ui7Sf.png)](https://i.stack.imgur.com/Ui7Sf.png) dots forming a "jump" on the X axis (as shown by the two red points I scored) and therefore JavaFX draws me the line between these two points. How do I remove that line between each "jump"? I post the code: ``` public class ControllerIndividua { public static void plotIndividuaFull(String path, Stage stage, String name) { final NumberAxis xAxisIntensity = new NumberAxis(); //Dichiarazione asseX final NumberAxis yAxisIntensity = new NumberAxis();//Dichiarazione asseY DetectionS1.countS1(); //Dichiarazione del tipo di grafico final LineChart<Number, Number> lineChartIntensity = new LineChart<Number, Number>(xAxisIntensity,yAxisIntensity); ArrayList<Double> extractedData; //Lista dei valori dello dell' intensità ArrayList<Double> extractedTime; //Lista del tempo ArrayList<Double> extractedS1; //Lista del tempo ArrayList<Double> extractedS1Time; //Lista del tempo //Gestione e settaggio del grafico lineChartIntensity.getData().clear(); try { //Popolamento delle liste extractedTime = IntensityExtractor.pointsTime(); extractedData = IntensityExtractor.pointsIntensity(); extractedS1 = DetectionS1.S1pitch(); extractedS1Time = DetectionS1.pointsS1Time(); XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>(); XYChart.Series<Number, Number> seriesS1 = new XYChart.Series<Number, Number>(); //Creazione seconda serie series.setName("Intensità di:\t" + name.toUpperCase()); for (int j = 0; j < extractedS1.size(); j++) { seriesS1.getData().add(new XYChart.Data<Number, Number>(extractedS1Time.get(j), extractedS1.get(j))); lineChartIntensity.getStyleClass().add("CSSintensity"); } //Creazione finestra e stampa del grafico Scene scene = new Scene(lineChartIntensity, 1000, 600); lineChartIntensity.getData().addAll(series,seriesS1); scene.getStylesheets().add("application/application.css"); stage.setScene(scene); stage.show(); } catch (java.lang.Exception e) { e.printStackTrace(); } } } ``` Someone also has a little idea on how I could do? Thank you all in advance.
2017/02/23
[ "https://Stackoverflow.com/questions/42424166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7142695/" ]
This is an old question with an accepted answer but I came across it and was curious. I wanted to know if it was possible to put a gap in a `LineChart` (at least without having to create a custom chart implementation). It turns out that there is. The solution is kind of hacky and brittle. It involves getting the [`Path`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/Path.html) by using [`XYChart.Series.getNode()`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/chart/XYChart.Series.html#nodeProperty) and manipulating the list of [`PathElement`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/PathElement.html)s. The following code gives an example: ``` import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.layout.StackPane; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) { LineChart<Number, Number> chart = new LineChart<>(new NumberAxis(), new NumberAxis()); chart.getXAxis().setLabel("X"); chart.getYAxis().setLabel("Y"); chart.setLegendVisible(false); chart.getData().add(new XYChart.Series<>()); for (int x = 0; x <= 10; x++) { chart.getData().get(0).getData().add(new XYChart.Data<>(x, Math.pow(x, 2))); } /* * Had to wrap the call in a Platform.runLater otherwise the Path was * redrawn after the modifications are made. */ primaryStage.setOnShown(we -> Platform.runLater(() -> { Path path = (Path) chart.getData().get(0).getNode(); LineTo lineTo = (LineTo) path.getElements().get(8); path.getElements().set(8, new MoveTo(lineTo.getX(), lineTo.getY())); })); primaryStage.setScene(new Scene(new StackPane(chart), 500, 300)); primaryStage.setTitle("LineChart Gap"); primaryStage.show(); } } ``` This code results in the following: [![Screenshot of LineChart with gap in the line](https://i.stack.imgur.com/bOk6e.png)](https://i.stack.imgur.com/bOk6e.png) This is possible because the `ObservableList` of `PathElement`s seems to be a [`MoveTo`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/MoveTo.html) followed by a bunch of [`LineTo`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/LineTo.html)s. I simply picked a `LineTo` and replaced it with a `MoveTo` to the same coordinates. I haven't quite figured out which index of `LineTo` matches with which `XYChart.Data`, however, and picked `8` for the example randomly. There are a couple of issues with this solution. The first and obvious one is that this relies on the internal implementation of `LineChart`. The second is where the real brittleness comes from though. Any change to the data, either axes' value ranges, the chart's width or height, or pretty much *anything* that causes the chart to redraw itself will cause the `Path` to be recomputed and redrawn. This means if you use this solution you'll have to reapply the modification *every time* the chart redraws itself.
I made a GapLineChart that automatically sets a MoveTo like Slaw pointed it whenever it sees a Double.NaN. You can find it here <https://gist.github.com/sirolf2009/ae8a7897b57dcf902b4ed747b05641f9>. Check the first comment for an example
42,424,166
I have a curious question about the graph LineChart JavaFX. I have this graph: [![Grapg](https://i.stack.imgur.com/Ui7Sf.png)](https://i.stack.imgur.com/Ui7Sf.png) dots forming a "jump" on the X axis (as shown by the two red points I scored) and therefore JavaFX draws me the line between these two points. How do I remove that line between each "jump"? I post the code: ``` public class ControllerIndividua { public static void plotIndividuaFull(String path, Stage stage, String name) { final NumberAxis xAxisIntensity = new NumberAxis(); //Dichiarazione asseX final NumberAxis yAxisIntensity = new NumberAxis();//Dichiarazione asseY DetectionS1.countS1(); //Dichiarazione del tipo di grafico final LineChart<Number, Number> lineChartIntensity = new LineChart<Number, Number>(xAxisIntensity,yAxisIntensity); ArrayList<Double> extractedData; //Lista dei valori dello dell' intensità ArrayList<Double> extractedTime; //Lista del tempo ArrayList<Double> extractedS1; //Lista del tempo ArrayList<Double> extractedS1Time; //Lista del tempo //Gestione e settaggio del grafico lineChartIntensity.getData().clear(); try { //Popolamento delle liste extractedTime = IntensityExtractor.pointsTime(); extractedData = IntensityExtractor.pointsIntensity(); extractedS1 = DetectionS1.S1pitch(); extractedS1Time = DetectionS1.pointsS1Time(); XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>(); XYChart.Series<Number, Number> seriesS1 = new XYChart.Series<Number, Number>(); //Creazione seconda serie series.setName("Intensità di:\t" + name.toUpperCase()); for (int j = 0; j < extractedS1.size(); j++) { seriesS1.getData().add(new XYChart.Data<Number, Number>(extractedS1Time.get(j), extractedS1.get(j))); lineChartIntensity.getStyleClass().add("CSSintensity"); } //Creazione finestra e stampa del grafico Scene scene = new Scene(lineChartIntensity, 1000, 600); lineChartIntensity.getData().addAll(series,seriesS1); scene.getStylesheets().add("application/application.css"); stage.setScene(scene); stage.show(); } catch (java.lang.Exception e) { e.printStackTrace(); } } } ``` Someone also has a little idea on how I could do? Thank you all in advance.
2017/02/23
[ "https://Stackoverflow.com/questions/42424166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7142695/" ]
This is an old question with an accepted answer but I came across it and was curious. I wanted to know if it was possible to put a gap in a `LineChart` (at least without having to create a custom chart implementation). It turns out that there is. The solution is kind of hacky and brittle. It involves getting the [`Path`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/Path.html) by using [`XYChart.Series.getNode()`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/chart/XYChart.Series.html#nodeProperty) and manipulating the list of [`PathElement`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/PathElement.html)s. The following code gives an example: ``` import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.XYChart; import javafx.scene.layout.StackPane; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) { LineChart<Number, Number> chart = new LineChart<>(new NumberAxis(), new NumberAxis()); chart.getXAxis().setLabel("X"); chart.getYAxis().setLabel("Y"); chart.setLegendVisible(false); chart.getData().add(new XYChart.Series<>()); for (int x = 0; x <= 10; x++) { chart.getData().get(0).getData().add(new XYChart.Data<>(x, Math.pow(x, 2))); } /* * Had to wrap the call in a Platform.runLater otherwise the Path was * redrawn after the modifications are made. */ primaryStage.setOnShown(we -> Platform.runLater(() -> { Path path = (Path) chart.getData().get(0).getNode(); LineTo lineTo = (LineTo) path.getElements().get(8); path.getElements().set(8, new MoveTo(lineTo.getX(), lineTo.getY())); })); primaryStage.setScene(new Scene(new StackPane(chart), 500, 300)); primaryStage.setTitle("LineChart Gap"); primaryStage.show(); } } ``` This code results in the following: [![Screenshot of LineChart with gap in the line](https://i.stack.imgur.com/bOk6e.png)](https://i.stack.imgur.com/bOk6e.png) This is possible because the `ObservableList` of `PathElement`s seems to be a [`MoveTo`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/MoveTo.html) followed by a bunch of [`LineTo`](https://docs.oracle.com/javase/10/docs/api/javafx/scene/shape/LineTo.html)s. I simply picked a `LineTo` and replaced it with a `MoveTo` to the same coordinates. I haven't quite figured out which index of `LineTo` matches with which `XYChart.Data`, however, and picked `8` for the example randomly. There are a couple of issues with this solution. The first and obvious one is that this relies on the internal implementation of `LineChart`. The second is where the real brittleness comes from though. Any change to the data, either axes' value ranges, the chart's width or height, or pretty much *anything* that causes the chart to redraw itself will cause the `Path` to be recomputed and redrawn. This means if you use this solution you'll have to reapply the modification *every time* the chart redraws itself.
I was in need of adapting LineChart so that it drew line segments, so each pair of data points created a single line segment. It's pretty straight-forward to do by extending `LineChart` and overriding the `layoutPlotChildren` function, although I had to delete an animation `y`-scaling variable as it was `private` in the super class, but I'm not animating the graph so it was fine. Anyway, here is the Kotlin version (which you can easily adapt to Java, or just copy the Java `LineChart` `layoutPlotChildren` code and adapt). It's easy to adapt to your circumstances, just change the contents of the `for` loop at the very end. ``` import javafx.scene.chart.Axis import javafx.scene.chart.LineChart import javafx.scene.shape.LineTo import javafx.scene.shape.MoveTo import javafx.scene.shape.Path import java.util.* import kotlin.collections.ArrayList class GapLineChart<X, Y>(xAxis: Axis<X>?, yAxis: Axis<Y>?) : LineChart<X, Y>(xAxis, yAxis) { public override fun layoutPlotChildren() { val constructedPath = ArrayList<LineTo>(data.size) for (seriesIndex in 0 until data.size) { val series = data[seriesIndex] if (series.node is Path) { val seriesLine = (series.node as Path).elements val it = getDisplayedDataIterator(series) seriesLine.clear() constructedPath.clear() var parity = true while (it.hasNext()) { val item = it.next() val x = xAxis.getDisplayPosition(item.xValue) val y = yAxis.getDisplayPosition(yAxis.toRealValue(yAxis.toNumericValue(item.yValue))) if (java.lang.Double.isNaN(x) || java.lang.Double.isNaN(y)) { continue } if(parity) constructedPath.add(LineTo(x, y)) val symbol = item.node if (symbol != null) { val w = symbol.prefWidth(-1.0) val h = symbol.prefHeight(-1.0) symbol.resizeRelocate(x - w / 2, y - h / 2, w, h) } } when (axisSortingPolicy) { SortingPolicy.X_AXIS -> constructedPath.sortWith(Comparator { e1, e2 -> java.lang.Double.compare(e1.x, e2.x) }) SortingPolicy.Y_AXIS -> constructedPath.sortWith(Comparator { e1, e2 -> java.lang.Double.compare(e1.y, e2.y) }) } if (!constructedPath.isEmpty()) { for (i in 0 until constructedPath.size-1 step 2) { seriesLine.add(MoveTo(constructedPath[i].x, constructedPath[i].y)) seriesLine.add(LineTo(constructedPath[i+1].x, constructedPath[i+1].y)) } } } } } } ```
42,424,166
I have a curious question about the graph LineChart JavaFX. I have this graph: [![Grapg](https://i.stack.imgur.com/Ui7Sf.png)](https://i.stack.imgur.com/Ui7Sf.png) dots forming a "jump" on the X axis (as shown by the two red points I scored) and therefore JavaFX draws me the line between these two points. How do I remove that line between each "jump"? I post the code: ``` public class ControllerIndividua { public static void plotIndividuaFull(String path, Stage stage, String name) { final NumberAxis xAxisIntensity = new NumberAxis(); //Dichiarazione asseX final NumberAxis yAxisIntensity = new NumberAxis();//Dichiarazione asseY DetectionS1.countS1(); //Dichiarazione del tipo di grafico final LineChart<Number, Number> lineChartIntensity = new LineChart<Number, Number>(xAxisIntensity,yAxisIntensity); ArrayList<Double> extractedData; //Lista dei valori dello dell' intensità ArrayList<Double> extractedTime; //Lista del tempo ArrayList<Double> extractedS1; //Lista del tempo ArrayList<Double> extractedS1Time; //Lista del tempo //Gestione e settaggio del grafico lineChartIntensity.getData().clear(); try { //Popolamento delle liste extractedTime = IntensityExtractor.pointsTime(); extractedData = IntensityExtractor.pointsIntensity(); extractedS1 = DetectionS1.S1pitch(); extractedS1Time = DetectionS1.pointsS1Time(); XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>(); XYChart.Series<Number, Number> seriesS1 = new XYChart.Series<Number, Number>(); //Creazione seconda serie series.setName("Intensità di:\t" + name.toUpperCase()); for (int j = 0; j < extractedS1.size(); j++) { seriesS1.getData().add(new XYChart.Data<Number, Number>(extractedS1Time.get(j), extractedS1.get(j))); lineChartIntensity.getStyleClass().add("CSSintensity"); } //Creazione finestra e stampa del grafico Scene scene = new Scene(lineChartIntensity, 1000, 600); lineChartIntensity.getData().addAll(series,seriesS1); scene.getStylesheets().add("application/application.css"); stage.setScene(scene); stage.show(); } catch (java.lang.Exception e) { e.printStackTrace(); } } } ``` Someone also has a little idea on how I could do? Thank you all in advance.
2017/02/23
[ "https://Stackoverflow.com/questions/42424166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7142695/" ]
I made a GapLineChart that automatically sets a MoveTo like Slaw pointed it whenever it sees a Double.NaN. You can find it here <https://gist.github.com/sirolf2009/ae8a7897b57dcf902b4ed747b05641f9>. Check the first comment for an example
I was in need of adapting LineChart so that it drew line segments, so each pair of data points created a single line segment. It's pretty straight-forward to do by extending `LineChart` and overriding the `layoutPlotChildren` function, although I had to delete an animation `y`-scaling variable as it was `private` in the super class, but I'm not animating the graph so it was fine. Anyway, here is the Kotlin version (which you can easily adapt to Java, or just copy the Java `LineChart` `layoutPlotChildren` code and adapt). It's easy to adapt to your circumstances, just change the contents of the `for` loop at the very end. ``` import javafx.scene.chart.Axis import javafx.scene.chart.LineChart import javafx.scene.shape.LineTo import javafx.scene.shape.MoveTo import javafx.scene.shape.Path import java.util.* import kotlin.collections.ArrayList class GapLineChart<X, Y>(xAxis: Axis<X>?, yAxis: Axis<Y>?) : LineChart<X, Y>(xAxis, yAxis) { public override fun layoutPlotChildren() { val constructedPath = ArrayList<LineTo>(data.size) for (seriesIndex in 0 until data.size) { val series = data[seriesIndex] if (series.node is Path) { val seriesLine = (series.node as Path).elements val it = getDisplayedDataIterator(series) seriesLine.clear() constructedPath.clear() var parity = true while (it.hasNext()) { val item = it.next() val x = xAxis.getDisplayPosition(item.xValue) val y = yAxis.getDisplayPosition(yAxis.toRealValue(yAxis.toNumericValue(item.yValue))) if (java.lang.Double.isNaN(x) || java.lang.Double.isNaN(y)) { continue } if(parity) constructedPath.add(LineTo(x, y)) val symbol = item.node if (symbol != null) { val w = symbol.prefWidth(-1.0) val h = symbol.prefHeight(-1.0) symbol.resizeRelocate(x - w / 2, y - h / 2, w, h) } } when (axisSortingPolicy) { SortingPolicy.X_AXIS -> constructedPath.sortWith(Comparator { e1, e2 -> java.lang.Double.compare(e1.x, e2.x) }) SortingPolicy.Y_AXIS -> constructedPath.sortWith(Comparator { e1, e2 -> java.lang.Double.compare(e1.y, e2.y) }) } if (!constructedPath.isEmpty()) { for (i in 0 until constructedPath.size-1 step 2) { seriesLine.add(MoveTo(constructedPath[i].x, constructedPath[i].y)) seriesLine.add(LineTo(constructedPath[i+1].x, constructedPath[i+1].y)) } } } } } } ```
39,707,749
I am looking for a way to maintain a *truly global* variable in Java, one that is valid for the entire JVM instance. If I simply used a `static` field somewhere, [it will fail](http://www.oracle.com/technetwork/articles/java/singleton-1577166.html) if the class containing the field is loaded multiple times by different classloaders. I can think of some nasty ways to resolve this, such as using only JDK standard classes (which should normally be loaded by the same classloader always), or asking a custom MBean to keep the global state, but these seem like hacks to me. Disclaimer: I know that global state is bad, and yes, I avoid it whenever I can. Promise.
2016/09/26
[ "https://Stackoverflow.com/questions/39707749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1005481/" ]
System properties are available throughout one VM, but not cross-process. One VM, one set of properties. Also see [Scope of the Java System Properties](https://stackoverflow.com/questions/908903/scope-of-the-java-system-properties)
The only reliable approach I can come up with that doesn't rely on manipulating the base classloader of the container would be to use JNI. Write an adapter to native code that uses a shared memory segment or other similar mechanism to back the global state.
39,707,749
I am looking for a way to maintain a *truly global* variable in Java, one that is valid for the entire JVM instance. If I simply used a `static` field somewhere, [it will fail](http://www.oracle.com/technetwork/articles/java/singleton-1577166.html) if the class containing the field is loaded multiple times by different classloaders. I can think of some nasty ways to resolve this, such as using only JDK standard classes (which should normally be loaded by the same classloader always), or asking a custom MBean to keep the global state, but these seem like hacks to me. Disclaimer: I know that global state is bad, and yes, I avoid it whenever I can. Promise.
2016/09/26
[ "https://Stackoverflow.com/questions/39707749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1005481/" ]
If your problem is related to multiple classloaders, then you need the global object to be loaded by the system classloader, or other shared classloader. How that is setup depends on how you run your app, e.g. in Tomcat, any jar file in the `CATALINA_BASE/lib` folder is added to the shared classloader. Once you class is loaded by the correct classloader, `static` fields will work the way you want them to.
The only reliable approach I can come up with that doesn't rely on manipulating the base classloader of the container would be to use JNI. Write an adapter to native code that uses a shared memory segment or other similar mechanism to back the global state.
57,133,926
Im fetching lat and lng from firebase but it runs after onMapReady hence when i pass coords to onMapReady it crashed beacause arraylist has nothing I want to run onMapReady after my data is loaded in my arrays ``` private void loadMapPins(){ Query q = FirebaseDatabase.getInstance().getReference("HOSTELS").orderByChild("LOCATION_ID").equalTo(hostelID); q.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot childsnap:dataSnapshot.getChildren()){ LatAndLng latAndLng = childsnap.child("MAP_LOCATION").getValue(LatAndLng.class); lat.add(String.valueOf(latAndLng.getLATITUDE())); lng.add(String.valueOf(latAndLng.getLONGITUDE() )); Log.d("latitudess", "onDataChange: "+String.valueOf(latAndLng.getLATITUDE())); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public void onMapReady(GoogleMap googleMap) { LatLng sydney = new LatLng(lat.get(0), lng.get(0)); googleMap.addMarker(new MarkerOptions().position(sydney) .title("Marker in Sydney")); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,15f)); } @Override public void onMapReady(GoogleMap googleMap) { loadMapPins(); LatLng sydney = new LatLng(Float.parseFloat(lat.get(0)), Float.parseFloat(lng.get(0))); googleMap.addMarker(new MarkerOptions().position(sydney)); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,15f)); } ``` Can anyone help me out?
2019/07/21
[ "https://Stackoverflow.com/questions/57133926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11591977/" ]
I called the on map ready inside on datachange so that whenever i got dta onMapReady runs after that only ``` @Override public void onMapReady(GoogleMap googleMap) { Query q = FirebaseDatabase.getInstance().getReference("HOSTELS").orderByChild("LOCATION_ID").equalTo(hostelID); q.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot childsnap:dataSnapshot.getChildren()){ LatAndLng latAndLng = childsnap.child("MAP_LOCATION").getValue(LatAndLng.class); lat.add(String.valueOf(latAndLng.getLATITUDE())); lng.add(String.valueOf(latAndLng.getLONGITUDE() )); Log.d("latitudess", "onDataChange: "+String.valueOf(latAndLng.getLATITUDE())); } LatLng sydney = new LatLng(Float.parseFloat(lat.get(0)), Float.parseFloat(lng.get(0))); googleMap.addMarker(new MarkerOptions().position(sydney)); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,15f)); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); ```
You have to asynchronous actions: 1. Loading the data that is displayed in the map 2. Loading the map that displays the data Since the map is dependent on the data, you should only start loading the map once the data is available. I can't show the code of how to do this, but you'll need to make the call that wires up whatever calls `onMapReady` from within `onDataChange` with something like: ``` mapRef=FirebaseDatabase.getInstance().getReference().child("HOSTELS").child(hostelID).child("MAP_LOCATION"); mapRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Inside_location inside_location=dataSnapshot.getValue(Inside_location.class); lat.add(Double.valueOf(inside_location.getLATITUDE()) ); lng.add(Double.valueOf(inside_location.getLONGITUDE())) ; // TODO: start loading the map based on the lat and lng } @Override public void onCancelled(@NonNull DatabaseError databaseError) { throw databaseError.toException(); // don't ignore errors } }); ```
57,133,926
Im fetching lat and lng from firebase but it runs after onMapReady hence when i pass coords to onMapReady it crashed beacause arraylist has nothing I want to run onMapReady after my data is loaded in my arrays ``` private void loadMapPins(){ Query q = FirebaseDatabase.getInstance().getReference("HOSTELS").orderByChild("LOCATION_ID").equalTo(hostelID); q.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot childsnap:dataSnapshot.getChildren()){ LatAndLng latAndLng = childsnap.child("MAP_LOCATION").getValue(LatAndLng.class); lat.add(String.valueOf(latAndLng.getLATITUDE())); lng.add(String.valueOf(latAndLng.getLONGITUDE() )); Log.d("latitudess", "onDataChange: "+String.valueOf(latAndLng.getLATITUDE())); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } @Override public void onMapReady(GoogleMap googleMap) { LatLng sydney = new LatLng(lat.get(0), lng.get(0)); googleMap.addMarker(new MarkerOptions().position(sydney) .title("Marker in Sydney")); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,15f)); } @Override public void onMapReady(GoogleMap googleMap) { loadMapPins(); LatLng sydney = new LatLng(Float.parseFloat(lat.get(0)), Float.parseFloat(lng.get(0))); googleMap.addMarker(new MarkerOptions().position(sydney)); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,15f)); } ``` Can anyone help me out?
2019/07/21
[ "https://Stackoverflow.com/questions/57133926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11591977/" ]
I called the on map ready inside on datachange so that whenever i got dta onMapReady runs after that only ``` @Override public void onMapReady(GoogleMap googleMap) { Query q = FirebaseDatabase.getInstance().getReference("HOSTELS").orderByChild("LOCATION_ID").equalTo(hostelID); q.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot childsnap:dataSnapshot.getChildren()){ LatAndLng latAndLng = childsnap.child("MAP_LOCATION").getValue(LatAndLng.class); lat.add(String.valueOf(latAndLng.getLATITUDE())); lng.add(String.valueOf(latAndLng.getLONGITUDE() )); Log.d("latitudess", "onDataChange: "+String.valueOf(latAndLng.getLATITUDE())); } LatLng sydney = new LatLng(Float.parseFloat(lat.get(0)), Float.parseFloat(lng.get(0))); googleMap.addMarker(new MarkerOptions().position(sydney)); googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney,15f)); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); ```
You must wait google map for load to do actions over it. In your case, call loadMapPins in onMapReady and your current onMapReady code move to the end of onDataChange method.
71,171,252
I'm working on an mongo database with mongoose in Node.js. I have a collection like this : ```json { cinema: 'xxx', account: 'yyy', media: { data: [{ id: 1, name: 'zzz' }, { id: 2, name: 'zzz' }, ... ] } } ``` Schema: ```js const dataCacheSchema = new mongoose.Schema( { cinemaName: String, account: String }, { timestamps: true, strict: false } ); ``` The list of data can be long. I would like to retrieve a single media from a findOne query : ```json { id: 1, name: 'zzz' } ``` I've tried like this : ```js const doc: mongoose.Document[] | null = await DataCache.findOne( { cinemaName: ci.cinema, account: ci.account, 'media.data': { $exists: true, $elemMatch: { id: mediaId } } }, { media: { data: { $elemMatch: { id: mediaId } } } } ).exec(); ``` But it crashes with the error message : `MongoError: Cannot use $elemMatch projection on a nested field.`
2022/02/18
[ "https://Stackoverflow.com/questions/71171252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6661258/" ]
You could use `dict.setdefault` to first store a dict of lists (where the keys are "street" and "number") and then iterate over the values of this dictionary to check if multiple dicts have the same "street" and "number" and modify "some\_flag" of those that are multiple: ``` tmp = {} for d in a: tmp.setdefault((d['street'], d['number']), []).append(d) out = [] for v in tmp.values(): if len(v) > 1: for d in v: d['some_flag'] = 1 out.extend(v) ``` Output: ``` [{'street': 'ocean drive', 'number': '1', 'some_flag': 0}, {'street': 'ocean drive', 'number': '3', 'some_flag': 0}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'apple tree rd.', 'number': '3', 'some_flag': 0}] ```
Simply can be done by: ```py import pandas as pd import numpy as np # Your code a = [ {'street': 'ocean drive', 'number': '1', 'some_flag': 0}, {'street': 'ocean drive', 'number': '3', 'some_flag': 0}, {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'apple tree rd.', 'number': '3', 'some_flag': 0}, ] # My code data = pd.DataFrame(a) data["some_flag"]= np.where(data.duplicated(keep=False), 1, data["some_flag"]) data ``` #### Output | | street | number | some\_flag | | --- | --- | --- | --- | | 0 | ocean drive | 1 | 0 | | 1 | ocean drive | 3 | 0 | | 2 | ocean drive | 4 | 1 | | 3 | ocean drive | 4 | 1 | | 4 | apple tree rd. | 3 | 0 | If you are interested in having a dictionary instead of the dataframe, you can try changing the dataframe to dictionary using `to_dict` function: ```py data.to_dict(orient="list") ``` which results in : ``` {'number': ['1', '3', '4', '4', '3'], 'some_flag': [0, 0, 1, 1, 0], 'street': ['ocean drive', 'ocean drive', 'ocean drive', 'ocean drive', 'apple tree rd.']} ``` #### Explanation Using `duplicated` function on a dataframe and assigning `False` to the `keep` parameter, you can find the duplicated rows. Then using `where` which is a numpy function, you can assign a value to an array based on a logical statement.
71,171,252
I'm working on an mongo database with mongoose in Node.js. I have a collection like this : ```json { cinema: 'xxx', account: 'yyy', media: { data: [{ id: 1, name: 'zzz' }, { id: 2, name: 'zzz' }, ... ] } } ``` Schema: ```js const dataCacheSchema = new mongoose.Schema( { cinemaName: String, account: String }, { timestamps: true, strict: false } ); ``` The list of data can be long. I would like to retrieve a single media from a findOne query : ```json { id: 1, name: 'zzz' } ``` I've tried like this : ```js const doc: mongoose.Document[] | null = await DataCache.findOne( { cinemaName: ci.cinema, account: ci.account, 'media.data': { $exists: true, $elemMatch: { id: mediaId } } }, { media: { data: { $elemMatch: { id: mediaId } } } } ).exec(); ``` But it crashes with the error message : `MongoError: Cannot use $elemMatch projection on a nested field.`
2022/02/18
[ "https://Stackoverflow.com/questions/71171252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6661258/" ]
If the list of dictionaries is not sorted, then we'd have to check every possible pair of elements for equality, which would take `O(n^2)` time. But if the list is sorted, then we could check each element with its next element, if they weren't equal, then there is no point checking that element with the following elements. On the other hand, if they were equal, we continue checking with the next one, and so on. ``` def is_duplicate(d_1, d_2): return d_1['street'] == d_2['street'] and d_1['number'] == d_2['number'] def set_duplicate(d_1, d_2): d_1['some_flag'] = 1 d_2['some_flag'] = 1 a = sorted(a, key=lambda k: (k['street'].lower(), k['number'])) cur_index = 0 while cur_index < len(a): next_index = cur_index + 1 while next_index < len(a) and is_duplicate(a[cur_index], a[next_index]): set_duplicate(a[cur_index], a[next_index]) next_index += 1 cur_index += 1 print(a) ```
Simply can be done by: ```py import pandas as pd import numpy as np # Your code a = [ {'street': 'ocean drive', 'number': '1', 'some_flag': 0}, {'street': 'ocean drive', 'number': '3', 'some_flag': 0}, {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'apple tree rd.', 'number': '3', 'some_flag': 0}, ] # My code data = pd.DataFrame(a) data["some_flag"]= np.where(data.duplicated(keep=False), 1, data["some_flag"]) data ``` #### Output | | street | number | some\_flag | | --- | --- | --- | --- | | 0 | ocean drive | 1 | 0 | | 1 | ocean drive | 3 | 0 | | 2 | ocean drive | 4 | 1 | | 3 | ocean drive | 4 | 1 | | 4 | apple tree rd. | 3 | 0 | If you are interested in having a dictionary instead of the dataframe, you can try changing the dataframe to dictionary using `to_dict` function: ```py data.to_dict(orient="list") ``` which results in : ``` {'number': ['1', '3', '4', '4', '3'], 'some_flag': [0, 0, 1, 1, 0], 'street': ['ocean drive', 'ocean drive', 'ocean drive', 'ocean drive', 'apple tree rd.']} ``` #### Explanation Using `duplicated` function on a dataframe and assigning `False` to the `keep` parameter, you can find the duplicated rows. Then using `where` which is a numpy function, you can assign a value to an array based on a logical statement.
71,171,252
I'm working on an mongo database with mongoose in Node.js. I have a collection like this : ```json { cinema: 'xxx', account: 'yyy', media: { data: [{ id: 1, name: 'zzz' }, { id: 2, name: 'zzz' }, ... ] } } ``` Schema: ```js const dataCacheSchema = new mongoose.Schema( { cinemaName: String, account: String }, { timestamps: true, strict: false } ); ``` The list of data can be long. I would like to retrieve a single media from a findOne query : ```json { id: 1, name: 'zzz' } ``` I've tried like this : ```js const doc: mongoose.Document[] | null = await DataCache.findOne( { cinemaName: ci.cinema, account: ci.account, 'media.data': { $exists: true, $elemMatch: { id: mediaId } } }, { media: { data: { $elemMatch: { id: mediaId } } } } ).exec(); ``` But it crashes with the error message : `MongoError: Cannot use $elemMatch projection on a nested field.`
2022/02/18
[ "https://Stackoverflow.com/questions/71171252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6661258/" ]
You could use `dict.setdefault` to first store a dict of lists (where the keys are "street" and "number") and then iterate over the values of this dictionary to check if multiple dicts have the same "street" and "number" and modify "some\_flag" of those that are multiple: ``` tmp = {} for d in a: tmp.setdefault((d['street'], d['number']), []).append(d) out = [] for v in tmp.values(): if len(v) > 1: for d in v: d['some_flag'] = 1 out.extend(v) ``` Output: ``` [{'street': 'ocean drive', 'number': '1', 'some_flag': 0}, {'street': 'ocean drive', 'number': '3', 'some_flag': 0}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'apple tree rd.', 'number': '3', 'some_flag': 0}] ```
You can also achieve this without pandas with a little more code e.g. like this: ``` import copy a = [ {'street': 'ocean drive', 'number': '1', 'some_flag': 0}, {'street': 'ocean drive', 'number': '3', 'some_flag': 0}, {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'apple tree rd.', 'number': '3', 'some_flag': 0}, ] result = copy.deepcopy(a) #duplicate a to not override your input last_entry = "" for entry in result: if last_entry == "": #skip first iteration to have two entries to compare last_entry = entry continue if last_entry["street"] == entry["street"] and last_entry["number"] == entry["number"]: last_entry["some_flag"] = 1 entry["some_flag"] = 1 last_entry = entry print(result) ```
71,171,252
I'm working on an mongo database with mongoose in Node.js. I have a collection like this : ```json { cinema: 'xxx', account: 'yyy', media: { data: [{ id: 1, name: 'zzz' }, { id: 2, name: 'zzz' }, ... ] } } ``` Schema: ```js const dataCacheSchema = new mongoose.Schema( { cinemaName: String, account: String }, { timestamps: true, strict: false } ); ``` The list of data can be long. I would like to retrieve a single media from a findOne query : ```json { id: 1, name: 'zzz' } ``` I've tried like this : ```js const doc: mongoose.Document[] | null = await DataCache.findOne( { cinemaName: ci.cinema, account: ci.account, 'media.data': { $exists: true, $elemMatch: { id: mediaId } } }, { media: { data: { $elemMatch: { id: mediaId } } } } ).exec(); ``` But it crashes with the error message : `MongoError: Cannot use $elemMatch projection on a nested field.`
2022/02/18
[ "https://Stackoverflow.com/questions/71171252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6661258/" ]
You could use `dict.setdefault` to first store a dict of lists (where the keys are "street" and "number") and then iterate over the values of this dictionary to check if multiple dicts have the same "street" and "number" and modify "some\_flag" of those that are multiple: ``` tmp = {} for d in a: tmp.setdefault((d['street'], d['number']), []).append(d) out = [] for v in tmp.values(): if len(v) > 1: for d in v: d['some_flag'] = 1 out.extend(v) ``` Output: ``` [{'street': 'ocean drive', 'number': '1', 'some_flag': 0}, {'street': 'ocean drive', 'number': '3', 'some_flag': 0}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'apple tree rd.', 'number': '3', 'some_flag': 0}] ```
If the list of dictionaries is not sorted, then we'd have to check every possible pair of elements for equality, which would take `O(n^2)` time. But if the list is sorted, then we could check each element with its next element, if they weren't equal, then there is no point checking that element with the following elements. On the other hand, if they were equal, we continue checking with the next one, and so on. ``` def is_duplicate(d_1, d_2): return d_1['street'] == d_2['street'] and d_1['number'] == d_2['number'] def set_duplicate(d_1, d_2): d_1['some_flag'] = 1 d_2['some_flag'] = 1 a = sorted(a, key=lambda k: (k['street'].lower(), k['number'])) cur_index = 0 while cur_index < len(a): next_index = cur_index + 1 while next_index < len(a) and is_duplicate(a[cur_index], a[next_index]): set_duplicate(a[cur_index], a[next_index]) next_index += 1 cur_index += 1 print(a) ```
71,171,252
I'm working on an mongo database with mongoose in Node.js. I have a collection like this : ```json { cinema: 'xxx', account: 'yyy', media: { data: [{ id: 1, name: 'zzz' }, { id: 2, name: 'zzz' }, ... ] } } ``` Schema: ```js const dataCacheSchema = new mongoose.Schema( { cinemaName: String, account: String }, { timestamps: true, strict: false } ); ``` The list of data can be long. I would like to retrieve a single media from a findOne query : ```json { id: 1, name: 'zzz' } ``` I've tried like this : ```js const doc: mongoose.Document[] | null = await DataCache.findOne( { cinemaName: ci.cinema, account: ci.account, 'media.data': { $exists: true, $elemMatch: { id: mediaId } } }, { media: { data: { $elemMatch: { id: mediaId } } } } ).exec(); ``` But it crashes with the error message : `MongoError: Cannot use $elemMatch projection on a nested field.`
2022/02/18
[ "https://Stackoverflow.com/questions/71171252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6661258/" ]
You could use `dict.setdefault` to first store a dict of lists (where the keys are "street" and "number") and then iterate over the values of this dictionary to check if multiple dicts have the same "street" and "number" and modify "some\_flag" of those that are multiple: ``` tmp = {} for d in a: tmp.setdefault((d['street'], d['number']), []).append(d) out = [] for v in tmp.values(): if len(v) > 1: for d in v: d['some_flag'] = 1 out.extend(v) ``` Output: ``` [{'street': 'ocean drive', 'number': '1', 'some_flag': 0}, {'street': 'ocean drive', 'number': '3', 'some_flag': 0}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'apple tree rd.', 'number': '3', 'some_flag': 0}] ```
``` du = {} for d in a: new_key = d['street'] + "_" + d['number'] if new_key in du.keys(): du[new_key] = du[new_key] + 1 else: du[new_key] = 1 print(du) # {'ocean drive_1': 1, 'ocean drive_3': 1, 'ocean drive_4': 2, 'apple tree rd._3': 1} for k, v in du.items(): if v > 1: k1 = k.split("_")[0] k2 = k.split("_")[1] for d in a: if d['street'] == k1 and d['number'] == k2: d['some_flag'] = 1 print(a) # [{'street': 'ocean drive', 'number': '1', 'some_flag': 0}, {'street': 'ocean drive', 'number': '3', 'some_flag': 0}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'apple tree rd.', 'number': '3', 'some_flag': 0}] ```
71,171,252
I'm working on an mongo database with mongoose in Node.js. I have a collection like this : ```json { cinema: 'xxx', account: 'yyy', media: { data: [{ id: 1, name: 'zzz' }, { id: 2, name: 'zzz' }, ... ] } } ``` Schema: ```js const dataCacheSchema = new mongoose.Schema( { cinemaName: String, account: String }, { timestamps: true, strict: false } ); ``` The list of data can be long. I would like to retrieve a single media from a findOne query : ```json { id: 1, name: 'zzz' } ``` I've tried like this : ```js const doc: mongoose.Document[] | null = await DataCache.findOne( { cinemaName: ci.cinema, account: ci.account, 'media.data': { $exists: true, $elemMatch: { id: mediaId } } }, { media: { data: { $elemMatch: { id: mediaId } } } } ).exec(); ``` But it crashes with the error message : `MongoError: Cannot use $elemMatch projection on a nested field.`
2022/02/18
[ "https://Stackoverflow.com/questions/71171252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6661258/" ]
If the list of dictionaries is not sorted, then we'd have to check every possible pair of elements for equality, which would take `O(n^2)` time. But if the list is sorted, then we could check each element with its next element, if they weren't equal, then there is no point checking that element with the following elements. On the other hand, if they were equal, we continue checking with the next one, and so on. ``` def is_duplicate(d_1, d_2): return d_1['street'] == d_2['street'] and d_1['number'] == d_2['number'] def set_duplicate(d_1, d_2): d_1['some_flag'] = 1 d_2['some_flag'] = 1 a = sorted(a, key=lambda k: (k['street'].lower(), k['number'])) cur_index = 0 while cur_index < len(a): next_index = cur_index + 1 while next_index < len(a) and is_duplicate(a[cur_index], a[next_index]): set_duplicate(a[cur_index], a[next_index]) next_index += 1 cur_index += 1 print(a) ```
You can also achieve this without pandas with a little more code e.g. like this: ``` import copy a = [ {'street': 'ocean drive', 'number': '1', 'some_flag': 0}, {'street': 'ocean drive', 'number': '3', 'some_flag': 0}, {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'ocean drive', 'number': '4', 'some_flag': 0}, # duplicate street / number keys {'street': 'apple tree rd.', 'number': '3', 'some_flag': 0}, ] result = copy.deepcopy(a) #duplicate a to not override your input last_entry = "" for entry in result: if last_entry == "": #skip first iteration to have two entries to compare last_entry = entry continue if last_entry["street"] == entry["street"] and last_entry["number"] == entry["number"]: last_entry["some_flag"] = 1 entry["some_flag"] = 1 last_entry = entry print(result) ```
71,171,252
I'm working on an mongo database with mongoose in Node.js. I have a collection like this : ```json { cinema: 'xxx', account: 'yyy', media: { data: [{ id: 1, name: 'zzz' }, { id: 2, name: 'zzz' }, ... ] } } ``` Schema: ```js const dataCacheSchema = new mongoose.Schema( { cinemaName: String, account: String }, { timestamps: true, strict: false } ); ``` The list of data can be long. I would like to retrieve a single media from a findOne query : ```json { id: 1, name: 'zzz' } ``` I've tried like this : ```js const doc: mongoose.Document[] | null = await DataCache.findOne( { cinemaName: ci.cinema, account: ci.account, 'media.data': { $exists: true, $elemMatch: { id: mediaId } } }, { media: { data: { $elemMatch: { id: mediaId } } } } ).exec(); ``` But it crashes with the error message : `MongoError: Cannot use $elemMatch projection on a nested field.`
2022/02/18
[ "https://Stackoverflow.com/questions/71171252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6661258/" ]
If the list of dictionaries is not sorted, then we'd have to check every possible pair of elements for equality, which would take `O(n^2)` time. But if the list is sorted, then we could check each element with its next element, if they weren't equal, then there is no point checking that element with the following elements. On the other hand, if they were equal, we continue checking with the next one, and so on. ``` def is_duplicate(d_1, d_2): return d_1['street'] == d_2['street'] and d_1['number'] == d_2['number'] def set_duplicate(d_1, d_2): d_1['some_flag'] = 1 d_2['some_flag'] = 1 a = sorted(a, key=lambda k: (k['street'].lower(), k['number'])) cur_index = 0 while cur_index < len(a): next_index = cur_index + 1 while next_index < len(a) and is_duplicate(a[cur_index], a[next_index]): set_duplicate(a[cur_index], a[next_index]) next_index += 1 cur_index += 1 print(a) ```
``` du = {} for d in a: new_key = d['street'] + "_" + d['number'] if new_key in du.keys(): du[new_key] = du[new_key] + 1 else: du[new_key] = 1 print(du) # {'ocean drive_1': 1, 'ocean drive_3': 1, 'ocean drive_4': 2, 'apple tree rd._3': 1} for k, v in du.items(): if v > 1: k1 = k.split("_")[0] k2 = k.split("_")[1] for d in a: if d['street'] == k1 and d['number'] == k2: d['some_flag'] = 1 print(a) # [{'street': 'ocean drive', 'number': '1', 'some_flag': 0}, {'street': 'ocean drive', 'number': '3', 'some_flag': 0}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'ocean drive', 'number': '4', 'some_flag': 1}, {'street': 'apple tree rd.', 'number': '3', 'some_flag': 0}] ```
47,870,991
I've written a simple Java bytecode parser to do some experimentation and recently it failed in an unexpected place. While reading `java/lang/reflect/Member.java` from Java 1.1.8.16's `rt.jar`, my parser got mad because `Member` starts out like so (note the missing `ACC_ABSTRACT` flag): ``` Classfile Member.class Last modified Aug 8, 2002; size 350 bytes MD5 checksum 9a1aaec8e70e9a2ff9d63331cb0ea34e Compiled from "Member.java" public interface java.lang.reflect.Member minor version: 3 major version: 45 flags: (0x0201) ACC_PUBLIC, ACC_INTERFACE ... ``` The version from Java 1.2.2.17 corrects this and has flags set to `0x0601` (`ACC_ABSTRACT | ACC_INTERFACE | ACC_PUBLIC`). The earliest JVM specification I can find (purportedly 1.0.2) has this to say (§4.1, p. 86, emphasis added): > > An interface is implicitly abstract (§2.13.1); its `ACC_ABSTRACT` flag **must be set**. An interface cannot be final; its implementation could never be completed (§2.13.1) if it were, so it could not have its `ACC_FINAL` flag set. > > > Version 9 of the JVM spec [has similar words to say](https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.1): > > If the `ACC_INTERFACE` flag is set, the `ACC_ABSTRACT` flag **must also be set**, and the `ACC_FINAL`, `ACC_SUPER`, `ACC_ENUM`, and `ACC_MODULE` flags set must not be set. > > > Does the Oracle/Sun JVM enforce this requirement that "must be" so? If so, since when? And if not, why does the JVM specification bother to pretend it is required?
2017/12/18
[ "https://Stackoverflow.com/questions/47870991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1911388/" ]
This was a bug [JDK-4059153](https://bugs.openjdk.java.net/browse/JDK-4059153): javac did not set `ACC_ABSTRACT` for interfaces. The bug was fixed in 1.2, but since there were already many classes compiled with this bug, JVM got a workaround to add `ACC_ABSTRACT` automatically for all classes with `ACC_INTERFACE`. This worked until Java 6, when it was finally decided to strictly follow the specification for newer class files. However, for backward compatibility with older versions of class files, the workaround still exists up until now, see [classFileParser.cpp](http://hg.openjdk.java.net/jdk9/jdk9/hotspot/file/b756e7a2ec33/src/share/vm/classfile/classFileParser.cpp#l3093): ``` if ((flags & JVM_ACC_INTERFACE) && _major_version < JAVA_6_VERSION) { // Set abstract bit for old class files for backward compatibility flags |= JVM_ACC_ABSTRACT; } ```
It's not clear to me *why* but I experimented by creating the following classes, compiling them with Java 9's `javac` and then manually editing `access_flags` to `0x200` in `Foo`; then manually cycling `minor_version` and `major_version` through the different Java versions to see what would happen: ``` interface Foo { } class Bar implements Foo { public static void main(String[] args) { System.out.println("BAZ"); } } ``` Results: ``` ╭──────╥───────┬───────┬─────╮ │ Java ║ minor │ major │ out │ ╞══════╬═══════╪═══════╪═════╡ │ 1.1 ║ 03 │ 2d │ BAZ │ │ 1.2 ║ " │ " │ BAZ │ │ 1.3 ║ " │ 2e │ BAZ │ │ 1.4 ║ 00 │ 2f │ BAZ │ │ 5 ║ 00 │ 31 │ BAZ │ │ 6 ║ 00 │ 32 │ err │ │ 7 ║ 00 │ 33 │ err │ │ 8 ║ 00 │ 34 │ err │ │ 9 ║ 00 │ 35 │ err │ └──────╨───────┴───────┴─────┘ ``` Where "err" really prints out like this: ``` Error: LinkageError occurred while loading main class Bar java.lang.ClassFormatError: Illegal class modifiers in class Foo: 0x200 ``` So I guess they finally got around to enforcing it in Java 6. Still not sure why.
58,508,895
I have 2 sibling divs that I need to float to make a 2 column layout. Div 1 and 2 have to float left and div 3 has to float right. Normally I can get this by rearranging Div 2 and Div 3's positions but because the markup is generated by Javascript I dont have the luxury to rearrange them, nor do I have to option to group Div1 and 2 together as a result. No matter what I try or what clear CSS i attempt, Div 3 always appears below Div 2 on the right side, when I need it on the top next to Div 1. This is what I have to work with: ```css .parent{ width:800px; } .div1{ float:left; width:60%; height:100px; background:red; } .div2{ float:left; width:60%; height:100px; background:red; } .div3{ float:right; width:40%; background:blue; height:100px; } ``` ```html <div class="parent"> <div class="div1">Div 1</div> <div class="div2">Div 2</div> <div class="div3">Div 3</div> </div> ``` Is there any way to make Div 3 float next to Div1 without rearranging the markup?
2019/10/22
[ "https://Stackoverflow.com/questions/58508895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2904208/" ]
Okay tried to do it with flex box and giving a order property o all the divs. ``` .parent{ width:800px; display: flex; flex-wrap: wrap; } .div1{ width:60%; height:100px; background:red; order: 1; } .div2{ width:60%; height:100px; background:red; order: 3; } .div3{ width:40%; background:blue; height:100px; order: 2; } ``` working example : <https://codepen.io/shubham997/pen/ExxWYEd?editors=0100>
I suggest you to use flex on parent div and correct your percentage ratio of the child divs so that it sums to 100%. I have given margin-left:auto for the child you wanted to place at right end, which will float on right side even if you reduce the width of other divs. Demo [here](https://codepen.io/AravinthAro/pen/RwwKXOd) ``` <div class="parent"> <div class="col-left"> <div class="div1">Div 1</div> <div class="div2">Div 2</div> </div> <div class="div3">Div 3</div> </div> .parent{ width:800px; display:flex; } .col-left{ display:flex; flex-direction:column; width:60%; } .div1, .div2{ height:100px; background:red; width:100%; } .div3{ margin-left:auto; width:40%; background:blue; height:100px; } ```
5,749,188
I have a Python `float`, and I want to have the `float`s which are 1 [ULP](http://en.wikipedia.org/wiki/Unit_in_the_last_place) greater and lesser. In Java, I would do this with [`Math.nextUp(x)`](http://download.oracle.com/javase/6/docs/api/java/lang/Math.html#nextUp%28double%29) and [`Math.nextAfter(x, Double.NEGATIVE_INFINITY)`](http://download.oracle.com/javase/6/docs/api/java/lang/Math.html#nextAfter%28double,%20double%29). Is there a way to do this in Python? I thought about implementing it myself with [`math.frexp` and `math.ldexp`](http://docs.python.org/library/math.html) but as far as I know Python doesn't specify the size of floating point types.
2011/04/21
[ "https://Stackoverflow.com/questions/5749188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/599152/" ]
**Update:** In Python 3.9+ there is [`math.nextafter()`](https://docs.python.org/3/library/math.html#math.nextafter): ```py >>> import math >>> x = 4 >>> math.nextafter(x, math.inf) 4.000000000000001 ``` --- Old answer: You could look at how [`Decimal.next_plus()`/`Decimal.next_minus()`](http://hg.python.org/cpython/file/fecf9e6d7630/Lib/decimal.py#l3448) are implemented: ``` >>> from decimal import Decimal as D >>> d = D.from_float(123456.78901234567890) >>> d Decimal('123456.789012345674564130604267120361328125') >>> d.next_plus() Decimal('123456.7890123456745641306043') >>> d.next_minus() Decimal('123456.7890123456745641306042') >>> d.next_toward(D('-inf')) Decimal('123456.7890123456745641306042') ``` Make sure that [decimal context](http://docs.python.org/library/decimal.html#decimal.Context) has values that you need: ``` >>> from decimal import getcontext >>> getcontext() Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capitals=1, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow]) ``` --- Alternatives: * Call [C99 `nextafter()`](https://stackoverflow.com/a/6163157/4279) using `ctypes`: ``` >>> import ctypes >>> nextafter = ctypes.CDLL(None).nextafter >>> nextafter.argtypes = ctypes.c_double, ctypes.c_double >>> nextafter.restype = ctypes.c_double >>> nextafter(4, float('+inf')) 4.000000000000001 >>> _.as_integer_ratio() (4503599627370497, 1125899906842624) ``` Using `numpy`: ``` >>> import numpy >>> numpy.nextafter(4, float('+inf')) 4.0000000000000009 >>> _.as_integer_ratio() (4503599627370497, 1125899906842624) ``` Despite different `repr()`, the result is the same. * If we ignore edge cases then a simple frexp/ldexp solution from [@S.Lott answer](https://stackoverflow.com/a/6064066/4279) works: ``` >>> import math, sys >>> m, e = math.frexp(4.0) >>> math.ldexp(2 * m + sys.float_info.epsilon, e - 1) 4.000000000000001 >>> _.as_integer_ratio() (4503599627370497, 1125899906842624) ``` * [pure Python `next_after(x, y)` implementation by @Mark Dickinson](https://stackoverflow.com/a/10426033/4279) that takes into account edge cases. The result is the same in this case.
I am not sure if this is what you want, but `sys.float_info.epsilon` is the "difference between 1 and the least value greater than 1 that is representable as a float", and you could do `x * (1 + sys.float_info.epsilon)`. <http://docs.python.org/library/sys.html#sys.float_info>
25,412,090
I'm trying to establish replication between two linux boxes. My master and slave are on LAN, both can ping each other and can telnet ip 3306, meaning the mysql ports are open on both ends. I created a replication user on master and on slave: ``` change master to master_host ='master_ip'; change master to master_user ='replicator'; change master to master_password ='password'; ``` Master gives this when showing master status: ``` +------------------+----------+--------------+------------------+ | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | +------------------+----------+--------------+------------------+ | mysql-bin.000001 | 546050 | | | +------------------+----------+--------------+------------------+ 1 row in set (0.01 sec) ``` I'm getting the following error on show slave status: ``` Slave_IO_Running: Connecting Slave_SQL_Running: Yes .. Last_IO_Errno: 2003 Last_IO_Error: error connecting to master 'replicator@master_ip:3306' - retry-time: 60 retries: 86400 ``` Anyone has any ideas as to what this could be, or any other info you may need? EDIT: On the slave the last line of show slave status\G reads: Master\_Server\_Id: 0 Shouldn't that say 1 as that is master's ID?
2014/08/20
[ "https://Stackoverflow.com/questions/25412090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1617364/" ]
I suspect your `Textbox` is actually within some other containers, like a `Panel`. Try to find your control using a recursive approach: ``` public static Control FindTargetTextbox(Control control, string targetName) { foreach (Control child in control.Controls) { if (child is TextBox && child.Name == targetName) { return child; } } foreach (Control child in control.Controls) { Control target = FindTargetComponent(child); if (target != null) { return target; } } return null; } ``` Bear in mind that your form is the biggest container, therefore you should pass it in as the starting point: ``` TextBox textBox = FindTargetTextbox(this, name); ``` **Edit** As @mikeng mentioned in the comment, we are able to merge two `foreach` into one like this: ``` public static Control FindTargetTextbox(Control control, string targetName) { foreach (Control child in control.Controls) { if (child is TextBox && child.Name == targetName) { return child; } Control target = FindTargetComponent(child); if (target != null) { return target; } } return null; } ``` This is indeed another valid approach, but one should choose the most appropriate approach based on the real situation: The first approach explores **all controls in the same container** before it goes deep into a child control of that container, which is a **Breadth First Search**, while the second approach focuses on **nested controls one by one**, i.e. it goes to next container only after it finishes processing all controls in the current container, which is a **Depth First Search**.
As i said your is correct so 1)The isn't a textbox with the specified name 2)There is a textbox but it is inside a container In any case,use this code to find which controls exist on your form and then call the Find method from the correct container ``` foreach (Control item in this.Controls) { if (item is TextBox) Console.WriteLine("TextBox:" + item.Name); else Console.WriteLine(item.GetType().Name + ":" + item.Name); ``` }
43,601,057
``` <html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="/css/graph2.css"> <title>Graph</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script> </head> <body> <canvas id="updating-chart" width="200" height="200"></canvas> </body> </html> ``` That is the html I am using and I am using `Chart.js 2.1.4`, but I am unable to reduce the size no matter what I do. **Javascript:** ``` <script type="text/javascript"> var canvas = document.getElementById('updating-chart'), ctx = canvas.getContext('2d'), startingData = { labels: ["A", "B", "C", "D"], datasets: [ { label: "Product A", fillColor: "rgba(220,220,220,0.5)", strokeColor: "rgba(220,220,220,0.8)", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "#fff", data: [65, 59, 80, 81] } ] }; var myLiveChart = new Chart(ctx,{ type: 'bar', data: startingData, responsive: true, maintainAspectRatio: true }); </script> ``` How can I fix this? I always a get a really big graph, covering the whole screen completely no matter what I change in the `canvas` HTML fields. Help?
2017/04/25
[ "https://Stackoverflow.com/questions/43601057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7715987/" ]
If you put the canvas in container and use CSS to set the width on that, it will size the graph. <https://jsfiddle.net/ug5eczp2/1/> HTML: ``` <section> <canvas id="updating-chart" width="200" height="200"></canvas> </section> ``` CSS: ``` section { width: 50%; } ```
The canvas will fit the section container. Code below. just change the width of the section to the value you want. ``` <section> <canvas id="updating-chart" ></canvas> </section> section { width: 100%; } section > canvas { top: 0; bottom: 0; right: 0; left: 0; } ```
43,601,057
``` <html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="/css/graph2.css"> <title>Graph</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script> </head> <body> <canvas id="updating-chart" width="200" height="200"></canvas> </body> </html> ``` That is the html I am using and I am using `Chart.js 2.1.4`, but I am unable to reduce the size no matter what I do. **Javascript:** ``` <script type="text/javascript"> var canvas = document.getElementById('updating-chart'), ctx = canvas.getContext('2d'), startingData = { labels: ["A", "B", "C", "D"], datasets: [ { label: "Product A", fillColor: "rgba(220,220,220,0.5)", strokeColor: "rgba(220,220,220,0.8)", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "#fff", data: [65, 59, 80, 81] } ] }; var myLiveChart = new Chart(ctx,{ type: 'bar', data: startingData, responsive: true, maintainAspectRatio: true }); </script> ``` How can I fix this? I always a get a really big graph, covering the whole screen completely no matter what I change in the `canvas` HTML fields. Help?
2017/04/25
[ "https://Stackoverflow.com/questions/43601057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7715987/" ]
If you put the canvas in container and use CSS to set the width on that, it will size the graph. <https://jsfiddle.net/ug5eczp2/1/> HTML: ``` <section> <canvas id="updating-chart" width="200" height="200"></canvas> </section> ``` CSS: ``` section { width: 50%; } ```
you can try remove the width value, specified height value only ``` <canvas id="updating-chart" height="200"></canvas> ```
30,142,669
I have a problem with the new Google Play Service and its GPS function. Right now I am using this code: ``` package my.app.client; import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.location.Location; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStatusCodes; import java.text.DateFormat; import java.util.Date; /** * Using location settings. * <p/> * Uses the {@link com.google.android.gms.location.SettingsApi} to ensure that the device's system * settings are properly configured for the app's location needs. When making a request to * Location services, the device's system settings may be in a state that prevents the app from * obtaining the location data that it needs. For example, GPS or Wi-Fi scanning may be switched * off. The {@code SettingsApi} makes it possible to determine if a device's system settings are * adequate for the location request, and to optionally invoke a dialog that allows the user to * enable the necessary settings. * <p/> * This sample allows the user to request location updates using the ACCESS_FINE_LOCATION setting * (as specified in AndroidManifest.xml). The sample requires that the device has location enabled * and set to the "High accuracy" mode. If location is not enabled, or if the location mode does * not permit high accuracy determination of location, the activity uses the {@code SettingsApi} * to invoke a dialog without requiring the developer to understand which settings are needed for * different Location requirements. */ public class NewGPSClient extends ActionBarActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener, ResultCallback<LocationSettingsResult> { protected static final String TAG = "location-settings"; /** * Constant used in the location settings dialog. */ protected static final int REQUEST_CHECK_SETTINGS = 0x1; /** * The desired interval for location updates. Inexact. Updates may be more or less frequent. */ public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; /** * The fastest rate for active location updates. Exact. Updates will never be more frequent * than this value. */ public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2; // Keys for storing activity state in the Bundle. protected final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates"; protected final static String KEY_LOCATION = "location"; protected final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string"; /** * Provides the entry point to Google Play services. */ protected GoogleApiClient mGoogleApiClient; /** * Stores parameters for requests to the FusedLocationProviderApi. */ protected LocationRequest mLocationRequest; /** * Stores the types of location services the client is interested in using. Used for checking * settings to determine if the device has optimal location settings. */ protected LocationSettingsRequest mLocationSettingsRequest; /** * Represents a geographical location. */ protected Location mCurrentLocation; // UI Widgets. protected Button mStartUpdatesButton; protected Button mStopUpdatesButton; protected TextView mLastUpdateTimeTextView; protected TextView mLatitudeTextView; protected TextView mLongitudeTextView; /** * Tracks the status of the location updates request. Value changes when the user presses the * Start Updates and Stop Updates buttons. */ protected Boolean mRequestingLocationUpdates; /** * Time when the location was updated represented as a String. */ protected String mLastUpdateTime; @Override public void onCreate(Bundle savedInstanceState) { //super.onCreate(savedInstanceState); //setContentView(R.layout.main_activity); // Locate the UI widgets. /*mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button); mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button); mLatitudeTextView = (TextView) findViewById(R.id.latitude_text); mLongitudeTextView = (TextView) findViewById(R.id.longitude_text); mLastUpdateTimeTextView = (TextView) findViewById(R.id.last_update_time_text);*/ Log.e(TAG, "NEWGPSCLIENT created successfully!"); mRequestingLocationUpdates = false; mLastUpdateTime = ""; // Update values using data stored in the Bundle. //updateValuesFromBundle(savedInstanceState); // Kick off the process of building the GoogleApiClient, LocationRequest, and // LocationSettingsRequest objects. buildGoogleApiClient(); createLocationRequest(); buildLocationSettingsRequest(); startLocationUpdates(); } /** * Updates fields based on data stored in the bundle. * * @param savedInstanceState The activity state saved in the Bundle. */ private void updateValuesFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { // Update the value of mRequestingLocationUpdates from the Bundle, and make sure that // the Start Updates and Stop Updates buttons are correctly enabled or disabled. if (savedInstanceState.keySet().contains(KEY_REQUESTING_LOCATION_UPDATES)) { mRequestingLocationUpdates = savedInstanceState.getBoolean( KEY_REQUESTING_LOCATION_UPDATES); } // Update the value of mCurrentLocation from the Bundle and update the UI to show the // correct latitude and longitude. if (savedInstanceState.keySet().contains(KEY_LOCATION)) { // Since KEY_LOCATION was found in the Bundle, we can be sure that mCurrentLocation // is not null. mCurrentLocation = savedInstanceState.getParcelable(KEY_LOCATION); } // Update the value of mLastUpdateTime from the Bundle and update the UI. if (savedInstanceState.keySet().contains(KEY_LAST_UPDATED_TIME_STRING)) { mLastUpdateTime = savedInstanceState.getString(KEY_LAST_UPDATED_TIME_STRING); } updateUI(); } } /** * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the * LocationServices API. */ protected synchronized void buildGoogleApiClient() { Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } /** * Sets up the location request. Android has two location request settings: * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in * the AndroidManifest.xml. * <p/> * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update * interval (5 seconds), the Fused Location Provider API returns location updates that are * accurate to within a few feet. * <p/> * These settings are appropriate for mapping applications that show real-time location * updates. */ protected void createLocationRequest() { mLocationRequest = new LocationRequest(); // Sets the desired interval for active location updates. This interval is // inexact. You may not receive updates at all if no location sources are available, or // you may receive them slower than requested. You may also receive updates faster than // requested if other applications are requesting location at a faster interval. mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); // Sets the fastest rate for active location updates. This interval is exact, and your // application will never receive updates faster than this value. mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } /** * Uses a {@link com.google.android.gms.location.LocationSettingsRequest.Builder} to build * a {@link com.google.android.gms.location.LocationSettingsRequest} that is used for checking * if a device has the needed location settings. */ protected void buildLocationSettingsRequest() { LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); mLocationSettingsRequest = builder.build(); } /** * Check if the device's location settings are adequate for the app's needs using the * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} method, with the results provided through a {@code PendingResult}. */ protected void checkLocationSettings() { PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings( mGoogleApiClient, mLocationSettingsRequest ); result.setResultCallback(this); } /** * The callback invoked when * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} is called. Examines the * {@link com.google.android.gms.location.LocationSettingsResult} object and determines if * location settings are adequate. If they are not, begins the process of presenting a location * settings dialog to the user. */ public void onResult(LocationSettingsResult locationSettingsResult) { final Status status = locationSettingsResult.getStatus(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: Log.i(TAG, "All location settings are satisfied."); startLocationUpdates(); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" + "upgrade location settings "); /* try { // Show the dialog by calling startResolutionForResult(), and check the result // in onActivityResult(). // status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { Log.i(TAG, "PendingIntent unable to execute request."); }*/ break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " + "not created."); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: Log.i(TAG, "User agreed to make required location settings changes."); startLocationUpdates(); break; case Activity.RESULT_CANCELED: Log.i(TAG, "User chose not to make required location settings changes."); break; } break; } } /** * Handles the Start Updates button and requests start of location updates. Does nothing if * updates have already been requested. */ public void startUpdatesButtonHandler(View view) { checkLocationSettings(); } /** * Handles the Stop Updates button, and requests removal of location updates. */ public void stopUpdatesButtonHandler(View view) { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. stopLocationUpdates(); } /** * Requests location updates from the FusedLocationApi. */ protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this ).setResultCallback(new ResultCallback<Status>() { public void onResult(Status status) { mRequestingLocationUpdates = true; //setButtonsEnabledState(); } }); } /** * Updates all UI fields. */ private void updateUI() { //setButtonsEnabledState(); updateLocationUI(); } /** * Disables both buttons when functionality is disabled due to insuffucient location settings. * Otherwise ensures that only one button is enabled at any time. The Start Updates button is * enabled if the user is not requesting location updates. The Stop Updates button is enabled * if the user is requesting location updates. */ /*private void setButtonsEnabledState() { if (mRequestingLocationUpdates) { mStartUpdatesButton.setEnabled(false); mStopUpdatesButton.setEnabled(true); } else { mStartUpdatesButton.setEnabled(true); mStopUpdatesButton.setEnabled(false); } }*/ /** * Sets the value of the UI fields for the location latitude, longitude and last update time. */ private void updateLocationUI() { if (mCurrentLocation != null) { mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude())); mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude())); mLastUpdateTimeTextView.setText(mLastUpdateTime); } } /** * Removes location updates from the FusedLocationApi. */ protected void stopLocationUpdates() { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this ).setResultCallback(new ResultCallback<Status>() { public void onResult(Status status) { mRequestingLocationUpdates = false; //setButtonsEnabledState(); } }); } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override public void onResume() { super.onResume(); // Within {@code onPause()}, we pause location updates, but leave the // connection to GoogleApiClient intact. Here, we resume receiving // location updates if the user has requested them. if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { startLocationUpdates(); } } @Override protected void onPause() { super.onPause(); // Stop location updates to save battery, but don't disconnect the GoogleApiClient object. if (mGoogleApiClient.isConnected()) { stopLocationUpdates(); } } @Override protected void onStop() { super.onStop(); mGoogleApiClient.disconnect(); } /** * Runs when a GoogleApiClient object successfully connects. */ public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); if (mCurrentLocation == null) { mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); } } /** * Callback that fires when the location changes. */ public void onLocationChanged(Location location) { mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); /*Toast.makeText(this, getResources().getString(R.string.location_updated_message), Toast.LENGTH_SHORT).show();*/ } public void onConnectionSuspended(int cause) { Log.i(TAG, "Connection suspended"); } public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } /** * Stores activity data in the Bundle. */ public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putBoolean(KEY_REQUESTING_LOCATION_UPDATES, mRequestingLocationUpdates); savedInstanceState.putParcelable(KEY_LOCATION, mCurrentLocation); savedInstanceState.putString(KEY_LAST_UPDATED_TIME_STRING, mLastUpdateTime); super.onSaveInstanceState(savedInstanceState); } } ``` Which is more or less an example code of the newest Play Store location services. Anyway if I want to activate the service by using this code: ``` NewGPSClient GPSM = new NewGPSClient(); GPSM.onCreate(savedInstanceState); ``` There is the following error log I get: > > 05-09 18:45:11.344: I/location-settings(14284): Building GoogleApiClient > 05-09 18:45:11.344: D/AndroidRuntime(14284): Shutting down VM > 05-09 18:45:11.344: W/dalvikvm(14284): threadid=1: thread exiting with uncaught exception (group=0x4180ac08) > 05-09 18:45:11.349: E/AndroidRuntime(14284): FATAL EXCEPTION: main > 05-09 18:45:11.349: E/AndroidRuntime(14284): Process: my.app.client, PID: 14284 > 05-09 18:45:11.349: E/AndroidRuntime(14284): java.lang.RuntimeException: Unable to start activity ComponentInfo{my.app.client/my.app.client.LauncherActivity}: java.lang.NullPointerException > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2449) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.access$900(ActivityThread.java:172) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.os.Handler.dispatchMessage(Handler.java:102) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.os.Looper.loop(Looper.java:146) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.main(ActivityThread.java:5694) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at java.lang.reflect.Method.invokeNative(Native Method) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at java.lang.reflect.Method.invoke(Method.java:515) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at dalvik.system.NativeStart.main(Native Method) > 05-09 18:45:11.349: E/AndroidRuntime(14284): Caused by: java.lang.NullPointerException > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.content.ContextWrapper.getMainLooper(ContextWrapper.java:109) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at com.google.android.gms.common.api.GoogleApiClient$Builder.(Unknown Source) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at my.app.client.NewGPSClient.buildGoogleApiClient(NewGPSClient.java:183) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at my.app.client.NewGPSClient.onCreate(NewGPSClient.java:142) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at my.app.client.LauncherActivity.onCreate(LauncherActivity.java:97) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.Activity.performCreate(Activity.java:5541) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413) > 05-09 18:45:11.349: E/AndroidRuntime(14284): ... 11 more > > > So with that new code I get the following errors anyway: > > 05-09 22:10:22.809: W/dalvikvm(25531): threadid=1: thread exiting with uncaught exception (group=0x4180ac08) > 05-09 22:10:22.809: E/AndroidRuntime(25531): FATAL EXCEPTION: main > 05-09 22:10:22.809: E/AndroidRuntime(25531): Process: my.app.client, PID: 25531 > 05-09 22:10:22.809: E/AndroidRuntime(25531): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{my.app.client/my.app.client.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "my.app.client.MainActivity" on path: DexPathList[[zip file "/data/app/my.app.client-68.apk"],nativeLibraryDirectories=[/data/app-lib/my.app.client-68, /vendor/lib, /system/lib]] > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2321) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.access$900(ActivityThread.java:172) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.os.Handler.dispatchMessage(Handler.java:102) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.os.Looper.loop(Looper.java:146) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.main(ActivityThread.java:5694) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.reflect.Method.invokeNative(Native Method) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.reflect.Method.invoke(Method.java:515) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at dalvik.system.NativeStart.main(Native Method) > 05-09 22:10:22.809: E/AndroidRuntime(25531): Caused by: java.lang.ClassNotFoundException: Didn't find class "my.app.client.MainActivity" on path: DexPathList[[zip file "/data/app/my.app.client-68.apk"],nativeLibraryDirectories=[/data/app-lib/my.app.client-68, /vendor/lib, /system/lib]] > 05-09 22:10:22.809: E/AndroidRuntime(25531): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.ClassLoader.loadClass(ClassLoader.java:497) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.ClassLoader.loadClass(ClassLoader.java:457) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.Instrumentation.newActivity(Instrumentation.java:1067) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2312) > 05-09 22:10:22.809: E/AndroidRuntime(25531): ... 11 more > > > So here the manifest: ``` > <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.app.client" android:versionCode="59" android:versionName="2.7.1" > <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.STORAGE" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:debuggable="true"> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <service android:name="my.app.client.Client" > <intent-filter> <action android:name=".Client" /> <category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </service> <service android:name=".GPSClient"> <intent-filter> <action android:name=".GPSClient" /> </intent-filter> </service> <activity android:name="my.app.client.LauncherActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ``` In fact, the GPS is now in the class LauncherActivity.
2015/05/09
[ "https://Stackoverflow.com/questions/30142669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3727877/" ]
I was receiving a `NoClassDefFoundError` and it was because I had included `play-services-gcm` but forgot to include `play-services-location`. ``` compile 'com.google.android.gms:play-services-gcm:7.5.0' compile 'com.google.android.gms:play-services-location:7.5.0' ``` Not 100% related to your error, but this post is in the top 10 when googling `java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.location.LocationServices" on path`
I was able to get your code working with a couple minor changes, and just used the latitude, longitude, and last update time to test it (I just un-commented the lines pertaining to those fields). First of all, you should never create the Activity using `new NewGPSClient();`. Instead, use `startActivity()` like below: ``` Intent i = new Intent(this, NewGPSClient.class); startActivity(i); ``` Second, you were calling `startLocationUpdates();` before the asynchronous call to connect to the SDK had completed. I moved the call to `startLocationUpdates();` into `onConnected(Bundle connectionHint)`, and now it works. Here is the full working code: ``` public class NewGPSClient extends ActionBarActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener, ResultCallback<LocationSettingsResult> { protected static final String TAG = "location-settings"; /** * Constant used in the location settings dialog. */ protected static final int REQUEST_CHECK_SETTINGS = 0x1; /** * The desired interval for location updates. Inexact. Updates may be more or less frequent. */ public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; /** * The fastest rate for active location updates. Exact. Updates will never be more frequent * than this value. */ public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2; // Keys for storing activity state in the Bundle. protected final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates"; protected final static String KEY_LOCATION = "location"; protected final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string"; /** * Provides the entry point to Google Play services. */ protected GoogleApiClient mGoogleApiClient; /** * Stores parameters for requests to the FusedLocationProviderApi. */ protected LocationRequest mLocationRequest; /** * Stores the types of location services the client is interested in using. Used for checking * settings to determine if the device has optimal location settings. */ protected LocationSettingsRequest mLocationSettingsRequest; /** * Represents a geographical location. */ protected Location mCurrentLocation; // UI Widgets. protected Button mStartUpdatesButton; protected Button mStopUpdatesButton; protected TextView mLastUpdateTimeTextView; protected TextView mLatitudeTextView; protected TextView mLongitudeTextView; /** * Tracks the status of the location updates request. Value changes when the user presses the * Start Updates and Stop Updates buttons. */ protected Boolean mRequestingLocationUpdates; /** * Time when the location was updated represented as a String. */ protected String mLastUpdateTime; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); // Locate the UI widgets. /*mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button); mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button); */ mLatitudeTextView = (TextView) findViewById(R.id.latitude_text); mLongitudeTextView = (TextView) findViewById(R.id.longitude_text); mLastUpdateTimeTextView = (TextView) findViewById(R.id.last_update_time_text); Log.e(TAG, "NEWGPSCLIENT created successfully!"); mRequestingLocationUpdates = false; mLastUpdateTime = ""; // Update values using data stored in the Bundle. //updateValuesFromBundle(savedInstanceState); // Kick off the process of building the GoogleApiClient, LocationRequest, and // LocationSettingsRequest objects. buildGoogleApiClient(); createLocationRequest(); buildLocationSettingsRequest(); //startLocationUpdates(); //Don't call this here, the SDK is not connected yet } /** * Updates fields based on data stored in the bundle. * * @param savedInstanceState The activity state saved in the Bundle. */ private void updateValuesFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { // Update the value of mRequestingLocationUpdates from the Bundle, and make sure that // the Start Updates and Stop Updates buttons are correctly enabled or disabled. if (savedInstanceState.keySet().contains(KEY_REQUESTING_LOCATION_UPDATES)) { mRequestingLocationUpdates = savedInstanceState.getBoolean( KEY_REQUESTING_LOCATION_UPDATES); } // Update the value of mCurrentLocation from the Bundle and update the UI to show the // correct latitude and longitude. if (savedInstanceState.keySet().contains(KEY_LOCATION)) { // Since KEY_LOCATION was found in the Bundle, we can be sure that mCurrentLocation // is not null. mCurrentLocation = savedInstanceState.getParcelable(KEY_LOCATION); } // Update the value of mLastUpdateTime from the Bundle and update the UI. if (savedInstanceState.keySet().contains(KEY_LAST_UPDATED_TIME_STRING)) { mLastUpdateTime = savedInstanceState.getString(KEY_LAST_UPDATED_TIME_STRING); } updateUI(); } } /** * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the * LocationServices API. */ protected synchronized void buildGoogleApiClient() { Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } /** * Sets up the location request. Android has two location request settings: * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in * the AndroidManifest.xml. * <p/> * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update * interval (5 seconds), the Fused Location Provider API returns location updates that are * accurate to within a few feet. * <p/> * These settings are appropriate for mapping applications that show real-time location * updates. */ protected void createLocationRequest() { mLocationRequest = new LocationRequest(); // Sets the desired interval for active location updates. This interval is // inexact. You may not receive updates at all if no location sources are available, or // you may receive them slower than requested. You may also receive updates faster than // requested if other applications are requesting location at a faster interval. mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); // Sets the fastest rate for active location updates. This interval is exact, and your // application will never receive updates faster than this value. mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } /** * Uses a {@link com.google.android.gms.location.LocationSettingsRequest.Builder} to build * a {@link com.google.android.gms.location.LocationSettingsRequest} that is used for checking * if a device has the needed location settings. */ protected void buildLocationSettingsRequest() { LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); mLocationSettingsRequest = builder.build(); } /** * Check if the device's location settings are adequate for the app's needs using the * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} method, with the results provided through a {@code PendingResult}. */ protected void checkLocationSettings() { PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings( mGoogleApiClient, mLocationSettingsRequest ); result.setResultCallback(this); } /** * The callback invoked when * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} is called. Examines the * {@link com.google.android.gms.location.LocationSettingsResult} object and determines if * location settings are adequate. If they are not, begins the process of presenting a location * settings dialog to the user. */ public void onResult(LocationSettingsResult locationSettingsResult) { final Status status = locationSettingsResult.getStatus(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: Log.i(TAG, "All location settings are satisfied."); startLocationUpdates(); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" + "upgrade location settings "); /* try { // Show the dialog by calling startResolutionForResult(), and check the result // in onActivityResult(). // status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { Log.i(TAG, "PendingIntent unable to execute request."); }*/ break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " + "not created."); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: Log.i(TAG, "User agreed to make required location settings changes."); startLocationUpdates(); break; case Activity.RESULT_CANCELED: Log.i(TAG, "User chose not to make required location settings changes."); break; } break; } } /** * Handles the Start Updates button and requests start of location updates. Does nothing if * updates have already been requested. */ public void startUpdatesButtonHandler(View view) { checkLocationSettings(); } /** * Handles the Stop Updates button, and requests removal of location updates. */ public void stopUpdatesButtonHandler(View view) { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. stopLocationUpdates(); } /** * Requests location updates from the FusedLocationApi. */ protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this ).setResultCallback(new ResultCallback<Status>() { public void onResult(Status status) { mRequestingLocationUpdates = true; //setButtonsEnabledState(); } }); } /** * Updates all UI fields. */ private void updateUI() { //setButtonsEnabledState(); updateLocationUI(); } /** * Disables both buttons when functionality is disabled due to insuffucient location settings. * Otherwise ensures that only one button is enabled at any time. The Start Updates button is * enabled if the user is not requesting location updates. The Stop Updates button is enabled * if the user is requesting location updates. */ /*private void setButtonsEnabledState() { if (mRequestingLocationUpdates) { mStartUpdatesButton.setEnabled(false); mStopUpdatesButton.setEnabled(true); } else { mStartUpdatesButton.setEnabled(true); mStopUpdatesButton.setEnabled(false); } }*/ /** * Sets the value of the UI fields for the location latitude, longitude and last update time. */ private void updateLocationUI() { if (mCurrentLocation != null) { mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude())); mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude())); mLastUpdateTimeTextView.setText(mLastUpdateTime); } } /** * Removes location updates from the FusedLocationApi. */ protected void stopLocationUpdates() { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this ).setResultCallback(new ResultCallback<Status>() { public void onResult(Status status) { mRequestingLocationUpdates = false; //setButtonsEnabledState(); } }); } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override public void onResume() { super.onResume(); // Within {@code onPause()}, we pause location updates, but leave the // connection to GoogleApiClient intact. Here, we resume receiving // location updates if the user has requested them. if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { startLocationUpdates(); } } @Override protected void onPause() { super.onPause(); // Stop location updates to save battery, but don't disconnect the GoogleApiClient object. if (mGoogleApiClient.isConnected()) { stopLocationUpdates(); } } @Override protected void onStop() { super.onStop(); mGoogleApiClient.disconnect(); } /** * Runs when a GoogleApiClient object successfully connects. */ public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); startLocationUpdates(); //add this here // If the initial location was never previously requested, we use // FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store // its value in the Bundle and check for it in onCreate(). We // do not request it again unless the user specifically requests location updates by pressing // the Start Updates button. // // Because we cache the value of the initial location in the Bundle, it means that if the // user launches the activity, // moves to a new location, and then changes the device orientation, the original location // is displayed as the activity is re-created. if (mCurrentLocation == null) { mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); } } /** * Callback that fires when the location changes. */ public void onLocationChanged(Location location) { mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); /*Toast.makeText(this, getResources().getString(R.string.location_updated_message), Toast.LENGTH_SHORT).show();*/ } public void onConnectionSuspended(int cause) { Log.i(TAG, "Connection suspended"); } public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } /** * Stores activity data in the Bundle. */ public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putBoolean(KEY_REQUESTING_LOCATION_UPDATES, mRequestingLocationUpdates); savedInstanceState.putParcelable(KEY_LOCATION, mCurrentLocation); savedInstanceState.putString(KEY_LAST_UPDATED_TIME_STRING, mLastUpdateTime); super.onSaveInstanceState(savedInstanceState); } } ```
30,142,669
I have a problem with the new Google Play Service and its GPS function. Right now I am using this code: ``` package my.app.client; import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.location.Location; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStatusCodes; import java.text.DateFormat; import java.util.Date; /** * Using location settings. * <p/> * Uses the {@link com.google.android.gms.location.SettingsApi} to ensure that the device's system * settings are properly configured for the app's location needs. When making a request to * Location services, the device's system settings may be in a state that prevents the app from * obtaining the location data that it needs. For example, GPS or Wi-Fi scanning may be switched * off. The {@code SettingsApi} makes it possible to determine if a device's system settings are * adequate for the location request, and to optionally invoke a dialog that allows the user to * enable the necessary settings. * <p/> * This sample allows the user to request location updates using the ACCESS_FINE_LOCATION setting * (as specified in AndroidManifest.xml). The sample requires that the device has location enabled * and set to the "High accuracy" mode. If location is not enabled, or if the location mode does * not permit high accuracy determination of location, the activity uses the {@code SettingsApi} * to invoke a dialog without requiring the developer to understand which settings are needed for * different Location requirements. */ public class NewGPSClient extends ActionBarActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener, ResultCallback<LocationSettingsResult> { protected static final String TAG = "location-settings"; /** * Constant used in the location settings dialog. */ protected static final int REQUEST_CHECK_SETTINGS = 0x1; /** * The desired interval for location updates. Inexact. Updates may be more or less frequent. */ public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; /** * The fastest rate for active location updates. Exact. Updates will never be more frequent * than this value. */ public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2; // Keys for storing activity state in the Bundle. protected final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates"; protected final static String KEY_LOCATION = "location"; protected final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string"; /** * Provides the entry point to Google Play services. */ protected GoogleApiClient mGoogleApiClient; /** * Stores parameters for requests to the FusedLocationProviderApi. */ protected LocationRequest mLocationRequest; /** * Stores the types of location services the client is interested in using. Used for checking * settings to determine if the device has optimal location settings. */ protected LocationSettingsRequest mLocationSettingsRequest; /** * Represents a geographical location. */ protected Location mCurrentLocation; // UI Widgets. protected Button mStartUpdatesButton; protected Button mStopUpdatesButton; protected TextView mLastUpdateTimeTextView; protected TextView mLatitudeTextView; protected TextView mLongitudeTextView; /** * Tracks the status of the location updates request. Value changes when the user presses the * Start Updates and Stop Updates buttons. */ protected Boolean mRequestingLocationUpdates; /** * Time when the location was updated represented as a String. */ protected String mLastUpdateTime; @Override public void onCreate(Bundle savedInstanceState) { //super.onCreate(savedInstanceState); //setContentView(R.layout.main_activity); // Locate the UI widgets. /*mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button); mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button); mLatitudeTextView = (TextView) findViewById(R.id.latitude_text); mLongitudeTextView = (TextView) findViewById(R.id.longitude_text); mLastUpdateTimeTextView = (TextView) findViewById(R.id.last_update_time_text);*/ Log.e(TAG, "NEWGPSCLIENT created successfully!"); mRequestingLocationUpdates = false; mLastUpdateTime = ""; // Update values using data stored in the Bundle. //updateValuesFromBundle(savedInstanceState); // Kick off the process of building the GoogleApiClient, LocationRequest, and // LocationSettingsRequest objects. buildGoogleApiClient(); createLocationRequest(); buildLocationSettingsRequest(); startLocationUpdates(); } /** * Updates fields based on data stored in the bundle. * * @param savedInstanceState The activity state saved in the Bundle. */ private void updateValuesFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { // Update the value of mRequestingLocationUpdates from the Bundle, and make sure that // the Start Updates and Stop Updates buttons are correctly enabled or disabled. if (savedInstanceState.keySet().contains(KEY_REQUESTING_LOCATION_UPDATES)) { mRequestingLocationUpdates = savedInstanceState.getBoolean( KEY_REQUESTING_LOCATION_UPDATES); } // Update the value of mCurrentLocation from the Bundle and update the UI to show the // correct latitude and longitude. if (savedInstanceState.keySet().contains(KEY_LOCATION)) { // Since KEY_LOCATION was found in the Bundle, we can be sure that mCurrentLocation // is not null. mCurrentLocation = savedInstanceState.getParcelable(KEY_LOCATION); } // Update the value of mLastUpdateTime from the Bundle and update the UI. if (savedInstanceState.keySet().contains(KEY_LAST_UPDATED_TIME_STRING)) { mLastUpdateTime = savedInstanceState.getString(KEY_LAST_UPDATED_TIME_STRING); } updateUI(); } } /** * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the * LocationServices API. */ protected synchronized void buildGoogleApiClient() { Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } /** * Sets up the location request. Android has two location request settings: * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in * the AndroidManifest.xml. * <p/> * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update * interval (5 seconds), the Fused Location Provider API returns location updates that are * accurate to within a few feet. * <p/> * These settings are appropriate for mapping applications that show real-time location * updates. */ protected void createLocationRequest() { mLocationRequest = new LocationRequest(); // Sets the desired interval for active location updates. This interval is // inexact. You may not receive updates at all if no location sources are available, or // you may receive them slower than requested. You may also receive updates faster than // requested if other applications are requesting location at a faster interval. mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); // Sets the fastest rate for active location updates. This interval is exact, and your // application will never receive updates faster than this value. mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } /** * Uses a {@link com.google.android.gms.location.LocationSettingsRequest.Builder} to build * a {@link com.google.android.gms.location.LocationSettingsRequest} that is used for checking * if a device has the needed location settings. */ protected void buildLocationSettingsRequest() { LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); mLocationSettingsRequest = builder.build(); } /** * Check if the device's location settings are adequate for the app's needs using the * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} method, with the results provided through a {@code PendingResult}. */ protected void checkLocationSettings() { PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings( mGoogleApiClient, mLocationSettingsRequest ); result.setResultCallback(this); } /** * The callback invoked when * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} is called. Examines the * {@link com.google.android.gms.location.LocationSettingsResult} object and determines if * location settings are adequate. If they are not, begins the process of presenting a location * settings dialog to the user. */ public void onResult(LocationSettingsResult locationSettingsResult) { final Status status = locationSettingsResult.getStatus(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: Log.i(TAG, "All location settings are satisfied."); startLocationUpdates(); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" + "upgrade location settings "); /* try { // Show the dialog by calling startResolutionForResult(), and check the result // in onActivityResult(). // status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { Log.i(TAG, "PendingIntent unable to execute request."); }*/ break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " + "not created."); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: Log.i(TAG, "User agreed to make required location settings changes."); startLocationUpdates(); break; case Activity.RESULT_CANCELED: Log.i(TAG, "User chose not to make required location settings changes."); break; } break; } } /** * Handles the Start Updates button and requests start of location updates. Does nothing if * updates have already been requested. */ public void startUpdatesButtonHandler(View view) { checkLocationSettings(); } /** * Handles the Stop Updates button, and requests removal of location updates. */ public void stopUpdatesButtonHandler(View view) { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. stopLocationUpdates(); } /** * Requests location updates from the FusedLocationApi. */ protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this ).setResultCallback(new ResultCallback<Status>() { public void onResult(Status status) { mRequestingLocationUpdates = true; //setButtonsEnabledState(); } }); } /** * Updates all UI fields. */ private void updateUI() { //setButtonsEnabledState(); updateLocationUI(); } /** * Disables both buttons when functionality is disabled due to insuffucient location settings. * Otherwise ensures that only one button is enabled at any time. The Start Updates button is * enabled if the user is not requesting location updates. The Stop Updates button is enabled * if the user is requesting location updates. */ /*private void setButtonsEnabledState() { if (mRequestingLocationUpdates) { mStartUpdatesButton.setEnabled(false); mStopUpdatesButton.setEnabled(true); } else { mStartUpdatesButton.setEnabled(true); mStopUpdatesButton.setEnabled(false); } }*/ /** * Sets the value of the UI fields for the location latitude, longitude and last update time. */ private void updateLocationUI() { if (mCurrentLocation != null) { mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude())); mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude())); mLastUpdateTimeTextView.setText(mLastUpdateTime); } } /** * Removes location updates from the FusedLocationApi. */ protected void stopLocationUpdates() { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this ).setResultCallback(new ResultCallback<Status>() { public void onResult(Status status) { mRequestingLocationUpdates = false; //setButtonsEnabledState(); } }); } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override public void onResume() { super.onResume(); // Within {@code onPause()}, we pause location updates, but leave the // connection to GoogleApiClient intact. Here, we resume receiving // location updates if the user has requested them. if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { startLocationUpdates(); } } @Override protected void onPause() { super.onPause(); // Stop location updates to save battery, but don't disconnect the GoogleApiClient object. if (mGoogleApiClient.isConnected()) { stopLocationUpdates(); } } @Override protected void onStop() { super.onStop(); mGoogleApiClient.disconnect(); } /** * Runs when a GoogleApiClient object successfully connects. */ public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); if (mCurrentLocation == null) { mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); } } /** * Callback that fires when the location changes. */ public void onLocationChanged(Location location) { mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); /*Toast.makeText(this, getResources().getString(R.string.location_updated_message), Toast.LENGTH_SHORT).show();*/ } public void onConnectionSuspended(int cause) { Log.i(TAG, "Connection suspended"); } public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } /** * Stores activity data in the Bundle. */ public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putBoolean(KEY_REQUESTING_LOCATION_UPDATES, mRequestingLocationUpdates); savedInstanceState.putParcelable(KEY_LOCATION, mCurrentLocation); savedInstanceState.putString(KEY_LAST_UPDATED_TIME_STRING, mLastUpdateTime); super.onSaveInstanceState(savedInstanceState); } } ``` Which is more or less an example code of the newest Play Store location services. Anyway if I want to activate the service by using this code: ``` NewGPSClient GPSM = new NewGPSClient(); GPSM.onCreate(savedInstanceState); ``` There is the following error log I get: > > 05-09 18:45:11.344: I/location-settings(14284): Building GoogleApiClient > 05-09 18:45:11.344: D/AndroidRuntime(14284): Shutting down VM > 05-09 18:45:11.344: W/dalvikvm(14284): threadid=1: thread exiting with uncaught exception (group=0x4180ac08) > 05-09 18:45:11.349: E/AndroidRuntime(14284): FATAL EXCEPTION: main > 05-09 18:45:11.349: E/AndroidRuntime(14284): Process: my.app.client, PID: 14284 > 05-09 18:45:11.349: E/AndroidRuntime(14284): java.lang.RuntimeException: Unable to start activity ComponentInfo{my.app.client/my.app.client.LauncherActivity}: java.lang.NullPointerException > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2449) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.access$900(ActivityThread.java:172) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.os.Handler.dispatchMessage(Handler.java:102) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.os.Looper.loop(Looper.java:146) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.main(ActivityThread.java:5694) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at java.lang.reflect.Method.invokeNative(Native Method) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at java.lang.reflect.Method.invoke(Method.java:515) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at dalvik.system.NativeStart.main(Native Method) > 05-09 18:45:11.349: E/AndroidRuntime(14284): Caused by: java.lang.NullPointerException > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.content.ContextWrapper.getMainLooper(ContextWrapper.java:109) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at com.google.android.gms.common.api.GoogleApiClient$Builder.(Unknown Source) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at my.app.client.NewGPSClient.buildGoogleApiClient(NewGPSClient.java:183) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at my.app.client.NewGPSClient.onCreate(NewGPSClient.java:142) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at my.app.client.LauncherActivity.onCreate(LauncherActivity.java:97) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.Activity.performCreate(Activity.java:5541) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413) > 05-09 18:45:11.349: E/AndroidRuntime(14284): ... 11 more > > > So with that new code I get the following errors anyway: > > 05-09 22:10:22.809: W/dalvikvm(25531): threadid=1: thread exiting with uncaught exception (group=0x4180ac08) > 05-09 22:10:22.809: E/AndroidRuntime(25531): FATAL EXCEPTION: main > 05-09 22:10:22.809: E/AndroidRuntime(25531): Process: my.app.client, PID: 25531 > 05-09 22:10:22.809: E/AndroidRuntime(25531): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{my.app.client/my.app.client.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "my.app.client.MainActivity" on path: DexPathList[[zip file "/data/app/my.app.client-68.apk"],nativeLibraryDirectories=[/data/app-lib/my.app.client-68, /vendor/lib, /system/lib]] > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2321) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.access$900(ActivityThread.java:172) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.os.Handler.dispatchMessage(Handler.java:102) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.os.Looper.loop(Looper.java:146) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.main(ActivityThread.java:5694) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.reflect.Method.invokeNative(Native Method) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.reflect.Method.invoke(Method.java:515) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at dalvik.system.NativeStart.main(Native Method) > 05-09 22:10:22.809: E/AndroidRuntime(25531): Caused by: java.lang.ClassNotFoundException: Didn't find class "my.app.client.MainActivity" on path: DexPathList[[zip file "/data/app/my.app.client-68.apk"],nativeLibraryDirectories=[/data/app-lib/my.app.client-68, /vendor/lib, /system/lib]] > 05-09 22:10:22.809: E/AndroidRuntime(25531): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.ClassLoader.loadClass(ClassLoader.java:497) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.ClassLoader.loadClass(ClassLoader.java:457) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.Instrumentation.newActivity(Instrumentation.java:1067) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2312) > 05-09 22:10:22.809: E/AndroidRuntime(25531): ... 11 more > > > So here the manifest: ``` > <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.app.client" android:versionCode="59" android:versionName="2.7.1" > <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.STORAGE" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:debuggable="true"> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <service android:name="my.app.client.Client" > <intent-filter> <action android:name=".Client" /> <category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </service> <service android:name=".GPSClient"> <intent-filter> <action android:name=".GPSClient" /> </intent-filter> </service> <activity android:name="my.app.client.LauncherActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ``` In fact, the GPS is now in the class LauncherActivity.
2015/05/09
[ "https://Stackoverflow.com/questions/30142669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3727877/" ]
I was able to get your code working with a couple minor changes, and just used the latitude, longitude, and last update time to test it (I just un-commented the lines pertaining to those fields). First of all, you should never create the Activity using `new NewGPSClient();`. Instead, use `startActivity()` like below: ``` Intent i = new Intent(this, NewGPSClient.class); startActivity(i); ``` Second, you were calling `startLocationUpdates();` before the asynchronous call to connect to the SDK had completed. I moved the call to `startLocationUpdates();` into `onConnected(Bundle connectionHint)`, and now it works. Here is the full working code: ``` public class NewGPSClient extends ActionBarActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener, ResultCallback<LocationSettingsResult> { protected static final String TAG = "location-settings"; /** * Constant used in the location settings dialog. */ protected static final int REQUEST_CHECK_SETTINGS = 0x1; /** * The desired interval for location updates. Inexact. Updates may be more or less frequent. */ public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; /** * The fastest rate for active location updates. Exact. Updates will never be more frequent * than this value. */ public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2; // Keys for storing activity state in the Bundle. protected final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates"; protected final static String KEY_LOCATION = "location"; protected final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string"; /** * Provides the entry point to Google Play services. */ protected GoogleApiClient mGoogleApiClient; /** * Stores parameters for requests to the FusedLocationProviderApi. */ protected LocationRequest mLocationRequest; /** * Stores the types of location services the client is interested in using. Used for checking * settings to determine if the device has optimal location settings. */ protected LocationSettingsRequest mLocationSettingsRequest; /** * Represents a geographical location. */ protected Location mCurrentLocation; // UI Widgets. protected Button mStartUpdatesButton; protected Button mStopUpdatesButton; protected TextView mLastUpdateTimeTextView; protected TextView mLatitudeTextView; protected TextView mLongitudeTextView; /** * Tracks the status of the location updates request. Value changes when the user presses the * Start Updates and Stop Updates buttons. */ protected Boolean mRequestingLocationUpdates; /** * Time when the location was updated represented as a String. */ protected String mLastUpdateTime; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); // Locate the UI widgets. /*mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button); mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button); */ mLatitudeTextView = (TextView) findViewById(R.id.latitude_text); mLongitudeTextView = (TextView) findViewById(R.id.longitude_text); mLastUpdateTimeTextView = (TextView) findViewById(R.id.last_update_time_text); Log.e(TAG, "NEWGPSCLIENT created successfully!"); mRequestingLocationUpdates = false; mLastUpdateTime = ""; // Update values using data stored in the Bundle. //updateValuesFromBundle(savedInstanceState); // Kick off the process of building the GoogleApiClient, LocationRequest, and // LocationSettingsRequest objects. buildGoogleApiClient(); createLocationRequest(); buildLocationSettingsRequest(); //startLocationUpdates(); //Don't call this here, the SDK is not connected yet } /** * Updates fields based on data stored in the bundle. * * @param savedInstanceState The activity state saved in the Bundle. */ private void updateValuesFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { // Update the value of mRequestingLocationUpdates from the Bundle, and make sure that // the Start Updates and Stop Updates buttons are correctly enabled or disabled. if (savedInstanceState.keySet().contains(KEY_REQUESTING_LOCATION_UPDATES)) { mRequestingLocationUpdates = savedInstanceState.getBoolean( KEY_REQUESTING_LOCATION_UPDATES); } // Update the value of mCurrentLocation from the Bundle and update the UI to show the // correct latitude and longitude. if (savedInstanceState.keySet().contains(KEY_LOCATION)) { // Since KEY_LOCATION was found in the Bundle, we can be sure that mCurrentLocation // is not null. mCurrentLocation = savedInstanceState.getParcelable(KEY_LOCATION); } // Update the value of mLastUpdateTime from the Bundle and update the UI. if (savedInstanceState.keySet().contains(KEY_LAST_UPDATED_TIME_STRING)) { mLastUpdateTime = savedInstanceState.getString(KEY_LAST_UPDATED_TIME_STRING); } updateUI(); } } /** * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the * LocationServices API. */ protected synchronized void buildGoogleApiClient() { Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } /** * Sets up the location request. Android has two location request settings: * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in * the AndroidManifest.xml. * <p/> * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update * interval (5 seconds), the Fused Location Provider API returns location updates that are * accurate to within a few feet. * <p/> * These settings are appropriate for mapping applications that show real-time location * updates. */ protected void createLocationRequest() { mLocationRequest = new LocationRequest(); // Sets the desired interval for active location updates. This interval is // inexact. You may not receive updates at all if no location sources are available, or // you may receive them slower than requested. You may also receive updates faster than // requested if other applications are requesting location at a faster interval. mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); // Sets the fastest rate for active location updates. This interval is exact, and your // application will never receive updates faster than this value. mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } /** * Uses a {@link com.google.android.gms.location.LocationSettingsRequest.Builder} to build * a {@link com.google.android.gms.location.LocationSettingsRequest} that is used for checking * if a device has the needed location settings. */ protected void buildLocationSettingsRequest() { LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); mLocationSettingsRequest = builder.build(); } /** * Check if the device's location settings are adequate for the app's needs using the * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} method, with the results provided through a {@code PendingResult}. */ protected void checkLocationSettings() { PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings( mGoogleApiClient, mLocationSettingsRequest ); result.setResultCallback(this); } /** * The callback invoked when * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} is called. Examines the * {@link com.google.android.gms.location.LocationSettingsResult} object and determines if * location settings are adequate. If they are not, begins the process of presenting a location * settings dialog to the user. */ public void onResult(LocationSettingsResult locationSettingsResult) { final Status status = locationSettingsResult.getStatus(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: Log.i(TAG, "All location settings are satisfied."); startLocationUpdates(); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" + "upgrade location settings "); /* try { // Show the dialog by calling startResolutionForResult(), and check the result // in onActivityResult(). // status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { Log.i(TAG, "PendingIntent unable to execute request."); }*/ break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " + "not created."); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: Log.i(TAG, "User agreed to make required location settings changes."); startLocationUpdates(); break; case Activity.RESULT_CANCELED: Log.i(TAG, "User chose not to make required location settings changes."); break; } break; } } /** * Handles the Start Updates button and requests start of location updates. Does nothing if * updates have already been requested. */ public void startUpdatesButtonHandler(View view) { checkLocationSettings(); } /** * Handles the Stop Updates button, and requests removal of location updates. */ public void stopUpdatesButtonHandler(View view) { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. stopLocationUpdates(); } /** * Requests location updates from the FusedLocationApi. */ protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this ).setResultCallback(new ResultCallback<Status>() { public void onResult(Status status) { mRequestingLocationUpdates = true; //setButtonsEnabledState(); } }); } /** * Updates all UI fields. */ private void updateUI() { //setButtonsEnabledState(); updateLocationUI(); } /** * Disables both buttons when functionality is disabled due to insuffucient location settings. * Otherwise ensures that only one button is enabled at any time. The Start Updates button is * enabled if the user is not requesting location updates. The Stop Updates button is enabled * if the user is requesting location updates. */ /*private void setButtonsEnabledState() { if (mRequestingLocationUpdates) { mStartUpdatesButton.setEnabled(false); mStopUpdatesButton.setEnabled(true); } else { mStartUpdatesButton.setEnabled(true); mStopUpdatesButton.setEnabled(false); } }*/ /** * Sets the value of the UI fields for the location latitude, longitude and last update time. */ private void updateLocationUI() { if (mCurrentLocation != null) { mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude())); mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude())); mLastUpdateTimeTextView.setText(mLastUpdateTime); } } /** * Removes location updates from the FusedLocationApi. */ protected void stopLocationUpdates() { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this ).setResultCallback(new ResultCallback<Status>() { public void onResult(Status status) { mRequestingLocationUpdates = false; //setButtonsEnabledState(); } }); } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override public void onResume() { super.onResume(); // Within {@code onPause()}, we pause location updates, but leave the // connection to GoogleApiClient intact. Here, we resume receiving // location updates if the user has requested them. if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { startLocationUpdates(); } } @Override protected void onPause() { super.onPause(); // Stop location updates to save battery, but don't disconnect the GoogleApiClient object. if (mGoogleApiClient.isConnected()) { stopLocationUpdates(); } } @Override protected void onStop() { super.onStop(); mGoogleApiClient.disconnect(); } /** * Runs when a GoogleApiClient object successfully connects. */ public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); startLocationUpdates(); //add this here // If the initial location was never previously requested, we use // FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store // its value in the Bundle and check for it in onCreate(). We // do not request it again unless the user specifically requests location updates by pressing // the Start Updates button. // // Because we cache the value of the initial location in the Bundle, it means that if the // user launches the activity, // moves to a new location, and then changes the device orientation, the original location // is displayed as the activity is re-created. if (mCurrentLocation == null) { mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); } } /** * Callback that fires when the location changes. */ public void onLocationChanged(Location location) { mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); /*Toast.makeText(this, getResources().getString(R.string.location_updated_message), Toast.LENGTH_SHORT).show();*/ } public void onConnectionSuspended(int cause) { Log.i(TAG, "Connection suspended"); } public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } /** * Stores activity data in the Bundle. */ public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putBoolean(KEY_REQUESTING_LOCATION_UPDATES, mRequestingLocationUpdates); savedInstanceState.putParcelable(KEY_LOCATION, mCurrentLocation); savedInstanceState.putString(KEY_LAST_UPDATED_TIME_STRING, mLastUpdateTime); super.onSaveInstanceState(savedInstanceState); } } ```
Add the following line in your **build.gradle** file, ``` dependencies { ... implementation "com.google.android.gms:play-services-location:+" } ```
30,142,669
I have a problem with the new Google Play Service and its GPS function. Right now I am using this code: ``` package my.app.client; import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.location.Location; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStatusCodes; import java.text.DateFormat; import java.util.Date; /** * Using location settings. * <p/> * Uses the {@link com.google.android.gms.location.SettingsApi} to ensure that the device's system * settings are properly configured for the app's location needs. When making a request to * Location services, the device's system settings may be in a state that prevents the app from * obtaining the location data that it needs. For example, GPS or Wi-Fi scanning may be switched * off. The {@code SettingsApi} makes it possible to determine if a device's system settings are * adequate for the location request, and to optionally invoke a dialog that allows the user to * enable the necessary settings. * <p/> * This sample allows the user to request location updates using the ACCESS_FINE_LOCATION setting * (as specified in AndroidManifest.xml). The sample requires that the device has location enabled * and set to the "High accuracy" mode. If location is not enabled, or if the location mode does * not permit high accuracy determination of location, the activity uses the {@code SettingsApi} * to invoke a dialog without requiring the developer to understand which settings are needed for * different Location requirements. */ public class NewGPSClient extends ActionBarActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener, ResultCallback<LocationSettingsResult> { protected static final String TAG = "location-settings"; /** * Constant used in the location settings dialog. */ protected static final int REQUEST_CHECK_SETTINGS = 0x1; /** * The desired interval for location updates. Inexact. Updates may be more or less frequent. */ public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; /** * The fastest rate for active location updates. Exact. Updates will never be more frequent * than this value. */ public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2; // Keys for storing activity state in the Bundle. protected final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates"; protected final static String KEY_LOCATION = "location"; protected final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string"; /** * Provides the entry point to Google Play services. */ protected GoogleApiClient mGoogleApiClient; /** * Stores parameters for requests to the FusedLocationProviderApi. */ protected LocationRequest mLocationRequest; /** * Stores the types of location services the client is interested in using. Used for checking * settings to determine if the device has optimal location settings. */ protected LocationSettingsRequest mLocationSettingsRequest; /** * Represents a geographical location. */ protected Location mCurrentLocation; // UI Widgets. protected Button mStartUpdatesButton; protected Button mStopUpdatesButton; protected TextView mLastUpdateTimeTextView; protected TextView mLatitudeTextView; protected TextView mLongitudeTextView; /** * Tracks the status of the location updates request. Value changes when the user presses the * Start Updates and Stop Updates buttons. */ protected Boolean mRequestingLocationUpdates; /** * Time when the location was updated represented as a String. */ protected String mLastUpdateTime; @Override public void onCreate(Bundle savedInstanceState) { //super.onCreate(savedInstanceState); //setContentView(R.layout.main_activity); // Locate the UI widgets. /*mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button); mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button); mLatitudeTextView = (TextView) findViewById(R.id.latitude_text); mLongitudeTextView = (TextView) findViewById(R.id.longitude_text); mLastUpdateTimeTextView = (TextView) findViewById(R.id.last_update_time_text);*/ Log.e(TAG, "NEWGPSCLIENT created successfully!"); mRequestingLocationUpdates = false; mLastUpdateTime = ""; // Update values using data stored in the Bundle. //updateValuesFromBundle(savedInstanceState); // Kick off the process of building the GoogleApiClient, LocationRequest, and // LocationSettingsRequest objects. buildGoogleApiClient(); createLocationRequest(); buildLocationSettingsRequest(); startLocationUpdates(); } /** * Updates fields based on data stored in the bundle. * * @param savedInstanceState The activity state saved in the Bundle. */ private void updateValuesFromBundle(Bundle savedInstanceState) { if (savedInstanceState != null) { // Update the value of mRequestingLocationUpdates from the Bundle, and make sure that // the Start Updates and Stop Updates buttons are correctly enabled or disabled. if (savedInstanceState.keySet().contains(KEY_REQUESTING_LOCATION_UPDATES)) { mRequestingLocationUpdates = savedInstanceState.getBoolean( KEY_REQUESTING_LOCATION_UPDATES); } // Update the value of mCurrentLocation from the Bundle and update the UI to show the // correct latitude and longitude. if (savedInstanceState.keySet().contains(KEY_LOCATION)) { // Since KEY_LOCATION was found in the Bundle, we can be sure that mCurrentLocation // is not null. mCurrentLocation = savedInstanceState.getParcelable(KEY_LOCATION); } // Update the value of mLastUpdateTime from the Bundle and update the UI. if (savedInstanceState.keySet().contains(KEY_LAST_UPDATED_TIME_STRING)) { mLastUpdateTime = savedInstanceState.getString(KEY_LAST_UPDATED_TIME_STRING); } updateUI(); } } /** * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the * LocationServices API. */ protected synchronized void buildGoogleApiClient() { Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } /** * Sets up the location request. Android has two location request settings: * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in * the AndroidManifest.xml. * <p/> * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update * interval (5 seconds), the Fused Location Provider API returns location updates that are * accurate to within a few feet. * <p/> * These settings are appropriate for mapping applications that show real-time location * updates. */ protected void createLocationRequest() { mLocationRequest = new LocationRequest(); // Sets the desired interval for active location updates. This interval is // inexact. You may not receive updates at all if no location sources are available, or // you may receive them slower than requested. You may also receive updates faster than // requested if other applications are requesting location at a faster interval. mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); // Sets the fastest rate for active location updates. This interval is exact, and your // application will never receive updates faster than this value. mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } /** * Uses a {@link com.google.android.gms.location.LocationSettingsRequest.Builder} to build * a {@link com.google.android.gms.location.LocationSettingsRequest} that is used for checking * if a device has the needed location settings. */ protected void buildLocationSettingsRequest() { LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); mLocationSettingsRequest = builder.build(); } /** * Check if the device's location settings are adequate for the app's needs using the * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} method, with the results provided through a {@code PendingResult}. */ protected void checkLocationSettings() { PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings( mGoogleApiClient, mLocationSettingsRequest ); result.setResultCallback(this); } /** * The callback invoked when * {@link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient, * LocationSettingsRequest)} is called. Examines the * {@link com.google.android.gms.location.LocationSettingsResult} object and determines if * location settings are adequate. If they are not, begins the process of presenting a location * settings dialog to the user. */ public void onResult(LocationSettingsResult locationSettingsResult) { final Status status = locationSettingsResult.getStatus(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: Log.i(TAG, "All location settings are satisfied."); startLocationUpdates(); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" + "upgrade location settings "); /* try { // Show the dialog by calling startResolutionForResult(), and check the result // in onActivityResult(). // status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { Log.i(TAG, "PendingIntent unable to execute request."); }*/ break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " + "not created."); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: Log.i(TAG, "User agreed to make required location settings changes."); startLocationUpdates(); break; case Activity.RESULT_CANCELED: Log.i(TAG, "User chose not to make required location settings changes."); break; } break; } } /** * Handles the Start Updates button and requests start of location updates. Does nothing if * updates have already been requested. */ public void startUpdatesButtonHandler(View view) { checkLocationSettings(); } /** * Handles the Stop Updates button, and requests removal of location updates. */ public void stopUpdatesButtonHandler(View view) { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. stopLocationUpdates(); } /** * Requests location updates from the FusedLocationApi. */ protected void startLocationUpdates() { LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this ).setResultCallback(new ResultCallback<Status>() { public void onResult(Status status) { mRequestingLocationUpdates = true; //setButtonsEnabledState(); } }); } /** * Updates all UI fields. */ private void updateUI() { //setButtonsEnabledState(); updateLocationUI(); } /** * Disables both buttons when functionality is disabled due to insuffucient location settings. * Otherwise ensures that only one button is enabled at any time. The Start Updates button is * enabled if the user is not requesting location updates. The Stop Updates button is enabled * if the user is requesting location updates. */ /*private void setButtonsEnabledState() { if (mRequestingLocationUpdates) { mStartUpdatesButton.setEnabled(false); mStopUpdatesButton.setEnabled(true); } else { mStartUpdatesButton.setEnabled(true); mStopUpdatesButton.setEnabled(false); } }*/ /** * Sets the value of the UI fields for the location latitude, longitude and last update time. */ private void updateLocationUI() { if (mCurrentLocation != null) { mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude())); mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude())); mLastUpdateTimeTextView.setText(mLastUpdateTime); } } /** * Removes location updates from the FusedLocationApi. */ protected void stopLocationUpdates() { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. LocationServices.FusedLocationApi.removeLocationUpdates( mGoogleApiClient, this ).setResultCallback(new ResultCallback<Status>() { public void onResult(Status status) { mRequestingLocationUpdates = false; //setButtonsEnabledState(); } }); } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override public void onResume() { super.onResume(); // Within {@code onPause()}, we pause location updates, but leave the // connection to GoogleApiClient intact. Here, we resume receiving // location updates if the user has requested them. if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) { startLocationUpdates(); } } @Override protected void onPause() { super.onPause(); // Stop location updates to save battery, but don't disconnect the GoogleApiClient object. if (mGoogleApiClient.isConnected()) { stopLocationUpdates(); } } @Override protected void onStop() { super.onStop(); mGoogleApiClient.disconnect(); } /** * Runs when a GoogleApiClient object successfully connects. */ public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); if (mCurrentLocation == null) { mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); } } /** * Callback that fires when the location changes. */ public void onLocationChanged(Location location) { mCurrentLocation = location; mLastUpdateTime = DateFormat.getTimeInstance().format(new Date()); updateLocationUI(); /*Toast.makeText(this, getResources().getString(R.string.location_updated_message), Toast.LENGTH_SHORT).show();*/ } public void onConnectionSuspended(int cause) { Log.i(TAG, "Connection suspended"); } public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } /** * Stores activity data in the Bundle. */ public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putBoolean(KEY_REQUESTING_LOCATION_UPDATES, mRequestingLocationUpdates); savedInstanceState.putParcelable(KEY_LOCATION, mCurrentLocation); savedInstanceState.putString(KEY_LAST_UPDATED_TIME_STRING, mLastUpdateTime); super.onSaveInstanceState(savedInstanceState); } } ``` Which is more or less an example code of the newest Play Store location services. Anyway if I want to activate the service by using this code: ``` NewGPSClient GPSM = new NewGPSClient(); GPSM.onCreate(savedInstanceState); ``` There is the following error log I get: > > 05-09 18:45:11.344: I/location-settings(14284): Building GoogleApiClient > 05-09 18:45:11.344: D/AndroidRuntime(14284): Shutting down VM > 05-09 18:45:11.344: W/dalvikvm(14284): threadid=1: thread exiting with uncaught exception (group=0x4180ac08) > 05-09 18:45:11.349: E/AndroidRuntime(14284): FATAL EXCEPTION: main > 05-09 18:45:11.349: E/AndroidRuntime(14284): Process: my.app.client, PID: 14284 > 05-09 18:45:11.349: E/AndroidRuntime(14284): java.lang.RuntimeException: Unable to start activity ComponentInfo{my.app.client/my.app.client.LauncherActivity}: java.lang.NullPointerException > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2449) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.access$900(ActivityThread.java:172) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.os.Handler.dispatchMessage(Handler.java:102) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.os.Looper.loop(Looper.java:146) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.main(ActivityThread.java:5694) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at java.lang.reflect.Method.invokeNative(Native Method) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at java.lang.reflect.Method.invoke(Method.java:515) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at dalvik.system.NativeStart.main(Native Method) > 05-09 18:45:11.349: E/AndroidRuntime(14284): Caused by: java.lang.NullPointerException > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.content.ContextWrapper.getMainLooper(ContextWrapper.java:109) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at com.google.android.gms.common.api.GoogleApiClient$Builder.(Unknown Source) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at my.app.client.NewGPSClient.buildGoogleApiClient(NewGPSClient.java:183) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at my.app.client.NewGPSClient.onCreate(NewGPSClient.java:142) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at my.app.client.LauncherActivity.onCreate(LauncherActivity.java:97) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.Activity.performCreate(Activity.java:5541) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093) > 05-09 18:45:11.349: E/AndroidRuntime(14284): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413) > 05-09 18:45:11.349: E/AndroidRuntime(14284): ... 11 more > > > So with that new code I get the following errors anyway: > > 05-09 22:10:22.809: W/dalvikvm(25531): threadid=1: thread exiting with uncaught exception (group=0x4180ac08) > 05-09 22:10:22.809: E/AndroidRuntime(25531): FATAL EXCEPTION: main > 05-09 22:10:22.809: E/AndroidRuntime(25531): Process: my.app.client, PID: 25531 > 05-09 22:10:22.809: E/AndroidRuntime(25531): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{my.app.client/my.app.client.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "my.app.client.MainActivity" on path: DexPathList[[zip file "/data/app/my.app.client-68.apk"],nativeLibraryDirectories=[/data/app-lib/my.app.client-68, /vendor/lib, /system/lib]] > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2321) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.access$900(ActivityThread.java:172) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.os.Handler.dispatchMessage(Handler.java:102) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.os.Looper.loop(Looper.java:146) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.main(ActivityThread.java:5694) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.reflect.Method.invokeNative(Native Method) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.reflect.Method.invoke(Method.java:515) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at dalvik.system.NativeStart.main(Native Method) > 05-09 22:10:22.809: E/AndroidRuntime(25531): Caused by: java.lang.ClassNotFoundException: Didn't find class "my.app.client.MainActivity" on path: DexPathList[[zip file "/data/app/my.app.client-68.apk"],nativeLibraryDirectories=[/data/app-lib/my.app.client-68, /vendor/lib, /system/lib]] > 05-09 22:10:22.809: E/AndroidRuntime(25531): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:67) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.ClassLoader.loadClass(ClassLoader.java:497) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at java.lang.ClassLoader.loadClass(ClassLoader.java:457) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.Instrumentation.newActivity(Instrumentation.java:1067) > 05-09 22:10:22.809: E/AndroidRuntime(25531): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2312) > 05-09 22:10:22.809: E/AndroidRuntime(25531): ... 11 more > > > So here the manifest: ``` > <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="my.app.client" android:versionCode="59" android:versionName="2.7.1" > <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.STORAGE" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:debuggable="true"> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <service android:name="my.app.client.Client" > <intent-filter> <action android:name=".Client" /> <category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </service> <service android:name=".GPSClient"> <intent-filter> <action android:name=".GPSClient" /> </intent-filter> </service> <activity android:name="my.app.client.LauncherActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> ``` In fact, the GPS is now in the class LauncherActivity.
2015/05/09
[ "https://Stackoverflow.com/questions/30142669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3727877/" ]
I was receiving a `NoClassDefFoundError` and it was because I had included `play-services-gcm` but forgot to include `play-services-location`. ``` compile 'com.google.android.gms:play-services-gcm:7.5.0' compile 'com.google.android.gms:play-services-location:7.5.0' ``` Not 100% related to your error, but this post is in the top 10 when googling `java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.location.LocationServices" on path`
Add the following line in your **build.gradle** file, ``` dependencies { ... implementation "com.google.android.gms:play-services-location:+" } ```
21,313,561
I have been working a long time on a project using MS Access 2013. One issue i am having is i have very very long "Comments" in tables i need to break down and insert into new tables. Each comment is linked to a "RouteID" and their relationships between the two can be many to many. The main issue i am having is there are duplicate comments in the table i am moving data FROM. There is no need to keep the duplicate "Comments", the only difference in the rows is the "RouteID". Basically i have an OLD comments table and a NEW comments table. **My issue is its not correctly checking if comments from my OLD table are in the NEW table and is creating duplicates.** SOME COMMENTS ARE found to be duplicates, others are not and the size of the comments that are found to NOT BE DUPLICATES vary on size and symbols from short to very long. Here is some code i have written, i have attempted multiple versions of SQL and VBA/VB6 code, however the result is still the same, duplicate comments are showing up in my new table. Please feel free to critique this regardless if it has to do with my issue or not. I am aware that some queries can be far far too long to work so i have made a SQL query to compare the TABLE'S together however that also fails and duplicate comments remain. I have checked my code and i do not believe that i am doing the logic incorrectly Please help! No one seems to know what to do in my circle of friends / professors. I have an idea to take the comments and HASH them and put them into a similar table and use that to check ``` If Not (rsOLD.EOF And rsOLD.BOF) Then rsOLD.MoveFirst Do Until (rsOLD.EOF = True) TComment = rsOLD(CommentColumn) TResponse = rsOLD(ResponseColumn) If Not IsNull(TComment) Then TComment = Replace(TComment, "'", "''") SQL = "SELECT Comment, ID FROM Comments WHERE Comment = (SELECT '" & CommentColumn & _ "' FROM CommentsOld WHERE (CommentsOld.ID = " & rsOLD!ID & "));" 'SQL = "SELECT Comment FROM Comments" & _ ' " INNER JOIN CommentsOld" & _ ' " ON Comments.Comment = CommentsOld." & CommentColumn & _ ' " WHERE CommentsOld.ID = " & rsOLD!ID & ";" Set rsCHECK = CurrentDb.OpenRecordset(SQL, dbOpenDynaset) If (rsCHECK.EOF And rsCHECK.BOF) Then 'IF COMMENT DOES NOT EXIST, NOTHING FOUND ``` I have attempted to work with a bool function that loops through a recordset, but the BigO of the loops is far to large to complete in a reasonable amount of time given the size of the records in each table.
2014/01/23
[ "https://Stackoverflow.com/questions/21313561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1354571/" ]
One possible cause would be that your code is doing ```vbs SQL = "SELECT Comment, ID FROM Comments WHERE Comment = (SELECT '" & CommentColumn & _ "' FROM CommentsOld WHERE (CommentsOld.ID = " & rsOLD!ID & "));" ``` so instead of returning the *contents of* the column whose name is in the variable `CommentColumn` you are returning the column name as a literal string. That is, if `CommentColumn` contains `"Column1"` then your SQL code is not doing ```sql ... (Select Column1 FROM CommentsOld ... ``` it is doing ```sql ... (Select 'Column1' FROM CommentsOld ... ``` Perhaps you should try ```vbs SQL = "SELECT Comment, ID FROM Comments WHERE Comment = (SELECT [" & CommentColumn & _ "] FROM CommentsOld WHERE (CommentsOld.ID = " & rsOLD!ID & "));" ``` **Edit re: comment** Since there are some significant restrictions on Memo (Long Text) fields compared with Text (Short Text) fields w.r.t. joins, DISTINCT queries (as discussed in another answer), etc. your hashing idea is starting to look increasingly appealing. There are links to some VBA/VB6 implementations of various hashing algorithms in an answer [here](https://stackoverflow.com/a/125844/2144390). Generating a hash for every comment could potentially be rather time-consuming so you'll probably only want to do it once. If you could add a [...\_hash] column for each comment column (e.g., add a Short Text column named [CP1\_hash] for the Long Text column [CP1]) and store the hashes in there, that would be ideal. Once the hashing was done you could compare comment *hashes* instead of the comments themselves. In addition, the hash columns could be joined, fully indexed, and manipulated in other useful ways. (Yes, there would be the remote chance of a hash collision, but I think it would be extremely unlikely given the length of the strings you are likely to be processing.) One thing you would certainly **not** want to do is use the hashing function itself in a WHERE clause or a JOIN condition. That would cause a table scan and force the re-calculation of all the hash values for every row, and that could really slow things down.
Start with an empty table, NewTable. Then run this query: ``` insert into NewTable (Comment) SELECT distinct Comment FROM OldTable; ``` the 'distinct' will exclude all duplicates, so what ends up in NewTable should be unique. You can then go through OldTable and do what you like with each of the RouteIDs.
62,386,986
I'm building an API with Django, I want to query the Github GraphQL API, and I found this [GraphQL client](https://github.com/graphql-python/gql) for python that suits my needs. But now, I'm wondering, where is the proper place to initialize such a client inside my Django App? inside the request? in the apps.py? in views.py? any guidelines will be appreciated! here is my current Django Project folder structure: ``` . ├── LICENSE ├── README.md ├── api │   ├── __init__.py │   ├── admin.py │   ├── apps.py │   ├── migrations │   │   └── __init__.py │   ├── models.py │   ├── tests.py │   ├── urls.py │   └── views.py ├── db.sqlite3 ├── manage.py ├── portfolio │   ├── __init__.py │   ├── asgi.py │   ├── settings.py │   ├── urls.py │   └── wsgi.py ├── requirements.txt └── setup.py ``` Thanks in advance!
2020/06/15
[ "https://Stackoverflow.com/questions/62386986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11731187/" ]
As per definition a graphql client needs it's own configuration, modules and error handling I would suggest you to create a namespace adjacent to your other projects. Django uses the concept of [Applications](https://docs.djangoproject.com/en/3.0/ref/applications/#module-django.apps) which is providing seperated configuration, logging and error handling for this case. You define additional Applications in your project in your `settings.py` in `INSTALLED_APPS` ([Docs](https://docs.djangoproject.com/en/3.0/ref/settings/#installed-apps)). Your project structure would then look smth like: ``` . ├── LICENSE ├── README.md ├── graphql-client │ ├── __init__.py │ ├── main.py │ ├── client.py │ ├── ressources │ │ ├── __init__.py │ ├── ├── repository.py │ │ └── user.py │ ├── settings.py │ └── views.py ├── api │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── portfolio │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── requirements.txt └── setup.py ```
I ended up creating a python module in the `/api` Application called `graphql.py` that init the graphql client. from here, it is easily importable. I decide not to create a separate Django Application for this because that will be overkill on this context, due to the simplicity of the code: in `graphql.py`: ```py from gql import Client from gql.transport.requests import RequestsHTTPTransport from django.conf import settings # Instaciate a graphql client client = Client( transport=RequestsHTTPTransport( url='https://api.github.com/graphql', headers={'Authorization': 'bearer {token}'.format(token=settings.GITHUB_TOKEN)}, verify=False, retries=3, ), fetch_schema_from_transport=True, ) ```
62,386,986
I'm building an API with Django, I want to query the Github GraphQL API, and I found this [GraphQL client](https://github.com/graphql-python/gql) for python that suits my needs. But now, I'm wondering, where is the proper place to initialize such a client inside my Django App? inside the request? in the apps.py? in views.py? any guidelines will be appreciated! here is my current Django Project folder structure: ``` . ├── LICENSE ├── README.md ├── api │   ├── __init__.py │   ├── admin.py │   ├── apps.py │   ├── migrations │   │   └── __init__.py │   ├── models.py │   ├── tests.py │   ├── urls.py │   └── views.py ├── db.sqlite3 ├── manage.py ├── portfolio │   ├── __init__.py │   ├── asgi.py │   ├── settings.py │   ├── urls.py │   └── wsgi.py ├── requirements.txt └── setup.py ``` Thanks in advance!
2020/06/15
[ "https://Stackoverflow.com/questions/62386986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11731187/" ]
**TLDR**: instantiate ***new client right in the view method*** = new client for each request. (good option - overriding [`initial`](https://www.django-rest-framework.org/api-guide/views/#initialself-request-42args-kwargs) view method). Improve later. --- **It depends.** If there are no request / user options for the client (= client is **the same** *for every request / user*): 1. import one from submodule as @ElPapi42 suggested (= same as instantiate new client in views.py globally, not as part of method logic) 2. or instantiate new client right in the view method - new client for each request If there are request / user specific options (i.e. client need to have `request.user` specific options / credentials): 2. instantiate new client right in the view method --- Option 1 - Client is instantiated once per worker view. Although it provides some performance benefits they are subtle and obscured: * you may not know what it means: shared client => possibly use methods that modify client state for different requests / users that rely on the state * worker lifetime is (should be) actually not that long * hard to assess performance benefits with hard to assess proper implementation In reality you may want to connect to github with some current `request.user` specific options, perform multiple requests (= cookies may be involved and auto-added in subsequent requests => client cannot be shared with multiple users) = at least separate client for each user.
As per definition a graphql client needs it's own configuration, modules and error handling I would suggest you to create a namespace adjacent to your other projects. Django uses the concept of [Applications](https://docs.djangoproject.com/en/3.0/ref/applications/#module-django.apps) which is providing seperated configuration, logging and error handling for this case. You define additional Applications in your project in your `settings.py` in `INSTALLED_APPS` ([Docs](https://docs.djangoproject.com/en/3.0/ref/settings/#installed-apps)). Your project structure would then look smth like: ``` . ├── LICENSE ├── README.md ├── graphql-client │ ├── __init__.py │ ├── main.py │ ├── client.py │ ├── ressources │ │ ├── __init__.py │ ├── ├── repository.py │ │ └── user.py │ ├── settings.py │ └── views.py ├── api │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── db.sqlite3 ├── manage.py ├── portfolio │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── requirements.txt └── setup.py ```
62,386,986
I'm building an API with Django, I want to query the Github GraphQL API, and I found this [GraphQL client](https://github.com/graphql-python/gql) for python that suits my needs. But now, I'm wondering, where is the proper place to initialize such a client inside my Django App? inside the request? in the apps.py? in views.py? any guidelines will be appreciated! here is my current Django Project folder structure: ``` . ├── LICENSE ├── README.md ├── api │   ├── __init__.py │   ├── admin.py │   ├── apps.py │   ├── migrations │   │   └── __init__.py │   ├── models.py │   ├── tests.py │   ├── urls.py │   └── views.py ├── db.sqlite3 ├── manage.py ├── portfolio │   ├── __init__.py │   ├── asgi.py │   ├── settings.py │   ├── urls.py │   └── wsgi.py ├── requirements.txt └── setup.py ``` Thanks in advance!
2020/06/15
[ "https://Stackoverflow.com/questions/62386986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11731187/" ]
**TLDR**: instantiate ***new client right in the view method*** = new client for each request. (good option - overriding [`initial`](https://www.django-rest-framework.org/api-guide/views/#initialself-request-42args-kwargs) view method). Improve later. --- **It depends.** If there are no request / user options for the client (= client is **the same** *for every request / user*): 1. import one from submodule as @ElPapi42 suggested (= same as instantiate new client in views.py globally, not as part of method logic) 2. or instantiate new client right in the view method - new client for each request If there are request / user specific options (i.e. client need to have `request.user` specific options / credentials): 2. instantiate new client right in the view method --- Option 1 - Client is instantiated once per worker view. Although it provides some performance benefits they are subtle and obscured: * you may not know what it means: shared client => possibly use methods that modify client state for different requests / users that rely on the state * worker lifetime is (should be) actually not that long * hard to assess performance benefits with hard to assess proper implementation In reality you may want to connect to github with some current `request.user` specific options, perform multiple requests (= cookies may be involved and auto-added in subsequent requests => client cannot be shared with multiple users) = at least separate client for each user.
I ended up creating a python module in the `/api` Application called `graphql.py` that init the graphql client. from here, it is easily importable. I decide not to create a separate Django Application for this because that will be overkill on this context, due to the simplicity of the code: in `graphql.py`: ```py from gql import Client from gql.transport.requests import RequestsHTTPTransport from django.conf import settings # Instaciate a graphql client client = Client( transport=RequestsHTTPTransport( url='https://api.github.com/graphql', headers={'Authorization': 'bearer {token}'.format(token=settings.GITHUB_TOKEN)}, verify=False, retries=3, ), fetch_schema_from_transport=True, ) ```
31,832,269
I'm using a batch script with fnr.exe to perform bulk search and replace operations over multiple files, but I'm having trouble figuring out how to use capture groups in fnr.exe. I can use them fine in a similar utility called FAR that uses java regex's, but FAR can't be run from the command line, so I'm unable to automate it. Fnr.exe says in it's documentation that it uses .NET regular expressions, and the documentation for .NET regular expressions is great when it comes to how to capture a group, but when it comes to outputting the captured group, it's rather lacking and assumes I'm writing C# or VB code where I can call things like: ``` Console.WriteLine("Match: {0}", match.Value) ``` I have a bunch of strings like the following, with the original string on the left and my desired replacement string on the right: ``` include "fooPrintDriver.h"; | include "barPrintDriver.h"; include "fooSearchAgent.h"; | include "barSearchAgent.h"; include "fooEventListener.h"; | include "barEventListener.h"; ``` In FAR, I could find the strings on the left with ``` foo(.*?)\.h" ``` And then replace it with my desired string using ``` bar\1.h" ``` Where the '\1' would be PrintDriver or SearchAgent or EventListener, however when I try the same thing in fnr.exe, the '\1' is literally '\1', so my input and output will be: ``` include "fooPrintDriver.h"; | include "bar\1.h"; include "fooSearchAgent.h"; | include "bar\1.h"; include "fooEventListener.h"; | include "bar\1.h"; ``` Anyone know how to get it working in fnr.exe?
2015/08/05
[ "https://Stackoverflow.com/questions/31832269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4618054/" ]
I figured it out. I need to use the following: ``` bar$1.h" ```
Good to see you figured it out. However, having tried it and initially failed, it's important to group it with the parentheses. For example, if you used \w to find the letters after foo (a more reliable method than you used), using $1 would have replaced those with literal $1. You'd need to use (\w). Then the $1 would replace correctly.
32,309,772
[Reference](http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html) I am trying to build a form with the functionality something similar to word search. I have a text-area and a series of divs with contents. When a user types a word or a sentence, the words that match with the div contents are highlighted in yellow and when text-area content is removed or emptied, highlighting is also removed. The sample that I made highlights the words but doesn't highlight it completely. Only first character is highlighted. And when I try to search for a new word, previously highlighted words are still highlighted. **HTML** ``` <textarea id="my_ta" name="my_ta"></textarea> <hr> Similiar Words <hr> <div> This is a serious question </div> <div> Does this question ring a bell inside your head? </div> <div> This question is a question about questions </div> ``` **CSS** ``` .highlight { background-color: yellow } ``` **JavaScript** ``` $(document).ready(function(){ $('#my_ta').keypress(function() { var value = $(this).val(); if(value) { $('div').highlight(value); } else { $('.highlight').removeHighlight(); } }); }); ``` [FIDDLE](http://jsfiddle.net/iamsajeev/2vsgbmgz/1/)
2015/08/31
[ "https://Stackoverflow.com/questions/32309772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4222192/" ]
Looking at the documentation, seems that you'de be good to go just with ``` $(document).ready(function(){ $('#my_ta').on('input',function(){ $('div').removeHighlight().highlight($(this).val()); }); }); ``` Use `input` or `keyup` instead of `keypress`. <http://jsfiddle.net/2vsgbmgz/3/>
Rather use Regular Expressions. It's easier to find anything you're looking for. --- HTML ---- ``` <div> You can have any text inside a <div> or any valid html tag you want. </div> ``` --- CSS --- ``` #highlight { background-color: red } ``` --- jQuery ------ ``` function highlight() { $.each($('div'), function() { //-------------------------Get Text var str = $(this).html(); //-------------------------Wrap Matching Text str = str.replace(/hi/ig, '<span id="highlight">$&</span>'); //-------------------------Insert Coloured Text $(this).html(str); }); } highlight(); ``` [jsFiddle](http://jsfiddle.net/HovyTech/5fxrvvxp/4/)
68,759,342
Supposing I have a temporary table created using `WITH` clause as follows: ```sql WITH temporary_table AS ( VALUES ('First', 1), ('Second', 2), ('Third', 3)) ``` Is it possible to refer to the nth column in the `SELECT` clause? Something like: ```sql WITH temporary_table AS ( VALUES ('First', 1), ('Second', 2), ('Third', 3) ) SELECT second_column FROM temporary_table; ``` If not - is there any other way to make up some temporary table only for query purposes when having read only privileges? I haven't found anything helpful on [WITH](https://www.postgresql.org/docs/11/queries-with.html) or [SELECT](https://www.postgresql.org/docs/11/sql-select.html) PostgreSQL docs.
2021/08/12
[ "https://Stackoverflow.com/questions/68759342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10699128/" ]
In order to write correct C programs, one should always indicate the correct return type of the function. In case a function does not return any value, a "special" return type `void` is used. Example function that returns an `int`: ```c int add(int a, int b) { return a + b; } ``` Example function that returns nothing: ```c void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } ``` You can ignore the return value of a function if you don't need it: ```c void test(void) { int x = add(3, 5); // correct, we're using the return value of add() add(1, 2); // also correct, we're just ignoring the return value of add() (void) add(1, 2); // more correct, this is just like previous line, but we're making it obvious to the reader that we are explicitly ignoring the return value, and it is not a mistake } ``` EDIT: in order to make my answer more useful, I will add some examples of what SHOULD NOT be done in C. Example 1: ```c // WRONG, because we defined neg() to return an int, but we're not returning it // NOTE: this is wrong even if we ignore the return value of neg() int neg(int* a) { *a = -(*a); } // POSSIBLE CORRECT ALTERNATIVE void neg(int* a) { *a = -(*a); } // ANOTHER POSSIBLE CORRECT ALTERNATIVE int neg(int* a) { *a = -(*a); return *a; } ``` Example 2: ```c // WRONG, because we defined foo() to return nothing, but we're actually returning an int void foo(int a) { return a; } // CORRECT ALTERNATIVE int foo(int a) { return a; } ``` Example 3: ```c // CORRECT void foo(int a, int b) { if (a == 0) { return; // we're returning early from the function (and we're returning nothing, of course, since function is void) } printf("%d %d\n", a, b); return; // this is really not needed and it is implicit in void functions: when they reach the end, they return nothing } // WRONG int bar(int a, int b) { if (a == 0) { return; // WRONG, we must return an int } int x = foo(1, 2); // WRONG: foo() returns nothing (i.e.: void), and we cannot therefore use the return value of foo() // WRONG: reached end of function, but we never returned an int } ``` Example 4: ```c void test(void) { printf("Hello, I'm ignoring your return value.\n"); // CORRECT, printf() is a standard function that returns the number of characters written (returned as an int), and if we don't need this information, we can just ignore the returning value malloc(500); // WRONG, malloc() is a standard function defined to return a pointer, and it is one of many functions that we should never ignore the return value of // The difference between printf() and malloc() must be learned from the docs: there we can find out that printf()'s return value can be safely ignored, while malloc()'s cannot } ``` EDIT 2: in my answer the words `CORRECT` and `WRONG` are not always used to say "it is correct/wrong according to the ISO C standard", but sometimes (as in the example of `malloc() vs printf()`) they mean "it is correct/wrong according to good programming practices"
Yes. Always do a clean return from any non-void function. Otherwise the consequences are * confused colleagues * confused future you * more risks at code changes
68,759,342
Supposing I have a temporary table created using `WITH` clause as follows: ```sql WITH temporary_table AS ( VALUES ('First', 1), ('Second', 2), ('Third', 3)) ``` Is it possible to refer to the nth column in the `SELECT` clause? Something like: ```sql WITH temporary_table AS ( VALUES ('First', 1), ('Second', 2), ('Third', 3) ) SELECT second_column FROM temporary_table; ``` If not - is there any other way to make up some temporary table only for query purposes when having read only privileges? I haven't found anything helpful on [WITH](https://www.postgresql.org/docs/11/queries-with.html) or [SELECT](https://www.postgresql.org/docs/11/sql-select.html) PostgreSQL docs.
2021/08/12
[ "https://Stackoverflow.com/questions/68759342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10699128/" ]
I guess there are sort of two questions here: 1. If a function is declared to return a value (or not), how wrong is it to not return a value (or to return a value)? 2. If a function returns a value (or not), how wrong is it for the caller not to use the value (or to use the value)? Let's examine these in turn. First, if a function is declared to return a value (or not), how wrong is it to not return a value (or to return a value)? There are four cases: 1. function declared to return value, function does return value: this is obviously good and proper. 2. function declared to return `void`, function does not return value: this is obviously good and proper. 3. function declared to return `void`, function does return value: this is obviously an error, and the compiler will emit an error message and halt compilation. 4. function declared to return value, function does not return value: this is probably an error, but for historical reasons, *the compiler might not complain*. Good compilers will at least issue a warning here. It sounds like your compiler didn't. You might want to think about getting a better compiler, or changing compilation options so it issues more warnings. (It's also *possible* for this situation not to be an error, as described in Eric Postpischil's answer, and this helps explains why the situation is not, in fact, illegal. There may also be subtle differences between the case where the function "falls off the end" and hits the terminating `}` without ever having a `return` statement, versus the case where it has an explicit `return;` statement without a value.) That might answer your question, but if not, let's move on to my second question: if a function returns a value (or not), how wrong is it for the caller not to use the value (or to use the value)? Again, there are four cases: 1. function declared to return value, caller uses return value: this is obviously good and proper. 2. function declared to return `void`, caller does not use return value: this is obviously good and proper. 3. function declared to return `void`, caller does use return value: this is obviously an error, and the compiler will emit an error message and halt compilation. 4. function declared to return value, caller does not use return value: this is the interesting case. It might be a problem, or it might not be a problem. Let's expand on this further: For a function like `sqrt`, whose sole function is to compute and return a value, it would obviously be very strange to not use the return value. For example, if you write ``` sqrt(100); ``` alone on a line, you're asking to compute the square root of 100, and then throwing away the return value. This is not an error, but a good compiler will probably warn about it, because it's probably not what you want. There are other functions that return a value, that you might not care about. For example, it's not well known that the venerable `printf` function returns a value: the number of characters printed. But `printf` is *not* a function whose sole function is to compute and return a value; `printf` also does something interesting off to the side: it prints stuff. So if you call ``` printf("Hello, world!\n"); ``` but if you throw away the return value, that's fine, almost no one would object to that. (Theoretically there's a chance that `printf` might fail, due to some kind of an i/o error, and return -1 to try to tell you this, but most programs don't care about this, and in the grand scheme of things that's not a problem.) Finally, there are programs that return a value, that you might not think you care about, but that you probably should care about. Consider this fragment: ``` int i; printf("enter an integer:\n"); scanf("%d", &i); printf("you typed %d\n, i); ``` Here, the problem is that if the user types something like "no, I won't", `scanf` will be unable to read an integer as requested by `%d`, and it will return 0 to say that it performed no conversion, but the program won't notice, and since `i` is an uninitialized value, it's hard to see what the program might print. If we think about this carefully, we see that there might be sort of a "hidden" attribute of functions, namely: "How okay is it for the caller to ignore the return value?" `printf` is a function that returns `int`, but it's usually (in all but the most paranoid programs) okay to ignore the return value. But `scanf` is a function that returns `int` where, as we've just seen, it's not a good idea to ignore the return value (although lots of programmers do). And `sqrt` is a function returning `double`, where it's almost certainly an error not to use the return value. So if a compiler decides to help you out by warning you when you forget to use a function's return value, how does it avoid spamming you with warnings every time you call `printf`? And the answer is that such a compiler has to invent a special way to implement that property -- a property not defined by the C language, which is why I called it "hidden" -- that specifies whether or not the warning is appropriate. Also -- and this gets down to the meat of your question as asked -- there's a higher-order question that sort of combines the two top-level questions I've been exploring: *If a function is declared as returning a value, but does not return a value, what happens if the caller does/doesn't try to use the returned value?* And the answer is that if a function is declared as returning a value, but it doesn't actually return a value, but the caller doesn't try to use the return value, that's fine -- although this might seem like kind of a dicey situation! And on the other hand, if the caller does try to use the value that wasn't returned, that's obviously a bad situation. As far as the C Standard is concerned, it falls into the dreaded category of *undefined behavior*, and there's a pretty good reason for this: deciding whether it's *actually* a problem is a hard, almost impossible problem. If a function is declared as returning a value, and if it sometimes doesn't return a value, and if the caller sometimes doesn't try to use the returned non-value, deciding whether it's *actually* a problem would theoretically requiring (a) examining the code for both the function and its caller and (b) deciding under which circumstances the function does or doesn't return a value. Both of these subproblems are basically impossible to solve. C supports separate compilation, so in the general case a compiler won;t be able to inspect both the function and its caller at once. And solving subproblem (b) is basically the [halting problem](https://en.wikipedia.org/wiki/Halting_problem). So it's up to you, the programmer, to keep things straight in this case: the compiler can't be required to issue an error if you try to use the value that wasn't returned by a function declared as if it returned one. In the end, though, the `Swap()` function you posted could probably an example of the "don't care" case. It's defined as returning `int *`, but it doesn't actually return a value, but the caller doesn't try to use it, so it's okay. But this is potentially quite confusing and error-prone, so I would suggest that it would be much better to either (a) have it actually return a value or (b) redeclare it as returning `void`.
In order to write correct C programs, one should always indicate the correct return type of the function. In case a function does not return any value, a "special" return type `void` is used. Example function that returns an `int`: ```c int add(int a, int b) { return a + b; } ``` Example function that returns nothing: ```c void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } ``` You can ignore the return value of a function if you don't need it: ```c void test(void) { int x = add(3, 5); // correct, we're using the return value of add() add(1, 2); // also correct, we're just ignoring the return value of add() (void) add(1, 2); // more correct, this is just like previous line, but we're making it obvious to the reader that we are explicitly ignoring the return value, and it is not a mistake } ``` EDIT: in order to make my answer more useful, I will add some examples of what SHOULD NOT be done in C. Example 1: ```c // WRONG, because we defined neg() to return an int, but we're not returning it // NOTE: this is wrong even if we ignore the return value of neg() int neg(int* a) { *a = -(*a); } // POSSIBLE CORRECT ALTERNATIVE void neg(int* a) { *a = -(*a); } // ANOTHER POSSIBLE CORRECT ALTERNATIVE int neg(int* a) { *a = -(*a); return *a; } ``` Example 2: ```c // WRONG, because we defined foo() to return nothing, but we're actually returning an int void foo(int a) { return a; } // CORRECT ALTERNATIVE int foo(int a) { return a; } ``` Example 3: ```c // CORRECT void foo(int a, int b) { if (a == 0) { return; // we're returning early from the function (and we're returning nothing, of course, since function is void) } printf("%d %d\n", a, b); return; // this is really not needed and it is implicit in void functions: when they reach the end, they return nothing } // WRONG int bar(int a, int b) { if (a == 0) { return; // WRONG, we must return an int } int x = foo(1, 2); // WRONG: foo() returns nothing (i.e.: void), and we cannot therefore use the return value of foo() // WRONG: reached end of function, but we never returned an int } ``` Example 4: ```c void test(void) { printf("Hello, I'm ignoring your return value.\n"); // CORRECT, printf() is a standard function that returns the number of characters written (returned as an int), and if we don't need this information, we can just ignore the returning value malloc(500); // WRONG, malloc() is a standard function defined to return a pointer, and it is one of many functions that we should never ignore the return value of // The difference between printf() and malloc() must be learned from the docs: there we can find out that printf()'s return value can be safely ignored, while malloc()'s cannot } ``` EDIT 2: in my answer the words `CORRECT` and `WRONG` are not always used to say "it is correct/wrong according to the ISO C standard", but sometimes (as in the example of `malloc() vs printf()`) they mean "it is correct/wrong according to good programming practices"
68,759,342
Supposing I have a temporary table created using `WITH` clause as follows: ```sql WITH temporary_table AS ( VALUES ('First', 1), ('Second', 2), ('Third', 3)) ``` Is it possible to refer to the nth column in the `SELECT` clause? Something like: ```sql WITH temporary_table AS ( VALUES ('First', 1), ('Second', 2), ('Third', 3) ) SELECT second_column FROM temporary_table; ``` If not - is there any other way to make up some temporary table only for query purposes when having read only privileges? I haven't found anything helpful on [WITH](https://www.postgresql.org/docs/11/queries-with.html) or [SELECT](https://www.postgresql.org/docs/11/sql-select.html) PostgreSQL docs.
2021/08/12
[ "https://Stackoverflow.com/questions/68759342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10699128/" ]
The C standard does not require a function declared with a non-void return type to return a value. It is not, by itself, undefined behavior for such a function not to return a value. It is undefined behavior if the caller attempts to use the value of a function that did not return a value. C 2018 6.9.1 12 says: > > Unless otherwise specified, if the `}` that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined. > > > (It is “otherwise specified” for `main`: In a hosted environment, if the return type of `main` is `int` and it reaches the `}` that terminates its body, it returns zero, per C 2018 5.1.2.2.3 1.) In most cases, it is good practice for a function declared with a non-void return type to return a value, and compilers may warn if they do not. However, there are situations in which a function may be intentionally designed not to return a value in all cases. For example: ``` typedef enum { Get, Set } CommandType; int DoCommand(CommandType Command, int Value) { switch (Command) { command Get: return SavedValue; command Set: SavedValue = Value; break; } } ``` This is a very simplified abstracted example—with simple situations, we might want to separate this routine into two routines, one to set and one to get. But in more complicated software, it might make sense to wrap these and other “commands” that operate on various objects (not shown) into a single command-and-control routine which sometimes returns a value and sometimes does not.
In order to write correct C programs, one should always indicate the correct return type of the function. In case a function does not return any value, a "special" return type `void` is used. Example function that returns an `int`: ```c int add(int a, int b) { return a + b; } ``` Example function that returns nothing: ```c void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } ``` You can ignore the return value of a function if you don't need it: ```c void test(void) { int x = add(3, 5); // correct, we're using the return value of add() add(1, 2); // also correct, we're just ignoring the return value of add() (void) add(1, 2); // more correct, this is just like previous line, but we're making it obvious to the reader that we are explicitly ignoring the return value, and it is not a mistake } ``` EDIT: in order to make my answer more useful, I will add some examples of what SHOULD NOT be done in C. Example 1: ```c // WRONG, because we defined neg() to return an int, but we're not returning it // NOTE: this is wrong even if we ignore the return value of neg() int neg(int* a) { *a = -(*a); } // POSSIBLE CORRECT ALTERNATIVE void neg(int* a) { *a = -(*a); } // ANOTHER POSSIBLE CORRECT ALTERNATIVE int neg(int* a) { *a = -(*a); return *a; } ``` Example 2: ```c // WRONG, because we defined foo() to return nothing, but we're actually returning an int void foo(int a) { return a; } // CORRECT ALTERNATIVE int foo(int a) { return a; } ``` Example 3: ```c // CORRECT void foo(int a, int b) { if (a == 0) { return; // we're returning early from the function (and we're returning nothing, of course, since function is void) } printf("%d %d\n", a, b); return; // this is really not needed and it is implicit in void functions: when they reach the end, they return nothing } // WRONG int bar(int a, int b) { if (a == 0) { return; // WRONG, we must return an int } int x = foo(1, 2); // WRONG: foo() returns nothing (i.e.: void), and we cannot therefore use the return value of foo() // WRONG: reached end of function, but we never returned an int } ``` Example 4: ```c void test(void) { printf("Hello, I'm ignoring your return value.\n"); // CORRECT, printf() is a standard function that returns the number of characters written (returned as an int), and if we don't need this information, we can just ignore the returning value malloc(500); // WRONG, malloc() is a standard function defined to return a pointer, and it is one of many functions that we should never ignore the return value of // The difference between printf() and malloc() must be learned from the docs: there we can find out that printf()'s return value can be safely ignored, while malloc()'s cannot } ``` EDIT 2: in my answer the words `CORRECT` and `WRONG` are not always used to say "it is correct/wrong according to the ISO C standard", but sometimes (as in the example of `malloc() vs printf()`) they mean "it is correct/wrong according to good programming practices"
68,759,342
Supposing I have a temporary table created using `WITH` clause as follows: ```sql WITH temporary_table AS ( VALUES ('First', 1), ('Second', 2), ('Third', 3)) ``` Is it possible to refer to the nth column in the `SELECT` clause? Something like: ```sql WITH temporary_table AS ( VALUES ('First', 1), ('Second', 2), ('Third', 3) ) SELECT second_column FROM temporary_table; ``` If not - is there any other way to make up some temporary table only for query purposes when having read only privileges? I haven't found anything helpful on [WITH](https://www.postgresql.org/docs/11/queries-with.html) or [SELECT](https://www.postgresql.org/docs/11/sql-select.html) PostgreSQL docs.
2021/08/12
[ "https://Stackoverflow.com/questions/68759342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10699128/" ]
I guess there are sort of two questions here: 1. If a function is declared to return a value (or not), how wrong is it to not return a value (or to return a value)? 2. If a function returns a value (or not), how wrong is it for the caller not to use the value (or to use the value)? Let's examine these in turn. First, if a function is declared to return a value (or not), how wrong is it to not return a value (or to return a value)? There are four cases: 1. function declared to return value, function does return value: this is obviously good and proper. 2. function declared to return `void`, function does not return value: this is obviously good and proper. 3. function declared to return `void`, function does return value: this is obviously an error, and the compiler will emit an error message and halt compilation. 4. function declared to return value, function does not return value: this is probably an error, but for historical reasons, *the compiler might not complain*. Good compilers will at least issue a warning here. It sounds like your compiler didn't. You might want to think about getting a better compiler, or changing compilation options so it issues more warnings. (It's also *possible* for this situation not to be an error, as described in Eric Postpischil's answer, and this helps explains why the situation is not, in fact, illegal. There may also be subtle differences between the case where the function "falls off the end" and hits the terminating `}` without ever having a `return` statement, versus the case where it has an explicit `return;` statement without a value.) That might answer your question, but if not, let's move on to my second question: if a function returns a value (or not), how wrong is it for the caller not to use the value (or to use the value)? Again, there are four cases: 1. function declared to return value, caller uses return value: this is obviously good and proper. 2. function declared to return `void`, caller does not use return value: this is obviously good and proper. 3. function declared to return `void`, caller does use return value: this is obviously an error, and the compiler will emit an error message and halt compilation. 4. function declared to return value, caller does not use return value: this is the interesting case. It might be a problem, or it might not be a problem. Let's expand on this further: For a function like `sqrt`, whose sole function is to compute and return a value, it would obviously be very strange to not use the return value. For example, if you write ``` sqrt(100); ``` alone on a line, you're asking to compute the square root of 100, and then throwing away the return value. This is not an error, but a good compiler will probably warn about it, because it's probably not what you want. There are other functions that return a value, that you might not care about. For example, it's not well known that the venerable `printf` function returns a value: the number of characters printed. But `printf` is *not* a function whose sole function is to compute and return a value; `printf` also does something interesting off to the side: it prints stuff. So if you call ``` printf("Hello, world!\n"); ``` but if you throw away the return value, that's fine, almost no one would object to that. (Theoretically there's a chance that `printf` might fail, due to some kind of an i/o error, and return -1 to try to tell you this, but most programs don't care about this, and in the grand scheme of things that's not a problem.) Finally, there are programs that return a value, that you might not think you care about, but that you probably should care about. Consider this fragment: ``` int i; printf("enter an integer:\n"); scanf("%d", &i); printf("you typed %d\n, i); ``` Here, the problem is that if the user types something like "no, I won't", `scanf` will be unable to read an integer as requested by `%d`, and it will return 0 to say that it performed no conversion, but the program won't notice, and since `i` is an uninitialized value, it's hard to see what the program might print. If we think about this carefully, we see that there might be sort of a "hidden" attribute of functions, namely: "How okay is it for the caller to ignore the return value?" `printf` is a function that returns `int`, but it's usually (in all but the most paranoid programs) okay to ignore the return value. But `scanf` is a function that returns `int` where, as we've just seen, it's not a good idea to ignore the return value (although lots of programmers do). And `sqrt` is a function returning `double`, where it's almost certainly an error not to use the return value. So if a compiler decides to help you out by warning you when you forget to use a function's return value, how does it avoid spamming you with warnings every time you call `printf`? And the answer is that such a compiler has to invent a special way to implement that property -- a property not defined by the C language, which is why I called it "hidden" -- that specifies whether or not the warning is appropriate. Also -- and this gets down to the meat of your question as asked -- there's a higher-order question that sort of combines the two top-level questions I've been exploring: *If a function is declared as returning a value, but does not return a value, what happens if the caller does/doesn't try to use the returned value?* And the answer is that if a function is declared as returning a value, but it doesn't actually return a value, but the caller doesn't try to use the return value, that's fine -- although this might seem like kind of a dicey situation! And on the other hand, if the caller does try to use the value that wasn't returned, that's obviously a bad situation. As far as the C Standard is concerned, it falls into the dreaded category of *undefined behavior*, and there's a pretty good reason for this: deciding whether it's *actually* a problem is a hard, almost impossible problem. If a function is declared as returning a value, and if it sometimes doesn't return a value, and if the caller sometimes doesn't try to use the returned non-value, deciding whether it's *actually* a problem would theoretically requiring (a) examining the code for both the function and its caller and (b) deciding under which circumstances the function does or doesn't return a value. Both of these subproblems are basically impossible to solve. C supports separate compilation, so in the general case a compiler won;t be able to inspect both the function and its caller at once. And solving subproblem (b) is basically the [halting problem](https://en.wikipedia.org/wiki/Halting_problem). So it's up to you, the programmer, to keep things straight in this case: the compiler can't be required to issue an error if you try to use the value that wasn't returned by a function declared as if it returned one. In the end, though, the `Swap()` function you posted could probably an example of the "don't care" case. It's defined as returning `int *`, but it doesn't actually return a value, but the caller doesn't try to use it, so it's okay. But this is potentially quite confusing and error-prone, so I would suggest that it would be much better to either (a) have it actually return a value or (b) redeclare it as returning `void`.
Yes. Always do a clean return from any non-void function. Otherwise the consequences are * confused colleagues * confused future you * more risks at code changes
68,759,342
Supposing I have a temporary table created using `WITH` clause as follows: ```sql WITH temporary_table AS ( VALUES ('First', 1), ('Second', 2), ('Third', 3)) ``` Is it possible to refer to the nth column in the `SELECT` clause? Something like: ```sql WITH temporary_table AS ( VALUES ('First', 1), ('Second', 2), ('Third', 3) ) SELECT second_column FROM temporary_table; ``` If not - is there any other way to make up some temporary table only for query purposes when having read only privileges? I haven't found anything helpful on [WITH](https://www.postgresql.org/docs/11/queries-with.html) or [SELECT](https://www.postgresql.org/docs/11/sql-select.html) PostgreSQL docs.
2021/08/12
[ "https://Stackoverflow.com/questions/68759342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10699128/" ]
The C standard does not require a function declared with a non-void return type to return a value. It is not, by itself, undefined behavior for such a function not to return a value. It is undefined behavior if the caller attempts to use the value of a function that did not return a value. C 2018 6.9.1 12 says: > > Unless otherwise specified, if the `}` that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined. > > > (It is “otherwise specified” for `main`: In a hosted environment, if the return type of `main` is `int` and it reaches the `}` that terminates its body, it returns zero, per C 2018 5.1.2.2.3 1.) In most cases, it is good practice for a function declared with a non-void return type to return a value, and compilers may warn if they do not. However, there are situations in which a function may be intentionally designed not to return a value in all cases. For example: ``` typedef enum { Get, Set } CommandType; int DoCommand(CommandType Command, int Value) { switch (Command) { command Get: return SavedValue; command Set: SavedValue = Value; break; } } ``` This is a very simplified abstracted example—with simple situations, we might want to separate this routine into two routines, one to set and one to get. But in more complicated software, it might make sense to wrap these and other “commands” that operate on various objects (not shown) into a single command-and-control routine which sometimes returns a value and sometimes does not.
Yes. Always do a clean return from any non-void function. Otherwise the consequences are * confused colleagues * confused future you * more risks at code changes
6,530,115
We want to get the remote database data into local database first and then we want to access the local database. Can you please suggest us how to approach for this with sample code. Our remote database is MSSQL Server.
2011/06/30
[ "https://Stackoverflow.com/questions/6530115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/818942/" ]
Have the app query the remote server, return the data from MSSQL to android code via JSON, insert into SQLite. **Edit**: type MySQL to MSSQL
Get desired data from mysql ...in the form of xml from server. Parse that xml in android and fill desired java beans inside collection. then write state of object's in collection to sqlite dataabase.
6,530,115
We want to get the remote database data into local database first and then we want to access the local database. Can you please suggest us how to approach for this with sample code. Our remote database is MSSQL Server.
2011/06/30
[ "https://Stackoverflow.com/questions/6530115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/818942/" ]
Have the app query the remote server, return the data from MSSQL to android code via JSON, insert into SQLite. **Edit**: type MySQL to MSSQL
I would suggest next time providing some code that indicates at least that you attempted to connect to your database first, and then if you run into trouble, someone here may be able to help. As opposed to just asking for sample code. If you're talking about replication, I'm not sure this is possible from SQL Server to SQLite, otherwise, the answer to your question is simple, you would connect to your SQL Server database probably through some sort of exposed API, retrieve the data, parse it, and update your local SQLite Database accordingly. Here's a link to a tutorial that covers connecting to local databases: [NotePad Tutorial](http://developer.android.com/resources/tutorials/notepad/index.html)
15,735,469
I'm tring to execute query in a db2 procedure: ``` CREATE OR REPLACE PROCEDURE TEST (IN indbnm VARCHAR(30), IN intblnm VARCHAR(30)) LANGUAGE SQL BEGIN DECLARE statmnt2 VARCHAR(1000); DECLARE VAR_COD_TIPO_ARQU CHAR(1); DECLARE stmt1 STATEMENT; SET statmnt2 = 'SELECT COD_TIPO_ARQU FROM '||indbnm||'.'||intblnm||' FETCH FIRST 1 ROWS ONLY'; PREPARE stmt1 FROM statmnt2; SET VAR_COD_TIPO_ARQU = EXECUTE (stmt1); END@ ``` This gives following error: ``` DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0206N "STMT1" is not valid in the context where it is used. LINE NUMBER=33. SQLSTATE=42703 ``` What's the right way to set `VAR_COD_TIPO_ARQU` with `COD_TIPO_ARQU` value dynamically? ThankYou.
2013/03/31
[ "https://Stackoverflow.com/questions/15735469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2230284/" ]
The problem is the way you are setting the result from the execution: ``` EXECUTE stmt1 into VAR_COD_TIPO_ARQU ; ``` This is the complete code that is executed succefuly ``` CREATE OR REPLACE PROCEDURE TEST (IN indbnm VARCHAR(30), IN intblnm VARCHAR(30)) LANGUAGE SQL BEGIN DECLARE statmnt2 VARCHAR(1000); DECLARE VAR_COD_TIPO_ARQU CHAR(1); DECLARE stmt1 STATEMENT; SET statmnt2 = 'SELECT COD_TIPO_ARQU FROM '||indbnm||'.'||intblnm||' FETCH FIRST 1 ROWS ONLY'; PREPARE stmt1 FROM statmnt2; EXECUTE stmt1 into VAR_COD_TIPO_ARQU ; END@ ```
Thanks @Marcos `EXECUTE... INTO ...` worked. Additionally, creating the stored proc with `OUT` parameter will let you access the value set by `EXECUTE... INTO ...` outside the stored proc. ``` CREATE OR REPLACE PROCEDURE ISH.SAMPLEPROC (OUT o_result VARCHAR(5)) specific proc_user_data_retrieval dynamic result sets 1 reads sql data language sql BEGIN DECLARE stmt varchar(5000) default null; DECLARE VAR_X VARCHAR(5); DECLARE stmt_final STATEMENT; SET stmt = 'SET (?) = ('||'SELECT JOB_ROLE FROM ISH.USER_DATA LIMIT 1'||')'; PREPARE stmt_final FROM stmt; EXECUTE stmt_final INTO VAR_X; SET o_result = VAR_X; END ``` Then call the stored proc using `CALL ISH.SAMPLEPROC(?);`
15,735,469
I'm tring to execute query in a db2 procedure: ``` CREATE OR REPLACE PROCEDURE TEST (IN indbnm VARCHAR(30), IN intblnm VARCHAR(30)) LANGUAGE SQL BEGIN DECLARE statmnt2 VARCHAR(1000); DECLARE VAR_COD_TIPO_ARQU CHAR(1); DECLARE stmt1 STATEMENT; SET statmnt2 = 'SELECT COD_TIPO_ARQU FROM '||indbnm||'.'||intblnm||' FETCH FIRST 1 ROWS ONLY'; PREPARE stmt1 FROM statmnt2; SET VAR_COD_TIPO_ARQU = EXECUTE (stmt1); END@ ``` This gives following error: ``` DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0206N "STMT1" is not valid in the context where it is used. LINE NUMBER=33. SQLSTATE=42703 ``` What's the right way to set `VAR_COD_TIPO_ARQU` with `COD_TIPO_ARQU` value dynamically? ThankYou.
2013/03/31
[ "https://Stackoverflow.com/questions/15735469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2230284/" ]
Hi is it correct solutuion: ``` SET statmnt = 'SELECT COD_TIPO_ARQU FROM '||indbnm||'.'||intblnm||' FETCH FIRST 1 ROWS ONLY'; PREPARE stmt1 FROM statmnt; BEGIN DECLARE c1 CURSOR FOR stmt1; OPEN c1; FETCH c1 into sttmresult; CLOSE c1; END; ``` TY.
Thanks @Marcos `EXECUTE... INTO ...` worked. Additionally, creating the stored proc with `OUT` parameter will let you access the value set by `EXECUTE... INTO ...` outside the stored proc. ``` CREATE OR REPLACE PROCEDURE ISH.SAMPLEPROC (OUT o_result VARCHAR(5)) specific proc_user_data_retrieval dynamic result sets 1 reads sql data language sql BEGIN DECLARE stmt varchar(5000) default null; DECLARE VAR_X VARCHAR(5); DECLARE stmt_final STATEMENT; SET stmt = 'SET (?) = ('||'SELECT JOB_ROLE FROM ISH.USER_DATA LIMIT 1'||')'; PREPARE stmt_final FROM stmt; EXECUTE stmt_final INTO VAR_X; SET o_result = VAR_X; END ``` Then call the stored proc using `CALL ISH.SAMPLEPROC(?);`
15,735,469
I'm tring to execute query in a db2 procedure: ``` CREATE OR REPLACE PROCEDURE TEST (IN indbnm VARCHAR(30), IN intblnm VARCHAR(30)) LANGUAGE SQL BEGIN DECLARE statmnt2 VARCHAR(1000); DECLARE VAR_COD_TIPO_ARQU CHAR(1); DECLARE stmt1 STATEMENT; SET statmnt2 = 'SELECT COD_TIPO_ARQU FROM '||indbnm||'.'||intblnm||' FETCH FIRST 1 ROWS ONLY'; PREPARE stmt1 FROM statmnt2; SET VAR_COD_TIPO_ARQU = EXECUTE (stmt1); END@ ``` This gives following error: ``` DB21034E The command was processed as an SQL statement because it was not a valid Command Line Processor command. During SQL processing it returned: SQL0206N "STMT1" is not valid in the context where it is used. LINE NUMBER=33. SQLSTATE=42703 ``` What's the right way to set `VAR_COD_TIPO_ARQU` with `COD_TIPO_ARQU` value dynamically? ThankYou.
2013/03/31
[ "https://Stackoverflow.com/questions/15735469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2230284/" ]
I know it's been a while since this question was asked, but I found that none of the given answers worked. @AngocA's solution was close but, as @Mani\_Swetha pointed out, the `EXECUTE` statement fails due to the `SELECT` bit. After searching and combining solutions around the web, this is what finally worked for me: ``` CREATE OR REPLACE PROCEDURE TEST (IN indbnm VARCHAR(30), IN intblnm VARCHAR(30)) LANGUAGE SQL BEGIN DECLARE statmnt2 VARCHAR(1000); DECLARE VAR_COD_TIPO_ARQU CHAR(1); DECLARE stmt1 STATEMENT; SET statmnt2 = 'set ? = (SELECT COD_TIPO_ARQU FROM '||indbnm||'.'||intblnm||' FETCH FIRST 1 ROWS ONLY)'; PREPARE stmt1 FROM statmnt2; EXECUTE stmt1 into VAR_COD_TIPO_ARQU ; END@ ``` Note that now the executed command is a `set` statement with a `SELECT` inside, rather than a pure `SELECT` statement. This is what makes the trick.
Thanks @Marcos `EXECUTE... INTO ...` worked. Additionally, creating the stored proc with `OUT` parameter will let you access the value set by `EXECUTE... INTO ...` outside the stored proc. ``` CREATE OR REPLACE PROCEDURE ISH.SAMPLEPROC (OUT o_result VARCHAR(5)) specific proc_user_data_retrieval dynamic result sets 1 reads sql data language sql BEGIN DECLARE stmt varchar(5000) default null; DECLARE VAR_X VARCHAR(5); DECLARE stmt_final STATEMENT; SET stmt = 'SET (?) = ('||'SELECT JOB_ROLE FROM ISH.USER_DATA LIMIT 1'||')'; PREPARE stmt_final FROM stmt; EXECUTE stmt_final INTO VAR_X; SET o_result = VAR_X; END ``` Then call the stored proc using `CALL ISH.SAMPLEPROC(?);`
21,005,205
We've got a multi-project app that we're moving to gradle. The build results in Java compilation errors like: ``` AFragment.java:159: constant expression required case R.id.aBtn: ``` We've confirmed that the constants reported in errors are in the generated `R.java`. One clue is that errors are only for switch values. For example there's no error using `findViewById(R.id.aBtn)`. also note that the constants are from the main project, not one of the library projects. for anyone looking to get rid of the errors laalto's suggestion will solve it. the link he provided, together with the fact that eclipse doesn't show the errors that occur when building with gradle gave me another clue. the R.java generated by eclipse defines the main project constants as 'final' but the gradle generated values are not 'final'. the real solution must be in correcting the gradle build files. SOLUTION (2014-01-09) our build.gradle for the app was applying the android-library plugin instead of the android plugin. it was this: apply plugin: 'android-library' changing it to this: apply plugin: 'android' fixed the problem.
2014/01/08
[ "https://Stackoverflow.com/questions/21005205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3174822/" ]
Library project resource identifiers are not constant `static final int`s, just `static int`s. Convert the code that needs to switch on library resource ids to `if`-`else` structures. Further reading: <http://tools.android.com/tips/non-constant-fields>
This happens if you use Resources from a **Library project**. In that case, the the ids in the `R` class are not really constants and thus cannot be used in a switch statement.
187,397
I've worked up a solution to this exercise from [Think Python](http://greenteapress.com/thinkpython2/html/thinkpython2013.html): > > Exercise 3 Two words form a “metathesis pair” if you can transform > one into the other by swapping two letters; for example, “converse” > and “conserve”. Write a program that finds all of the metathesis pairs > in the dictionary. Hint: don’t test all pairs of words, and don’t test > all possible swaps. Solution: > <http://thinkpython2.com/code/metathesis.py>. Credit: This exercise is > inspired by an example at <http://puzzlers.org>. > > > I'm just looking for general feedback, as my solution differs from the given solution, thanks! ``` def make_words_list(input_filename): """ Takes a text file, returns a list of words in that file. input_filename: text file returns: list """ words_list = [] with open(input_filename) as input_file: for line in input_file: word = line.split()[0] words_list.append(word) return words_list def sorted_word(word): """ Returns a string with characters rearranged in ASCII order. word: string returns: string """ return ''.join(sorted(word)) def anagram_sets(wordlist): """ Returns a dictionary with letter groups as strings, and anagrams of those strings as keys. wordlist: list returns: dict """ anagram_dict = {} for word in wordlist: word_family = sorted_word(word) if word_family in anagram_dict: anagram_dict[word_family].append(word) else: anagram_dict[word_family] = [word] # Pare down dict to keys with more than one word (ie words with an anagram) for word_family, anagram_list in list(anagram_dict.items()): if len(anagram_list) < 2: del anagram_dict[word_family] return anagram_dict def is_metathesis_pair(word1, word2): assert word1 != word2, "Words are the same word." assert len(word1) == len(word2), "Words are not equal in length." assert sorted_word(word1) == sorted_word(word2), ( f"Words '{word1}', '{word2}' are not anagrams of eachother.") letter_pairs = zip(word1, word2) count = 0 for letter_1, letter_2 in letter_pairs: if count > 2: return False if letter_1 != letter_2: count += 1 if count == 2: return True elif count > 2: return False else: return "Error." def find_metathesis_pairs(anagram_dict): """ Takes a dict mapping word families to words, and looks in each to find words that are metathesis pairs (ie words that are the same, except for a single pair of swapped letters. Returns a list of tuples of these pairs. anagram_dict: dict returns: list """ metathesis_pairs_list = [] for word_family in anagram_dict.keys(): # Prevent iterating over a pair more than once by iterating over a word # and subsequent words in list. for word1_index in range(len(anagram_dict[word_family])): word1 = anagram_dict[word_family][word1_index] for word2 in anagram_dict[word_family][word1_index+1:]: if word1 != word2: if is_metathesis_pair(word1, word2): metathesis_pairs_list.append((word1, word2)) return metathesis_pairs_list def metathesis_pairs(input_filename): """ Return list of metathesis pairs from a file (ie all pairs of words that differ by swapping two letters). input_filename: text file returns: list of tuples """ wordlist = make_words_list(input_filename) anagram_dict = anagram_sets(wordlist) return find_metathesis_pairs(anagram_dict) ```
2018/02/12
[ "https://codereview.stackexchange.com/questions/187397", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/138213/" ]
1. The code is well-documented and clear. 2. The docstring for `make_words_list` says ```none returns a list of words in that file. ``` but if you look carefully at the behaviour, what it does it return a list containing the *first* word on each line of the file: ``` word = line.split()[0] ``` 3. When you have a function like `make_words_list` that returns a list of results, it's often more convenient to *generate* the results one at a time using the `yield` statement. This means that if the results are also being consumed one at a time, then the whole list does not have to be kept in memory. So `make_words_list` could become: ``` def read_words(filename): "Generate the first word on each line of the named file." with open(filename) as file: for line in file: yield line.split()[0] ``` If the caller really does need a list, it is easy enough to call [`list`](https://docs.python.org/3/library/functions.html#list): ``` list(read_words(filename)) ``` 4. `anagram_sets` could be simplified using [`collections.defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict), like this: ``` anagram_dict = defaultdict(list) for word in wordlist: anagram_dict[sorted_word(word)].append(word) ``` 5. But actually it might be even better to use sets here rather than lists — this would ensure that no word could get added twice, and so you could avoid the test `word1 != word2` later on. ``` anagram_dict = defaultdict(set) for word in wordlist: anagram_dict[sorted_word(word)].add(word) ``` 6. In `anagram_dict` you go to some trouble to remove words with no anagrams. But this is unnecessary — if you look at the logic in `find_metathesis_pairs` you'll see that nothing will go wrong if `len(anagram_dict[word_family])` is 1. So it would be simpler to leave the dictionary alone. 7. `is_metathesis_pair` is missing a docstring. 8. `is_metathesis_pair` returns the string `"Error"` to indicate an error. It is risky to return an exceptional value like this to indicate an error, because the caller may forget to check for the exceptional value. And in fact this is what happened: ``` if is_metathesis_pair(word1, word2): ``` So in the error case, `is_metathesis_pair` returns the string `"Error"`, but this treated the same as `True` by the `if` statement, and so the error gets ignored. It is better to raise an exception in exceptional cases. 9. `is_metathesis_pair` maintains a running count of mismatched letters in order to provide an early exit from the loop. But in practice we expect words to be short: in my computer's dictionary the average word length is just 10 letters. So we are not saving very much time by exiting early from the loop, and we are paying the cost of checking the count. So I think it would be better not to worry about the early exit, and just count all the mismatches: ``` count = sum(l1 != l1 for l1, l2 in zip(word1, word2)) ``` 10. In `find_metathesis_pairs` there is a loop over the keys of a dictionary: ``` for word_family in anagram_dict.keys(): ``` and then in the body of the loop the expression `anagram_dict[word_family]` occurs several times. When you have a loop like this it is better to loop over the keys and values simultaneous: ``` for word_family, anagrams in anagram_dict.items(): ``` But if you do this, you'll see that you don't actually need `word_family` any more: it was only ever needed to look up the list of anagrams. So you might as well only loop over the values: ``` for anagrams in anagram_dict.values(): ``` 11. There is a loop over all pairs of distinct words in each family: ``` for word_family in anagram_dict.keys(): for word1_index in range(len(anagram_dict[word_family])): word1 = anagram_dict[word_family][word1_index] for word2 in anagram_dict[word_family][word1_index+1:]: ``` When you have a loop over distinct pairs, you can use [`itertools.combinations`](https://docs.python.org/3/library/itertools.html#itertools.combinations) to combine the two loops into one: ``` for anagrams in anagram_dict.values(): for word1, word2 in combinations(anagrams, 2) ``` 12. The changes I've suggested above have reduced the length of the code considerably. It might now make sense to inline some of the functions at their point of use. This results in the following: ``` from collections import defaultdict from itertools import combinations def find_metathesis_pairs(words): "Generate the metathesis pairs in an iterable of words." families = defaultdict(set) for word in words: families[''.join(sorted(word))].add(word) for family in families.values(): for pair in combinations(family, 2): if sum(l1 != l2 for l1, l2 in zip(*pair)) == 2: yield pair ``` Inlining functions doesn't always make sense, and you might legitimately prefer the version of the code with multiple small functions, but in this case I think joining them together makes the logic easier to follow.
You have a very well written piece of code. It is well documented, split into proper functions; can be followed through without needing any external help. However, a few points to note: ``` for word_family, anagram_list in list(anagram_dict.items()): if len(anagram_list) < 2: del anagram_dict[word_family] ``` Here, you are calling `list` on an iterator. Python 3's [`dict.items()`](https://devdocs.io/python~3.6/library/stdtypes#dict.items) returns an iterator object, which can be used as is for your `for` loop operation. If you wrap it inside a `list`, it takes up the memory to store the whole list of items. As you don't need to actually have the whole list at any point, just go over them one-by-one. ``` for word_family, anagram_list in anagram_dict.items(): if len(anagram_list) < 2: del anagram_dict[word_family] ``` --- Seeing the following: ``` if word1 != word2: ``` I do not think that the dictionary file might have duplicates, but if you think that they might, then instead of list, I'd suggest using [`set()`](https://devdocs.io/python~3.6/library/stdtypes#set) which won't allow for duplicates. ``` for word_family, anagram_list in anagram_dict.items(): if len(anagram_list) < 2: del anagram_dict[word_family] else: anagram_dict[word_family] = set(anagram_list) ``` --- ``` for word_family in anagram_dict.keys(): # Prevent iterating over a pair more than once by iterating over a word # and subsequent words in list. for word1_index in range(len(anagram_dict[word_family])): word1 = anagram_dict[word_family][word1_index] ``` I notice that you want to iterate over `index` and `word` of the `anagram_dict` values. I think you'll love the [`enumerate`](https://devdocs.io/python~3.6/library/functions#enumerate) function (no need to compute length of list/set etc.) ``` for words_list in anagram_dict.values(): # Prevent iterating over a pair more than once by iterating over a word # and subsequent words in list. for index, word1 in enumerate(words_list): for word2 in words_list[index+1:]: if word1 != word2: if is_metathesis_pair(word1, word2): metathesis_pairs_list.append((word1, word2)) ``` In the `is_metathesis_pair` check, the whole of following: ``` if count == 2: return True elif count > 2: return False else: return "Error." ``` can be reduced to: ``` return count == 2 ``` When you `return "Error"`, it is a truthy value in Python, and your `metathesis_pairs_list` will get those words stored in it. You do not want that. --- ``` for letter_1, letter_2 in letter_pairs: if count > 2: return False if letter_1 != letter_2: count += 1 ``` Changing the order of those `if` statements will save you one iteration when your counter goes from \$ 2 \$ to \$ 3 \$. ``` for letter_1, letter_2 in letter_pairs: if letter_1 != letter_2: count += 1 if count > 2: return False ```
123,568
Can I move a SQL 2000 32-bit database to a SQL 2005 64-bit database server
2010/03/17
[ "https://serverfault.com/questions/123568", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
Yes you can. There are two easy ways to do this: 1. Create a backup of the database and restore it on the new server. 2. Detach the database and then move the .mdf and .ldf to the new server and attach them to to it. I prefer to use the backup method since as the name implies, you're working with a backup of the data so it's relatively low risk.
32 bit to 64bit should not matter. The procedure is actually fairly straight forward. Here is a tutorial that explains it step by step <http://www.aspfree.com/c/a/MS-SQL-Server/Moving-Data-from-SQL-Server-2000-to-SQL-Server-2005/> Take care and good luck HTH
123,568
Can I move a SQL 2000 32-bit database to a SQL 2005 64-bit database server
2010/03/17
[ "https://serverfault.com/questions/123568", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
Yes you can. There are two easy ways to do this: 1. Create a backup of the database and restore it on the new server. 2. Detach the database and then move the .mdf and .ldf to the new server and attach them to to it. I prefer to use the backup method since as the name implies, you're working with a backup of the data so it's relatively low risk.
You should also test that your Applications that use those Databases work once you move it over (Backup method is best way to go). If any of the applications fail you may need to look into using compatibility mode which you can set in the Database Properties, I would suggest making a list of all applications and then doing test first to be sure that nothing plays up.
123,568
Can I move a SQL 2000 32-bit database to a SQL 2005 64-bit database server
2010/03/17
[ "https://serverfault.com/questions/123568", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
You should also test that your Applications that use those Databases work once you move it over (Backup method is best way to go). If any of the applications fail you may need to look into using compatibility mode which you can set in the Database Properties, I would suggest making a list of all applications and then doing test first to be sure that nothing plays up.
32 bit to 64bit should not matter. The procedure is actually fairly straight forward. Here is a tutorial that explains it step by step <http://www.aspfree.com/c/a/MS-SQL-Server/Moving-Data-from-SQL-Server-2000-to-SQL-Server-2005/> Take care and good luck HTH
35,200,653
I have 2 tables in a database: `images_1` and `wp_posts`, in them one of the entries is image file name, while the other has similar name for the post title, it's just that in wordpress database that entry has image file type attached to it. Since I'm making import from `table_1`, I need to check if that post already exists in `wp_post` table before I import it. So my `table_1` has structure kinda like this: **table\_1** ``` filename_uploaded ----------------- asd654as8_dasd3 a32asd586as_d6584 asdad_asdlf ``` While my `wp_post` table has, for `post_type = attachment` **wp\_post** ``` post_title ---------- asd654as8_dasd3.jpg a32asd586as_d6584.jpg asdad_asdlf.png ``` So I tried with: ``` $img_query = "SELECT * FROM table_1 WHERE NOT EXISTS (SELECT * FROM wp_posts WHERE wp_posts.post_title LIKE table_1.filename_uploaded AND wp_posts.post_type = 'attachment')"; $img_query_query = $wpdb->get_results($img_query, ARRAY_A); ``` Which doesn't work. The thing is that I cannot check if they are equal, because they are not. They are similar, but the `post_title` has file type extension. I searched about using [regular expressions in mysql queries](http://dev.mysql.com/doc/refman/5.7/en/regexp.html), but I'm not sure how to do it. Any help will do. EDIT: I just notice I get > > [Illegal mix of collations (utf8\_general\_ci,IMPLICIT) and (utf8\_swedish\_ci,IMPLICIT) for operation 'like'] > > > My `table_1` is in swedish\_ci and `wp_post` is in general\_ci. I tried adding `COLLATE utf8_swedish_ci` at the end, but no luck. Following Gordon Linoff's advice I tried ``` "SELECT t_img.* FROM img_images t_img WHERE NOT EXISTS (SELECT * FROM wp_posts p WHERE p.post_title LIKE CONCAT(t_img.filename_uploaded, '.%') AND p.post_type = 'attachment') COLLATE utf8_swedish_ci"; ``` But no luck.
2016/02/04
[ "https://Stackoverflow.com/questions/35200653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629127/" ]
You are close but not taking the suffix into account. So: ``` SELECT t1.* FROM table_1 t1 WHERE NOT EXISTS (SELECT * FROM wp_posts p WHERE p.post_title LIKE CONCAT(t1.filename_uploaded, '.%') AND p.post_type = 'attachment' ); ```
If it's only the extension that's being added, try with: ``` ... WHERE wp_posts.post_title LIKE table_1.filename_uploaded + '%' ... ``` SQL Like operator: <http://www.w3schools.com/sql/sql_like.asp>
35,200,653
I have 2 tables in a database: `images_1` and `wp_posts`, in them one of the entries is image file name, while the other has similar name for the post title, it's just that in wordpress database that entry has image file type attached to it. Since I'm making import from `table_1`, I need to check if that post already exists in `wp_post` table before I import it. So my `table_1` has structure kinda like this: **table\_1** ``` filename_uploaded ----------------- asd654as8_dasd3 a32asd586as_d6584 asdad_asdlf ``` While my `wp_post` table has, for `post_type = attachment` **wp\_post** ``` post_title ---------- asd654as8_dasd3.jpg a32asd586as_d6584.jpg asdad_asdlf.png ``` So I tried with: ``` $img_query = "SELECT * FROM table_1 WHERE NOT EXISTS (SELECT * FROM wp_posts WHERE wp_posts.post_title LIKE table_1.filename_uploaded AND wp_posts.post_type = 'attachment')"; $img_query_query = $wpdb->get_results($img_query, ARRAY_A); ``` Which doesn't work. The thing is that I cannot check if they are equal, because they are not. They are similar, but the `post_title` has file type extension. I searched about using [regular expressions in mysql queries](http://dev.mysql.com/doc/refman/5.7/en/regexp.html), but I'm not sure how to do it. Any help will do. EDIT: I just notice I get > > [Illegal mix of collations (utf8\_general\_ci,IMPLICIT) and (utf8\_swedish\_ci,IMPLICIT) for operation 'like'] > > > My `table_1` is in swedish\_ci and `wp_post` is in general\_ci. I tried adding `COLLATE utf8_swedish_ci` at the end, but no luck. Following Gordon Linoff's advice I tried ``` "SELECT t_img.* FROM img_images t_img WHERE NOT EXISTS (SELECT * FROM wp_posts p WHERE p.post_title LIKE CONCAT(t_img.filename_uploaded, '.%') AND p.post_type = 'attachment') COLLATE utf8_swedish_ci"; ``` But no luck.
2016/02/04
[ "https://Stackoverflow.com/questions/35200653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629127/" ]
You are close but not taking the suffix into account. So: ``` SELECT t1.* FROM table_1 t1 WHERE NOT EXISTS (SELECT * FROM wp_posts p WHERE p.post_title LIKE CONCAT(t1.filename_uploaded, '.%') AND p.post_type = 'attachment' ); ```
There are a multitude of string functions in MYSQL [See the manual](https://dev.mysql.com/doc/refman/5.6/en/string-functions.html) Using those you could do this ``` $img_query = "SELECT * FROM table_1 t1 WHERE NOT EXISTS (SELECT * FROM wp_posts WHERE wp_posts.post_title = SUBSTRING_INDEX(t1.filename_upload, '.', 1) AND wp_posts.post_type = 'attachment')"; ``` This will also cope with any file extensions so if you have `.jpg` and `.png` and `.gif` etc image formats uploaded you are covered.
35,200,653
I have 2 tables in a database: `images_1` and `wp_posts`, in them one of the entries is image file name, while the other has similar name for the post title, it's just that in wordpress database that entry has image file type attached to it. Since I'm making import from `table_1`, I need to check if that post already exists in `wp_post` table before I import it. So my `table_1` has structure kinda like this: **table\_1** ``` filename_uploaded ----------------- asd654as8_dasd3 a32asd586as_d6584 asdad_asdlf ``` While my `wp_post` table has, for `post_type = attachment` **wp\_post** ``` post_title ---------- asd654as8_dasd3.jpg a32asd586as_d6584.jpg asdad_asdlf.png ``` So I tried with: ``` $img_query = "SELECT * FROM table_1 WHERE NOT EXISTS (SELECT * FROM wp_posts WHERE wp_posts.post_title LIKE table_1.filename_uploaded AND wp_posts.post_type = 'attachment')"; $img_query_query = $wpdb->get_results($img_query, ARRAY_A); ``` Which doesn't work. The thing is that I cannot check if they are equal, because they are not. They are similar, but the `post_title` has file type extension. I searched about using [regular expressions in mysql queries](http://dev.mysql.com/doc/refman/5.7/en/regexp.html), but I'm not sure how to do it. Any help will do. EDIT: I just notice I get > > [Illegal mix of collations (utf8\_general\_ci,IMPLICIT) and (utf8\_swedish\_ci,IMPLICIT) for operation 'like'] > > > My `table_1` is in swedish\_ci and `wp_post` is in general\_ci. I tried adding `COLLATE utf8_swedish_ci` at the end, but no luck. Following Gordon Linoff's advice I tried ``` "SELECT t_img.* FROM img_images t_img WHERE NOT EXISTS (SELECT * FROM wp_posts p WHERE p.post_title LIKE CONCAT(t_img.filename_uploaded, '.%') AND p.post_type = 'attachment') COLLATE utf8_swedish_ci"; ``` But no luck.
2016/02/04
[ "https://Stackoverflow.com/questions/35200653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629127/" ]
You are close but not taking the suffix into account. So: ``` SELECT t1.* FROM table_1 t1 WHERE NOT EXISTS (SELECT * FROM wp_posts p WHERE p.post_title LIKE CONCAT(t1.filename_uploaded, '.%') AND p.post_type = 'attachment' ); ```
you need to use this query and don't use like query it's give problem when some user name like this `pratik` , `pratik12` you will execute `pratik` and like give you both records ``` select * from table_1 left join wp_post on wp_post.post_title = CONCAT(table_1.filename_uploaded,'.jpg') where wp_post.post_title = null ```
35,200,653
I have 2 tables in a database: `images_1` and `wp_posts`, in them one of the entries is image file name, while the other has similar name for the post title, it's just that in wordpress database that entry has image file type attached to it. Since I'm making import from `table_1`, I need to check if that post already exists in `wp_post` table before I import it. So my `table_1` has structure kinda like this: **table\_1** ``` filename_uploaded ----------------- asd654as8_dasd3 a32asd586as_d6584 asdad_asdlf ``` While my `wp_post` table has, for `post_type = attachment` **wp\_post** ``` post_title ---------- asd654as8_dasd3.jpg a32asd586as_d6584.jpg asdad_asdlf.png ``` So I tried with: ``` $img_query = "SELECT * FROM table_1 WHERE NOT EXISTS (SELECT * FROM wp_posts WHERE wp_posts.post_title LIKE table_1.filename_uploaded AND wp_posts.post_type = 'attachment')"; $img_query_query = $wpdb->get_results($img_query, ARRAY_A); ``` Which doesn't work. The thing is that I cannot check if they are equal, because they are not. They are similar, but the `post_title` has file type extension. I searched about using [regular expressions in mysql queries](http://dev.mysql.com/doc/refman/5.7/en/regexp.html), but I'm not sure how to do it. Any help will do. EDIT: I just notice I get > > [Illegal mix of collations (utf8\_general\_ci,IMPLICIT) and (utf8\_swedish\_ci,IMPLICIT) for operation 'like'] > > > My `table_1` is in swedish\_ci and `wp_post` is in general\_ci. I tried adding `COLLATE utf8_swedish_ci` at the end, but no luck. Following Gordon Linoff's advice I tried ``` "SELECT t_img.* FROM img_images t_img WHERE NOT EXISTS (SELECT * FROM wp_posts p WHERE p.post_title LIKE CONCAT(t_img.filename_uploaded, '.%') AND p.post_type = 'attachment') COLLATE utf8_swedish_ci"; ``` But no luck.
2016/02/04
[ "https://Stackoverflow.com/questions/35200653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629127/" ]
you need to use this query and don't use like query it's give problem when some user name like this `pratik` , `pratik12` you will execute `pratik` and like give you both records ``` select * from table_1 left join wp_post on wp_post.post_title = CONCAT(table_1.filename_uploaded,'.jpg') where wp_post.post_title = null ```
If it's only the extension that's being added, try with: ``` ... WHERE wp_posts.post_title LIKE table_1.filename_uploaded + '%' ... ``` SQL Like operator: <http://www.w3schools.com/sql/sql_like.asp>
35,200,653
I have 2 tables in a database: `images_1` and `wp_posts`, in them one of the entries is image file name, while the other has similar name for the post title, it's just that in wordpress database that entry has image file type attached to it. Since I'm making import from `table_1`, I need to check if that post already exists in `wp_post` table before I import it. So my `table_1` has structure kinda like this: **table\_1** ``` filename_uploaded ----------------- asd654as8_dasd3 a32asd586as_d6584 asdad_asdlf ``` While my `wp_post` table has, for `post_type = attachment` **wp\_post** ``` post_title ---------- asd654as8_dasd3.jpg a32asd586as_d6584.jpg asdad_asdlf.png ``` So I tried with: ``` $img_query = "SELECT * FROM table_1 WHERE NOT EXISTS (SELECT * FROM wp_posts WHERE wp_posts.post_title LIKE table_1.filename_uploaded AND wp_posts.post_type = 'attachment')"; $img_query_query = $wpdb->get_results($img_query, ARRAY_A); ``` Which doesn't work. The thing is that I cannot check if they are equal, because they are not. They are similar, but the `post_title` has file type extension. I searched about using [regular expressions in mysql queries](http://dev.mysql.com/doc/refman/5.7/en/regexp.html), but I'm not sure how to do it. Any help will do. EDIT: I just notice I get > > [Illegal mix of collations (utf8\_general\_ci,IMPLICIT) and (utf8\_swedish\_ci,IMPLICIT) for operation 'like'] > > > My `table_1` is in swedish\_ci and `wp_post` is in general\_ci. I tried adding `COLLATE utf8_swedish_ci` at the end, but no luck. Following Gordon Linoff's advice I tried ``` "SELECT t_img.* FROM img_images t_img WHERE NOT EXISTS (SELECT * FROM wp_posts p WHERE p.post_title LIKE CONCAT(t_img.filename_uploaded, '.%') AND p.post_type = 'attachment') COLLATE utf8_swedish_ci"; ``` But no luck.
2016/02/04
[ "https://Stackoverflow.com/questions/35200653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/629127/" ]
you need to use this query and don't use like query it's give problem when some user name like this `pratik` , `pratik12` you will execute `pratik` and like give you both records ``` select * from table_1 left join wp_post on wp_post.post_title = CONCAT(table_1.filename_uploaded,'.jpg') where wp_post.post_title = null ```
There are a multitude of string functions in MYSQL [See the manual](https://dev.mysql.com/doc/refman/5.6/en/string-functions.html) Using those you could do this ``` $img_query = "SELECT * FROM table_1 t1 WHERE NOT EXISTS (SELECT * FROM wp_posts WHERE wp_posts.post_title = SUBSTRING_INDEX(t1.filename_upload, '.', 1) AND wp_posts.post_type = 'attachment')"; ``` This will also cope with any file extensions so if you have `.jpg` and `.png` and `.gif` etc image formats uploaded you are covered.
62,818,307
I have json like this ``` { "NetworkAcls": [ { "Associations": [ { "NetworkAclAssociationId": "aclassoc-0360bceb2b4788870", "NetworkAclId": "acl-09811190de1965cd4", "SubnetId": "subnet-9fa0aac4" }, { "NetworkAclAssociationId": "aclassoc-08ceb0c1375cb9729", "NetworkAclId": "acl-09811190de1965cd4", "SubnetId": "subnet-db2de5bd" } ], "Entries": [ { "CidrBlock": "0.0.0.0/0", "Egress": true, "PortRange": { "From": 80, "To": 80 }, "Protocol": "6", "RuleAction": "allow", "RuleNumber": 100 }, { "CidrBlock": "0.0.0.0/0", "Egress": true, "PortRange": { "From": 443, "To": 443 }, "Protocol": "6", "RuleAction": "allow", "RuleNumber": 200 } ], "IsDefault": false, "NetworkAclId": "acl-09811190de1965cd4", "VpcId": "vpc-12345678", "OwnerId": "1234567890" }, { "Associations": [ { "NetworkAclAssociationId": "aclassoc-0531b6837ee6948dc", "NetworkAclId": "acl-0f1c265110106d23d", "SubnetId": "subnet-7f23eb19" }, { "NetworkAclAssociationId": "aclassoc-01314abbaca73ae21", "NetworkAclId": "acl-0f1c265110106d23d", "SubnetId": "subnet-44bdb71f" } ], "Entries": [ { "CidrBlock": "0.0.0.0/0", "Egress": false, "PortRange": { "From": 80, "To": 80 }, "Protocol": "6", "RuleAction": "deny", "RuleNumber": 100 }, { "CidrBlock": "0.0.0.0/0", "Egress": true, "PortRange": { "From": 443, "To": 443 }, "Protocol": "7", "RuleAction": "deny", "RuleNumber": 200 } ], "IsDefault": false, "NetworkAclId": "acl-0f1c265110106d23d", "VpcId": "vpc-12345678", "OwnerId": "1234567890" } ] } ``` and I need to produce a table like this ``` | NetworkAclId | RuleNumber | Egress | Protocol | PortRange.From | PortRange.To | CidrBlock | RuleAction | |-------------------------|---------------|-----------|-----------|-------------------|---------------|-----------|-------------| | acl-09811190de1965cd4 | 100 | true | 6 | 80 | 80 | 0.0.0.0/0 | allow | | acl-09811190de1965cd4 | 200 | true | 6 | 443 | 443 | 0.0.0.0/0 | allow | | acl-0f1c265110106d23d | 100 | false | 6 | 80 | 80 | 0.0.0.0/0 | deny | | acl-0f1c265110106d23d | 200 | true | 7 | 443 | 443 | 0.0.0.0/0 | deny | ``` The Entries.\* should only correspond to the NetworkAclId of its parent. The closest I got was this but it produces so much duplication that I have to kill it. ``` .[][] | "\(.Associations[].NetworkAclId) \(.Associations[].SubnetId) \(.Entries[] | .CidrBlock) \(.Entries[] | .Egress) \(.Entries[] | .PortRange.From) \(.Entries[] | .PortRange.To) \(.Entries[] | .Protocol) \(.Entries[] | .RuleAction) \(.Entries[] | .RuleNumber)" ``` Something I don't get about jq is why every new field I add seems to produce exponentially increasing results. For example this produces 4 results as expected: ``` .[][] | "\(.Associations[].NetworkAclId)" ``` But this produces 42 instead of the expected 4. ``` .[][] | "\(.Associations[].NetworkAclId) \(.Entries[] | .RuleNumber)" ``` How do I get jq to keep the associations of children to parent without associating every possible permutation of values in the input? Thank you
2020/07/09
[ "https://Stackoverflow.com/questions/62818307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8307455/" ]
I found a formulation to output the data you want as CSV: ```sh jq -r ' .NetworkAcls[] | range(.Associations | length) as $i | [ .Associations[$i].NetworkAclId, (.Entries[$i] | .RuleNumber, .Egress, .Protocol, .PortRange.From, .PortRange.To, .CidrBlock, .RuleAction ) ] | @csv ' file.json ``` ```none "acl-09811190de1965cd4",100,true,"6",80,80,"0.0.0.0/0","allow" "acl-09811190de1965cd4",200,true,"6",443,443,"0.0.0.0/0","allow" "acl-0f1c265110106d23d",100,false,"6",80,80,"0.0.0.0/0","deny" "acl-0f1c265110106d23d",200,true,"7",443,443,"0.0.0.0/0","deny" ``` I figure it's easier to ask how to turn CSV into a table than JSON.
You could use something like the following : ``` .NetworkAcls[] | [.Associations, .Entries] | combinations | \ "\(.[0].NetworkAclId) \(.[1].RuleNumber) \(.[1].Egress) \(.[1].Protocol) \(.[1].PortRange.From) \(.[1].PortRange.To) \(.[1].CidrBlock) \(.[1].RuleAction)" ``` [Try it here](https://jqplay.org/s/L2PUyy4J6J) This returns 8 elements as there are two NetworkAcls elements with each two associations and two entries.
67,047,148
So I couldn't find a good answer for how to get a numeric date format in client-side JavaScript specific to the users locale. E.g. if your language is 'en-US' I would like to get 'MM/DD/YYYY'.
2021/04/11
[ "https://Stackoverflow.com/questions/67047148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10049849/" ]
You could get the `SignalStrengthLTE` like below. ``` TelephonyManager mTel; mTel = (TelephonyManager)GetSystemService(TelephonyService); CellInfoLte cellInfoLte = (CellInfoLte)mTel.AllCellInfo[0]; CellSignalStrengthLte cellSignalStrengthLte = cellInfoLte.CellSignalStrength; ```
``` TelephonyManager tm = (TelephonyManager)this.GetSystemService(Context.TelephonyService); var cellInfoList = tm.AllCellInfo; foreach (var item in cellInfoList) { if (item.GetType() == typeof(CellInfoLte)) { var value = ((CellInfoLte)item).CellSignalStrength.Rsrp; } } ```
73,543,134
I added an express global error handler at the last few lines of app.js, however a thrown exception in a controller still crashed the application. identity.controller.js ``` const createError = require('http-errors'); exports.identifyUser = async (req, res) => { throw new createError(404, 'Test'); } ``` app.js ``` // Configure routes routes.register(app); app.use(function(err, req, res, next) { res.status(err.status || 500).json(response.error(err.status || 500)); }); module.exports = app; ``` When `identifyUser` was called, I expect an error response 500 from express. However, an exception was uncaught and killed my application. ``` NotFoundError: Test at exports.identifyUser (C:\Users\......\src\api\controllers\identity.controller.js:9:11) at Layer.handle [as handle_request] (C:\Users\......\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\......\node_modules\express\lib\router\route.js:144:13) at C:\Users\......\src\api\middlewares\authUser.js:30:16 at C:\Users\......\node_modules\jsonwebtoken\verify.js:223:12 at getSecret (C:\Users\......\node_modules\jsonwebtoken\verify.js:90:14) at module.exports [as verify] (C:\Users\......\node_modules\jsonwebtoken\verify.js:94:10) at C:\Users\......\src\api\middlewares\authUser.js:19:16 at Layer.handle [as handle_request] (C:\Users\......\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\......\node_modules\express\lib\router\route.js:144:13) at Route.dispatch (C:\Users\......\node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (C:\Users\......\node_modules\express\lib\router\layer.js:95:5) at C:\Users\......\node_modules\express\lib\router\index.js:284:15 at Function.process_params (C:\Users\......\node_modules\express\lib\router\index.js:346:12) at next (C:\Users\......\node_modules\express\lib\router\index.js:280:10) at Function.handle (C:\Users\......\node_modules\express\lib\router\index.js:175:3) at router (C:\Users\......\node_modules\express\lib\router\index.js:47:12) at Layer.handle [as handle_request] (C:\Users\......\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\......\node_modules\express\lib\router\index.js:328:13) at C:\Users\......\node_modules\express\lib\router\index.js:286:9 at Function.process_params (C:\Users\......\node_modules\express\lib\router\index.js:346:12) at next (C:\Users\......\node_modules\express\lib\router\index.js:280:10) Node.js v18.7.0 [nodemon] app crashed - waiting for file changes before starting... ``` I'm running Node.js v18.7.0 with Express 4.18.1 on Windows 11.
2022/08/30
[ "https://Stackoverflow.com/questions/73543134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802671/" ]
From the Express documentation: > > For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them. > > > Try replace ``` exports.identifyUser = async (req, res) => { throw new createError(404, 'Test'); } ``` by ``` exports.identifyUser = async (req, res, next) => { next(new createError(404, 'Test')); } ```
The global error handler from Express will not catch any error in your application, you still have to do it yourself with a try/catch block then call the `next` function with your error as parameter. ``` const createError = require('http-errors'); exports.identifyUser = async (req, res, next) => { try { throw new createError(404, 'Test'); } catch(err) { next(err); } } ```
73,543,134
I added an express global error handler at the last few lines of app.js, however a thrown exception in a controller still crashed the application. identity.controller.js ``` const createError = require('http-errors'); exports.identifyUser = async (req, res) => { throw new createError(404, 'Test'); } ``` app.js ``` // Configure routes routes.register(app); app.use(function(err, req, res, next) { res.status(err.status || 500).json(response.error(err.status || 500)); }); module.exports = app; ``` When `identifyUser` was called, I expect an error response 500 from express. However, an exception was uncaught and killed my application. ``` NotFoundError: Test at exports.identifyUser (C:\Users\......\src\api\controllers\identity.controller.js:9:11) at Layer.handle [as handle_request] (C:\Users\......\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\......\node_modules\express\lib\router\route.js:144:13) at C:\Users\......\src\api\middlewares\authUser.js:30:16 at C:\Users\......\node_modules\jsonwebtoken\verify.js:223:12 at getSecret (C:\Users\......\node_modules\jsonwebtoken\verify.js:90:14) at module.exports [as verify] (C:\Users\......\node_modules\jsonwebtoken\verify.js:94:10) at C:\Users\......\src\api\middlewares\authUser.js:19:16 at Layer.handle [as handle_request] (C:\Users\......\node_modules\express\lib\router\layer.js:95:5) at next (C:\Users\......\node_modules\express\lib\router\route.js:144:13) at Route.dispatch (C:\Users\......\node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (C:\Users\......\node_modules\express\lib\router\layer.js:95:5) at C:\Users\......\node_modules\express\lib\router\index.js:284:15 at Function.process_params (C:\Users\......\node_modules\express\lib\router\index.js:346:12) at next (C:\Users\......\node_modules\express\lib\router\index.js:280:10) at Function.handle (C:\Users\......\node_modules\express\lib\router\index.js:175:3) at router (C:\Users\......\node_modules\express\lib\router\index.js:47:12) at Layer.handle [as handle_request] (C:\Users\......\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\......\node_modules\express\lib\router\index.js:328:13) at C:\Users\......\node_modules\express\lib\router\index.js:286:9 at Function.process_params (C:\Users\......\node_modules\express\lib\router\index.js:346:12) at next (C:\Users\......\node_modules\express\lib\router\index.js:280:10) Node.js v18.7.0 [nodemon] app crashed - waiting for file changes before starting... ``` I'm running Node.js v18.7.0 with Express 4.18.1 on Windows 11.
2022/08/30
[ "https://Stackoverflow.com/questions/73543134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802671/" ]
From the Express documentation: > > For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them. > > > Try replace ``` exports.identifyUser = async (req, res) => { throw new createError(404, 'Test'); } ``` by ``` exports.identifyUser = async (req, res, next) => { next(new createError(404, 'Test')); } ```
I don't think you need http-errors as long as you're using express, you can just throw new Error. Try This: ``` exports.identifyUser = async (request, response, next) => { try { throw new Error (404, 'Test')); } catch { next (Error); } } ```
27,553,047
I'm trying to send an email in a separate thread (for budget reason I don't want resque etc at the moment) . The email is sent when I call the mail function without a thread , but when I wrap it in a thread there is no email sent . ``` #Thread.new do puts "hello1" mail(to: "myemail@etc.etc", subject: "blah blah",body: some_var.text) puts "hello2" # end ``` So this piece of code works , but when I uncomment it the email isn't sent (I do however see "hello1 hello2" printed and I can step into the mail function , so the thread is calling the function and it finishes , but alas no mail is being sent). I'm on Rails 4.16 , development mode (Webrick running from Rubymine) .
2014/12/18
[ "https://Stackoverflow.com/questions/27553047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1032663/" ]
You could do multiple `foreach` to loop though every nested array that you want to loop though. ``` foreach ($array as $a) { foreach ($a["B"] as $c) { foreach ($c as $d) { // Do something with $d } } } ``` This would be `$array[*]["B"][*][*]` **Edit:** You could combine my suggestion with a `while` loop. ``` $innerArray = $array; while (true) { foreach ($array as $key => $value) { if ($key == "D") { // Do something with this value } else if (is_array($value)) { $innerArray = $value; } else { break; } } } ```
Thanks to @Sepehr-Farshid it just crossed my mind that I can use recursive function (Something that I haven't use for quiet a while. So here a example. ``` $newarray = array(); $tempArray = $oldarray; $levels[] = 1; $keys[] = 2; $levels[] = 4; $keys[] = "ItemPrice"; $lastLevel =4; recurArray($tempArray, 0); function recurArray($array, $level) { foreach($array as $key => $value) { if(array_search($level, $GLOBALS["levels"]) { $tempKey = array_search($level, $GLOBALS["levels"]; if($key == $GLOBALS["keys"][$tempKey] { if($level == $GLOBALS["lastLevel"]) $GLOBALS["newarray"] = $value; else recurArray($value, $level + 1); } else { return; } } else { recurArray($value, $level + 1); } } } ``` this might not be the optimum way, but it will work and can be refined. :D