_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 21
37k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d17735
|
val
|
getWcmMode() is a final method in WCMUsePojo, mockito does not support mocking final methods by default.
you will have to enable it by creating a file named org.mockito.plugins.MockMaker in classpath (put it in the test resources/mockito-extensions folder) and put the following single line
mock-maker-inline
then you can use when to specify function return values as usual-
@Test
public void testSomeComponetnInNOTEDITMode() {
//setup wcmmode
SightlyWCMMode fakeDisabledMode = mock(SightlyWCMMode.class);
when(fakeDisabledMode.isEdit()).thenReturn(false);
//ComponentUseClass extends WCMUsePojo
ComponentUseClass fakeComponent = mock(ComponentUseClass.class);
when(fakeComponent.getWcmMode()).thenReturn(fakeDisabledMode);
assertFalse(fakeComponent.getWcmMode().isEdit());
//do some more not Edit mode testing on fakeComponent.
}
|
unknown
| |
d17737
|
val
|
A few things wrong here. The definitive SPF checker is Scott Kitterman's. It finds this error:
PermError SPF Permanent Error: Unknown mechanism found: postbox.pidatacenters.com
It's not clear why this is presented as this particular error because the syntax itself is valid, but you have a recursive definition - your SPF includes postbox.pidatacenters.com, but the SPF for that domain includes itself, which makes no sense. It also contains the google SPF, so you don't need to include that again.
I suggest you set your SPF records to these. For pidatacenters.com:
v=spf1 ip4:192.186.236.104 mx include:bmsend.com include:postbox.pidatacenters.com ~all
you don't need the a clause in there because it resolves to the same IP as you already listed. It's polite to put ip clauses first as they are fastest to resolve for receivers, as they do not require DNS lookups.
For postbox.pidatacenters.com:
v=spf1 include:_spf.google.com ~all
A: The reason why your getting the syntax error with that test is because any valid syntax checker authenticates the entire SPF Statement. Which means it has to test the SPF records of every included statement.
When it checks the include for "postbox.pidatacenters.com" in the SPF syntax for pidatacenters.com, it will see this.
v=spf1 include:_spf.google.com postbox.pidatacenters.com ~all
Which is invalid.
Anyway, you should follow Synchro's Advice and change the records to what he stated.
Also testing with the site Synchro recommended is fine, but it relies on a lot of expert knowledge you might not have. You might think you're emailing one way, but you're really not.
It's better to get a real live example using a reflector, just send an email to each of these and you'll get results back telling you if the SPF is correct, I always use multiple reflectors, to ensure things are accurate.
[email protected]
[email protected]
|
unknown
| |
d17739
|
val
|
This should work
Private Sub txtbarcode_KeyPress(KeyAscii As Integer)
If KeyAscii = 32 Then
'replace space with underscore
KeyAscii = 95
End If
End Sub
|
unknown
| |
d17741
|
val
|
In fact, it was quite easy: if you put the absolute path to an executable file in the browser option, it takes it smoothly.
So options should be something like :
{ port: 9000,
server: {
baseDir: [...
],
routes: {
'/bower_components': 'bower_components',
'/node_modules': 'node_modules',
'/temp': 'temp'
}
},
logLevel: 'info',
notify: true,
browser: 'C:\\Program Files (x86)\\Firefox Developer Edition\\firefox.exe',
reloadDelay: 0 //1000
}
|
unknown
| |
d17743
|
val
|
Based on discussions at the Apple dev forums (https://devforums.apple.com/message/749949) it looks like this is a bug affecting a lot of people. Probably due to a change in Apple's validations servers.
I was able to work around it by changing the build architecture in Build Settings from Standard(armv7,armv7s) to armv7 and rebuilding. This should only have the effect that the compiled code is not optimized for iPhone 5. It will still run, but may not be quite as fast as if it were compiled for armv7s. I suspect the performance difference would be negligible in most cases.
A: This helped me:
Project -> Build Settings -> remove the architecture from "valid
architectures" as well as setting the "Build Active Architecture Only"
to Yes in the Project
A: I had the same problem today. My app has no third-party libraries.
12 days ago I submitted a build from Xcode 4.5.1 that was subsequently reviewed and released to the App Store. Today I tried to submit a new build and suddenly received this error.
I then tried to validate the same executable (not a rebuild) from within Xcode that I had submitted 12 days ago and that had passed validation and is now available for download in the App Store, but this time it failed validation with the above error.
Performing step 4 above allowed me to submit the new build. But the executable is smaller even though I have added a small amount of code and three small png/jpegs. This makes me think that armv7s code is missing from the archive.
What is happening? Why should step 4 above 'work'? Why does an executable that previously submitted OK and was released suddenly no longer pass validation?
Note: this is not a duplicate of any previous post that I was able to find 15 hours ago. This is the first time I have seen any mention made of seeing this error when submitting to iTunes Connect rather than receiving a compiler warning. So please do not mark this as a duplicate. It is not.
A: Most of the answers here are ones that I did not find ideal, mainly because they essentially suggest that you remove armv7s support from your app. While that will make you app pass validation, that could potentially make your app run slower on the iPhone 5.
Here is the workaround I'm using (though, I must say that I wouldn't call this a solution).
Instead of using XCode Organizer, I'm uploading the binary using Application Loader.
To upload the binary using Application Loader
Open Organizer > Right Click on Archive > Reveal in Finder.
Right Click the Archive file > Show Archive Content
Go to Products > Application > YourAPP.app
Compress YourAPP.app and upload using Application Loader.
A: My problem was the fact I was using an old version of Application Loader.
The solution for me was to download the latest version of Application Loader iTunes Connect > Manage Your Applications > Download Application Loader and try again.
A: Try this:
1.Select your project in Xcode (with the blue icon)
2.Select Build Settings
3.Set the view to All/Combined
4.Set "Build Active Architecture Only" to Yes
|
unknown
| |
d17749
|
val
|
Use Bootstrap 3 which can do exactly what you wish using its css media queries.
Alternatively you can simpy write your own CSS to be responsive using media queries.
A: As mccainz mentioned, you have several options. All of those examples are under an umberalla term called "responsive design".
According to Wikipedia, "Responsive Web design (RWD) is a Web design approach aimed at crafting sites to provide an optimal viewing experience—easy reading and navigation with a minimum of resizing, panning, and scrolling—across a wide range of devices (from mobile phones to desktop computer monitors)".
Now, there are many options when it comes to responsive design. Either use ready-made libraries or create it yourself.
Check the links below and see when resizing the browser how the layout changes so that you get an optimal view experience.
*
*Bootstrap
*Skeleton
*Foundation
*HTML Kickstart
All of them share the same idea: Use the great and holy CSS to decouple the layout from the real code, so that people like you who want to have the same codebase and different view experience do not have to re-write the code. Beauty of the CSS lies here.
Also, if you think above libraries do not do what you want write your own responsive CSS. For that, I highly recommend to check the following two books:
*
*HTML & CSS by John ducket
*The Modern Web: Multi-Device Web Development with HTML5, CSS3, and JavaScript by Peter Gasston
UPDATE: Since you commented that you want to avoid Responsive Layouts, There are a few people who think that responsive layout does not work and then use adaptive approaches.Check this out Why responsive layout does not worth it. The author explains a few minimal optimziation points and believes that Responsive layouts are overkill in many circumstances. He offers techniques such as lazy loading (under section 4).
Other resource: Alternatives to responsive design: part 1 (mobile) discusses the issues again with responsive layout.
With adaptive approaches, it is you who decide what is a good experience on devices and you sort of do some part of optimziation with pre-coded layouts for each case, but generally there are no rule of thumbs for that. Just the books comes to my mind.
Also try liquid layouts as well.
|
unknown
| |
d17751
|
val
|
You simply (I say simply, but if can be one of the most aggravating parts of iOS development) need to make sure you are providing the developers with the private key for the certificate, the certificate, and provisioning profile for development. If your project settings are correct, you should not get the team prefix problem. Also, I would encourage the other team members to delete all their other certificates and profiles before installing yours.
The other option would be to add their Apple IDs to your account as a team member. They can have their own credentials, but still access the account through xCode.
|
unknown
| |
d17757
|
val
|
Yes. You should create conection of emr_default of the right type for the operator (you have to pick the right one from the list) .
Here is a detailed instruction on what to do. This is is "1.10.11" Airlfow documentation and if you need any other airflow resources and docs you can always go there and use "Saerch" functionality. I got to that page by choosing Airlfow 1.10.11 version and searching for "connection".
https://airflow.apache.org/docs/apache-airflow/1.10.11/howto/connection/index.html?highlight=connections
A: Try the following connection of emr_default that works for me.
Connection Id: emr_default
Connection Type: Amazon Elastic MapReduce
Login: access_key
Password: secret_key
Extra: {"region_name": "eu-west-3"}
Replace "eu-west-3" with your region
|
unknown
| |
d17759
|
val
|
The better option for large number of files transfer is to use ftp protocol. For that you need an ftp server. And, using org.apache.commons.net.ftp.FTPClient you may upload files in to the server (and also various file management).
The storeFile(String, InputStream) method of org.apache.commons.net.ftp.FTPClient can give the file upload status, i.e. if the file is uploaded successfully it will return true otherwise false.
Please refer this link for a sample program.
|
unknown
| |
d17761
|
val
|
Thanks to all that responded for the clues that helped me solve this. I looked in the console and saw the error message "No 'Access-Control-Allow-Origin' header is present on the requested resource".
What wasn't clear in my question was that the url I was trying to reach was on a different server and I was encountering this problem.
Thanks for the help.
|
unknown
| |
d17763
|
val
|
To get the current date, you need to specify which time zone you're in. So given a clock and a time zone, you'd use:
LocalDate today = clock.Now.InZone(zone).Date;
While you can use SystemClock.Instance, it's generally better to inject an IClock into your code, so you can test it easily.
Note that in Noda Time 2.0 this will be simpler, using ZonedClock, where it will just be:
LocalDate today = zonedClock.GetCurrentDate();
... but of course you'll need to create a ZonedClock by combining an IClock and a DateTimeZone. The fundamentals are still the same, it's just a bit more convenient if you're using the same zone in multiple places. For example:
// These are IClock extension methods...
ZonedClock zonedClock = SystemClock.Instance.InTzdbSystemDefaultZone();
// Or...
ZonedClock zonedClock = SystemClock.Instance.InZone(specificZone);
|
unknown
| |
d17765
|
val
|
Easy steps to create Cocoapod from existing xcode project
*
*Create a repository on your git account (Repo name, check README,
choose MIT under license).
*Copy the url of your repository.Open terminal and run following command.
git clone copied your repository url
*Now copy your Xcode project inside the cloned repository folder on
your Mac. Now run following commands
git add -u to add all files (if not added use: git add filepath/folder)
git commit -m "your custom message"
git push origin master
*Create a new release to go to your git repository or run following commands
git tag 1.0.0
git push --tags
*First, we need to make sure that you have CocoaPods installed and
ready to use in your Terminal. run the following command:
sudo gem install cocoapods --pre
Creating a Podspec
*
*All Pods have a podspec file. A podspec, as its name suggests,
defines the specifications of the Pod! Now let’s make one, run
following command on terminal
touch PodName.podspec
*After adding and modifying your .podspec file. Validate your .podspec
file by hitting following command on terminal
pod lib lint
*Once you validate it successfully without errors run following
command to register you and build cocoapod respectively
pod trunk register
pod trunk push PodName.podspec
If all goes well, you will get this on terminal
PodName (1.0.0) successfully published
February 5th, 02:32
https://cocoapods.org/pods/PodName
Tell your friends!
Yeah!!!!! congrats you have got your pod link. Use wherever you want to use it.
A: Here is some useful links . You can follow the same.
https://www.appcoda.com/cocoapods-making-guide/
https://www.raywenderlich.com/5823-how-to-create-a-cocoapod-in-swift
|
unknown
| |
d17769
|
val
|
If you use rake to run rspec tests then you can edit spec/spec.opts
http://rspec.info/rails/runners.html
A: As you can see in the docs here, the intended use is creating ~/.rspec and in it putting your options, such as --color.
To quickly create an ~/.rspec file with the --color option, just run:
echo '--color' >> ~/.rspec
A: Or simply add alias spec=spec --color --format specdoc to your ~/.bashrc file like me.
A: One can also use a spec_helper.rb file in all projects. The file should include the following:
RSpec.configure do |config|
# Use color in STDOUT
config.color = true
# Use color not only in STDOUT but also in pagers and files
config.tty = true
# Use the specified formatter
config.formatter = :documentation # :progress, :html,
# :json, CustomFormatterClass
end
Any example file must require the helper to be able to use that options.
A: In your spec_helper.rb file, include the following option:
RSpec.configure do |config|
config.color_enabled = true
end
You then must require in each *_spec.rb file that should use that option.
A: One thing to be aware of is the impact of the different ways of running RSpec.
I was trying to turn on the option with the following code in spec/spec_helper.rb -
Rspec.configure do |config|
config.tty = $stdout.tty?
end
*
*calling the 'rspec' binary directly - or as 'bundle exec rspec' and checking $stdout.tty? will return true.
*invoking the 'rake spec' task - or as 'bundle exec rake spec' - Rake will invoke rspec in a separate process, and $stdout.tty? will return false.
In the end I used the ~/.rspec option, with just --tty as its contents. Works well for me and keeps our CI server output clean.
|
unknown
| |
d17771
|
val
|
The results of expressions in a Python script are not normally printed - this is a feature of the interpreter and the notebook. In a script it would not make much sense to compute x * y and do nothing with it.
Try this instead: print(3j * 9)
|
unknown
| |
d17773
|
val
|
Create the ZIP file locally and use either commons-net FTP or SFTP to move the ZIP file across to the remote location, assuming that by "remote location" you mean some FTP server, or possibly a blade on your network.
If you are using the renameTo method on java.io.File, note that this doesn't work on some operating systems (e.g. Solaris) where the locations are on different shares. You would have to do a manual copy of the file data from one location to another. This is pretty simple using standard Java I/O.
|
unknown
| |
d17775
|
val
|
For setting up of environment variables.
1) Right-click the My Computer icon on your desktop and select Properties.
2) Click the Advanced tab.
3) Click the Environment Variables button.
4) Under System Variables, click New.
5) Enter the variable name as JAVA_HOME.
6) Enter the variable value as the installation path for the Java Development Kit.
If your Java installation directory has a space in its path name, you should use the shortened path name (e.g. C:\Progra~1\Java\jre6) in the environment variable instead.
Note for Windows users on 64-bit systems
Progra~1 = 'Program Files'
Progra~2 = 'Program Files(x86)'
7 )Click OK.
8) Click Apply Changes.
9) Close any command window which was open before you made these changes, and open a new command window. There is no way to reload environment variables from an active command prompt. If the changes do not take effect even after reopening the command window, restart Windows.
10) If you are running the Confluence EAR/WAR distribution, rather than the regular Confluence distribution, you may need to restart your application server.
Does one need to install ant if the ant libraries are already present in NetBeans?
No. You don't need to install it again.
Is there a better way to import the sphinx jars into my .java project in NetBeans than through using Cygwin?
Using Cygwin(linux environment in Windows) definately works , but unsure about any other method.
|
unknown
| |
d17777
|
val
|
for javaFX there is a library with write back support DataFX2.0
Sample Examples can be found here
If you need any further help on datafx then you can post in datafx google groups Link
|
unknown
| |
d17779
|
val
|
Google has fixed the issue: https://issuetracker.google.com/issues/112692348
I was able to run queries this morning using ordinal and offset with no issues.
|
unknown
| |
d17781
|
val
|
This is a duplicate of SLComposeViewController setInitialText not showing up in View.
This behaviour is by design; prefilling was not allowed by policy, and now it's also enforced.
About the cancel button; this is a known issue and will be fixed. See bug report: https://developers.facebook.com/bugs/962985360399542/
|
unknown
| |
d17783
|
val
|
Crap4j is one fairly good metrics that I'm aware of...
Its a Java implementation of the Change Risk Analysis and Predictions software metric which combines cyclomatic complexity and code coverage from automated tests.
A: If you are looking for some useful metrics that tell you about the quality (or lack there of) of your code, you should look into the following metrics:
*
*Cyclomatic Complexity
*
*This is a measure of how complex a method is.
*Usually 10 and lower is good, 11-25 is poor, higher is terrible.
*Nesting Depth
*
*This is a measure of how many nested scopes are in a method.
*Usually 4 and lower is good, 5-8 is poor, higher is terrible.
*Relational Cohesion
*
*This is a measure of how well related the types in a package or assembly are.
*Relational cohesion is somewhat of a relative metric, but useful none the less.
*Acceptable levels depends on the formula. Given the following:
*
*R: number of relationships in package/assembly
*N: number of types in package/assembly
*H: Cohesion of relationship between types
*Formula: H = (R+1)/N
*Given the above formula, acceptable range is 1.5 - 4.0
*Lack of Cohesion of Methods (LCOM)
*
*This is a measure of how cohesive a class is.
*Cohesion of a class is a measure of how many fields each method references.
*Good indication of whether your class meets the Principal of Single Responsibility.
*Formula: LCOM = 1 - (sum(MF)/M*F)
*
*M: number of methods in class
*F: number of instance fields in class
*MF: number of methods in class accessing a particular instance field
*sum(MF): the sum of MF over all instance fields
*A class that is totally cohesive will have an LCOM of 0.
*A class that is completely non-cohesive will have an LCOM of 1.
*The closer to 0 you approach, the more cohesive, and maintainable, your class.
These are just some of the key metrics that NDepend, a .NET metrics and dependency mapping utility, can provide for you. I recently did a lot of work with code metrics, and these 4 metrics are the core key metrics that we have found to be most useful. NDepend offers several other useful metrics, however, including Efferent & Afferent coupling and Abstractness & Instability, which combined provide a good measure of how maintainable your code will be (and whether or not your in what NDepend calls the Zone of Pain or the Zone of Uselessness.)
Even if you are not working with the .NET platform, I recommend taking a look at the NDepend metrics page. There is a lot of useful information there that you might be able to use to calculate these metrics on whatever platform you develop on.
A: Bug metrics are also important:
*
*Number of bugs coming in
*Number of bugs resolved
To detect for instance if bugs are not resolved as fast as new come in.
A: Code Coverage is just an indicator and helps pointing out lines which are not executed at all in your tests, which is quite interesting. If you reach 80% code coverage or so, it starts making sense to look at the remaining 20% of lines to identify if you are missing some use case. If you see "aha, this line gets executed if I pass an empty vector" then you can actually write a test which passes an empty vector.
As an alternative I can think of, if you have a specs document with Use Cases and Functional Requirements, you should map the unit tests to them and see how many UC are covered by FR (of course it should be 100%) and how many FR are covered by UT (again, it should be 100%).
If you don't have specs, who cares? Anything that happens will be ok :)
A: What about watching the trend of code coverage during your project?
As it is the case with many other metrics a single number does not say very much.
For example it is hard to tell wether there is a problem if "we have a Checkstyle rules compliance of 78.765432%". If yesterday's compliance was 100%, we are definitely in trouble. If it was 50% yesterday, we are probably doing a good job.
I alway get nervous when code coverage has gotten lower and lower over time. There are cases when this is okay, so you cannot turn off your head when looking at charts and numbers.
BTW, sonar (http://sonar.codehaus.org/) is a great tool for watching trends.
A: Using code coverage on it's own is mostly pointless, it gives you only insight if you are looking for unnecessary code.
Using it together with unit-tests and aiming for 100% coverage will tell you that all the 'tested' parts (assumed it was all successfully too) work as specified in the unit-test.
Writing unit-tests from a technical design/functional design, having 100% coverage and 100% successful tests will tell you that the program is working like described in the documentation.
Now the only thing you need is good documentation, especially the functional design, a programmer should not write that unless (s)he is an expert of that specific field.
A: Scenario coverage.
I don't think you really want to have 100% code coverage. Testing say, simple getters and setters looks like a waste of time.
The code always runs in some context, so you may list as many scenarios as you can (depending on the problem complexity sometimes even all of them) and test them.
Example:
// parses a line from .ini configuration file
// e.g. in the form of name=value1,value2
List parseConfig(string setting)
{
(name, values) = split_string_to_name_and_values(setting, '=')
values_list = split_values(values, ',')
return values_list
}
Now, you have many scenarios to test. Some of them:
*
*Passing correct value
*List item
*Passing null
*Passing empty string
*Passing ill-formated parameter
*Passing string with with leading or ending comma e.g. name=value1, or name=,value2
Running just first test may give you (depending on the code) 100% code coverage. But you haven't considered all the posibilities, so that metric by itself doesn't tell you much.
A: How about (lines of code)/(number of test cases)? Not extremely meaningful (since it depends on LOC), but at least it's easy to calculate.
Another one could be (number of test cases)/(number of methods).
A: As a rule of thumb, defect injection rates proportionally trail code yield and they both typically follow a Rayleigh distribution curve.
At some point your defect detection rate will peak and then start to diminish.
This apex represents 40% of discovered defects.
Moving forward with simple regression analysis you can estimate how many defects remain in your product at any point following the peak.
This is one component of Lawrence Putnam's model.
A: I wrote a blog post about why High Test Coverage Ratio is a Good Thing Anyway.
I agree that: when a portion of code is executed by tests, it doesn’t mean that the validity of the results produced by this portion of code is verified by tests.
But still, if you are heavily using contracts to check states validity during tests execution, high test coverage will mean a lot of verification anyway.
A: The value in code coverage is it gives you some idea of what has been exercised by tests.
The phrase "code coverage" is often used to mean statement coverage, e.g., "how much of my code (in lines) has been executed", but in fact there are over a hundred varieties of "coverage". These other versions of coverage try to provide a more sophisticated view what it means to exercise code.
For example, condition coverage measures how many of the separate elements of conditional expressions have been exercised. This is different than statement coverage. MC/DC
"modified condition/decision coverage" determines whether the elements of all conditional expressions have all been demonstrated to control the outcome of the conditional, and is required by the FAA for aircraft software. Path coverage meaures how many of the possible execution paths through your code have been exercised. This is a better measure than statement coverage, in that paths essentially represent different cases in the code. Which of these measures is best to use depends on how concerned you are about the effectiveness of your tests.
Wikipedia discusses many variations of test coverage reasonably well.
http://en.wikipedia.org/wiki/Code_coverage
A: This hasn't been mentioned, but the amount of change in a given file of code or method (by looking at version control history) is interesting particularly when you're building up a test suite for poorly tested code. Focus your testing on the parts of the code you change a lot. Leave the ones you don't for later.
Watch out for a reversal of cause and effect. You might avoid changing untested code and you might tend to change tested code more.
A: SQLite is an extremely well-tested library, and you can extract all kinds of metrics from it.
As of version 3.6.14 (all statistics in the report are against that release of SQLite), the SQLite library consists of approximately 63.2 KSLOC of C code. (KSLOC means thousands of "Source Lines Of Code" or, in other words, lines of code excluding blank lines and comments.) By comparison, the project has 715 times as much test code and test scripts - 45261.5 KSLOC.
In the end, what always strikes me as the most significant is none of those possible metrics seem to be as important as the simple statement, "it meets all the requirements." (So don't lose sight of that goal in the process of achieving it.)
If you want something to judge a team's progress, then you have to lay down individual requirements. This gives you something to point to and say "this one's done, this one isn't". It's not linear (solving each requirement will require varying work), and the only way you can linearize it is if the problem has already been solved elsewhere (and thus you can quantize work per requirement).
A: I like revenue, sales numbers, profit. They are pretty good metrics of a code base.
A: Probably not only measuring the code covered (touched) by the unit tests but how good the assertions are.
One metric easy to implement is to measure the size of the Assert.AreEqual
You can create your own Assert implementation calling Assert.AreEqual and measuring the size of the object passed as second parameter.
|
unknown
| |
d17789
|
val
|
I agree with @Bickknght that the unpacking is unnecessary. Don't use unpacking when dealing with an unknown or variable number of elements.
In [57]: alist = [np.arange(10), np.arange(10,20), np.arange(20,30)]
Making a list of arrays where the we don't need the ravel.
In [58]: for arr in np.nditer(alist):
...: print(arr)
...:
(array(0), array(10), array(20))
(array(1), array(11), array(21))
(array(2), array(12), array(22))
(array(3), array(13), array(23))
(array(4), array(14), array(24))
(array(5), array(15), array(25))
(array(6), array(16), array(26))
(array(7), array(17), array(27))
(array(8), array(18), array(28))
(array(9), array(19), array(29))
Compare this with a straight forward list zip iteration:
In [59]: for arr in zip(*alist):
...: print(arr)
...:
(0, 10, 20)
(1, 11, 21)
(2, 12, 22)
(3, 13, 23)
(4, 14, 24)
(5, 15, 25)
(6, 16, 26)
(7, 17, 27)
(8, 18, 28)
(9, 19, 29)
The difference is that nditer makes 0d arrays rather than scalars. So the elements have a shape ((0,)) and dtype. Or in some cases where you want to modify the arrays (but they have to be defined as read/write. Otherwise nditer does not offer any real advantages.
In [62]: %%timeit
...: ll = []
...: for arr in np.nditer(alist):
...: ll.append(np.var(arr))
...:
539 µs ± 17.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [63]: %%timeit
...: ll = []
...: for arr in zip(*alist):
...: ll.append(np.var(arr))
...:
524 µs ± 3.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
If you can avoid the Python level loops, things will be lot faster:
In [65]: np.stack(alist,1)
Out[65]:
array([[ 0, 10, 20],
[ 1, 11, 21],
[ 2, 12, 22],
[ 3, 13, 23],
[ 4, 14, 24],
[ 5, 15, 25],
[ 6, 16, 26],
[ 7, 17, 27],
[ 8, 18, 28],
[ 9, 19, 29]])
In [66]: np.var(np.stack(alist,1),axis=1)
Out[66]:
array([66.66666667, 66.66666667, 66.66666667, 66.66666667, 66.66666667,
66.66666667, 66.66666667, 66.66666667, 66.66666667, 66.66666667])
In [67]: timeit np.var(np.stack(alist,1),axis=1)
66.7 µs ± 1.47 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
I've not attempted to test for -inf.
===
Another important difference with nditer. It iterates on all elements in a flat sense - in effect it is do the ravel:
Make a list of 2d arrays.
In [81]: alist = [np.arange(10.).reshape(2,5), np.arange(10,20.).reshape(2,5), np.arange(20,30.).reshape(2,5)]
PLain iteration operates on the first dimension - in this case the 2, so zipped elements are arrays:
In [82]: for arr in zip(*alist):
...: print(arr)
...:
(array([0., 1., 2., 3., 4.]), array([10., 11., 12., 13., 14.]), array([20., 21., 22., 23., 24.]))
(array([5., 6., 7., 8., 9.]), array([15., 16., 17., 18., 19.]), array([25., 26., 27., 28., 29.]))
nditer generates the same tuples as in the 1d array case. Some cases that's fine, but it's hard to avoid if if you don't want it.
In [83]: for arr in np.nditer(alist):
...: print(arr)
...:
(array(0.), array(10.), array(20.))
(array(1.), array(11.), array(21.))
(array(2.), array(12.), array(22.))
(array(3.), array(13.), array(23.))
(array(4.), array(14.), array(24.))
(array(5.), array(15.), array(25.))
(array(6.), array(16.), array(26.))
(array(7.), array(17.), array(27.))
(array(8.), array(18.), array(28.))
(array(9.), array(19.), array(29.))
A: The zip function is a solution here, as explained by @hpaulj. Working with 2d arrays instead of 1d simply requires to use two times this function, as the following code shows :
variances = []
for arr in zip(*cost_surfaceS):
for element in zip(*arr):
if(float("-inf") not in element):
variance = np.var(element, dtype=np.float32)
variances.append(variance)
else:
variances.append(float("-inf"))
The -inf values are handled by the if condition that avoids computing the variance of arrays containing at least one infinity value.
|
unknown
| |
d17791
|
val
|
In your code
printf ( "%d\n", a[0] );
printf ( "%d\n", a[1] );
printf ( "%d\n", a[10] );
printf ( "%d\n", a[100] );
produces undefined behaviour by accessing out-of-bound memory.
|
unknown
| |
d17793
|
val
|
You are missing the new, when creating your viewmodel.
Your code should look like this:
ko.applyBindings(new ViewModel());
Without the new the this refers to the global window object so your remove function is declared globally, that is why the $parent is not working.
Demo JsFiddle.
|
unknown
| |
d17795
|
val
|
You can use a list comprehension.
x = [[el[1]] for el in filtered]
or:
x = [[y] for x,y in filtered]
You can also use map with itemgetter. To print it, iterate over the iterable object returned by map. You can use list for instance.
from operator import itemgetter
x = map(itemgetter(1), filtered)
print(list(x))
A: You are not closer to a solution trying to pass a key to map. map only takes a function and an iterable (or multiple iterables). Key functions are for ordering-related functions (sorted, max, etc.)
But you were actually pretty close to a solution in the start:
a = map(itemgetter(0), filtered)
The first problem is that you want the second item (item 1), but you're passing 0 instead of 1 to itemgetter. That obviously won't work.
The second problem is that a is a map object—a lazily iterable. It does in fact have the information you want:
>>> a = map(itemgetter(1), filtered)
>>> for val in a: print(val, sep=' ')
3.0 70.0 3.0 50.0 5.0 21.0
… but not as a list. If you want a list, you have to call list on it:
>>> a = list(map(itemgetter(1), filtered))
>>> print(a)
[3.0, 70.0, 3.0, 50.0, 5.0, 21.0]
Finally, you wanted a list of single-element lists, not a list of elements. In other words, you want the equivalent of item[1:] or [item[1]], not just item[1]. You can do that with itemgetter, but it's a pretty ugly, because you can't use slice syntax like [1:] directly, you have to manually construct the slice object:
>>> a = list(map(itemgetter(slice(1, None)), filtered))
>>> print(a)
[[3.0], [70.0], [3.0], [50.0], [5.0], [21.0]]
You could write this a lot more nicely by using a lambda function:
>>> a = list(map(lambda item: item[1:], filtered))
>>> print(a)
[[3.0], [70.0], [3.0], [50.0], [5.0], [21.0]]
But at this point, it's worth taking a step back: map does the same thing as a generator expression, but map takes a function, while a genexpr takes an expression. We already know exactly what expression we want here; the hard part was turning it into a function:
>>> a = list(item[1:] for item in filtered)
>>> print(a)
Plus, you don't need that extra step to turn it into a list with a genexpr; just swap the parentheses with brackets and you've got a list comprehension:
>>> a = [item[1:] for item in filtered]
>>> print(a)
|
unknown
| |
d17797
|
val
|
Your counter is indeed stoppping, but you then reassign mytimeout after the if statement so the timer starts again. I'm guessing the $state.go() still runs but the counter continues in the console.
Instead, call the timer if less than 10, otherwise call the resolving function.
$scope.startTimer = function() {
$scope.counter = 0;
$scope.onTimeout = function() {
$log.info($scope.counter);
if($scope.counter < 10){
mytimeout = $timeout($scope.onTimeout, 1000)
}else{
$scope.stop();
$state.go($state.current.name, {}, {
reload: true
})
}
$scope.counter++;
}
mytimeout = $timeout($scope.onTimeout, 1000);
}
|
unknown
| |
d17809
|
val
|
When you use file methods from Context, Android saves that file into app's directory (and encrypt it, compared to File.()) method). So, you can just clear app data and that file will be removed
|
unknown
| |
d17815
|
val
|
like this
item_test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="name" />
</LinearLayout>
adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder; // use holder
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_test, parent, false);
holder = new Holder(convertView);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.name.setText("name");
return convertView;
}
public class Holder {
private TextView name;
public Holder(View view) {
name = view.findViewById(R.id.name);
}
}
|
unknown
| |
d17821
|
val
|
Found what was wrong, the correct code is :
addListener((Property.ValueChangeListener) app);
and not
addListener((Property.ValueChangeListener), app);
Damn comma !
|
unknown
| |
d17823
|
val
|
Don't bother. The compiler optimizes better than you could.
You might perhaps try
len = ((len - 1) & 0x3f) + 1;
(but when len is 0 -or 65, etc...- this might not give what you want)
If that is so important for you, benchmark!
A: I created a program
#include <stdio.h>
int main(void) {
unsigned int len;
scanf("%u", &len);
len = len > 64 ? 64 : len;
printf("%u\n", len);
}
and compiled with gcc -O3 and it generated this assembly:
cmpl $64, 4(%rsp)
movl $64, %edx
leaq .LC1(%rip), %rsi
cmovbe 4(%rsp), %edx
the leaq there loads the "%u\n" string in between - I presume it is because the timing of the instructions. The generated code seems pretty efficient. There are no jumps, just a conditional move. No branch prediction failure.
So the best way to optimize your executable is to get a good compiler.
|
unknown
| |
d17825
|
val
|
how about the following jquery code?
$('.check-diff').click(function() {
if($(this).prop('checked')){
checkDiff();
} else{
$(".row").each(function(){
$(this).css("background-color","#fff");
});
}
});
function checkDiff(){
$(".row").each(function(){
var diff = false;
var source = $(this).find(".diff").first().text();
$(this).find(".diff").each(function(){
var compare = $(this).text();
if(source != compare){
diff = true;
}
});
if(diff == true){
$(this).css("background-color","red");
}
});
}
hope i got you right and you get an idea, how to move on! :)
A: You can use 2 each loops and a class name for the rows you want to check. Only row that has a class name checkDiff will be validated and cells that has a class name diff.
JSnippet DEMO - validate difference in rows base on the cell text
JS:
$(function(){
$('.check-diff').click(function() {
if($(this).prop('checked')){
$('.row.checkDiff').each(function(i,ele){
var values = $(ele).find('.diff');
var first = values.eq(0).text();
var diff = false;
values.each(function(j,e){
if ($(e).text() !== first) diff = true;
});
if (diff) $(ele).addClass('highlight');
});
} else{
$('.row.checkDiff').removeClass('highlight');
}
});
});
HTML:
<label for="">Click to see differences</label>
<input type="checkbox" class="check-diff">
<div class="compare-diff">
<div class="row">
<div class="col-sm-3 title">Name</div>
<div class="col-sm-3">John</div>
<div class="col-sm-3">Henry</div>
<div class="col-sm-3">Kim</div>
</div>
<div class="row checkDiff">
<div class="col-sm-3 title">Status</div>
<div class="col-sm-3 diff">Single</div>
<div class="col-sm-3 diff">Married</div>
<div class="col-sm-3 diff">Single</div>
</div>
<div class="row checkDiff">
<div class="col-sm-3 title">Car</div>
<div class="col-sm-3 diff">Yes</div>
<div class="col-sm-3 diff">Yes</div>
<div class="col-sm-3 diff">Yes</div>
</div>
<div class="row checkDiff">
<div class="col-sm-3 title">Kids</div>
<div class="col-sm-3 diff">Yes</div>
<div class="col-sm-3 diff">Yes</div>
<div class="col-sm-3 diff">No</div>
</div>
<div class="row checkDiff">
<div class="col-sm-3 title">Home</div>
<div class="col-sm-3 diff">Yes</div>
<div class="col-sm-3 diff">Yes</div>
<div class="col-sm-3 diff">Yes</div>
</div>
</div>
|
unknown
| |
d17827
|
val
|
you can use 'inline-block' instead of a table:
<div style="display:inline-block;width:10%;"><!-- #INCLUDE FILE="scripts\Logo2_C.aspx" --></div>
<div style="display:inline-block;width:90%;"><img src="/images/logos/logo.png" /></div>
|
unknown
| |
d17831
|
val
|
When you write val = f()(3,4)(5,6), you want f to return a function that also returns a function; compare with the simpler multi-line call:
t1 = f()
t2 = t1(3,4)
val = t2(5,6)
The function f defines and returns also has to define and return a function that can be called with 2 arguments. So, as @jonrsharpe said, you need more nesting:
def f():
def x(a, b):
def y(c, d):
return c + d
return y
return x
Now, f() produces the function named x, and f()(3,4) produces the function named y (ignoring its arguments 3 and 4 in the process), and f()(3,4)(5,6) evaluates (ultimately) to 5 + 6.
|
unknown
| |
d17833
|
val
|
Have you included the SessionHelper module in your controller?
From your example code, I'm assuming you're using the RailsTutorial by Michael Hartl. You have to include the SessionsHelper in your ApplicationController to be able to use it in all controllers. Check out Listing 8.14 in the book:
class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
# Force signout to prevent CSRF attacks
def handle_unverified_request
sign_out
super
end
end
|
unknown
| |
d17835
|
val
|
To use emoji icons with angularjs, you could use angular-emoji-filter module: https://github.com/globaldev/angular-emoji-filter.
|
unknown
| |
d17839
|
val
|
Create a fetch request for the entity you wish to retrieve. Don't give it a predicate, set whatever sort descriptor you want.
Execute the fetch request in a managed object context and it will return an array of all the objects of that entity.
This is purposely just a descriptive answer, you can find the specifics of how to do this from the Core Data introductory documentation; you are new in Core Data and this is a good way to learn it.
Also - don't think of Core Data in terms of rows of data that you turn into objects. It's an Object-Relationship graph. It stores the objects of entities and their relationships between them. You don't turn the "rows" into objects, you get the objects back directly.
A: The response of @Abizern with code :
NSManagedObjectContext *moc = // your managed object context;
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:@"Message" inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
// You can also add a predicate or sort descriptor to your request
NSError *error;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
// Deal with error...
}
|
unknown
| |
d17841
|
val
|
Is something like this what you want?
# create the data
var1 <- list('2003' = 1:3, '2004' = c(4:3), '2005' = c(6,4,1), '2006' = 1:4 )
var2 <- list('2003' = 1:3, '2004' = c(4:5), '2005' = c(2,3,6), '2006' = 2:3 )
# A couple of nested lapply statements
lapply(setNames(seq_along(var1), names(var1)),
function(i,l1,l2) length(intersect(l1[[i]], Reduce(union,l2[1:i]))),
l1 = var1,l2=var2)
$`2003`
[1] 3
$`2004`
[1] 2
$`2005`
[1] 3
$`2006`
[1] 4
note that Reduce(union,var2)reduces the list var2 by successively combining the elements using union (see ?Reduce)
Reduce(union,var2)
[1] 1 2 3 4 5 6
EDIT elegant alternative
use the accumulate = T argument in Reduce
lapply(mapply(intersect,var1, Reduce(union, var2, accumulate=T)),length)
Because --
Reduce(union, var2, accumulate = T)
## [[1]]
## [1] 1 2 3
##
## [[2]]
## [1] 1 2 3 4 5
##
## [[3]]
## [1] 1 2 3 4 5 6
##
## [[4]]
## [1] 1 2 3 4 5 6
|
unknown
| |
d17843
|
val
|
Check your scipy version:
import scipy
print(scipy.__version__)
find_peaks is new in version 1.1.0.
If you want to update:
pip install scipy --upgrade
A: I just had to reinstall scipy and it worked on Mac OS with M1 and Python 3.9
pip uninstall scipy
and then
pip install scipy
|
unknown
| |
d17845
|
val
|
If the array is declared as character array, like char arr[], you can call sizeof(arr) and you'll get the size of the array. But, if it is allocated some heap memory using malloc or calloc, you cannot get the size of the array, except for calling strlen(), which only gives the size of the string, not the memory location. So, either declare your string as an array of characters or store the size of the memory created (when created dynamically) and update it every time you extend/shrink your memory.
In your case, I think it would be simple if you allocate some storage for your output and iterate through input and insert data into output. This way, you know how much data to allocate to output and you don't need to extend it. Required space for your output would be (1 + 2 + 3 + 4 + 5 +... strlen(input) times) + (strlen(input)-1)
|
unknown
| |
d17847
|
val
|
http://demos.telerik.com/kendo-ui/grid/editing-inline
This should get you where you need to go.
A: I have actually found what I needed.
The event I was looking for is save
It is fired after the item is edited, when the item is being saved. This is where I need to plug in my code.
|
unknown
| |
d17849
|
val
|
I'm also searching for the same question's answer... but I haven't found it.
by the way, I finally write a library to get length of character (generate a range information which shows character length use Console.Write() and Console.CursorLeft, and then convert to C# code, when get character length, use binary search for higher speed)
nuget: NullLib.ConsoleEx
Project: https://github.com/SlimeNull/NullLib.ConsoleEx
A: According to .NET documentation, if you know the font used1, you could use the GlyphTypeface API to get the "AdvanceWidths" of each glyph of your font.
You still have to map the character with glyph index in your font. You can use CharacterToGlyphMap to do that.
var character = 'x';
GlyphTypeface glyphTypeface = new GlyphTypeface(new Uri("file:///C:\\WINDOWS\\Fonts\\Kooten.ttf"));
var index = glyphTypeface.CharacterToGlyphMap[character];
var width = glyphTypeface.AdvanceWidths[index];
[1] To get current console's font details I would recommend to read following question: Get current console font info
Related question: How to find exact size for an arbitrary glyph in WPF?
|
unknown
| |
d17853
|
val
|
You're using a condition in your link_to call, just remove the first argument like this :).
link_to("Sign out", destroy_user_session_path)
|
unknown
| |
d17859
|
val
|
Something like this should get you going...
with dates as (select * from unnest(generate_date_array('2018-01-01','2019-12-31', interval 1 day)) as cal_date),
cal as (select cal_date, cast(format_date('%Y', cal_date) as int64) as year, cast(format_date('%V', cal_date) as int64) as week_num, format_date('%A', cal_date) as weekday_name from dates)
select c1.cal_date, c1.week_num, c1.weekday_name, c2.cal_date as previous_year_same_weekday
from cal c1
inner join cal c2
on c1.year = c2.year+1 and c1.week_num = c2.week_num and c1.weekday_name = c2.weekday_name
The above query uses a week starting on a Monday, you may need to play around with the format_date() arguments as seen here to modify it for your needs.
A: This query returns no results, implying that SHIFT works. The function returns NULL if a year does not have the same number of weeks as its predecessor.
CREATE TEMP FUNCTION P_YEAR(y INT64) AS (
MOD(CAST(y + FLOOR(y / 4.0) - FLOOR(y / 100.0) + FLOOR(y / 400.0) AS INT64), 7)
);
CREATE TEMP FUNCTION WEEKS_YEAR(y INT64) AS (
52 + IF(P_YEAR(y) = 4 OR P_YEAR(y - 1) = 3, 1, 0)
);
CREATE TEMP FUNCTION SHIFT(d DATE) RETURNS DATE AS (
CASE
WHEN WEEKS_YEAR(EXTRACT(ISOYEAR FROM d)) != WEEKS_YEAR(EXTRACT(ISOYEAR FROM d) - 1)
THEN null
WHEN WEEKS_YEAR(EXTRACT(ISOYEAR FROM d)) = 52
THEN DATE_SUB(d, INTERVAL 52 WEEK)
ELSE d
END
);
WITH dates AS (
SELECT d
FROM UNNEST(GENERATE_DATE_ARRAY('2000-12-31', '2020-12-31', INTERVAL 1 DAY)) AS d
)
SELECT
d,
EXTRACT(ISOWEEK FROM d) AS orig_iso_week,
EXTRACT(ISOWEEK FROM SHIFT(d)) AS new_iso_week,
SHIFT(d) AS new_d
FROM dates
WHERE EXTRACT(ISOWEEK FROM d) != EXTRACT(ISOWEEK FROM SHIFT(d))
AND SHIFT(d) IS NOT NULL
|
unknown
| |
d17867
|
val
|
You can use .one(); note js at Question is missing closing parenthesis ) at click()
$(document).ready(function() {
$("#add_app").one("click", function() {
$("#box").append("<p>jQuery is Amazing...</p>");
this.removeAttribute('href');this.className='disabled';
})
});
A: Use this jQuery:
$(document).ready(function() {
$("#add_app").one("click", function() {
$("#box").append("<p>jQuery is Amazing...</p>");
this.removeAttribute('href');
});
});
I'm using the .one() event handler to indicate that you only want the click event to take place once. The rest of the code was more or less correct with a few small changes.
Here's a fiddle: https://jsfiddle.net/0mobshpr/1/
A: you can try this
HTML
<a style="cursor: pointer;" id="add_app" ><strong>Summon new element and disable me</strong></a>
<div id="box"></div>
and in your JS code you can write this i have tested it and it worked fine
$(function(){
$("#add_app").one("click",function(){
$("#box").append("<p>jQuery is Amazing...</p>");
});
});
A: you need to return false whwn the link is click.
try this one JQuery code..
$("#add_app").click(function() {
$("#box").append("<p>jQuery is Amazing...</p>");
return false;
});
|
unknown
| |
d17869
|
val
|
You need to set the root route for the entire application to be served with your blade view, in your case index_extjs.blade.php.
Why? Because when anyone opens up your site, you are loading up that page and hence, loading extjs too. After that page is loaded, you can handle page changes through extjs.
So to achieve this, you need to declare your root route to server this index file:
Route::get('/', function() {
return view('index_extjs');
});
Also you need to revert all extjs config changes back to default, because everything will be relative to your extjs app inside public folder and not relative to the project itself. I hope this makes sense
|
unknown
| |
d17871
|
val
|
The problem has been resolved.
Set the encoding option in requests, we were able to obtain the required value.
Thank you very much.
sub_result = requests.get(sub_url)
sub_result.encoding = 'utf-8'
sub_soup = BeautifulSoup(sub_result.text, 'lxml')
|
unknown
| |
d17873
|
val
|
Both Scala and Java compiles into Java Bytecode (.class files) and packed as .jar files. It's same bytecode, and can be used from any other JVM language under same classpath.
So your app can mix java bytecode produces from any other JVM language, including Java, Groovy, Scala, Clojure, Kotlin, etc. You can put such jars into /lib dir (if your Grails version supports this; it's less preferred way) or as dependency from Maven repository (local or remote). Then you can use such classes from your code
See:
*
*https://en.wikipedia.org/wiki/Java_bytecode
*http://grails.github.io/grails-doc/2.4.x/guide/conf.html#dependencyResolution for grails 2.4.x
*http://grails.github.io/grails-doc/latest/guide/conf.html#dependencyResolution for latest grails
PS there could be some incompatibilities with some classes, because of different nature of sources languages. But in general it should work.
A: Did some simple tests. In hello-world example, just use
groovy -cp the-assembly-SNAPSHOT.jar main-file.groovy
And in the main-file.groovy, should have an import, like in Java/Scala
|
unknown
| |
d17875
|
val
|
You have a single list sqd that you are appending scalar values to, so it will always just be a 1-dimensional list. If you want a list of lists (i.e. 2-dimensional matrix), you need to append lists to sqd, not scalar values:
matrix = [[2,0,2],[0,2,0],[2,0,2]]
sqd = []
for i in matrix:
row = [] # create a new list for each row
for e in i:
row.append(e*e) # append scalar to the row list
sqd.append(row) # append row to matrix list
print(sqd)
A: Because you append numbers to sqd inside the inner for e in i loop. Instead, you need to append those numbers to a temp list, then append that list to sqd.
matrix = [[2,0,2],[0,2,0],[2,0,2]]
sqd = []
for i in matrix:
row = []
for e in i:
row.append(e*e)
sqd.append(row)
print(sqd)
Or, as a list-comprehension:
matrix = [[2,0,2],[0,2,0],[2,0,2]]
sqd = [[e * e for e in row] for row in matrix]
print(sqd)
A: You have two for loops here. Your outer loop is going through the Columns of the matrix.
Your inner loop is going through the rows.
Your inner loop runs through the entire loop before going down to your next column.
Now that you understand that flow, you need to see that your list "sqd" has only one operation it is performing. That operation of append will happen for every loop of the inner loop. Each loop you are growing that list by adding the latest operation.
To create the matrix you wish to see, you are going to want some more work between your inner and outer loop.
I would recommend making a new list for every iteration of your outer loop. This new list will be appended by the inner loop, and once the inner loop completes, you can add this new temp list to "sqd".
|
unknown
| |
d17877
|
val
|
Use generic/very light views, pass a queryset to the template, and gather any remaining necessary information using custom template tags.
i.e. pass the queryset containing the categories, and for each category use a template tag to fetch the entries for that category
or B: Use custom/heavy views, pass one or more querysets + extra necessary information through the view, and use less template tags to fetch information.
i.e. pass a list of dictionaries that contains the categories + their entries.
The way I see it is that the view is there to take in HTTP requests, gather the required information (specific to what's been requested) and pass the HTTP request and Context to be rendered. Template tags should be used to fetch superflous information that isn't particularly related to the current template, (i.e. get the latest entries in a blog, or the most popular entries, but they can really do whatever you like.)
This lack of definition (or ignorance on my part) is starting to get to me, and I'd like to be consistent in my design and implementation, so any input is welcome!
A: I'd say that your understanding is quite right. The main method of gathering information and rendering it via a template is always the view. Template tags are there for any extra information and processing you might need to do, perhaps across multiple views, that is not directly related to the view you're rendering.
You shouldn't worry about making your views generic. That's what the built-in generic views are for, after all. Once you need to start stepping outside what they provide, then you should definitely make them specific to your use cases. You might of course find some common functionality that is used in multiple views, in which case you can factor that out into a separate function or even a context processor, but on the whole a view is a standalone bit of code for a particular specific use.
|
unknown
| |
d17879
|
val
|
Let's assume the answer to my questions was 'yes', you want the three numbers that occur most often and how often they occur.
I've tried a couple of ways of doing this. One way is to sort the numbers and use FREQUENCY to get the frequencies. Then you could use a query like this to get the top 3
=query(A1:B20,"select A,B order by B desc limit 3")
Another way is to get the mode, then the mode excluding the most frequent, then the mode excluding both of the previous ones etc.
=ArrayFormula(mode(if(iserror(match(A$2:A$20,F$1:F1,0)),A$2:A$20)))
starting in F2 - you don't need to sort them.
Then you can just use COUNTIF to get how many times they occur.
Then just put them into a chart.
|
unknown
| |
d17883
|
val
|
My "guidance" on constructing the object would be to avoid this style of inserting each string separately:
menuItems.product[0].product = "prod1";
menuItems.product[0].item[0] = "prod1Item1";
because this involves a lot of writing the same thing over and over, which is more error-prone and less readable/maintainable. I would prefer inserting more coarse-grained objects:
menuItems.product[0] = {
product: "prod1",
item: ["prod1Item1"];
}
Edit: Your edit is asking a completely different question, but it sounds like what you want to do is sort the elements of prodItems based on their "product" properties, then do the same thing for the "items" array inside the elements.
I think the simplest way to do this would be to use Array.sort() with a custom comparison function that returns -1 on the element you want to see at the top. Something like this (hastily written and untested):
function returnDict(product, item) {
prodItems = prodItems.sort(function(a, b) {
if(a.product === product) {
return -1;
} else if(b.product === product) {
return 1;
} else {
return 0;
}
});
prodItems[0].items = prodItems[0].items.sort(function(a, b) {
if(a === item) {
return -1;
} else if(b === item) {
return 1;
} else {
return 0;
}
});
return prodItems;
}
A: var menuItems = [];
menuItems.push({product:"prod1",item:[]})
menuItems[menuItems.length-1].item.push("product1Item1")
menuItems[menuItems.length-1].item.push("product1Item2")
menuItems.push({product:"prod2",item:[]})
menuItems[menuItems.length-1].item.push("product2Item1")
menuItems[menuItems.length-1].item.push("product2Item2")
menuItems[menuItems.length-1].item.push("product2Item3")
menuItems[menuItems.length-1].item.push("product2Item4")
A: var prodItems = [
{
"product": "prod1",
"item": ["prod1Item1", "prod2Item2"]
},
{
"product": "prod2",
"item": ["prod2Item1", "prod2Item2", "prod2Item3", "prod2Item4"]
}
];
alert(prodItems[0].product);
for(var i = 0; i < prodItems.length; i++) {
alert(prodItems[i].product);
}
A: I see your question has been answered, but I want to suggest a small improvement to keep your code more DRY (Do not Repeat Yourself). You can use a simple function that will save you some extra typing when adding new objects.
var prodItems=[];
function addProduct(productName, items){
var product={
product: productName,
items: items
};
prodItems.push(product);
};
//sample use
addProduct("prod2",["prod2Item3", "prod2Item1", "prod2Item2", "prod2Item4"])
This will definitely also become more flexible if you need to change the object structure at some later point.
|
unknown
| |
d17887
|
val
|
I searched around a bit and supposedly git doesn't have any way to ignore single file lines.
Good news you can do it.
How?
You will use something called hunk in git.
Hunk what?
Hunk allow you to choose which changes you want to add to the staging area and then committing them. You can choose any part of the file to add (as long as its a single change) or not to add.
Once you have chosen your changes to commit you will "leave" the changes you don't wish to commit in your working directory.
You can then choose if you want this file to be tracked as modified or not withe the help of the assume-unchanged flag.
Here is a sample code for you.
# make any changes to any given file
# add the file with the `-p` flag.
git add -p
# now you can choose form the following options what you want to do.
# usually you will use the `s` for splitting up your changes.
git add -P
Using git add -p to add only parts of changes which you will choose to commit.
You can choose which changes you wish to add (picking the changes) and not committing them all.
# once you done editing you will have 2 copies of the file
# (assuming you did not add all the changes)
# one file with the "private" changes in your working dir
# and the "public" changes waiting for commit in the staging area.
Add the file to .gitignore file
This will ignore the file and any changes made to it.
--assume-unchaged
Raise the --assume-unchaged flag on this file so it will stop tracking changes on this file
Using method (2) will tell git to ignore this file even when ts already committed.
It will allow you to modify the file without having to commit it to the repository.
git-update-index
--[no-]assume-unchanged
When this flag is specified, the object names recorded for the paths are not updated. Instead, this option sets/unsets the "assume unchanged" bit for the paths. When the "assume unchanged" bit is on, the user promises not to change the file and allows Git to assume that the working tree file matches what is recorded in the index. If you want to change the working tree file, you need to unset the bit to tell Git. This is sometimes helpful when working with a big project on a filesystem that has very slow lstat(2) system call (e.g. cifs).
Git will fail (gracefully) in case it needs to modify this file in the index e.g. when merging in a commit; thus, in case the assumed-untracked file is changed upstream, you will need to handle the situation manually.
|
unknown
| |
d17889
|
val
|
I took a wild guess that maybe the output of "sha1()" in the documention psuedo-code was a hex-string (like sha1() in PHP, etc), and that seems to output the expected password.
Updated code:
string testDateString = "2015-07-08T11:31:53+01:00";
string testNonce = "186269";
string testSecret = "Ok4IWYLBHbKn8juM1gFPvQxadieZmS2";
SHA1CryptoServiceProvider sha1Hasher = new SHA1CryptoServiceProvider();
byte[] hashedDataBytes = sha1Hasher.ComputeHash(Encoding.UTF8.GetBytes(testNonce + testDateString + testSecret));
var hexString = BitConverter.ToString(hashedDataBytes).Replace("-", string.Empty).ToLower();
string Sha1Password = Convert.ToBase64String(Encoding.UTF8.GetBytes(hexString));
|
unknown
| |
d17893
|
val
|
The directions service will either use the browser's configured language or you can specify the language to use when loading the API.
From the API docs:
Textual directions will be provided using the browser's preferred
language setting, or the language specified when loading the API
JavaScript using the language parameter. (For more information, see
Localization.)
A: Just specify your language using the language parameter when loading the API:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en-US"></script>
See full list of supported languages here : https://developers.google.com/+/web/api/supported-languages
|
unknown
| |
d17895
|
val
|
I do not know what resource you're using, but this does not say anything about a -l flag. It suggests
cython -a helloCopy.pyx
This creates a yourmod.c file, and the -a switch produces an annotated html file of the source code. Pass the -h flag for a complete list of supported flags.
gcc -shared -pthread -fPIC -fwrapv -O2 -Wall -fno-strict-aliasing -I/usr/include/python2.7 -o helloCopy.so helloCopy.c
(Linux)
On macOS I would try to compile with
gcc -I/usr/bin/python -o helloCopy.so helloCopy.c
to use the standard version of Python.
|
unknown
| |
d17903
|
val
|
Let's just see what happens when we simplify everything a little bit:
$firstBox = reset($parsed_wiki_syntax['infoboxes']);
if($firstBox) {
foreach($firstBox['contents'] as $content) {
$key = $content['key'];
$value = $content['value'];
echo "<b>" . $key . "</b>: " . $value . "<br><br>";
}
}
The use of array_keys() and the for/foreach loops get a little confusing quickly, so I'm not sure exactly what your error is without looking more. The big trick with my code above is the use of reset() which resets an array and returns (the first element). This lets us grab the first infobox and check if it exists in the next line (before attempting to get the contents of a non-existent key). Next, we just loop through all contents of this first infobox and access the key and value keys directly.
A: You if want to access both keys and values, a simple good ol' foreach will do. Consider this example:
$values = array('infoboxes' => array(array('type' => 'musical artist','type_key' => 'musical_artist','contents' => array(array('key' => 'name', 'value' => 'George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>'),array('key' => 'image', 'value' => 'George Harrison 1974 edited.jpg'),array('key' => 'alt', 'value' => 'Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.'),array('key' => 'caption', 'value' => 'George Harrison at the White House in 1974.'),),),),);
$contents = $values['infoboxes'][0]['contents'];
foreach($contents as $key => $value) {
echo "[key => " . $value['key'] . "][value = " . htmlentities($value['value']) . "]<br/>";
// just used htmlentities just as to not mess up the echo since there are html tags inside the value
}
Sample Output:
[key => name][value = George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>]
[key => image][value = George Harrison 1974 edited.jpg]
[key => alt][value = Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.]
[key => caption][value = George Harrison at the White House in 1974.]
Sample Fiddle
A: As an exercise in scanning the given array without hardcoding anything.
It doesn't simplify anything, it is not as clear as some of the other answers, however, it would process any structure like this whatever the keys were.
It uses the 'inherited' iterator, that all arrays have, for the 'types' and foreach for the contents.
<?php
$values = array('infoboxes' => array(array('type' => 'musical artist','type_key' => 'musical_artist','contents' => array(array('key' => 'name', 'value' => 'George Harrison <br /><small>[[Order of the British Empire|MBE]]</small>'),array('key' => 'image', 'value' => 'George Harrison 1974 edited.jpg'),array('key' => 'alt', 'value' => 'Black-and-white shot of a moustachioed man in his early thirties with long, dark hair.'),array('key' => 'caption', 'value' => 'George Harrison at the White House in 1974.'),),),),);
$typeList = current(current($values));
echo key($typeList), ' => ', current($typeList), '<br />';
next($typeList);
echo key($typeList), ' => ', current($typeList), '<br />';
next($typeList);
echo key($typeList), '...', '<br />';
foreach(current($typeList) as $content) {
$key = current($content);
next($content);
echo 'content: ', $key, ' => ', current($content), '<br />' ;
}
|
unknown
| |
d17905
|
val
|
Take a look at the Java Application Launcher man page.
java -cp aurora.jar; ojdbc6.jar
oracle.aurora.server.tools.loadjava.LoadJavaMain -thin -user sched/sched@teach:prod
%BOS_SRC%/credit/card/api/ScheduleCardApi
You have a space between your classpath entries aurora.jar; ojdbc6.jar. The launcher thinks the first jar is the only classpath entry and the ojdbc6.jar is your class containing the main(String[] args) method. It also considers everything after that as arguments to pass to the main(String[] args) method. Remove that space.
A: Remove the space between the aurora.jar; and the ojdbc6.jar
A: Spaces delimit the parameters each other. The JVM interprets the command as if you run "ojdbc6.jar" class: "jar" as a classname and "ojdbc6" as a package.
To concat the names of libraries you want to place into classpath for a specific class run please use semicolon with no spaces as "lib1;lib2"
P.S.: Could you please ask your colleagues if you may paste some of our credentials to the SO? :)
|
unknown
| |
d17907
|
val
|
Here you go
select visitors, date(datetime)
from corrected_scanners_per_half_hour
where date_format(datetime, '%H:%i') between '08:30' and '17:30'
|
unknown
| |
d17909
|
val
|
You forgot to include jQuery on your JS Fiddle. Add it and it works.
A: I guess there´s just an order problem...just a guess
*
*Include jquery
*Include your script at the bottom of your page in $(document).ready(function(){})
*Should work as expected.
|
unknown
| |
d17917
|
val
|
Rewriting URLs with query strings is slightly more complicated than rewriting plain URLs. You'll have to write something like this:
RewriteCond %{REQUEST_URI} ^/viewthread\.php$
RewriteCond %{QUERY_STRING} ^tid=12345$
RewriteRule ^(.*)$ http://mydomain.site/abc.php [R=302,L]
See those articles for more help:
*
*http://www.simonecarletti.com/blog/2009/01/apache-query-string-redirects/
*http://www.simonecarletti.com/blog/2009/01/apache-rewriterule-and-query-string/
A: i think because you have missed the ? in the rule...
RewriteRule ^viewthread.php?tid=12345$ abc.php
A: Shouldn't it be:
RewriteRule ^/viewthread\.php\?tid=12345$ /abc.php
|
unknown
| |
d17919
|
val
|
You can manually specify the tick labels with an array:
ticks: [[0, "0"], [1, ""], [2, ""], [3, ""], [4, ""], [5, "5"]],
Or, you can specify a function to do it:
ticks: function(axis) {
var tickArray = [[0,"0"]];
for(var i=axis.min; i<axis.max+1; i++) {
var label = i%5?"":i;
tickArray.push([i, label]);
}
return tickArray;
},
Demo: http://jsfiddle.net/jtbowden/gryozh7x/
You can also use a tickFormatter:
tickSize: 1,
tickFormatter: function (val, axis) {
return val%5?"":val;
}
Demo: http://jsfiddle.net/jtbowden/gryozh7x/1/
|
unknown
| |
d17921
|
val
|
This is an apache timeout error. If you run your PHP script from the command line (instead of through apache), you shouldn't get this timeout error. If you need to run the script through apache, you can increase the FcgidIOTimeout setting in /etc/httpd/conf.d/fcgid.conf, and restart apache, and that should solve the problem.
A: Try using curl, forcing timout
set_time_limit(400);// to infinity for example
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://vcdn8.yobt.tv/content/a8/68/e6/a868e6dc4688ecfc0c26de00ed08db7f871427/vid/1_1024x576.mp4");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds
$response = curl_exec($ch);
curl_close($ch);
Then save it to the file.
|
unknown
| |
d17923
|
val
|
Try this Active Records it'll let you know what you were doing along with query
function update($data = array(), $where = '') {
$where = array('pay_id'=>1,'status'=>'y');
$data = array('awarded' => '129');
$this->db->where($where);
$res = $this->db->update($this->main_table, $data);
$rs = $this->db->affected_rows();
return $rs;
}
A: Here is the query you need in your model function.
class my_model extends CI_Model {
function __construct(){
parent::__construct();
}
/*Model function*/
function update_by($condition = array(),$updateJob=array())
{
if($condition && $updateJob)
{
$this->db->where($condition);
$this->db->update('pay_project', $updateJob );
}
}
}
Now you can use your existing code from controller for your desired purpose.
$updateJob = ['awarded' => '129'];
$this->pay_project_model->update_by(array('pay_id'=>1,'status'=>'y'), $updateJob);
A: use this codeigniter active records for doing database operations
$data = array(
'awarded' => '129'
);
$where = array(
'pay_id'=>1,
'status'=>'y'
);
$this->db->where($where);
$this->db->update('pay_project', $data);
For documentation refer this link
codeigniter active records update
A: Use this
$query = $this->db->query("UPDATE pay_project SET awarded = '129' WHERE pay_id = '1' and status ='y' ");
$result = $query->result_array();
return $result;
A: If you are using Codeigniter My_model class, then you need to change your model like this to work the update_by() function
class Pay_project_model extends MY_Model {
protected $table='pay_project';
function update_by($where = array(),$data=array())
{
$this->db->where($where);
$query = $this->db->update($this->table,$data);
return $query;
}
}
In My_model class there is not a default option to update the class by multiple where conditions, So you need to write update_by() function. Simple copy paste the function inside your class, and this will be work perfectly.
|
unknown
| |
d17925
|
val
|
Notifications can be batched for performance optimizations and the delay to deliver notifications can vary based on service load and other factors.
While debugging you should also make sure there's no blocking conditions set by the IDE (like a break point for instance) that might block other incoming requests.
Lastly, it's pretty rare, but service outages can happen, in that case the best thing to do it to contact support.
|
unknown
| |
d17927
|
val
|
fn flatten<T>(x: Option<Option<T>>) -> Option<T> {
x.unwrap_or(None)
}
In my case, I was dealing with an Option-returning method in unwrap_or_else and forgot about plain or_else method.
A: These probably already exist, just as different names to what you expect. Check the docs for Option.
You'll see flat_map more normally as and_then:
let x = Some(1);
let y = x.and_then(|v| Some(v + 1));
The bigger way of doing what you want is to declare a trait with the methods you want, then implement it for Option:
trait MyThings {
fn more_optional(self) -> Option<Self>;
}
impl<T> MyThings for Option<T> {
fn more_optional(self) -> Option<Option<T>> {
Some(self)
}
}
fn main() {
let x = Some(1);
let y = x.more_optional();
println!("{:?}", y);
}
For flatten, I'd probably write:
fn flatten<T>(opt: Option<Option<T>>) -> Option<T> {
match opt {
None => None,
Some(v) => v,
}
}
fn main() {
let x = Some(Some(1));
let y = flatten(x);
println!("{:?}", y);
}
But if you wanted a trait:
trait MyThings<T> {
fn flatten(self) -> Option<T>;
}
impl<T> MyThings<T> for Option<Option<T>> {
fn flatten(self) -> Option<T> {
match self {
None => None,
Some(v) => v,
}
}
}
fn main() {
let x = Some(Some(1));
let y = x.flatten();
println!("{:?}", y);
}
Would there be a way to allow flatten to arbitrary depth
See How do I unwrap an arbitrary number of nested Option types?
|
unknown
| |
d17933
|
val
|
Because of the [{...}] you are getting an array in an array when you decode your array key.
So:
$exercise = $array['exercise'];
Should be:
$exercise = $array[0]['exercise'];
See the example here.
A: From looking at the result of $response['array'], it looks like $array is actually this
[['exercise' => 'foo', 'reps' => 'foo']]
that is, an associative array nested within a numeric one. You should probably do some value checking before blindly assigning values but in the interest of brevity...
$exercise = $array[0]['exercise'];
|
unknown
| |
d17939
|
test
|
TL;DR: Command substitution $(...) is a shell feature, therefore you must run your commands on a shell:
subprocess.call('docker stop $(docker ps -a -q)', shell=True)
subprocess.call('docker rm $(docker ps -a -q)', shell=True)
Additional improvements:
It's not required, but I would suggest using check_call (or run(..., check=True), see below) instead of call(), so that if an error occurs it doesn't go unnoticed:
subprocess.check_call('docker stop $(docker ps -a -q)', shell=True)
subprocess.check_call('docker rm $(docker ps -a -q)', shell=True)
You can also go another route: parse the output of docker ps -a -q and then pass to stop and rm:
container_ids = subprocess.check_output(['docker', 'ps', '-aq'], encoding='ascii')
container_ids = container_ids.strip().split()
if container_ids:
subprocess.check_call(['docker', 'stop'] + container_ids])
subprocess.check_call(['docker', 'rm'] + container_ids])
If you're using Python 3.5+, you can also use the newer run() function:
# With shell
subprocess.run('docker stop $(docker ps -a -q)', shell=True, check=True)
subprocess.run('docker rm $(docker ps -a -q)', shell=True, check=True)
# Without shell
proc = subprocess.run(['docker', 'ps', '-aq'], check=True, stdout=PIPE, encoding='ascii')
container_ids = proc.stdout.strip().split()
if container_ids:
subprocess.run(['docker', 'stop'] + container_ids], check=True)
subprocess.run(['docker', 'rm'] + container_ids], check=True)
A: There is nice official library for python, that helps with Docker.
https://docker-py.readthedocs.io/en/stable/index.html
import docker
client = docker.DockerClient(Config.DOCKER_BASE_URL)
docker_containers = client.containers.list(all=True)
for dc in docker_containers:
dc.remove(force=True)
We've received all containers and remove them all doesn't matter container status is 'started' or not.
The library could be useful if you can import it into code.
|
unknown
| |
d17943
|
test
|
It’s because when you $unwind a two dimensional array once you end up with just an array and $sum gives correct results when applied to numerical values in $group pipeline stage otherwise it will default to 0 if all operands are non-numeric.
To remedy this, you can use the $sum in a $project pipeline without the need to $unwind as $sum traverses into the array to operate on the numerical elements of the array to return a single value if the expression resolves to an array.
Consider running the following pipeline to get the correct results:
db.collection.aggregate([
{ '$project': {
'answerTotal': {
'$sum': {
'$map': {
'input': '$answers',
'as': 'ans',
'in': { '$sum': '$$ans' }
}
}
}
} }
])
|
unknown
| |
d17945
|
test
|
Found out the answers from wxWidget forum:
this->StatusBar->SetForegroundColour(wxColour(wxT("RED")));
wxStaticText* txt = new wxStaticText( this->StatusBar, wxID_ANY,wxT("Validation failed"), wxPoint(10, 5), wxDefaultSize, 0 );
txt->Show(true);
|
unknown
| |
d17951
|
test
|
I was able to work around the proxy by using the following:
$wc = New-Object System.Net.WebClient
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$wc.Proxy.Address = "http://proxyurl"
Once I did this I was able to use Install-PackageProvider Nuget to install the proivder.
|
unknown
| |
d17953
|
test
|
You have to set the origin of the Rotation:
Speed_Needle.qml :--
import QtQuick 2.0
Item {
property int value: 0
width: 186
height: 36
Image
{
id: root
source: "files/REE Demo images/pointer_needle2.png"
x : 0
y : 0
transform: Rotation {
id: needleRotation
angle : value
origin.x: root.width / 2 // here!
origin.y: root.height / 2
Behavior on angle {
SmoothedAnimation { velocity: 50 }
}
}
}
}
|
unknown
| |
d17955
|
test
|
You can set a property with some unique key for each consumer. Then when you consume messages, use a selector. The link you refer to have already an example selector, `symbol=KZNG', but you could use whatever key/value that suits your need.
Something like receiver=CentralAvenueOffice or receiver=theOldFishFactory
|
unknown
| |
d17959
|
test
|
One solution would be to "fake" the underline with a bottom border. It might not work depending on the structure of your HTML, but something like this:
text-decoration: none;
border-bottom: 1px solid #FF0000;
A: You cannot isolate the underline color and control it separate from text color; it inherits the same color from the text.
However, you can use border, instead.
nav a {
color: white
text-decoration: none;
border-bottom: 1px solid salmon;
background-color: salmon;
}
nav a.active {
color: #333;
border-bottom: 1px solid #333;
}
A: Use inline-block as display value for each link and apply a bottom border:
ul li a{
display:inline-block;
border-bottom:2px solid #eeeeee;
float:left;
padding: 10px;
background-color:red;
color:#ffffff;
text-decoration:none;
}
change padding, background color and font color as per your style.
A: This is another solution. Put the mouse over the element!
ul{
margin: 0;
padding: 0;
}
ul li a{
height: 50px;
position: relative;
padding: 0px 15px;
display: table-cell;
vertical-align: middle;
background: salmon;
color: black;
font-weight: bold;
text-decoration: none;
}
ul li a:hover:after{
display: block;
content: '\0020';
position: absolute;
bottom: 0px;
left: 0px;
width: 100%;
height: 3.5px;
background: #000000;
z-index: 9;
}
<ul>
<li><a href='#'>Menu Item</a></li>
</ul>
|
unknown
| |
d17963
|
test
|
This would be pointless. To use the variables in the code you'd need to know what the user had entered. (Hacks like reflection aside.)
Almost certainly what you want is a Map keyed on the String entered. You still have the problem of the type of the maps value, which will depend upon exactly how you are going to use it.
|
unknown
| |
d17967
|
test
|
This will happen if you have two sessions (in your case, Java threads) that try to insert the same ORDER_REF_ID. Consider the following scenario:
1) Session 1 executes this MERGE statement (without committing it):
merge into ORDER_LOCK al
using ( select 1 ORDER_REF_ID, sysdate ORDER_MSG_SENT from dual ) t
on (al.ORDER_REF_ID = t.ORDER_REF_ID)
when not matched then
insert (ORDER_ID, ORDER_REF_ID, ORDER_MSG_SENT)
values (ORDER_LOCK_SEQ.nextval, t.ORDER_REF_ID, t.ORDER_MSG_SENT);
2) Session 2 starts the same MERGE statement:
merge into ORDER_LOCK al
using ( select 1 ORDER_REF_ID, sysdate ORDER_MSG_SENT from dual ) t
on (al.ORDER_REF_ID = t.ORDER_REF_ID)
when not matched then
insert (ORDER_ID, ORDER_REF_ID, ORDER_MSG_SENT)
values (ORDER_LOCK_SEQ.nextval, t.ORDER_REF_ID, t.ORDER_MSG_SENT);
(this will try to insert the row, since Session 2 doesn't "see" the uncommitted changes from Session 1. Session 2 will block, since it is waiting for the lock held by Session 1):
3) Session 1 commits
=> Session 2 now tries to perform the insert, which will raise an ORA-00001: UNIQUE CONSTRAINT VIOLATION since the ORDER_REF_ID 1 already exists
UPDATE
To fix this problem, I'd suggest you modify your application and introduce some kind of affinity between Java threads and ORDER_REF_IDs - each ORDER_REF_ID should "belong" to exactly one thread, and that thread should exclusively insert / update data for its ORDER_REF_ID.
|
unknown
| |
d17969
|
test
|
The Fix is to apply scaling to mouse coordinates too:
let scale = 1;
$(document).ready(function ($) {
$(window).resize(function () {
nsZoomZoom();
});
//Get screen resolution.
origHeigth = window.screen.height * window.devicePixelRatio;
origWidth = window.screen.width * window.devicePixelRatio;
nsZoomZoom();
function nsZoomZoom() {
//Calculating scalse
let htmlWidth = $(window).innerWidth();
var htmlHeigth = $(window).height();
var xscale = htmlWidth / origWidth;
var yscale = htmlHeigth / origHeigth;
//This is done to handle both X and Y axis slacing
scale = Math.min(xscale, yscale);
//Add 10% to scale because window always less than screen resolution
scale += scale / 10;
//Change Cuacamole Display scale
guac.getDisplay().scale(scale);
}
});
...
guac = new Guacamole.Client(tunnel);
const guacEl = guac.getDisplay().getElement();
rootEl.appendChild(guacEl);
mouse = new Guacamole.Mouse(guacEl);
mouse.onmousedown = mouse.onmouseup = (state) => guac.sendMouseState(state);
//The fix is here
mouse.onmousemove = (state) => {
updateMouseState(state);
};
//Handle mouse coordinates scaling
let updateMouseState = (mouseState) => {
mouseState.y = mouseState.y / scale;
mouseState.x = mouseState.x / scale;
guac.sendMouseState(mouseState);
}
I hope it'll help someone.
A: kban,When drag and drop browser’s right-down corner,gua display zone will left a blank(down or right direction),this seems only executing browser’s guacamole js's scale function,how to solute this problem ?enter image description here
|
unknown
| |
d17971
|
test
|
You're correct, (0,0) is indeed the top left corner of the SVG area (at least before you start transforming the coordinates).
However, your text element <text x="0" y="0">hello</text> is positioned with the leftmost end of its baseline at (0,0), which means the text will appear entirely off the top of the SVG image.
Try this: change your text tag to <text x="0" y="0">goodbye</text>. You should now be able to see the descending parts of the 'g' and 'y' at the top of your SVG.
You can shift your text down by one line if you provide a y coordinate equal to the line height, for example:
<svg width="200" height="100">
<text x="0" y="1em">hello</text>
</svg>
Here's a JSFiddle link for you to play with.
A: To make <text> behave in a more standard way, you can use dominant-baseline: hanging like so:
<text x="0" style="dominant-baseline: hanging;">Hello</text>
You can see examples of different values of this property here.
|
unknown
| |
d17973
|
test
|
As @ChrisWagner states in his comment, you shouldn't need to do any of this in iOS8, at least for UIAlertView since there is a new UIAlertViewController that uses closures without any delegates. But from an academic point of view, this pattern is still interesting.
I wouldn't use anonymous class at all. I would just create a class that can be assigned as the delegate and accept closures to execute when something happens.
You could even upgrade this to accept a closure for each kind of action: onDismiss, onCancel, etc. Or you could even make this class spawn the alert view, setting itself as the delegate.
import UIKit
class AlertViewHandler: NSObject, UIAlertViewDelegate {
typealias ButtonCallback = (buttonIndex: Int)->()
var onClick: ButtonCallback?
init(onClick: ButtonCallback?) {
super.init()
self.onClick = onClick
}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
onClick?(buttonIndex: buttonIndex)
}
}
class ViewController: UIViewController {
// apparently, UIAlertView does NOT retain it's delegate.
// So we have to keep it around with this instance var
// It'll be nice when all of UIKit is properly Swift-ified :(
var alertHandler: AlertViewHandler?
func doSoemthing() {
alertHandler = AlertViewHandler({ (clickedIndex: Int) in
println("clicked button \(clickedIndex)")
})
let alertView = UIAlertView(
title: "Test",
message: "OK",
delegate: alertHandler!,
cancelButtonTitle: "Cancel"
)
}
}
Passing around closures should alleviate the need for anonymous classes. At least for the most common cases.
A: Unfortunately as far as I understand it, no you cannot effectively create anonymous inner classes. The syntax you suggest would be really nice IMO though.
Here is my attempt at getting something close to what you want, it's no where near as clean though.
import UIKit
class AlertViewDelegate: NSObject, UIAlertViewDelegate {
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
}
func alertView(alertView: UIAlertView!, didDismissWithButtonIndex buttonIndex: Int) {
}
func alertView(alertView: UIAlertView!, willDismissWithButtonIndex buttonIndex: Int) {
}
func alertViewCancel(alertView: UIAlertView!) {
}
func alertViewShouldEnableFirstOtherButton(alertView: UIAlertView!) -> Bool {
return true
}
}
class ViewController: UIViewController {
var confirmDelegate: AlertViewDelegate?
func doSoemthing() {
confirmDelegate = {
class ConfirmDelegate: AlertViewDelegate {
override func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
println("clicked button \(buttonIndex)")
}
}
return ConfirmDelegate()
}()
let alertView = UIAlertView(title: "Test", message: "OK", delegate: confirmDelegate, cancelButtonTitle: "Cancel")
}
}
|
unknown
| |
d17977
|
test
|
productList.get(0).setDrawableId(R.drawable.new_cloth_id); Type any position what you want instead of '0'. And then notify adapter.
A: Please make model(get/set) class of InfoProduct and in onClick of item you'll get the position. On that position you can set drawable to different drawable.
|
unknown
| |
d17981
|
test
|
Just use a more precise regular expression:
SELECT REGEXP_SUBSTR(STR, 'Date-([0-9]{2}-[0-9]{2}-[0-9]{4})', 1, 1, 'i', 1)
FROM x;
Or for less accuracy but more conciseness:
SELECT REGEXP_SUBSTR(STR, 'Date-([-0-9]{10})', 1, 1, 'i', 1)
A: You are zero-padding the date values so each term has a fixed length and have a fixed prefix so you do not need to use (slow) regular expressions and can just use simple string functions:
SELECT TO_DATE(SUBSTR(value, 6, 10), 'DD-MM-YYYY')
FROM table_name;
(Note: if you still want it as a string, rather than as a date, then just use SUBSTR without wrapping it in TO_DATE.)
For example:
WITH table_name ( value ) AS (
SELECT 'Date-08-01-2021-Trans-1000008-PH.0000-BA-CR-9999.21' FROM DUAL
)
SELECT TO_DATE(SUBSTR(value, 6, 10), 'DD-MM-YYYY') AS date_value
FROM table_name;
Outputs:
DATE_VALUE
08-JAN-21
db<>fiddle here
If the Date- prefix is not going to always be at the start then use INSTR to find it:
WITH table_name ( value ) AS (
SELECT 'Date-08-01-2021-Trans-1000008-PH.0000-BA-CR-9999.21' FROM DUAL UNION ALL
SELECT 'Trans-1000008-Date-08-02-2021-PH.0000-BA-CR-9999.21' FROM DUAL
)
SELECT TO_DATE(SUBSTR(value, INSTR(value, 'Date-') + 5, 10), 'DD-MM-YYYY') AS date_value
FROM table_name;
Which outputs:
DATE_VALUE
08-JAN-21
08-FEB-21
If you can have multiple Date- substrings and you want to find the one that is either at the start of the string or has a - prefix then you may need regular expressions:
WITH table_name ( value ) AS (
SELECT 'Date-08-01-2021-Trans-1000008-PH.0000-BA-CR-9999.21' FROM DUAL UNION ALL
SELECT 'TransDate-1000008-Date-08-02-2021-PH.0000-BA-CR-9999.21' FROM DUAL
)
SELECT TO_DATE(
REGEXP_SUBSTR(value, '(^|-)Date-(\d\d-\d\d-\d{4})([-.]|$)', 1, 1, 'i', 2),
'DD-MM-YYYY'
) AS date_value
FROM table_name;
db<>fiddle here
|
unknown
| |
d17985
|
test
|
You can directly use the bitwise or and xor commands.
or_result = bitmap1 | bitmap2
xor_result = bitmap1 ^ bitmap2
If this will not work because of how you've defined your bitmap1 and bitmap2 (which is unclear, is it a struct or an int or a char or something less useful like an array or something strange like a class with an operator[] defined? We need more information) then you'll probably have to change how you're storing your data.
|
unknown
| |
d17991
|
test
|
The content of a RichTextBox is not HTML, so an incompatible clipboard format may be part of the issue. If you are happy with the text only, try assigning the plain text to the clipboard:
Clipboard.SetText(RichTextBox1.Text);
If you want formatted text, you will need to convert the RTF to HTML. This article may help: http://www.codeproject.com/Articles/27431/Writing-Your-Own-RTF-Converter
A: Because your page html is null,try this example
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = "<html><body></body></html>";
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.Body.InnerText = richTextBox1.Text;
}
}
|
unknown
| |
d17999
|
test
|
A NullPointerException is a rather trivial exception and has actually nothing to do with JSP/Servlets, but with basic Java in general (look, it's an exception of java.lang package, not of javax.servlet package). It just means that some object is null while your code is trying to access/invoke it using the period . operator.
Something like:
SomeObject someObject = null;
someObject.doSomething(); // NullPointerException!
The 1st line of the stacktrace tells you in detail all about the class name, method name and line number where it occurred.
Fixing it is relatively easy. Just make sure that it's not null or bypass the access altogether. You should rather concentrate on why it is null and/or why your code is trying to deal with null.
|
unknown
| |
d18003
|
test
|
Press the menu key and then press 'O' or 'o'.
More about Menu Key: http://en.wikipedia.org/wiki/Menu_key
A: Create a macro with the following. The cell with the link should only include text of the hyperlink (and not use the Excel function hyperlink with an embedded link). Note that the "... chrome.exe " has a [space] between exe and quote (").
Sub ClickHyperlnk()
'
' ClickHyperlnk Macro
'
' Keyboard Shortcut: Ctrl+d
'
With Selection.Interior
URL = ActiveCell.Value
Shell "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe " & URL, vbNormalNoFocus
End With
End Sub
A: To open a hyperlinked file in excel, try the following
Select the cell.
Press application key (menu key).
Press O key twice.
Press enter key.
This works well for me.
A: Sub hyhperlink()
'
' hyhperlink Macro
' opens hyperlink
'
' Keyboard Shortcut: Ctrl+Shift+X
'
With Selection.Interior
Selection.Hyperlinks(1).Follow NewWindow:=False, AddHistory:=True
End With
End Sub
or record a macro for this operation
A: go in excel view tab
*
*Click on micro
*Click Record micro
*type text in shortcut key i.e.(Ctr+Q or q)
*enter OK
*Press the menu key and then press 'O' or 'o' in excel Where is your hyper link data & Enter
*again go in view > micro > click on stop micro
Now you can use your short cut key i.e. Ctr+Q or q
For hyperlink cells in excel
A: This is an old post but maybe it could help someone searching for this shortcut. To open a link without going through "Edit Links" follow these couple of steps:
*
*click on a cell that is linked to another file
*then press Ctrl + [
This will open the linked file. Hope this helps.
A: In Excel 2016 (English version), I would say that the simplest way to do this is to
*
*press the menu key (that has a similar effect to a right click)
*press "o" twice
*press "Enter".
The first "o" goes to "sort" ; the second "o" goes to "Open Hyperlink", and "Enter" then opens the hyperlink.
On a keyboard that does not have a menu key, one can press Shift + F10 instead.
A: I found out this command doesn't work for me with the 'o' twice, maybe because i have a column of hyperlinks? who knows.
What I do is:
*
*Select cell
*Menu key
*Up_Arrow
*Enter
Opening the link is the last proposition of the menu, so going up goes to the last option. Pressing enter activates it.
Chears
Ben
A: You can make keyboard shortcut for hyperlinks formula / function.
Just press ALT + F11 copy and paste the script below:
Sub OpenHyp()
Workbooks.Open "FOLDER ADDRESS\" & ActiveCell.Value & "FILE EXTENSION"
End Sub
replace the FOLDER ADDRESS = you can find it on address bar of the file location just copy, paste and add "\" at the end of file address.
no need to replace ActiveCell.Value = this is the filename of your file which is usually the content of cell.
replace the FILEEXTENSION = for pdf used ".pdf", for normal excel file used ".xlsx" and so on.
Then, go to developer tab, click Macros, select the code we make which is "OpenHyp" and click "Option". Now you can put the shortcut key
I hope this helps.
|
unknown
| |
d18005
|
test
|
When I had an issue with the documents directory on IOS5 I found this article which discusses the cache amongst other subjects.
As I understand it; yes the OS handles the cache and it will clear it when disk space is low. What low actually means in size I do not know.
|
unknown
| |
d18017
|
test
|
Assuming you have a hash:
my @item3s;
for my $item (@{ $hash{two}{items} }){
push @item3s, $item->{itemthree};
}
print "$_\n" for @item3s;
If it's in fact a hash reference, change $hash{two}{items} to $hash->{two}{items}
|
unknown
| |
d18019
|
test
|
Start with including:
Option Explicit
at the top of the module.
Then try with:
Function fMakeBackup() As Boolean
Dim objFSO As Object
Dim Source As String
Dim Target As String
Dim retval As Integer
' Disable error handling during development.
' On Error GoTo sysBackup_Err
Source = CurrentDb.Name
' Adjust if if backup folder is not \backups\.
Target = CurrentProject.Path & "\backups\"
Target = Target & Format(Now, "yyyymmdd-hhnn") & ".accdb"
' To run every time, use this line in plade of If DateDiff ...:
' If True Then
If DateDiff("d", DLookup("[BackupDate]", "[WinAutoBackup]", "[BckID] = 1"), Date) >= 3 Then
Set objFSO = CreateObject("Scripting.FileSystemObject")
retval = objFSO.CopyFile(Source, Target, True)
Set objFSO = Nothing
DoCmd.SetWarnings False
DoCmd.RunSQL "UPDATE WinAutoBackup SET WinAutoBackup.BackupDate = Date() WHERE [BckID] = 1;"
DoCmd.SetWarnings True
MsgBox "Backup successful. Next auto backup in 3 days."
End If
sysBackup_Exit:
Exit Function
sysBackup_Err:
MsgBox Err.Description, , "sysBackup()"
Resume sysBackup_Exit
End Function
|
unknown
| |
d18023
|
test
|
You might take a look at this question: split-files-using-tar-gz-zip-or-bzip2
I assume the reason you want to split it is to move it? And that you know you probably wont be able to import a small slice of the file into a database?
|
unknown
| |
d18027
|
test
|
@ComponentScan annotation will scan all classes with @Compoment or @Configuration annotation.
Then spring ioc will add them all to spring controlled beans.
If you want to only add specific configurations, you can use @import annotation.
example:
@Configuration
@Import(NameOfTheConfigurationYouWantToImport.class)
public class Config {
}
@Import Annotation Doc
A: The easiest way is to scan the package that the @Configuration class is in.
@ComponentScan("com.acme.otherJar.config")
or to just load it as a spring bean:
@Bean
public MyConfig myConfig() {
MyConfig myConfig = new MyConfig ();
return myConfig;
}
Where MyConfig is something like:
@Configuration
public class MyConfig {
// various @Bean definitions ...
}
See docs
|
unknown
| |
d18029
|
test
|
This does not work with your current relationship, I don't understand why you would want to add duplicates, but if you have to, then you'd have to create a new entity for that. One example would be something like this:
@Entity
public class ProductBatch {
@Id
private String id;
@OneToOne
private Product product;
private Integer count;
// getter & setter
}
and then you change your Client like this:
@Entity
public class Client {
@Id
private String id;
@OneToMany
private List<ProductBatch> products;
}
this makes something like this possible for your addNewProduct function:
public Client addNewProduct(Client client, Product newProduct) {
List<ProductBatch> products = client.getProducts();
boolean exists = false;
for(ProductBatch product : products) {
if(product.getProduct().equals(newProduct)) {
product.setCount(product.getCount() + 1);
exists = true;
}
}
if(!exists) {
BatchProduct product = new BatchProduct();
product.setProduct(newProduct);
product.setCount(0);
products.add(product);
}
client.setProducts(products);
return clientRepository.save(client);
}
A: That has nothing to do with JPA or Hibernate. A constraint is a Database constraint and it is right. If a Foreign Key is already part of the table, trying to add it again, violates this constraint. An ID is unique and it should stay that way. So adding duplicates (at least with the same ID) will not work.
|
unknown
| |
d18031
|
test
|
Migrations to create a new M2M relationship are not supported yet in EF5.0RC per my experience trying to track down the same issue. Thus why it will work on standard DB creation but doesn't work with Migration features. You can export the create SQL from the standard code first database initialization and run it manually on the migration for now.
This should be resolved when EF5.0 goes RTM but for now we have to wait it out.
|
unknown
| |
d18033
|
test
|
One option is to specify category as json object like below
{"code":"123","description":"bananas","category": { "id" : 1}}
|
unknown
| |
d18041
|
test
|
You are close. It's even simpler than you think, you can extract without reference to indices:
def func(name):
# do something
return value1, value2
x, y = func(var)
func returns a tuple (note parentheses are not required). You can then unpack via sequence unpacking. I would advise you choose variable names that are informative.
|
unknown
| |
d18045
|
test
|
One possible solution would be to have a hidden window that owns all the windows in your app.
You would declare it something like:
<Window
Opacity="0"
ShowInTaskbar="False"
AllowsTransparency="true"
WindowStyle="None">
Be sure to remove StartupUri from your App.xaml. And in your App.xaml.cs you would override OnStartup to look something like:
protected override void OnStartup(StartupEventArgs e)
{
HiddenMainWindow window = new HiddenMainWindow();
window.Show();
Window1 one = new Window1();
one.Owner = window;
one.Show();
Window2 two = new Window2();
two.Owner = window;
two.Show();
}
Another difficulty will be how you want to handle closing the actual application. If one of these windows is considered the MainWindow you can just change the application ShutdownMode to ShutdownMode.OnMainWindowClose and then set the MainWindow property to either of those windows. Otherwise you will need to determine when all windows are closed and call Shutdown explicitly.
|
unknown
| |
d18047
|
test
|
You're close, you just need to combine that with a FileStream object
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var str:String = fileStream.readMultiByte(file.size, File.systemCharset);
trace(str);
more info here
A: If you want to read the content of a file, use the following code:
var stream:FileStream = new FileStream();
stream.open("some path here", FileMode.READ);
var fileData:String = stream.readUTFBytes(stream.bytesAvailable);
trace(fileData);
The data property is inherited from FileReference class and it will be populated only after a load call (see this link).
|
unknown
| |
d18049
|
test
|
This is from the Apple document, "About File Metadata Queries" :
iOS allows metadata searches within iCloud to find files corresponding files. It provides only the Objective-C interface to file metadata query, NSMetadataQuery and NSMetadataItem, as well as only supporting the search scope that searches iCloud.
Unlike the desktop, the iOS application’s sandbox is not searchable using the metadata classes. In order to search your application’s sandbox, you will need to traverse the files within the sandbox file system recursively using the NSFileManager class. Once matching file or files is found, you can access that file in the manner that you require. You are also able to use the NSMedatataItem class to retrieve metadata for that particular file.
So, you have to use NSFileManager instead.
|
unknown
| |
d18051
|
test
|
URL::equals reference
URL urlOne = new URL("http://stackoverflow.com");
URL urlTwo = new URL("http://stackoverflow.com/");
if( urlOne.equals(urlTwo) )
{
// ....
}
Note from docs -
Two URL objects are equal if they have the same protocol, reference equivalent hosts, have the same port number on the host, and the same file and fragment of the file.
Two hosts are considered equivalent if both host names can be resolved into the same IP addresses; else if either host name can't be resolved, the host names must be equal without regard to case; or both host names equal to null.
Since hosts comparison requires name resolution, this operation is a blocking operation.
Note: The defined behavior for equals is known to be inconsistent with virtual hosting in HTTP.
So, instead you should prefer URI::equals reference as @Joachim suggested.
A: While URI.equals() (as well as the problematic URL.equals()) does not return true for these specific examples, I think it's the only case where equivalence can be assumed (because there is no empty path in the HTTP protocol).
The URIs http://stackoverflow.com/foo and http://stackoverflow.com/foo/ can not be assumed to be equivalent.
Maybe you can use URI.equals() wrapped in a utility method that handles this specific case explicitly.
A: The following may work for you - it validates that 2 urls are equal, allows the parameters to be supplied in different orders, and allows a variety of options to be configured, that being:
*
*Is the host case sensitive
*Is the path case sensitive
*Are query string parameters case sensitive
*Are query string values case sensitive
*Is the scheme case sensitive
You can test it like so:
class Main {
public static void main(String[] args)
{
UrlComparer urlComparer = new UrlComparer();
expectResult(false, "key a case different", urlComparer.urlsMatch("//test.com?A=a&B=b", "//test.com?a=a&b=b"));
expectResult(false, "key a case different", urlComparer.urlsMatch("https://WWW.TEST.COM?A=1&b=2", "https://www.test.com?b=2&a=1"));
expectResult(false, "key a value different", urlComparer.urlsMatch("/test?a=2&A=A", "/test?a=A&a=2"));
expectResult(false, "key a value different", urlComparer.urlsMatch("https://WWW.TEST.COM?A=a&b=2", "https://www.test.com?b=2&A=1"));
expectResult(false, "null", urlComparer.urlsMatch("/test", null));
expectResult(false, "null", urlComparer.urlsMatch(null, "/test"));
expectResult(false, "port different", urlComparer.urlsMatch("//test.com:22?A=a&B=b", "//test.com:443?A=a&B=b"));
expectResult(false, "port different", urlComparer.urlsMatch("https://WWW.TEST.COM:8443", "https://www.test.com"));
expectResult(false, "protocol different", urlComparer.urlsMatch("http://WWW.TEST.COM:2121", "https://www.test.com:2121"));
expectResult(false, "protocol different", urlComparer.urlsMatch("http://WWW.TEST.COM?A=a&b=2", "https://www.test.com?b=2&A=a"));
expectResult(true, "both null", urlComparer.urlsMatch(null, null));
expectResult(true, "host and scheme different case", urlComparer.urlsMatch("HTTPS://WWW.TEST.COM", "https://www.test.com"));
expectResult(true, "host different case", urlComparer.urlsMatch("https://WWW.TEST.COM:443", "https://www.test.com"));
expectResult(true, "identical urls", urlComparer.urlsMatch("//test.com:443?A=a&B=b", "//test.com:443?A=a&B=b"));
expectResult(true, "identical urls", urlComparer.urlsMatch("/test?a=A&a=2", "/test?a=A&a=2"));
expectResult(true, "identical urls", urlComparer.urlsMatch("https://www.test.com", "https://www.test.com"));
expectResult(true, "parameter order changed", urlComparer.urlsMatch("https://www.test.com?a=1&b=2&c=522%2fMe", "https://www.test.com?c=522%2fMe&b=2&a=1"));
expectResult(true, "parmeter order changed", urlComparer.urlsMatch("https://WWW.TEST.COM?a=1&b=2", "https://www.test.com?b=2&a=1"));
}
public static void expectResult(boolean expectedResult, String msg, boolean result)
{
if (expectedResult != result)
throw new RuntimeException(msg);
}
}
UrlComparer.java
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
public class UrlComparer
{
private boolean hostIsCaseSensitive = false;
private boolean pathIsCaseSensitive = true;
private boolean queryStringKeysAreCaseSensitive = true;
private boolean queryStringValuesAreCaseSensitive = false;
private boolean schemeIsCaseSensitive = false;
public boolean urlsMatch(String url1, String url2)
{
try
{
if (Objects.equals(url1, url2))
return true;
URI uri1 = new URI(url1);
URI uri2 = new URI(url2);
// Compare Query String Parameters
Map<String, String> mapParams1 = getQueryStringParams(uri1);
Map<String, String> mapParams2 = getQueryStringParams(uri2);
if (!mapsAreEqual(mapParams1, mapParams2, getQueryStringValuesAreCaseSensitive()))
return false;
// Compare scheme (http or https)
if (!stringsAreEqual(uri1.getScheme(), uri2.getScheme(), getSchemeIsCaseSensitive()))
return false;
// Compare host
if (!stringsAreEqual(uri1.getHost(), uri2.getHost(), getHostIsCaseSensitive()))
return false;
// Compare path
if (!stringsAreEqual(uri1.getPath(), uri2.getPath(), getPathIsCaseSensitive()))
return false;
// Compare ports
if (!portsAreEqual(uri1, uri2))
return false;
return true;
}
catch (Exception e)
{
return false;
}
}
protected Map<String, String> getQueryStringParams(URI uri)
{
Map<String, String> result = getListAsMap(URLEncodedUtils.parse(uri, "UTF-8"), getQueryStringKeysAreCaseSensitive());
return result;
}
protected boolean stringsAreEqual(String s1, String s2, boolean caseSensitive)
{
// Eliminate null cases
if (s1 == null || s2 == null)
{
if (s1 == s2)
return true;
return false;
}
if (caseSensitive)
{
return s1.equals(s2);
}
return s1.equalsIgnoreCase(s2);
}
protected boolean mapsAreEqual(Map<String, String> map1, Map<String, String> map2, boolean caseSensitiveValues)
{
for (Map.Entry<String, String> entry : map1.entrySet())
{
String key = entry.getKey();
String map1value = entry.getValue();
String map2value = map2.get(key);
if (!stringsAreEqual(map1value, map2value, caseSensitiveValues))
return false;
}
for (Map.Entry<String, String> entry : map2.entrySet())
{
String key = entry.getKey();
String map2value = entry.getValue();
String map1value = map2.get(key);
if (!stringsAreEqual(map1value, map2value, caseSensitiveValues))
return false;
}
return true;
}
protected boolean portsAreEqual(URI uri1, URI uri2)
{
int port1 = uri1.getPort();
int port2 = uri2.getPort();
if (port1 == port2)
return true;
if (port1 == -1)
{
String scheme1 = (uri1.getScheme() == null ? "http" : uri1.getScheme()).toLowerCase();
port1 = scheme1.equals("http") ? 80 : 443;
}
if (port2 == -1)
{
String scheme2 = (uri2.getScheme() == null ? "http" : uri2.getScheme()).toLowerCase();
port2 = scheme2.equals("http") ? 80 : 443;
}
boolean result = (port1 == port2);
return result;
}
protected Map<String, String> getListAsMap(List<NameValuePair> list, boolean caseSensitiveKeys)
{
Map<String, String> result;
if (caseSensitiveKeys)
{
result = new HashMap<String, String>();
}
else
{
result = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
}
for (NameValuePair param : list)
{
if (caseSensitiveKeys)
{
if (!result.containsKey(param.getName()))
result.put(param.getName(), param.getValue());
}
else
{
result.put(param.getName(), param.getValue());
}
}
return result;
}
public boolean getSchemeIsCaseSensitive()
{
return schemeIsCaseSensitive;
}
public void setSchemeIsCaseSensitive(boolean schemeIsCaseSensitive)
{
this.schemeIsCaseSensitive = schemeIsCaseSensitive;
}
public boolean getHostIsCaseSensitive()
{
return hostIsCaseSensitive;
}
public void setHostIsCaseSensitive(boolean hostIsCaseSensitive)
{
this.hostIsCaseSensitive = hostIsCaseSensitive;
}
public boolean getPathIsCaseSensitive()
{
return pathIsCaseSensitive;
}
public void setPathIsCaseSensitive(boolean pathIsCaseSensitive)
{
this.pathIsCaseSensitive = pathIsCaseSensitive;
}
public boolean getQueryStringKeysAreCaseSensitive()
{
return queryStringKeysAreCaseSensitive;
}
public void setQueryStringKeysAreCaseSensitive(boolean queryStringKeysAreCaseSensitive)
{
this.queryStringKeysAreCaseSensitive = queryStringKeysAreCaseSensitive;
}
public boolean getQueryStringValuesAreCaseSensitive()
{
return queryStringValuesAreCaseSensitive;
}
public void setQueryStringValuesAreCaseSensitive(boolean queryStringValuesAreCaseSensitive)
{
this.queryStringValuesAreCaseSensitive = queryStringValuesAreCaseSensitive;
}
}
A: sameFile
public boolean sameFile(URL other)Compares two URLs,
excluding the fragment component.
Returns true if this URL and the other argument are equal without taking the fragment component into consideration.
Parameters:
other - the URL to compare against.
Returns:
true if they reference the same remote object; false otherwise.
also please go through this link
http://download.oracle.com/javase/6/docs/api/java/net/URL.html#sameFile(java.net.URL)
As iam unable to add comment , browser throwing Javascript error. so iam adding my comment here. regret for inconvience.
//this what i suggeted
>URL url1 = new URL("http://stackoverflow.com/foo");
>URL url2 = new URL("http://stackoverflow.com/foo/");
>System.out.println(url1.sameFile(url2));
// this is suggested by Joachim Sauer
>URI uri = new URI("http://stackoverflow.com/foo/");
>System.out.println(uri.equals("http://stackoverflow.com/foo"));
// Both are giving same result
so Joachim Sauer check once.
|
unknown
| |
d18055
|
test
|
Inside the airport entity, the mappedBy reference should be like the following...
@OneToMany(mappedBy = "startLocation")
@OneToMany(mappedBy = "destination")
A: Define a relationship in Airport Entity, and specify the property mappedBy="".
MappedBy basically tells the hibernate not to create another join table as the relationship is already being mapped by the opposite entity of this relationship.
That basically refers to the variables used in Flight Entity like startLocation and destination.
It should look like this:-
public class Airport {
...
@OneToMany(mappedBy = "startLocation")
private Flight flight_departure_location;
@OneToMany(mappedBy = "destination")
private Flight flight_destination;
}
It should be something like this.
|
unknown
| |
d18057
|
test
|
var res = XDocument.Load(filename)
.Descendants("fieldLayout")
.OrderByDescending(x => x.Descendants("field").Count())
.First();
A: var fieldLayout = xDoc.Root
.Element("FieldLayout")
.Elements("fieldLayout")
.OrderByDescending(fl => fl.Element("fields")
.Elements("field")
.Count())
.First();
|
unknown
| |
d18059
|
test
|
$.each(data, function(i,item) {
var container = $('<div class="sex" />');
$('<img/>').attr("src", item.media_path).wrap('<div class="friend_pic' + item.id + '"></div>').appendTo(container);
$('<div class="friends-name' + item.id + '" id="fname_' + item.id + '" />').html(item.fname).appendTo(container);
container.appendTo('.mutual_row');
});
|
unknown
| |
d18065
|
test
|
If you want to change the color every 0.25 seconds, that should be the interval of the animation:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.animation import FuncAnimation
fig, ax = plt.subplots()
ax.axis('square')
c = Circle(xy = (0, 0), color = "red")
ax.add_patch(c)
ax.set_xlim([-50, 50])
ax.set_ylim([-50, 50])
def change_color(i):
c.set_fc((i/100, 0, 0, 1))
ani = FuncAnimation(fig, change_color, frames = range(100), interval=250)
plt.show()
|
unknown
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.