tl;dr Swift 1.0 is now as fast as C by this benchmark using the default release optimisation level [-O].
Here is an in-place quicksort in Swift Beta:
func quicksort_swift(inout a:CInt[], start:Int, end:Int) {
if (end - start < 2){
return
}
var p = a[start + (end - start)/2]
var l = start
var r = end - 1
while (l <= r){
if (a[l] < p){
l += 1
continue
}
if (a[r] > p){
r -= 1
continue
}
var t = a[l]
a[l] = a[r]
a[r] = t
l += 1
r -= 1
}
quicksort_swift(&a, start, r + 1)
quicksort_swift(&a, r + 1, end)
}
And the same in C:
void quicksort_c(int *a, int n) {
if (n < 2)
return;
int p = a[n / 2];
int *l = a;
int *r = a + n - 1;
while (l <= r) {
if (*l < p) {
l++;
continue;
}
if (*r > p) {
r--;
continue;
}
int t = *l;
*l++ = *r;
*r-- = t;
}
quicksort_c(a, r - a + 1);
quicksort_c(l, a + n - l);
}
Both work:
var a_swift:CInt[] = [0,5,2,8,1234,-1,2]
var a_c:CInt[] = [0,5,2,8,1234,-1,2]
quicksort_swift(&a_swift, 0, a_swift.count)
quicksort_c(&a_c, CInt(a_c.count))
// [-1, 0, 2, 2, 5, 8, 1234]
// [-1, 0, 2, 2, 5, 8, 1234]
Both are called in the same program as written.
var x_swift = CInt[](count: n, repeatedValue: 0)
var x_c = CInt[](count: n, repeatedValue: 0)
for var i = 0; i < n; ++i {
x_swift[i] = CInt(random())
x_c[i] = CInt(random())
}
let swift_start:UInt64 = mach_absolute_time();
quicksort_swift(&x_swift, 0, x_swift.count)
let swift_stop:UInt64 = mach_absolute_time();
let c_start:UInt64 = mach_absolute_time();
quicksort_c(&x_c, CInt(x_c.count))
let c_stop:UInt64 = mach_absolute_time();
This converts the absolute times to seconds:
static const uint64_t NANOS_PER_USEC = 1000ULL;
static const uint64_t NANOS_PER_MSEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MSEC;
mach_timebase_info_data_t timebase_info;
uint64_t abs_to_nanos(uint64_t abs) {
if ( timebase_info.denom == 0 ) {
(void)mach_timebase_info(&timebase_info);
}
return abs * timebase_info.numer / timebase_info.denom;
}
double abs_to_seconds(uint64_t abs) {
return abs_to_nanos(abs) / (double)NANOS_PER_SEC;
}
Here is a summary of the compiler's optimazation levels:
[-Onone] no optimizations, the default for debug.
[-O] perform optimizations, the default for release.
[-Ofast] perform optimizations and disable runtime overflow checks and runtime type checks.
Time in seconds with [-Onone] for n=10_000:
Swift: 0.895296452
C: 0.001223848
Here is Swift's builtin sort() for n=10_000:
Swift_builtin: 0.77865783
Here is [-O] for n=10_000:
Swift: 0.045478346
C: 0.000784666
Swift_builtin: 0.032513488
As you can see, Swift's performance improved by a factor of 20.
As per mweathers' answer, setting [-Ofast] makes the real difference, resulting in these times for n=10_000:
Swift: 0.000706745
C: 0.000742374
Swift_builtin: 0.000603576
And for n=1_000_000:
Swift: 0.107111846
C: 0.114957179
Swift_sort: 0.092688548
For comparison, this is with [-Onone] for n=1_000_000:
Swift: 142.659763258
C: 0.162065333
Swift_sort: 114.095478272
So Swift with no optimizations was almost 1000x slower than C in this benchmark, at this stage in its development. On the other hand with both compilers set to [-Ofast] Swift actually performed at least as well if not slightly better than C.
It has been pointed out that [-Ofast] changes the semantics of the language, making it potentially unsafe. This is what Apple states in the Xcode 5.0 release notes:
A new optimization level -Ofast, available in LLVM, enables aggressive optimizations. -Ofast relaxes some conservative restrictions, mostly for floating-point operations, that are safe for most code. It can yield significant high-performance wins from the compiler.
They all but advocate it. Whether that's wise or not I couldn't say, but from what I can tell it seems reasonable enough to use [-Ofast] in a release if you're not doing high-precision floating point arithmetic and you're confident no integer or array overflows are possible in your program. If you do need high performance and overflow checks / precise arithmetic then choose another language for now.
BETA 3 UPDATE:
n=10_000 with [-O]:
Swift: 0.019697268
C: 0.000718064
Swift_sort: 0.002094721
Swift in general is a bit faster and it looks like Swift's built-in sort has changed quite significantly.
FINAL UPDATE:
[-Onone]:
Swift: 0.678056695
C: 0.000973914
[-O]:
Swift: 0.001158492
C: 0.001192406
[-Ounchecked]:
Swift: 0.000827764
C: 0.001078914
In JavaScript, you cannot pass variables by reference to a function. However you can pass an object by reference.
you can do diff a on b and diff b on a, then merge both results
let a = [_x000D_
{ value: "0", display: "Jamsheer" },_x000D_
{ value: "1", display: "Muhammed" },_x000D_
{ value: "2", display: "Ravi" },_x000D_
{ value: "3", display: "Ajmal" },_x000D_
{ value: "4", display: "Ryan" }_x000D_
]_x000D_
_x000D_
let b = [_x000D_
{ value: "0", display: "Jamsheer" },_x000D_
{ value: "1", display: "Muhammed" },_x000D_
{ value: "2", display: "Ravi" },_x000D_
{ value: "3", display: "Ajmal" }_x000D_
]_x000D_
_x000D_
// b diff a_x000D_
let resultA = b.filter(elm => !a.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));_x000D_
_x000D_
// a diff b_x000D_
let resultB = a.filter(elm => !b.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm))); _x000D_
_x000D_
// show merge _x000D_
console.log([...resultA, ...resultB]);
_x000D_
A side comment here for those using any of these answers. Juba's answer is great, as it's very selective if your variables are either numberic or character strings. If however, you have a combination (e.g. a1, b1, a2, b2) etc. It will not convert the characters properly.
As @Trenton Hoffman notes,
library(dplyr)
df <- mutate_each(df, funs(toupper))
affects both character and factor classes and works for "mixed variables"; e.g. if your variable contains both a character and a numberic value (e.g. a1) both will be converted to a factor. Overall this isn't too much of a concern, but if you end up wanting match data.frames for example
df3 <- df1[df1$v1 %in% df2$v1,]
where df1 has been has been converted and df2 contains a non-converted data.frame or similar, this may cause some problems. The work around is that you briefly have to run
df2 <- df2 %>% mutate_each(funs(toupper), v1)
#or
df2 <- df2 %>% mutate_each(df2, funs(toupper))
#and then
df3 <- df1[df1$v1 %in% df2$v1,]
If you work with genomic data, this is when knowing this can come in handy.
I like to use this sort of process to parse commands as strings into enumerations. I normally have one of the enumerations as "unknown" so it helps to have that returned when the others are not found (even on a case insensitive basis) rather than null (that meaning there is no value). Hence I use this approach.
static <E extends Enum<E>> Enum getEnumValue(String what, Class<E> enumClass) {
Enum<E> unknown=null;
for (Enum<E> enumVal: enumClass.getEnumConstants()) {
if (what.compareToIgnoreCase(enumVal.name()) == 0) {
return enumVal;
}
if (enumVal.name().compareToIgnoreCase("unknown") == 0) {
unknown=enumVal;
}
}
return unknown;
}
The accepted answer didn't work for me. To fix that issue, I had to right-click on the file that was locked, select repo-browser
. This opened a popup with the files as they are on the SVN server. I then right-clicked on the locked file and selected break lock
.
When I closed the repository browser, back on explorer I could finally commit!
You can also take advantage of the fact that a lambda or anonymous method can close over variables in its enclosing scope.
MyType result;
SimpleUsing.DoUsing(db =>
{
result = db.SomeQuery(); //whatever returns the MyType result
});
//do something with result
Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:
All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.
This restriction accomplishes four functions, 1st and 3rd are important in this particular case:
And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.
One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.
There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:
If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.
Hope this will helps you to find the proper solution!
At this moment, PHP itself does not provide a way to get the project's root directory for sure.
But you can implement a very simple method yourself that will do exactly what you're looking for.
Solution
Create a new file in your project, let say D:/workspace/MySystem/Code/FilesManager.php
(use whatever name and path suit you the best). Then, use the following code:
<?php
class FilesManager
{
public static function rootDirectory()
{
// Change the second parameter to suit your needs
return dirname(__FILE__, 2);
}
}
Now you can do this in, let's say D:/workspace/MySystem/Code/a/b/c/Feature.php
:
echo FilesManager::rootDirectory();
And the expected result should be:
"D:/workspace/MySystem"
The output will be the same no matter where your "feature" file is located in the project.
Explanation
dirname is used to return the parent directory of the first parameter. We use the magic constant __FILE__
to give it FilesManager.php
's path. The second parameter tells how many times to go up in the hierarchy. In this case, we need to do it twice, but it really depends where you put your file in the hierarchy. You can omit the second parameter if you only need to got up once, meaning the file is located in the root. But then, you can return __DIR__
directly instead.
This solution is guaranteed to work, no matter where the root is located on your server. Unless you end up moving the utility class somewhere else in the hierarchy.
Additional note
I'd avoid using DOCUMENT_ROOT for the following reasons (according to this answer):
In the case of a dialog, it has a property called draggable, set it to false.
$("#yourDialog").dialog({
draggable: false
});
Eventhough the question is old, i tried the proposed solution and it did not work for the dialog. Hope this may help others like me.
Try using RegisterScriptBlock. Example from the link:
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
String csname2 = "ButtonClickScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
{
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
cstext2.Append("Form1.Message.value='Text from client script.'} </");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
}
}
If you still have the problem after trying all the solutions above, please try modify the API Level as shown below. Incorrect API Level may also cause the problem.
(Get-Content c:\FileWithEmptyLines.txt) |
Foreach { $_ -Replace "Old content", " New content" } |
Set-Content c:\FileWithEmptyLines.txt;
If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.
try {
//Dangerous code: could throw an error
} catch (Exception e) {
//Cleanup: make sure that this methods variables and such are in the desired state
throw e;
}
This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.
An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.
select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1
Just include #import "myProject-Swift.h" in .m or .h file
P.S You will not find "myProject-Swift.h" in file inspector it's hidden. But it is generated by app automatically.
We can alter in the default 'jquery-ui.css' file as below given code:
div.ui-datepicker {
font-size: 80%;
}
However, changing the default 'jquery-ui.css' file is not recommended as it might have been used somewhere else in the project. Changing values in the default file can alter datepicker font in other webpages where it has been used.
I used the below code to alter "font-size". I placed it just after datepicker() is called as shown below.
<script>
$(function () {
$( "#datepicker" ).datepicker();
$("div.ui-datepicker").css("font-size", "80%")
});
</script>
Hope this helps...
Encapsulation is hiding information.
Abstraction is hiding the functionality details.
Encapsulation is performed by constructing the class. Abstraction is achieved by creating either Abstract Classes or Interfaces on top of your class.
In the example given in the question, we are using the class for its functionality and we don't care about how the device achieves that. So we can say the details of the phone are "abstracted" from us.
Encapsulation is hiding WHAT THE PHONE USES to achieve whatever it does; Abstraction is hiding HOW IT DOES it.-
You can try this
$('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});
The $('div.easy_editor')
refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.
You should have one listview in your mainlist.xml
file with id as @android:id/list
<ListView
android:id="@android:id/list"
android:layout_height="wrap_content"
android:layout_height="fill_parent"/>
Add . (current directory) to your PATH variable.
You can do this by editing your .profile file.
put following line in your .profile file
PATH=$PATH:.
Just make sure to add Shebang (#!/bin/bash
) line at the starting of your script and make the script executable(using chmod +x <File Name>
).
I am only mentioning this as no one mentioned this. There's no programming language I am aware of which allows manipulation of the underlying filesystem. All programming languages rely on OS interrupts to actually get these things done. JavaScript that runs in the browser only has browser "interrupts" to work with which generally does not grant filesystem access unless the browser has been implemented to support such interrupts.
This being said the obvious way to have file system access using JavaScript is to use Node.js which does have the capability of interacting with the underlying OS directly.
I have made my own solution using NSTimer and Alamofire:
import Alamofire
public class ConnectionHelper: NSObject {
var request: Alamofire.Request?
func isInternetConnected(completionHandler: Bool -> Void) {
NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "requestTimeout", userInfo: nil, repeats: false)
request = Alamofire
.request(
Method.HEAD,
"http://www.testurl.com"
)
.response { response in
if response.3?.code == -999 {
completionHandler(
false
)
} else {
completionHandler(
true
)
}
}
}
func requestTimeout() {
request!.cancel()
}
}
The NSTimer is used as a timeout, and was used due to unreliable results using the Alamofire timeout. The request should be made to a URL you trust to be reliable, such as your own server or the server that is hosting the services you depend on.
When the timer expires, the request is cancelled and the results are returned using a completion handler.
Usage:
ConnectionHelper().isInternetConnected() { internetConnected in
if internetConnected {
// Connected
} else {
// Not connected
}
}
There is a Free tool named binarydoc which can generate UML Sequence Diagram
, or Control Flow Graph
(CFG
) from the bytecode
(instead of source code) of a Java method.
Here is an sample diagram binarydoc generated for the java method java.net.AbstractPlainSocketImpl.getInputStream:
java.net.AbstractPlainSocketImpl.getInputStream
:java.net.AbstractPlainSocketImpl.getInputStream
:I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:
it’s easier to use std::function as in:
void draw(int grid, std::function<void()> element)
and then call as:
grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));
or even easier:
grid.draw(12, [&]{a.draw()});
where you create a lambda that calls the object capturing it by reference
I think this is what you want, I already tested this code and works
The tools used are: (all these tools can be downloaded as Nuget packages)
http://fluentassertions.codeplex.com/
http://autofixture.codeplex.com/
https://nuget.org/packages/AutoFixture.AutoMoq
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();
var sut = fixture.CreateAnonymous<Transfer>();
myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
.Throws<System.IO.IOException>();
sut.Invoking(x =>
x.TransferFiles(
myInterface.Object,
It.IsAny<string>(),
It.IsAny<string>()
))
.ShouldThrow<System.IO.IOException>();
Edited:
Let me explain:
When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer
So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code
When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs
In this case your external dependency is IFileConnection
so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected
var fixture = new Fixture().Customize(new AutoMoqCustomization());
: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq
var myInterface = fixture.Freeze<Mock<IFileConnection>>();
: This freezes the IFileConnection
dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object
var sut = fixture.CreateAnonymous<Transfer>();
: Here AutoFixture is creating the SUT for us
myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>();
Here you are configuring the dependency to throw an exception whenever the Get
method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception
sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();
: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles
real method from the SUT and as parameters it receives the mocked IFileConnection
so whenever you call the IFileConnection.Get
in the normal flow of your SUT TransferFiles
method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>()
(from the FluentAssertions library)
References recommended:
http://martinfowler.com/articles/mocksArentStubs.html
http://misko.hevery.com/code-reviewers-guide/
http://misko.hevery.com/presentations/
http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded
http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded
It will probably be best to use UICollectionViewDelegate methods: (Swift 3)
// Called before the cell is displayed
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
print(indexPath.row)
}
// Called when the cell is displayed
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
print(indexPath.row)
}
This One Method For Published Solution To Show SpeciFic Page on startup.
Here Is the Route Example to Redirect to Specific Page...
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "YourSolutionName.Controllers" }
);
}
}
By Default Home Controllers Index method is executed when application is started, Here You Can Define yours.
Note : I am Using Visual Studio 2013 and "YourSolutionName" is to changed to your project Name..
Use []
notation for string representations of properties:
console.log(obj[name]);
Otherwise it's looking for the "name" property, rather than the "a" property.
Here's my quick and simple function for getting the absolute path from a relative path.
The difference from the accepted answer is that this function can handle relative paths that moves up to parent folders.
Example:
Workbooks.Open FileName:=GetAbsolutePath("..\..\TRICATEndurance Summary.html")
Code:
' Gets an absolute path from a relative path in the active workbook
Public Function GetAbsolutePath(relativePath As String) As String
Dim absPath As String
Dim pos As Integer
absPath = ActiveWorkbook.Path
' Make sure paths are in correct format
relativePath = Replace(relativePath, "/", "\")
absPath = Replace(absPath, "/", "\")
Do While Left$(relativePath, 3) = "..\"
' Remove level from relative path
relativePath = Mid$(relativePath, 4)
' Remove level from absolute path
pos = InStrRev(absPath, "\")
absPath = Left$(absPath, pos - 1)
Loop
GetAbsolutePath = PathCombine(absPath, relativePath)
End Function
Before I get to my reiterated answer; I am confessing that the only answer I would accept here is this one by KM. above. I down voted the other answers because none of them actually answered the question asked or they were not adequate. PRINT output does indeed show up in the Message window, but that is not what was asked at all.
Why doesn't the PRINT statement output show during my Stored Procedure execution?
The short version of this answer is that you are sending your sproc's execution over to the SQL server and it isn't going to respond until it is finished with the whole transaction. Here is a better answer located at this external link.
Don't do these things
Alternative to PRINT inside of a Stored Procedure
Really this is kind of an icky work around in my opinion because the syntax is confusing in the context that it is being used in, but who knows maybe it will be updated in the future by Microsoft. I just don't like the idea of raising an error for the sole purpose of printing out debug info...
It seems like the only way around this issue is to use, as has been explained numerous times already RAISERROR WITH NOWAIT. I am providing an example and pointing out a small problem with this approach:
ALTER
--CREATE
PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample]
AS
BEGIN
SET NOCOUNT ON;
-- This will print immediately
RAISERROR ('RE Start', 0, 1) WITH NOWAIT
SELECT 1;
-- Five second delay to simulate lengthy execution
WAITFOR DELAY '00:00:05'
-- This will print after the five second delay
RAISERROR ('RE End', 0, 1) WITH NOWAIT
SELECT 2;
END
GO
EXEC [dbo].[PrintVsRaiseErrorSprocExample]
Both SELECT statement results will only show after the execution is finished and the print statements will show in the order shown above.
Potential problem with this approach
Let's say you have both your PRINT statement and RAISERROR statement one after the other, then they both print. I'm sure this has something to do with buffering, but just be aware that this can happen.
ALTER
--CREATE
PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample2]
AS
BEGIN
SET NOCOUNT ON;
-- Both the PRINT and RAISERROR statements will show
PRINT 'P Start';
RAISERROR ('RE Start', 0, 1) WITH NOWAIT
SELECT 1;
WAITFOR DELAY '00:00:05'
-- Both the PRINT and RAISERROR statements will show
PRINT 'P End'
RAISERROR ('RE End', 0, 1) WITH NOWAIT
SELECT 2;
END
GO
EXEC [dbo].[PrintVsRaiseErrorSprocExample2]
Therefore the work around here is, don't use both PRINT and RAISERROR, just choose one over the other. If you want your output to show during the execution of a sproc then use RAISERROR WITH NOWAIT.
It turns out that this is important enough to get it's own module...
import base64
base64.b64encode(b'your name') # b'eW91ciBuYW1l'
base64.b64encode('your name'.encode('ascii')) # b'eW91ciBuYW1l'
I fixed this issue by adding a slash
at the beginning to my relative path
If the issue is to create all the necessary parent directories, you could consider using os.MkDirAll()
MkdirAll
creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.
The path_test.go is a good illustration on how to use it:
func TestMkdirAll(t *testing.T) {
tmpDir := TempDir()
path := tmpDir + "/_TestMkdirAll_/dir/./dir2"
err := MkdirAll(path, 0777)
if err != nil {
t.Fatalf("MkdirAll %q: %s", path, err)
}
defer RemoveAll(tmpDir + "/_TestMkdirAll_")
...
}
(Make sure to specify a sensible permission value, as mentioned in this answer)
For PyCharm Community Edition 2016.3.2 it is:
"Project Interpreter" -> Top right settings icon -> "More".
Then on the right side there should be a packages icon. When hovering over it it should say "Show paths for selected interpreter". Click it.
Then click the "Add" button or press "alt+insert" to add a new path.
Lets say if the class will not have more than one instance ever, then which one takes more memory:
private static final int ID = 250; or private final int ID = 250;
I've understood that static will refer to the class type with only one copy in the memory and non static will be in a new memory location for each instance variable. However internally if we just compare 1 instance of the same class ever (i.e. more than 1 instance would not be created), then is there any overhead in terms of space used by 1 static final variable?
There are various ways to achieve this. Here are three.
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println("using entrySet and toString");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry);
}
System.out.println();
System.out.println("using entrySet and manual string creation");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
System.out.println();
System.out.println("using keySet");
for (String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
System.out.println();
using entrySet and toString
key1=value1
key2=value2
key3=value3
using entrySet and manual string creation
key1=value1
key2=value2
key3=value3
using keySet
key1=value1
key2=value2
key3=value3
In the root web.config
for your project, under the system.web
node:
<system.web>
<httpRuntime maxUrlLength="10999" maxQueryStringLength="2097151" />
...
In addition, I had to add this under the system.webServer
node or I got a security error for my long query strings:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxUrl="10999" maxQueryString="2097151" />
</requestFiltering>
</security>
...
another solution:
add src/myproject
to $GOPATH.
Then import "mylib"
will compile.
I suggest to use a container for each img
p
like this:
<div class="image123">
<div style="float:left;margin-right:5px;">
<img src="/images/tv.gif" height="200" width="200" />
<p style="text-align:center;">This is image 1</p>
</div>
<div style="float:left;margin-right:5px;">
<img class="middle-img" src="/images/tv.gif/" height="200" width="200" />
<p style="text-align:center;">This is image 2</p>
</div>
<div style="float:left;margin-right:5px;">
<img src="/images/tv.gif/" height="200" width="200" />
<p style="text-align:center;">This is image 3</p>
</div>
</div>
Then apply float:left
to each container. I add and 5px
margin right
so there is a space between each image. Also alway close your elements. Maybe in html img
tag is not important to close but in XHTML is.
Also a friendly advice. Try to avoid inline styles as much as possible. Take a look here:
html
<div class="image123">
<div>
<img src="/images/tv.gif" />
<p>This is image 1</p>
</div>
<div>
<img class="middle-img" src="/images/tv.gif/" />
<p>This is image 2</p>
</div>
<div>
<img src="/images/tv.gif/" />
<p>This is image 3</p>
</div>
</div>
css
div{
float:left;
margin-right:5px;
}
div > img{
height:200px;
width:200px;
}
p{
text-align:center;
}
It's generally recommended that you use linked style sheets because:
For me, who is running with a monorepo, there was a hidden react-native version inside yarn.lock. It was not present in any package.json, but was never deleted.
I removed that particular react-native version from yarn.lock, and did a
yarn install
This cleaned out alot of old stuff and made sure that things was working fine.
I found simple way, it using shift()
function waitReq(id)
{
jQuery.ajax(
{
type: 'POST',
url: ajaxurl,
data:
{
"page": id
},
success: function(resp)
{
...........
// check array length if not "0" continue to use next array value
if(ids.length)
{
waitReq(ids.shift()); // 2
)
},
error: function(resp)
{
....................
if(ids.length)
{
waitReq(ids.shift());
)
}
});
}
var ids = [1, 2, 3, 4, 5];
// shift() = delete first array value (then print)
waitReq(ids.shift()); // print 1
The neatest command is
grep -vc ^$ fileName
with -c
option, you don't even need wc -l
Also make sure that you have allowed codeigniter to log the type of messages you want in a config file.
i.e $config['log_threshold'] = [log_level ranges 0-4];
Here's my best try so far. It handles the formats above but I'm sure I'm missing some other possible formats.
^\d?(?:(?:[\+]?(?:[\d]{1,3}(?:[ ]+|[\-.])))?[(]?(?:[\d]{3})[\-/)]?(?:[ ]+)?)?(?:[a-zA-Z2-9][a-zA-Z0-9 \-.]{6,})(?:(?:[ ]+|[xX]|(i:ext[\.]?)){1,2}(?:[\d]{1,5}))?$
You can also use Object.assign
from ECMAScript 2015
. It also allows you to add nested attributes at once. E.g.:
const myObject = {};
Object.assign(myObject, {
firstNewAttribute: {
nestedAttribute: 'woohoo!'
}
});
Ps: This will not override the existing object with the assigned attributes. Instead they'll be added. However if you assign a value to an existing attribute then it would be overridden.
SELECT * FROM table WHERE field1 NOT LIKE '%$x%';
(Make sure you escape $x properly beforehand to avoid SQL injection)
Edit: NOT IN
does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%'
can use an index. LIKE '%xxx'
or LIKE '%xxx%'
can't.
Another option is to use input
field of a regexp match result:
str = 'XYZ test';
switch (str) {
case (str.match(/^xyz/) || {}).input:
console.log("Matched a string that starts with 'xyz'");
break;
case (str.match(/test/) || {}).input:
console.log("Matched the 'test' substring");
break;
default:
console.log("Didn't match");
break;
}
You can use this implementation that ExecutorService provides
invokeAll(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit)
as
executor.invokeAll(Arrays.asList(task), 2 , TimeUnit.SECONDS);
However, in my case, I could not as Arrays.asList took extra 20ms.
From a user experience stand-point, you don't want a major action to be done passively.
Something major like a window close should be the result of an action by the user.
Using jQuery:
// Listen for click on toggle checkbox
$('#select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
} else {
$(':checkbox').each(function() {
this.checked = false;
});
}
});
HTML:
<input type="checkbox" name="checkbox-1" id="checkbox-1" />
<input type="checkbox" name="checkbox-2" id="checkbox-2" />
<input type="checkbox" name="checkbox-3" id="checkbox-3" />
<!-- select all boxes -->
<input type="checkbox" name="select-all" id="select-all" />
Reference: Practical usage of closures
In practice, closures may create elegant designs, allowing customization of various calculations, deferred calls, callbacks, creating encapsulated scope, etc.
An example is the sort method of arrays which accepts the sort condition function as an argument:
[1, 2, 3].sort(function (a, b) {
... // Sort conditions
});
Mapping functionals as the map method of arrays which maps a new array by the condition of the functional argument:
[1, 2, 3].map(function (element) {
return element * 2;
}); // [2, 4, 6]
Often it is convenient to implement search functions with using functional arguments defining almost unlimited conditions for search:
someCollection.find(function (element) {
return element.someProperty == 'searchCondition';
});
Also, we may note applying functionals as, for example, a forEach method which applies a function to an array of elements:
[1, 2, 3].forEach(function (element) {
if (element % 2 != 0) {
alert(element);
}
}); // 1, 3
A function is applied to arguments (to a list of arguments — in apply, and to positioned arguments — in call):
(function () {
alert([].join.call(arguments, ';')); // 1;2;3
}).apply(this, [1, 2, 3]);
Deferred calls:
var a = 10;
setTimeout(function () {
alert(a); // 10, after one second
}, 1000);
Callback functions:
var x = 10;
// Only for example
xmlHttpRequestObject.onreadystatechange = function () {
// Callback, which will be called deferral ,
// when data will be ready;
// variable "x" here is available,
// regardless that context in which,
// it was created already finished
alert(x); // 10
};
Creation of an encapsulated scope for the purpose of hiding auxiliary objects:
var foo = {};
(function (object) {
var x = 10;
object.getX = function _getX() {
return x;
};
})(foo);
alert(foo.getX()); // Get closured "x" – 10
Aren't you missing the #include "B.h" in A.h?
For MAMP running on Mac OSX
Find out the what version of PHP and install the right version via brew
brew install homebrew/php/php56-imagick
Add the extension by modifying the php.ini template in MAMP
Verify the Imagick
Use the GeoCoding API
For example, to lookup zip 77379 use a request like this:
As an empty string is not valid JSON it would be incorrect for JSON.parse('')
to return null
because "null"
is valid JSON. e.g.
JSON.parse("null");
returns null
. It would be a mistake for invalid JSON to also be parsed to null.
While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.
Which is to say a string that contains two quotes is not the same thing as an empty string.
JSON.parse('""');
will parse correctly, (returning an empty string). But
JSON.parse('');
will not.
Valid minimal JSON strings are
The empty object '{}'
The empty array '[]'
The string that is empty '""'
A number e.g. '123.4'
The boolean value true 'true'
The boolean value false 'false'
The null value 'null'
You can use == to compare with a zero value composite literal because all fields are comparable:
if (Session{}) == session {
fmt.Println("is zero value")
}
Because of a parsing ambiguity, parentheses are required around the composite literal in the if condition.
The use of ==
above applies to structs where all fields are comparable. If the struct contains a non-comparable field (slice, map or function), then the fields must be compared one by one to their zero values.
An alternative to comparing the entire value is to compare a field that must be set to a non-zero value in a valid session. For example, if the player id must be != "" in a valid session, use
if session.playerId == "" {
fmt.Println("is zero value")
}
Here is a slightly improved version:
urls = [
"http://stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
"Stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
"http://stackoverflow.com/some/folder?test=/questions/9626535/get-domain-name-from-url",
"https://StackOverflow.com:8080?test=/questions/9626535/get-domain-name-from-url",
"stackoverflow.com?test=questions&v=get-domain-name-from-url"]
for url in urls:
spltAr = url.split("://");
i = (0,1)[len(spltAr)>1];
dm = spltAr[i].split("?")[0].split('/')[0].split(':')[0].lower();
print dm
Output
stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com
Fiddle: https://pyfiddle.io/fiddle/23e4976e-88d2-4757-993e-532aa41b7bf0/?i=true
If you have sed:
sed -e '/REFERENCE/d' -e '/ERROR/d' [FILENAME]
Where FILENAME
is the name of the text file with the good & bad lines
Here is another solution, now using a match expression
Source filtering allows to control how the _source field is returned with every hit.
Tested with Elastiscsearch version 5.5
The keyword includes
defines the specifics fields.
GET /my_indice/my_indice_type/_search
{
"_source": {
"includes": [
"my_especific_field"
]
},
"query": {
"bool": {
"must": [
{
"match": {
"_id": "%my_id_here_without_percent%"
}
}
]
}
}
}
That error message usually means that either the password we are using doesn't match what MySQL thinks the password should be for the user we're connecting as, or a matching MySQL user doesn't exist (hasn't been created).
In MySQL, a user is identified by both a username ("test2") and a host ("localhost").
The error message identifies the user ("test2") and the host ("localhost") values...
'test2'@'localhost'
We can check to see if the user exists, using this query from a client we can connect from:
SELECT user, host FROM mysql.user
We're looking for a row that has "test2" for user, and "localhost" for host.
user host
------- -----------
test2 127.0.0.1 cleanup
test2 ::1
test2 localhost
If that row doesn't exist, then the host may be set to wildcard value of %
, to match any other host that isn't a match.
If the row exists, then the password may not match. We can change the password (if we're connected as a user with sufficient privileges, e.g. root
SET PASSWORD FOR 'test2'@'localhost' = PASSWORD('mysecretcleartextpassword')
We can also verify that the user has privileges on objects in the database.
GRANT SELECT ON jobs.* TO 'test2'@'localhost'
EDIT
If we make changes to mysql privilege tables with DML operations (INSERT,UPDATE,DELETE), those changes will not take effect until MySQL re-reads the tables. We can make changes effective by forcing a re-read with a FLUSH PRIVILEGES
statement, executed by a privileged user.
Late to the party, but what about
things.stream()
.map(this::resolve)
.filter(Optional::isPresent)
.findFirst().get();
You can get rid of the last get() if you create a util method to convert optional to stream manually:
things.stream()
.map(this::resolve)
.flatMap(Util::optionalToStream)
.findFirst();
If you return stream right away from your resolve function, you save one more line.
Bootstrap 4 removed .btn-group-justified. As a replacement you can use <div class="btn-group d-flex" role="group"></div>
as a wrapper around elements with .w-100.
Try this:
<div class="btn-group d-flex" role="group>
<button type="button" class="btn btn-primary w-100">Submit</button>
<button type="button" class="btn btn-primary w-100">Cancel</button>
</div>
If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:
String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e
The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc
sample.codePointCount(0, sample.length()) // returns 5
http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/
Just follow any of these:
For jackson it should work:
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
//will return json in string
For gson it should work:
Gson gson = new Gson();
return Response.ok(gson.toJson(yourClass)).build();
The following works with Java 7/8, secure urls, and shows how to add a cookie to your request as well. Note this is mostly a direct copy of this other great answer on this page, but added the cookie example, and clarification in that it works with secure urls as well ;-)
If you need to connect to a server with an invalid certificate or self signed certificate, this will throw security errors unless you import the certificate. If you need this functionality, you could consider the approach detailed in this answer to this related question on StackOverflow.
String result = getUrlAsString("https://www.google.com");
System.out.println(result);
outputs
<!doctype html><html itemscope="" .... etc
import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static String getUrlAsString(String url)
{
try
{
URL urlObj = new URL(url);
URLConnection con = urlObj.openConnection();
con.setDoOutput(true); // we want the response
con.setRequestProperty("Cookie", "myCookie=test123");
con.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
String newLine = System.getProperty("line.separator");
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine + newLine);
}
in.close();
return response.toString();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
According to http://caniuse.com/#feat=flexbox:
"IE10 and IE11 default values for flex
are 0 0 auto
rather than 0 1 auto
, as per the draft spec, as of September 2013"
So in plain words, if somewhere in your CSS you have something like this: flex:1
, that is not translated the same way in all browsers. Try changing it to 1 0 0
and I believe you will immediately see that it -kinda- works.
The problem is that this solution will probably mess up firefox, but then you can use some hacks to target only Mozilla and change it back:
@-moz-document url-prefix() {
#flexible-content{
flex: 1;
}
}
Since flexbox
is a W3C Candidate and not official, browsers tend to give different results, but I guess that will change in the immediate future.
If someone has a better answer I would like to know!
You can use join()
to wait for all threads to finish. Keep all objects of threads in the global ArrayList at the time of creating threads. After that keep it in loop like below:
for (int i = 0; i < 10; i++)
{
Thread T1 = new Thread(new ThreadTest(i));
T1.start();
arrThreads.add(T1);
}
for (int i = 0; i < arrThreads.size(); i++)
{
arrThreads.get(i).join();
}
Check here for complete details: http://www.letmeknows.com/2017/04/24/wait-for-threads-to-finish-java
public static void copyFile(File oldLocation, File newLocation) throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
Multi update was added recently, so is only available in the development releases (1.1.3). From the shell you do a multi update by passing true
as the fourth argument to update()
, where the the third argument is the upsert argument:
db.test.update({foo: "bar"}, {$set: {test: "success!"}}, false, true);
For versions of mongodb 2.2+ you need to set option multi true to update multiple documents at once.
db.test.update({foo: "bar"}, {$set: {test: "success!"}}, {multi: true})
For versions of mongodb 3.2+ you can also use new method updateMany()
to update multiple documents at once, without the need of separate multi
option.
db.test.updateMany({foo: "bar"}, {$set: {test: "success!"}})
There are two ways of doing it.
1.Right click on drawable New->Image Asset-> select your highest resolution image rest will be created automatically. once you finish you can see different resolution inside drawable folder
Now yourprojectname->app->src->main->res->
Aila You can see your drawable folders with hdpi mdpi etc.
I know this is a little old, but this but here is a concise function for counting regex patterns.
def regex_cnt(string, pattern):
return len(re.findall(pattern, string))
string = 'abc123'
regex_cnt(string, '[0-9]')
You could do this, which facilitates reading:
>&2 echo "error"
>&2
copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was originally referring to. For more information see the Bash Hackers Illustrated Redirection Tutorial.
If it's a single byte, just cast the byte
to a char
and it should work out to be fine i.e. give a char
entity corresponding to the codepoint value of the given byte. If not, use the String
constructor as mentioned elsewhere.
char ch = (char)0x63;
System.out.println(ch);
If you really want to micro optimise your code your best approach is always benchmarking.
The .net framework has an excellent stopwatch implementation - System.Diagnostics.Stopwatch
An answer that doesn't rely on numpy, either:
import math
from collections import Counter
def eta(data, unit='natural'):
base = {
'shannon' : 2.,
'natural' : math.exp(1),
'hartley' : 10.
}
if len(data) <= 1:
return 0
counts = Counter()
for d in data:
counts[d] += 1
ent = 0
probs = [float(c) / len(data) for c in counts.values()]
for p in probs:
if p > 0.:
ent -= p * math.log(p, base[unit])
return ent
This will accept any datatype you could throw at it:
>>> eta(['mary', 'had', 'a', 'little', 'lamb'])
1.6094379124341005
>>> eta([c for c in "mary had a little lamb"])
2.311097886212714
The answer provided by @Jarad suggested timings as well. To that end:
repeat_number = 1000000
e = timeit.repeat(
stmt='''eta(labels)''',
setup='''labels=[1,3,5,2,3,5,3,2,1,3,4,5];from __main__ import eta''',
repeat=3,
number=repeat_number)
Timeit results: (I believe this is ~4x faster than the best numpy approach)
print('Method: {}, Avg.: {:.6f}'.format("eta", np.array(e).mean()))
Method: eta, Avg.: 10.461799
It would be more beneficial for us if we could see the actual project structure, as the classes alone do not say that much.
Assuming that both .cs files are in the same project (if they are in different projects inside the same solution, you'd have to add a reference to the project containing Class2.cs), you can click on the Class2
occurrence in your code that is underlined in red and press CTRL + . (period) or click on the blue bar that should be there. The first option appearing will then add the appropriate using
statement automatically. If there is no such menu, it may indicate that there is something wrong with the project structure or a reference missing.
You could try making Class2
public
, but it sounds like this can't be a problem here, since by default what you did is internal class Class2
and thus Class2
should be accessible if both are living in the same project/assembly. If you are referencing a different assembly or project wherein Class2
is contained, you have to make it public
in order to access it, as internal
classes can't be accessed from outside their assembly.
As for renaming: You can click Program.cs
in the Solution Explorer and press F2 to rename it. It will then open up a dialog window asking you if the class Program
itself and all references thereof should be renamed as well, which is usually what you want. Or you could just rename the class Program
in the declaration and again open up the menu with the small blue bar (or, again, CTRL+.) and do the same, but it won't automatically rename the actual file accordingly.
Edit after your question edit: I have never used this option you used, but from quick checking I think that it's really not inside the same project then. Do the following when adding new classes to a project: In the Solution Explorer, right click the project you created and select [Add] -> [Class] or [Add] -> [New Item...] and then select 'Class'. This will automatically make the new class part of the project and thus the assembly (the assembly is basically the 'end product' after building the project). For me, there is also the shortcut Alt+Shift+C working to create a new class.
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.
write.csv(Data_output, "output.csv", row.names = F, quote = F)
Define the class before you use it:
class Something:
def out(self):
print("it works")
s = Something()
s.out()
You need to pass self
as the first argument to all instance methods.
TypeError
# the following line causes a TypeError
# test = 'Here is a test that can be run' + 15 + 'times'
# same intent with a f-string
i = 15
test = f'Here is a test that can be run {i} times'
print(test)
# output
'Here is a test that can be run 15 times'
i = 15
# t = 'test' + i # will cause a TypeError
# should be
t = f'test{i}'
print(t)
# output
'test15'
int
.dtype
i = '15'
# t = 15 + i # will cause a TypeError
# convert the string to int
t = 15 + int(i)
print(t)
# output
30
TypeError
shown in the question title, which is why people seem to be coming to this question.TypeError
is caused because message
type is a str
.char
, a str
type, to an int
char
to an int
secret_string
needs to be initialized with 0
instead of ""
.ValueError: chr() arg not in range(0x110000)
because 7429146
is out of range for chr()
.message = input("Enter a message you want to be revealed: ")
secret_string = 0
for char in message:
char = int(char)
value = char + 742146
secret_string += ord(chr(value))
print(f'\nRevealed: {secret_string}')
# Output
Enter a message you want to be revealed: 999
Revealed: 2226465
message
is now an int
type, so for char in message:
causes TypeError: 'int' object is not iterable
message
is converted to int
to make sure the input
is an int
.str()
value
to Unicode with chr
ord
while True:
try:
message = str(int(input("Enter a message you want to be decrypt: ")))
break
except ValueError:
print("Error, it must be an integer")
secret_string = ""
for char in message:
value = int(char) + 10000
secret_string += chr(value)
print("Decrypted", secret_string)
# output
Enter a message you want to be decrypt: 999
Decrypted ???
Enter a message you want to be decrypt: 100
Decrypted ???
The .NET garbage collector takes care of all this for you.
It is able to determine when objects are no longer referenced and will (eventually) free the memory that had been allocated to them.
First of all, this line
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click()
there.
If you read the JavaScript you've got there, document.getElementById('foo')
it's looking for an HTML element with an ID of foo
. You don't have one. Give your image that ID:
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
Alternatively, you could throw the JS in a function and put an onclick in your HTML:
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />
I suggest you do some reading up on JavaScript and HTML though.
The others are right about needing to move the <img>
above the JS click binding too.
this might be repetitive. I was trying to use pycharm to run flask - had anaconda 3, pycharm 2019.1.1 and windows 10. Created a new conda environment - it threw errors. Followed these steps -
Used the cmd to install python and flask after creating environment as suggested above.
Followed this answer.
Obviously kept the correct python interpreter (the one in the environment) everywhere.
Things you can add to declarations: [] in modules
Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.
I'd do it like this jsFiddle example.
JavaScript:
function check(elem) {
document.getElementById('mySelect1').disabled = !elem.selectedIndex;
}
HTML:
<form>
<select id="mySelect" onChange="check(this);">
<option>No</option>
<option>Yes</option>
</select>
<select id="mySelect1" disabled="disabled" >
<option>Dep1</option>
<option>Dep2</option>
<option>Dep3</option>
<option>Dep4</option>
</select>
</form>
64-bit tools are not available on Visual C++ Express by default. To enable 64-bit tools on Visual C++ Express, install the Windows Software Development Kit (SDK) in addition to Visual C++ Express. Otherwise, an error occurs when you attempt to configure a project to target a 64-bit platform using Visual C++ Express.
How to: Configure Visual C++ Projects to Target 64-Bit Platforms
From what I've learned with Alex Cowan in the course Continuous Delivery & DevOps, CI and CD is part of a product pipeline that consists in the time it goes from an Observations to a Released Product.
From Observations to Designs the goal is to get high quality testable ideas. This part of the process is considered Continuous Design.
What happens after, when we go from the Code onwards, it's considered a Continuous Delivery capability whose aim is to execute the ideas and release to the customer very fast (you can read Jez Humble's book Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation for more details). The following pipeline explains which steps Continuous Integration (CI) and Continuous Delivery (CD) consist of.
Continuous Integration, as Mattias Petter Johansson explains,
is when a software team has habit of doing multiple merges per day and they have an automated verification system in place to check those merges for problems.
(you can watch the following two videos for a more pratical overview using CircleCI - Getting started with CircleCI - Continuous Integration P2 and Running CircleCI on Pull Request).
One can specify the CI/CD pipeline as following, that goes from New Code to a released Product.
The first three steps have to do with Tests, extending the boundary of what's being tested.
Continuous Deployment, on the other hand, is to handle the Deployment automatically. So, any code commit that passes the automated testing phase is automatically released into the production.
Note: This isn't necessarily what your pipelines should look like, yet they can serve as reference.
You can just add style="min-height:100vh" to your page content conteiner and place footer in another conteiner
Set the second function parameter to true if you require an associative array
Some versions of php require a 2nd paramter of true if you require an associative array
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );
Actually I think using plain slices is the best solution in this case:
for i in range(0, len(data), 100):
chunk = data[i:i + 100]
...
If you want to avoid copying the slices, you could use itertools.islice()
, but it doesn't seem to be necessary here.
The itertools()
documentation also contains the famous "grouper" pattern:
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
You would need to modify it to treat the last chunk correctly, so I think the straight-forward solution using plain slices is preferable.
The Visitor design pattern works really well for "recursive" structures like directory trees, XML structures, or document outlines.
A Visitor object visits each node in the recursive structure: each directory, each XML tag, whatever. The Visitor object doesn't loop through the structure. Instead Visitor methods are applied to each node of the structure.
Here's a typical recursive node structure. Could be a directory or an XML tag. [If your a Java person, imagine of a lot of extra methods to build and maintain the children list.]
class TreeNode( object ):
def __init__( self, name, *children ):
self.name= name
self.children= children
def visit( self, someVisitor ):
someVisitor.arrivedAt( self )
someVisitor.down()
for c in self.children:
c.visit( someVisitor )
someVisitor.up()
The visit
method applies a Visitor object to each node in the structure. In this case, it's a top-down visitor. You can change the structure of the visit
method to do bottom-up or some other ordering.
Here's a superclass for visitors. It's used by the visit
method. It "arrives at" each node in the structure. Since the visit
method calls up
and down
, the visitor can keep track of the depth.
class Visitor( object ):
def __init__( self ):
self.depth= 0
def down( self ):
self.depth += 1
def up( self ):
self.depth -= 1
def arrivedAt( self, aTreeNode ):
print self.depth, aTreeNode.name
A subclass could do things like count nodes at each level and accumulate a list of nodes, generating a nice path hierarchical section numbers.
Here's an application. It builds a tree structure, someTree
. It creates a Visitor
, dumpNodes
.
Then it applies the dumpNodes
to the tree. The dumpNode
object will "visit" each node in the tree.
someTree= TreeNode( "Top", TreeNode("c1"), TreeNode("c2"), TreeNode("c3") )
dumpNodes= Visitor()
someTree.visit( dumpNodes )
The TreeNode visit
algorithm will assure that every TreeNode is used as an argument to the Visitor's arrivedAt
method.
*You can use layout_weight
properties. If you want to take 70% of parent width you must set child layout_width
property value 0dp, like android:layout_width="0dp"
*
My workaround for this issue was to set display: inline
to the image element.
With this, your image and text will be aligned to the right if you set text-align: right
from a parent container.
Use:
<a href="wantedText{/*/properties/property[@name='report']/@value)}"></a>
As a native and efficient approach, you don't need to use ord
or any loop over the characters. Just encode with ascii
and ignore the errors.
The following will just remove the non-ascii characters:
new_string = old_string.encode('ascii',errors='ignore')
Now if you want to replace the deleted characters just do the following:
final_string = new_string + b' ' * (len(old_string) - len(new_string))
You can use :
sheet.addMergedRegion(new CellRangeAddress(startRowIndx, endRowIndx, startColIndx,endColIndx));
Make sure the CellRangeAddress does not coincide with other merged regions as that will throw an exception.
For what you were trying to do this should work:
sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 0, 3));
The reason eval
and exec
are so dangerous is that the default compile
function will generate bytecode for any valid python expression, and the default eval
or exec
will execute any valid python bytecode. All the answers to date have focused on restricting the bytecode that can be generated (by sanitizing input) or building your own domain-specific-language using the AST.
Instead, you can easily create a simple eval
function that is incapable of doing anything nefarious and can easily have runtime checks on memory or time used. Of course, if it is simple math, than there is a shortcut.
c = compile(stringExp, 'userinput', 'eval')
if c.co_code[0]==b'd' and c.co_code[3]==b'S':
return c.co_consts[ord(c.co_code[1])+ord(c.co_code[2])*256]
The way this works is simple, any constant mathematic expression is safely evaluated during compilation and stored as a constant. The code object returned by compile consists of d
, which is the bytecode for LOAD_CONST
, followed by the number of the constant to load (usually the last one in the list), followed by S
, which is the bytecode for RETURN_VALUE
. If this shortcut doesn't work, it means that the user input isn't a constant expression (contains a variable or function call or similar).
This also opens the door to some more sophisticated input formats. For example:
stringExp = "1 + cos(2)"
This requires actually evaluating the bytecode, which is still quite simple. Python bytecode is a stack oriented language, so everything is a simple matter of TOS=stack.pop(); op(TOS); stack.put(TOS)
or similar. The key is to only implement the opcodes that are safe (loading/storing values, math operations, returning values) and not unsafe ones (attribute lookup). If you want the user to be able to call functions (the whole reason not to use the shortcut above), simple make your implementation of CALL_FUNCTION
only allow functions in a 'safe' list.
from dis import opmap
from Queue import LifoQueue
from math import sin,cos
import operator
globs = {'sin':sin, 'cos':cos}
safe = globs.values()
stack = LifoQueue()
class BINARY(object):
def __init__(self, operator):
self.op=operator
def __call__(self, context):
stack.put(self.op(stack.get(),stack.get()))
class UNARY(object):
def __init__(self, operator):
self.op=operator
def __call__(self, context):
stack.put(self.op(stack.get()))
def CALL_FUNCTION(context, arg):
argc = arg[0]+arg[1]*256
args = [stack.get() for i in range(argc)]
func = stack.get()
if func not in safe:
raise TypeError("Function %r now allowed"%func)
stack.put(func(*args))
def LOAD_CONST(context, arg):
cons = arg[0]+arg[1]*256
stack.put(context['code'].co_consts[cons])
def LOAD_NAME(context, arg):
name_num = arg[0]+arg[1]*256
name = context['code'].co_names[name_num]
if name in context['locals']:
stack.put(context['locals'][name])
else:
stack.put(context['globals'][name])
def RETURN_VALUE(context):
return stack.get()
opfuncs = {
opmap['BINARY_ADD']: BINARY(operator.add),
opmap['UNARY_INVERT']: UNARY(operator.invert),
opmap['CALL_FUNCTION']: CALL_FUNCTION,
opmap['LOAD_CONST']: LOAD_CONST,
opmap['LOAD_NAME']: LOAD_NAME
opmap['RETURN_VALUE']: RETURN_VALUE,
}
def VMeval(c):
context = dict(locals={}, globals=globs, code=c)
bci = iter(c.co_code)
for bytecode in bci:
func = opfuncs[ord(bytecode)]
if func.func_code.co_argcount==1:
ret = func(context)
else:
args = ord(bci.next()), ord(bci.next())
ret = func(context, args)
if ret:
return ret
def evaluate(expr):
return VMeval(compile(expr, 'userinput', 'eval'))
Obviously, the real version of this would be a bit longer (there are 119 opcodes, 24 of which are math related). Adding STORE_FAST
and a couple others would allow for input like 'x=5;return x+x
or similar, trivially easily. It can even be used to execute user-created functions, so long as the user created functions are themselves executed via VMeval (don't make them callable!!! or they could get used as a callback somewhere). Handling loops requires support for the goto
bytecodes, which means changing from a for
iterator to while
and maintaining a pointer to the current instruction, but isn't too hard. For resistance to DOS, the main loop should check how much time has passed since the start of the calculation, and certain operators should deny input over some reasonable limit (BINARY_POWER
being the most obvious).
While this approach is somewhat longer than a simple grammar parser for simple expressions (see above about just grabbing the compiled constant), it extends easily to more complicated input, and doesn't require dealing with grammar (compile
take anything arbitrarily complicated and reduces it to a sequence of simple instructions).
You may give a shot at using itoa. Another alternative is to use sprintf.
This is probably simpler than you're thinking:
int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
Here's a series of tutorials I've found on the topic: Drawing with Canvas Series
Try tagging it with:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
To my surprise you do not need users-permission CONTACT_READ to read the names and some basic information (Is the contact starred, what was the last calling time). However you do need permission to read the details of the contact like phone number.
For the Windows OS, I used Fiddler to work around the issue.
Run gem:
$ gem install --http-proxy http://localhost:8888 $gem_name
I have a similar situation but I want a consistent way to be able to use DateTime.Parse from the filename as well, so I went with
DateTime.Now.ToString("s").Replace(":", ".") // <-- 2016-10-25T16.50.35
When I want to parse, I can simply reverse the Replace call. This way I don't have to type in any yymmdd stuff or guess what formats DateTime.Parse allows.
$xml = $( $.parseXML( xml ) );
$xml.find("<<your_xml_tag_name>>").each(function(index,elem){
// elem = found XML element
});
This error occurs because of referenced jars are not checked in our project's order and export tab.
Choose Project ->ALT+Enter->Java Build Path ->Order and Export->check necessary jar files into your project.
Finally clean your project and run.It will run successfully.
Since @OscarLopez and I have different opinions on what the second largest means, I'll post the code according to my interpretation and in line with the first algorithm provided by the questioner.
def second_largest(numbers):
count = 0
m1 = m2 = float('-inf')
for x in numbers:
count += 1
if x > m2:
if x >= m1:
m1, m2 = x, m1
else:
m2 = x
return m2 if count >= 2 else None
(Note: Negative infinity is used here instead of None
since None
has different sorting behavior in Python 2 and 3 – see Python - Find second smallest number; a check for the number of elements in numbers
makes sure that negative infinity won't be returned when the actual answer is undefined.)
If the maximum occurs multiple times, it may be the second largest as well. Another thing about this approach is that it works correctly if there are less than two elements; then there is no second largest.
Running the same tests:
second_largest([20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7])
=> 74
second_largest([1,1,1,1,1,2])
=> 1
second_largest([2,2,2,2,2,1])
=> 2
second_largest([10,7,10])
=> 10
second_largest([1,1,1,1,1,1])
=> 1
second_largest([1])
=> None
second_largest([])
=> None
Update
I restructured the conditionals to drastically improve performance; almost by a 100% in my testing on random numbers. The reason for this is that in the original version, the elif
was always evaluated in the likely event that the next number is not the largest in the list. In other words, for practically every number in the list, two comparisons were made, whereas one comparison mostly suffices – if the number is not larger than the second largest, it's not larger than the largest either.
Go to command prompt and enter the command,
net user <username>
Will show your local group memberships.
If you're on a domain, use localgroup instead:
net localgroup Administrators or net localgroup [Admin group name]
Check the list of local groups with localgroup on its own.
net localgroup
Following is one liner for accepted answer ... (for one line lovers ..)
def search_dict(my_dict,searchFor):
s_val = [[ k if searchFor in v else None for v in my_dict[k]] for k in my_dict]
return s_val
git update-ref -d
resolved my instance of this error, e.g.
git update-ref -d refs/remotes/origin/user
Note that this doesn't impact remote.
In my case, a subsequent git fetch
fetched that branch again, and following git fetches/pulls no longer gave the error "remote ref is at but expected".
Note also that if you don't care about the branch in question (e.g. you just want to update master, not origin/user), a git pull
workaround is to fetch then just merge the particular branch you care about, e.g.
git fetch # may give an error for a particular branch, but other branches will still be successfully fetched
git merge origin/master
Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.
You could do:
UPDATE table SET posX=CASE
WHEN id=id[1] THEN posX[1]
WHEN id=id[2] THEN posX[2]
...
ELSE posX END, posY = CASE ... END
WHERE id IN (id[1], id[2], id[3]...);
The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.
Otherwise, I'd try with indexing on id, or modifying the architecture.
In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).
A static library is just an archive of .o
object files. Extract them with ar
(assuming Unix) and pack them back into one big library.
import glob
cv_img = []
for img in glob.glob("Path/to/dir/*.jpg"):
n= cv2.imread(img)
cv_img.append(n)`
That should work:
function get_content(){
var p = document.getElementById("txt");
var spans = p.getElementsByTagName("span");
var text = '';
for (var i = 0; i < spans.length; i++){
text += spans[i].innerHTML;
}
p.innerHTML = text;
}
Try this fiddle: http://jsfiddle.net/7gnyc/2/
I have to disagree with the other answers: the built in json
library (in Python 2.7) is not necessarily slower than simplejson
. It also doesn't have this annoying unicode bug.
Here is a simple benchmark:
import json
import simplejson
from timeit import repeat
NUMBER = 100000
REPEAT = 10
def compare_json_and_simplejson(data):
"""Compare json and simplejson - dumps and loads"""
compare_json_and_simplejson.data = data
compare_json_and_simplejson.dump = json.dumps(data)
assert json.dumps(data) == simplejson.dumps(data)
result = min(repeat("json.dumps(compare_json_and_simplejson.data)", "from __main__ import json, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print " json dumps {} seconds".format(result)
result = min(repeat("simplejson.dumps(compare_json_and_simplejson.data)", "from __main__ import simplejson, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print "simplejson dumps {} seconds".format(result)
assert json.loads(compare_json_and_simplejson.dump) == data
result = min(repeat("json.loads(compare_json_and_simplejson.dump)", "from __main__ import json, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print " json loads {} seconds".format(result)
result = min(repeat("simplejson.loads(compare_json_and_simplejson.dump)", "from __main__ import simplejson, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print "simplejson loads {} seconds".format(result)
print "Complex real world data:"
COMPLEX_DATA = {'status': 1, 'timestamp': 1362323499.23, 'site_code': 'testing123', 'remote_address': '212.179.220.18', 'input_text': u'ny monday for less than \u20aa123', 'locale_value': 'UK', 'eva_version': 'v1.0.3286', 'message': 'Successful Parse', 'muuid1': '11e2-8414-a5e9e0fd-95a6-12313913cc26', 'api_reply': {"api_reply": {"Money": {"Currency": "ILS", "Amount": "123", "Restriction": "Less"}, "ProcessedText": "ny monday for less than \\u20aa123", "Locations": [{"Index": 0, "Derived From": "Default", "Home": "Default", "Departure": {"Date": "2013-03-04"}, "Next": 10}, {"Arrival": {"Date": "2013-03-04", "Calculated": True}, "Index": 10, "All Airports Code": "NYC", "Airports": "EWR,JFK,LGA,PHL", "Name": "New York City, New York, United States (GID=5128581)", "Latitude": 40.71427, "Country": "US", "Type": "City", "Geoid": 5128581, "Longitude": -74.00597}]}}}
compare_json_and_simplejson(COMPLEX_DATA)
print "\nSimple data:"
SIMPLE_DATA = [1, 2, 3, "asasd", {'a':'b'}]
compare_json_and_simplejson(SIMPLE_DATA)
And the results on my system (Python 2.7.4, Linux 64-bit):
Complex real world data:
json dumps 1.56666707993 seconds
simplejson dumps 2.25638604164 seconds
json loads 2.71256899834 seconds
simplejson loads 1.29233884811 secondsSimple data:
json dumps 0.370109081268 seconds
simplejson dumps 0.574181079865 seconds
json loads 0.422876119614 seconds
simplejson loads 0.270955085754 seconds
For dumping, json
is faster than simplejson
.
For loading, simplejson
is faster.
Since I am currently building a web service, dumps()
is more important—and using a standard library is always preferred.
Also, cjson
was not updated in the past 4 years, so I wouldn't touch it.
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
Here is what i used to rename .edge
files to .blade.php
for file in *.edge; do mv "$file" "$(basename "$file" .edge).blade.php"; done
Works like charm.
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}
In Eclipse,
When you use JDBC in your servlet, the driver jar must be placed in the WEB-INF/lib directory of your project.
Integer value of ARGB color to hexadecimal string:
String hex = Integer.toHexString(color); // example for green color FF00FF00
Hexadecimal string to integer value of ARGB color:
int color = (Integer.parseInt( hex.substring( 0,2 ), 16) << 24) + Integer.parseInt( hex.substring( 2 ), 16);
I'd make a comparator using Guava's ComparisonChain
:
public class ReportComparator implements Comparator<Report> {
public int compare(Report r1, Report r2) {
return ComparisonChain.start()
.compare(r1.getReportKey(), r2.getReportKey())
.compare(r1.getStudentNumber(), r2.getStudentNumber())
.compare(r1.getSchool(), r2.getSchool())
.result();
}
}
I solved the problem.
In my apache, I have to specify:
PHPIniDir "C://php" AddType application/x-httpd-php .php
and for php.ini, instead of using the php.ini_recommend, use php.ini_dist to configure my php.ini.
then make sure the php engine has turned on. then it works now. Thanks all.
a rapid response not tested on several brosers, works on gg chrome / win
-> On focus event -> show/hide password
<input type="password" name="password">
script jQuery
// show on focus
$('input[type="password"]').on('focusin', function(){
$(this).attr('type', 'text');
});
// hide on focus Out
$('input[type="password"]').on('focusout', function(){
$(this).attr('type', 'password');
});
The way to do such a thing when you have modern C (C99) is to use a compound literal.
a = (const struct x){ 0 };
This is somewhat similar to David's solution, only that you don't have to worry to declare an the empty structure or whether to declare it static
. If you use the const
as I did, the compiler is free to allocate the compound literal statically in read-only storage if appropriate.
I've tried this in iOS 7 and it worked for me
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView sizeToFit];
}
You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?
Given your description, you want: ha='right'
n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]
fig, axs = plt.subplots(1,3, figsize=(12,3))
ha = ['right', 'center', 'left']
for n, ax in enumerate(axs):
ax.plot(x,y, 'o-')
ax.set_title(ha[n])
ax.set_xticks(x)
ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])
You can use numpy.logical_not
to invert the boolean array returned by isin
:
In [63]: s = pd.Series(np.arange(10.0))
In [64]: x = range(4, 8)
In [65]: mask = np.logical_not(s.isin(x))
In [66]: s[mask]
Out[66]:
0 0
1 1
2 2
3 3
8 8
9 9
As given in the comment by Wes McKinney you can also use
s[~s.isin(x)]
It took me more than 4 hours to fix this problem. I followed the guide from http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android
I'm using Android Studio (Eclipse with ADT could not work properly because of the build problem).
Solution that worked for me:
I put the /assets/www/index.html under app/src/main/assets directory. (take care AndroidStudio has different perspectives like Project or Android)
use super.loadUrl("file:///android_asset/www/index.html"); instead of super.loadUrl("file:///android_assets/www/index.html"); (no s)
hg update [-r REV]
If later you commit, you will effectively create a new branch. Then you might continue working only on this branch or eventually merge the existing one into it.
Any way to do this without manually re-installing the packages in a new virtualenv to get their dependencies ? This would be error-prone and I'd like to automate the process of cleaning the virtualenv from no-longer-needed old dependencies.
That's what pip-tools package is for (from https://github.com/jazzband/pip-tools):
$ pip install --upgrade pip # pip-tools needs pip==6.1 or higher (!)
$ pip install pip-tools
Suppose you have a Flask project, and want to pin it for production. Write the following line to a file:
# requirements.in
Flask
Now, run pip-compile requirements.in:
$ pip-compile requirements.in
#
# This file is autogenerated by pip-compile
# Make changes in requirements.in, then run this to update:
#
# pip-compile requirements.in
#
flask==0.10.1
itsdangerous==0.24 # via flask
jinja2==2.7.3 # via flask
markupsafe==0.23 # via jinja2
werkzeug==0.10.4 # via flask
And it will produce your requirements.txt
, with all the Flask dependencies (and all underlying dependencies) pinned. Put this file under version control as well and periodically re-run pip-compile
to update the packages.
Now that you have a requirements.txt
, you can use pip-sync
to update your virtual env to reflect exactly what's in there. Note: this will install/upgrade/uninstall everything necessary to match the requirements.txt
contents.
$ pip-sync
Uninstalling flake8-2.4.1:
Successfully uninstalled flake8-2.4.1
Collecting click==4.1
Downloading click-4.1-py2.py3-none-any.whl (62kB)
100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 65kB 1.8MB/s
Found existing installation: click 4.0
Uninstalling click-4.0:
Successfully uninstalled click-4.0
Successfully installed click-4.1
It appears to be relate to the graphics driver. In the emulator configuration, changing Emulated Graphics to Software - GLES 2.0
caused the crashes to stop.
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
The lifetime of function static
variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.
Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.
Example
struct emitter {
string str;
emitter(const string& s) : str(s) { cout << "Created " << str << endl; }
~emitter() { cout << "Destroyed " << str << endl; }
};
void foo(bool skip_first)
{
if (!skip_first)
static emitter a("in if");
static emitter b("in foo");
}
int main(int argc, char*[])
{
foo(argc != 2);
if (argc == 3)
foo(false);
}
Output:
C:>sample.exe
Created in foo
Destroyed in fooC:>sample.exe 1
Created in if
Created in foo
Destroyed in foo
Destroyed in ifC:>sample.exe 1 2
Created in foo
Created in if
Destroyed in if
Destroyed in foo
[0]
Since C++98[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.
[1]
C++98 section 3.6.3.1
[basic.start.term]
[2]
In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.
You should be pointing it towards the Developer
directory, not the Xcode application bundle. Run this:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.
with open('document.csv','a') as fd:
fd.write(myCsvRow)
Opening a file with the 'a'
parameter allows you to append to the end of the file instead of simply overwriting the existing content. Try that.
Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.
{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li> {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}
Try this if you want to remove all section header completely
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
Bonus answer since this use-case brought me here:
In the case where you need to do this as some other user
echo "some output" | sudo -u some_user tee /some/path/some_file
Note that the echo will happen as you and the file write will happen as "some_user" what will NOT work is if you were to run the echo as "some_user" and redirect the output with >> "some_file" because the file redirect will happen as you.
Hint: tee also supports append with the -a flag, if you need to replace a line in a file as another user you could execute sed as the desired user.
You can do it as follows.
This removes white space and split by comma where you do not need to worry about white spaces.
String myString= "A, B, C, D";
//Remove whitespace and split by comma
List<String> finalString= Arrays.asList(myString.split("\\s*,\\s*"));
System.out.println(finalString);
Found in one of the Chrome sample applications, although this is meant for larger blocks of data where you're okay with an asynchronous conversion.
/**
* Converts an array buffer to a string
*
* @private
* @param {ArrayBuffer} buf The buffer to convert
* @param {Function} callback The function to call when conversion is complete
*/
function _arrayBufferToString(buf, callback) {
var bb = new Blob([new Uint8Array(buf)]);
var f = new FileReader();
f.onload = function(e) {
callback(e.target.result);
};
f.readAsText(bb);
}
When you run OPENSSL command using s_client this is the output. See the Cipher, if the cipher NULL it means that version of TLS is not supported.
TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
Protocol : TLSv1
Cipher : ECDHE-RSA-AES256
Session-ID: A84600002D4945DE6
Session-ID-ctx:
Master-Key:
Start Time: 15852343333860
Timeout : 2343 (sec)
Verify return code: 0 (ok)
this one univesal way to get correct pid
pid=$(cut -d' ' -f4 < /proc/self/stat)
same nice worked for sub
SUB(){
pid=$(cut -d' ' -f4 < /proc/self/stat)
echo "$$ != $pid"
}
echo "pid = $$"
(SUB)
check output
pid = 8099
8099 != 8100
There is not 'goto' in the Java world. The main reason was developers realized that complex codes which had goto would lead to making the code really pathetic and it would be almost impossible to enhance or maintain the code.
However this code could be modified a little and using the concept of continue and break we could make the code work.
import java.util.*;
public class Factorial
{
public static void main(String[] args)
{
int x = 1;
int factValue = 1;
Scanner userInput = new Scanner(System.in);
restart: while(true){
System.out.println("Please enter a nonzero, nonnegative value to be factorialized.");
int factInput = userInput.nextInt();
while(factInput<=0)
{
System.out.println("Enter a nonzero, nonnegative value to be factorialized.");
factInput = userInput.nextInt();
}
if(x<1)//This is another way of doing what the above while loop does, I just wanted to have some fun.
{
System.out.println("The number you entered is not valid. Please try again.");
continue restart;
}
while(x<=factInput)
{
factValue*=x;
x++;
}
System.out.println(factInput+"! = "+factValue);
userInput.close();
break restart;
}
}
}
I just discovered a workaround: You can make your local machine accessible by using http://localtunnel.com . You'll need to (temporarily) change some URLs used in your app code / html so links point to the temporary domain, but at least facebook can reach your machine.
If you need to get width 100% of PDF file and auto height you can use 'getImageProperties' property of html2canvas library
html2canvas(input)
.then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({
orientation: 'landscape',
});
const imgProps= pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
pdf.save('download.pdf');
});
There is a purpose built utility for this,
apt install datamash
datamash transpose < yourfile
Taken from this site, https://www.gnu.org/software/datamash/ and http://www.thelinuxrain.com/articles/transposing-rows-and-columns-3-methods
netcat
(nc.exe
) is the right tool. I have a feeling that any tool that does what you want it to do will have exactly the same problem with your antivirus software. Just flag this program as "OK" in your antivirus software (how you do this will depend on what type of antivirus software you use).
Of course you will also need to configure your sysadmin to accept that you're not trying to do anything illegal...
To declare a string literal as an output column, leave the Table
off and just use Test
. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta()
, the table name will be an empty string because it isn't associated with a table.
SELECT
`field1`,
`field2`,
'Test' AS `field3`
FROM `Test`;
Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.
If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:
SELECT
field1,
field2,
field3
FROM
/* subquery wraps all fields to put the literal inside a table */
(SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test
Now field3
will come in the output as Test.field3
.
Go into Window > Preferences > Java > Installed JREs > and check your installed JREs. You should have an entry with a JDK there.
Some time, While executing insert query, we are facing:
Column not allowed here
error. Because of quote might missing in the string parameters. Add quote in the string params and try to execute.
Try this:
INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');
or
INSERT INTO LOCATION (ID, FIRST_NAME, LAST_NAME) VALUES('PQ95VM','HAPPY_STREET','FRANCE');
One quick solution I prefer which I suited most for this situation is simply delete .metadata folder of your work space and import your projects again. If you try all other option it wont guarantee the success. Sometimes the above solutions work sometime you will spend your precious hours to fix this configuration.
One day i decided to clean my work station.I arranged the projects to their suitable folders according to different clients. As a result all got messed up. After spending a whole day it did not end up in a fixed work space. Next day I simply deleted the .metadata folder of the work space and imported all the projects again. Bingo all set.
am startservice <INTENT>
or actually from the OS shell
adb shell am startservice <INTENT>
#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in wordcount.items():
print k, v
It looks like you have everything correct according to Laravel docs, but you have a typo
$item->push($product);
Should be
$items->push($product);
I also want to think the actual method you're looking for is put
$items->put('products', $product);
I had some decrypted byte arrays with padding characters and other stuff I didn't need, so I did this (probably not perfect, but it works for my limited use)
var junk = String.fromCharCode.apply(null, res).split('').map(char => char.charCodeAt(0) <= 127 && char.charCodeAt(0) >= 32 ? char : '').join('');
I was trying to find a solution and this is the best i could get (but works great and it's the easiest solution i've found even here).
In my case, i wanted to go back on history with an back button, but if the first page the user opened was an subpage of my app, it would go back to the main page.
The solution was, as soon the app is loaded, i just did an replace on the history state:
history.replaceState( {root: true}, '', window.location.pathname + window.location.hash)
This way, i just need to check history.state.root
before go back. If true, i make an history replace instead:
if(history.state && history.state.root)
history.replaceState( {root: true}, '', '/')
else
history.back()
I think this is the perfect use case warranting a GUI. - Although I totally understand that it can also be achieved well enough within the command line.
Personally, every commit of mine, I do from the git-gui. In which I can make multiple atomic commits with separate hunks/lines if it makes sense to do so.
Gut Gui enables viewing of the diffs in a well formatted colored interface, is rather light. Looks like this is something you should checkout too.
You can pass an array as the first AutoFilter argument and use the xlFilterValues operator.
This will display PDF, DOC and DOCX filetypes.
Criteria1:=Array(".pdf", ".doc", ".docx"), Operator:=xlFilterValues
I had to run project in VS2010 and I could not introduce any modifications in the code. My solution was to install vS2013 and in VS2010 point VC++ Directories->IncludeDirectories to Program Files(x86)\Microsoft Visual Studio 12.0\VC\include. Then my project compiled without any issues.
Try This
var data = 'allow~5';
var result=data.split('~');
RESULT
alert(result[0]);
Here's a hack I discovered that might work for you, although its not pretty and I'd personally be embarrassed to use such a line of code:
ng-click="profileForm.$valid ? updateMyProfile() : alert('failed')"
Now, you must be thinking 'but I don't want it to alert("failed") if my profileForm
isn't valid. Well that's the ugly part. For me, no matter what I put in the else clause of this ternary statement doesn't get executed ever.
Yet if its removed an error is thrown. So you can just stuff it with a pointless alert.
I told you it was ugly... but I don't even get any errors when I do something like this.
The proper way to do this is as Chen-Tsu mentioned, but to each their own.
This answer predates version 1.1.5 where a proper ternary in the $parse
function wasn't available. Use this answer if you're on a lower version, or as an example of filters:
angular.module('myApp.filters', [])
.filter('conditional', function() {
return function(condition, ifTrue, ifFalse) {
return condition ? ifTrue : ifFalse;
};
});
And then use it as
<i ng-class="checked | conditional:'icon-check':'icon-check-empty'"></i>
Another option would be to simply use grepl
function:
df[grepl('er', df$name), ]
CO2[grepl('non', CO2$Treatment), ]
df <- data.frame(name = c('bob','robert','peter'),
id = c(1,2,3)
)
# name id
# 2 robert 2
# 3 peter 3
Press ESC to first go into command mode
. Then Press Shift+D.
<html>
<head>
<style>
#main { border: 1px #000 solid; width: 600px; height: 400px; margin: auto;}
#one { width: 20%; height: 100%; background-color: blue; display: inline-block; }
#two { width: 80%; height: 100%; background-color: red; display: inline-block; }
</style>
</head>
<body>
<div id="main">
<span id="one">one</span><span id="two">two</span>
</div>
</body>
</html>
The secret is the inline-block
. If you use borders or margins, you may need to reduce the width of the div that use them.
NOTE: This doesn't work properly in IE6/7 if you use "DIV" instead of "SPAN". (see http://www.quirksmode.org/css/display.html)
Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.
Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.
Finally, delete the old package.
or Look into this post
You might want to add:
-webkit-appearance: none;
if you need it looking consistent on Mobile Safari...
Have you tried setting the selection properties of your tableView like this:
tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES;
If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
in your UITableView delegate. The documentation states:
Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected.
You can have this method return nil in cases where you don't want the selection to happen.
You can check data type of variable.
N = [2,3,5]
P = 5
type(P)
It will give you out put as data type of P.
<type 'int'>
So that you can differentiate that it is an integer or an array.
I strongly recommend using a combination of GitLens & GitGraph.
Below snapshot highlights how gitlens is showing commit over time
And the below picture is for the the amazing vivid GitGraph
What I have found, the correct way of doing it is: "C:\Program Files (x86)\netbeans-8.0.2-windows.exe" --javahome "C:\Program Files(x86)\Java\jdk1.7.0_51"
Note: run this link in the command prompt
As @stevebot said, do this:
https://<bucket-name>.s3.amazonaws.com/<key>
The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.
For the new Criteria since version Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);
Root<SomeClass> root = criteriaQuery.from(SomeClass.class);
Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");
Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);
Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);
Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);
criteriaQuery
.select(root)
.where(predicateResult);
List<SomeClass> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
Windows Environment
Additional this can be modified from Git Extensions --> Settings --> Global Settings
, if you have it installed in your systems.
Right Click on a folder/directory in Windows Environment to access these settings.
Update : How to switch/maintain multiple settings in Version 2.49
You should specify column names as below. It's good practice and probably solve your problem
insert into abc.employees (col1,col2)
select col1,col2 from employees where employee_id=100;
EDIT:
As you said employees
has 112 columns (sic!) try to run below select to compare both tables' columns
select *
from ALL_TAB_COLUMNS ATC1
left join ALL_TAB_COLUMNS ATC2 on ATC1.COLUMN_NAME = ATC1.COLUMN_NAME
and ATC1.owner = UPPER('2nd owner')
where ATC1.owner = UPPER('abc')
and ATC2.COLUMN_NAME is null
AND ATC1.TABLE_NAME = 'employees'
and than you should upgrade your tables to have the same structure.
In Windows Explorer, just go to the Address Bar at the top (keyboard shortcuts: Alt+D or Ctrl+L) and type powershell
or powershell_ise
and press Enter. A PowerShell command window opens with the current directory.
A simple tkinter code for Python 3 for setting background image .
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
C.pack()
top.mainloop
In C++ you can access fields or methods, using different operators, depending on it's type:
Note that :: should be used with a class name rather than a class instance, since static fields or methods are common to all instances of a class.
class AClass{
public:
static int static_field;
int instance_field;
static void static_method();
void method();
};
then you access this way:
AClass instance;
AClass *pointer = new AClass();
instance.instance_field; //access instance_field through a reference to AClass
instance.method();
pointer->instance_field; //access instance_field through a pointer to AClass
pointer->method();
AClass::static_field;
AClass::static_method();
You could use a div
with a background image instead and this CSS3 property:
background-size: contain
You can check out an example on:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain
To quote Mozilla:
The contain value specifies that regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.
However, keep in mind that your image will be upscaled if the div
is larger than your original image.
Update:
The original answer makes it difficult (and in some cases impossible) to correctly handle promise rejections. The correct solution is to use Promise.all
:
const [someResult, anotherResult] = await Promise.all([someCall(), anotherCall()]);
Original answer:
Just make sure you call both functions before you await either one:
// Call both functions
const somePromise = someCall();
const anotherPromise = anotherCall();
// Await both promises
const someResult = await somePromise;
const anotherResult = await anotherPromise;
json.dump() will preserve the ordder of your dictionary. Open the file in a text editor and you will see. It will preserve the order regardless of whether you send it an OrderedDict.
But json.load() will lose the order of the saved object unless you tell it to load into an OrderedDict(), which is done with the object_pairs_hook parameter as J.F.Sebastian instructed above.
It would otherwise lose the order because under usual operation, it loads the saved dictionary object into a regular dict and a regular dict does not preserve the oder of the items it is given.
As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.
It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.
library(grid)
library(gridExtra)
library(plyr)
# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))
# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") +
xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category))
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") +
labs(title = "Proportion of total Frequency accounted by each Category in given Year")
# bring them together
grid.arrange(totals,proportion)
This will give you a 2 panel display like this:
If you want to add Frequency values a table is the best format.
I wrote a function for my own project to do this (it doesn't use numpy, though):
def partition(seq, chunks):
"""Splits the sequence into equal sized chunks and them as a list"""
result = []
for i in range(chunks):
chunk = []
for element in seq[i:len(seq):chunks]:
chunk.append(element)
result.append(chunk)
return result
If you want the chunks to be randomized, just shuffle the list before passing it in.
Here's the correct code for your service:
myApp.service('userService', [
'$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {
var user = {
access: false
};
var me = this;
this.initialized = false;
this.isAuthenticated = function() {
var deferred = $q.defer();
user = {
first_name: 'First',
last_name: 'Last',
email: '[email protected]',
access: 'institution'
};
deferred.resolve(user);
me.initialized = true;
return deferred.promise;
};
}
]);
Then you controller should align accordingly:
myApp.run([
'$rootScope', 'userService', function($rootScope, userService) {
return userService.isAuthenticated().then(function(user) {
if (user) {
// You have access to the object you passed in the service, not to the response.
// You should either put response.data on the user or use a different property.
return $rootScope.$broadcast('login', user.email);
} else {
return userService.logout();
}
});
}
]);
Few points to note about the service:
Expose in a service only what needs to be exposed. User should be kept internally and be accessed by getters only.
When in functions, use 'me' which is the service to avoid edge cases of this with javascript.
I guessed what initialized was meant to do, feel free to correct me if I guessed wrong.
In my case, I accidentally put component name (Home
) as the first argument to connect
function while it was supposed to be at the end. duh.
This one -surely- gave me the error:
export default connect(Home)(mapStateToProps, mapDispatchToProps)
But this one worked -surely- fine:
export default connect(mapStateToProps, mapDispatchToProps)(Home)
Perhaps manager app does not exist look if you the manager application is on $APACHE_HOME/server/webapps directory. on this directory you must have : docs,examples, host-manager,manager, ROOT.
Lots of answers already here, but I found they didn't handle all cases, such as the base and target being the same. This function takes a base directory and a target path and returns the relative path. If no relative path exists, the target path is returned. File.separator is unnecessary.
public static String getRelativePath (String baseDir, String targetPath) {
String[] base = baseDir.replace('\\', '/').split("\\/");
targetPath = targetPath.replace('\\', '/');
String[] target = targetPath.split("\\/");
// Count common elements and their length.
int commonCount = 0, commonLength = 0, maxCount = Math.min(target.length, base.length);
while (commonCount < maxCount) {
String targetElement = target[commonCount];
if (!targetElement.equals(base[commonCount])) break;
commonCount++;
commonLength += targetElement.length() + 1; // Directory name length plus slash.
}
if (commonCount == 0) return targetPath; // No common path element.
int targetLength = targetPath.length();
int dirsUp = base.length - commonCount;
StringBuffer relative = new StringBuffer(dirsUp * 3 + targetLength - commonLength + 1);
for (int i = 0; i < dirsUp; i++)
relative.append("../");
if (commonLength < targetLength) relative.append(targetPath.substring(commonLength));
return relative.toString();
}
Nice elegant solution with ROW_NUMBER window function (supported by PostgreSQL - see in SQL Fiddle):
SELECT username, ip, time_stamp FROM (
SELECT username, ip, time_stamp,
ROW_NUMBER() OVER (PARTITION BY username ORDER BY time_stamp DESC) rn
FROM Users
) tmp WHERE rn = 1;
Something on the lines of this i belive should work.
parent.document.getElementById(iFrameID).style.height=framedPage.scrollHeight;
Load this with your body onload on the iframe content.
Personally, I find it easiest to modify commit messages after the fact in vi
(or whatever your git editor of choice is) rather than on the command line, by doing git commit --amend
right after git commit
.
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)
This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.
class name - User is accepted but user is not.
If you want an actual boolean column:
ALTER TABLE users ADD "priv_user" boolean DEFAULT false;
To encode mp3 audio ffmpeg.org shows the following example:
ffmpeg -i input.wav -codec:a libmp3lame -qscale:a 2 output.mp3
I extracted the audio from a video just by replacing input.wav
with the video filename. The 2
means 190 kb/sec. You can see the other quality levels at my link above.
The backslash-paren stuff means, "while matching the pattern, hold on to the stuff that matches in here." Later, on the replacement text side, you can get those remembered fragments back with "\1" (first parenthesized block), "\2" (second block), and so on.