For swift 3 and XCode 8 I find this answer:
First, you need set privacy into info.plist. Insert string NSLocationWhenInUseUsageDescription with your description why you want get user location. For example, set string "For map in application".
Second, use this code example
@IBOutlet weak var mapView: MKMapView!
private var locationManager: CLLocationManager!
private var currentLocation: CLLocation?
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// Check for Location Services
if CLLocationManager.locationServicesEnabled() {
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
}
// MARK - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
defer { currentLocation = locations.last }
if currentLocation == nil {
// Zoom to user location
if let userLocation = locations.last {
let viewRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 2000, 2000)
mapView.setRegion(viewRegion, animated: false)
}
}
}
Third, set User Location flag in storyboard for mapView.
Objective-C
@interface PopupView : UIView
@property (nonatomic, copy) void (^onHideComplete)();
@end
@interface PopupView ()
...
- (IBAction)hideButtonDidTouch:(id sender) {
// Do something
...
// Callback
if (onHideComplete) onHideComplete ();
}
@end
PopupView * popupView = [[PopupView alloc] init]
popupView.onHideComplete = ^() {
...
}
Swift
class PopupView: UIView {
var onHideComplete: (() -> Void)?
@IBAction func hideButtonDidTouch(sender: AnyObject) {
// Do something
....
// Callback
if let callback = self.onHideComplete {
callback ()
}
}
}
var popupView = PopupView ()
popupView.onHideComplete = {
() -> Void in
...
}
The problem for me was that the class that was the CLLocationManagerDelegate
was private, which prevented all the delegate methods from being called. Guess it's not a very common situation but thought I'd mention it in case t helps anyone.
It seems that stopUpdatingLocation is what triggers the background watchdog timer, so I replaced it in didUpdateLocation with:
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
[self.locationManager setDistanceFilter:99999];
which appears to effectively power down the GPS. The selector for the background NSTimer then becomes:
- (void) changeAccuracy {
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
}
All I'm doing is periodically toggling the accuracy to get a high-accuracy coordinate every few minutes and because the locationManager hasn't been stopped, backgroundTimeRemaining stays at its maximum value. This reduced battery consumption from ~10% per hour (with constant kCLLocationAccuracyBest in the background) to ~2% per hour on my device
Apple has added a new method for IOS 7 to simplify life a bit.
[mapView showAnnotations:yourAnnotationArray animated:YES];
You can easily pull from an array stored in the map view:
yourAnnotationArray = mapView.annotations;
and quickly adjust the camera too!
mapView.camera.altitude *= 1.4;
this won't work unless the user has iOS 7+ or OS X 10.9+ installed. check out custom animation here
You can use setBounds(x, y, width, height)
to specify the position and size of a GUI component if you set the layout
to null
. Then (x, y)
is the coordinate of the upper-left corner of that component.
From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.
I was looking for a listing of macOS but found nothing, maybe this helps someone.
Output on macOS Catalina (10.15.7) using net5.0
# SpecialFolders (Only with value)
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.System: /System
SpecialFolder.UserProfile: /Users/$USER
# SpecialFolders (All)
SpecialFolder.AdminTools:
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CDBurning:
SpecialFolder.CommonAdminTools:
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.CommonDesktopDirectory:
SpecialFolder.CommonDocuments:
SpecialFolder.CommonMusic:
SpecialFolder.CommonOemLinks:
SpecialFolder.CommonPictures:
SpecialFolder.CommonProgramFiles:
SpecialFolder.CommonProgramFilesX86:
SpecialFolder.CommonPrograms:
SpecialFolder.CommonStartMenu:
SpecialFolder.CommonStartup:
SpecialFolder.CommonTemplates:
SpecialFolder.CommonVideos:
SpecialFolder.Cookies:
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.History:
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.LocalizedResources:
SpecialFolder.MyComputer:
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.MyVideos:
SpecialFolder.NetworkShortcuts:
SpecialFolder.PrinterShortcuts:
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.ProgramFilesX86:
SpecialFolder.Programs:
SpecialFolder.Recent:
SpecialFolder.Resources:
SpecialFolder.SendTo:
SpecialFolder.StartMenu:
SpecialFolder.Startup:
SpecialFolder.System: /System
SpecialFolder.SystemX86:
SpecialFolder.Templates:
SpecialFolder.UserProfile: /Users/$USER
SpecialFolder.Windows:
I have replaced my username with $USER.
Code Snippet from pogosama.
foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
string commonAppData = Environment.GetFolderPath(f);
Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();
I found this answer while looking for a way to do that with a Dictionary, and it turns out it's quite easy to adapt it, just pass a tuple for the element.
// Swift 2
var list = ["a": 1, "b": 2]
for (index, (letter, value)) in list.enumerate() {
print("Item \(index): \(letter) \(value)")
}
In Swift, iOS 8+ project I like to make an extension on UIScreen
, like:
extension UIScreen {
var isPhone4: Bool {
return self.nativeBounds.size.height == 960;
}
var isPhone5: Bool {
return self.nativeBounds.size.height == 1136;
}
var isPhone6: Bool {
return self.nativeBounds.size.height == 1334;
}
var isPhone6Plus: Bool {
return self.nativeBounds.size.height == 2208;
}
}
(NOTE: nativeBounds
is in pixels).
And then the code will be like:
if UIScreen.mainScreen().isPhone4 {
// do smth on the smallest screen
}
So the code makes it clear that this is a check for the main screen, not for the device model.
Read Kernighan and Ritchie
#include <string.h>
void reverse(char s[])
{
int length = strlen(s) ;
int c, i, j;
for (i = 0, j = length - 1; i < j; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
I created a folder named '.nuget' in solution root folder Then added file 'NuGet.Config' in this folder with following content
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
</configuration>
Then created file '.nuGet.targets' as below $(MSBuildProjectDirectory)..\
<!-- Enable the restore command to run before builds -->
<RestorePackages Condition=" '$(RestorePackages)' == '' ">false</RestorePackages>
<!-- Property that enables building a package from a project -->
<BuildPackage Condition=" '$(BuildPackage)' == '' ">false</BuildPackage>
<!-- Determines if package restore consent is required to restore packages -->
<RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'false' ">true</RequireRestoreConsent>
<!-- Download NuGet.exe if it does not already exist -->
<DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">false</DownloadNuGetExe>
</PropertyGroup>
<ItemGroup Condition=" '$(PackageSources)' == '' ">
<!-- Package sources used to restore packages. By default will used the registered sources under %APPDATA%\NuGet\NuGet.Config -->
<!--
<PackageSource Include="https://nuget.org/api/v2/" />
<PackageSource Include="https://my-nuget-source/nuget/" />
-->
</ItemGroup>
<PropertyGroup Condition=" '$(OS)' == 'Windows_NT'">
<!-- Windows specific commands -->
<NuGetToolsPath>$([System.IO.Path]::Combine($(SolutionDir), ".nuget"))</NuGetToolsPath>
<PackagesConfig>$([System.IO.Path]::Combine($(ProjectDir), "packages.config"))</PackagesConfig>
<PackagesDir>$([System.IO.Path]::Combine($(SolutionDir), "packages"))</PackagesDir>
</PropertyGroup>
<PropertyGroup Condition=" '$(OS)' != 'Windows_NT'">
<!-- We need to launch nuget.exe with the mono command if we're not on windows -->
<NuGetToolsPath>$(SolutionDir).nuget</NuGetToolsPath>
<PackagesConfig>packages.config</PackagesConfig>
<PackagesDir>$(SolutionDir)packages</PackagesDir>
</PropertyGroup>
<PropertyGroup>
<!-- NuGet command -->
<NuGetExePath Condition=" '$(NuGetExePath)' == '' ">$(NuGetToolsPath)\nuget.exe</NuGetExePath>
<PackageSources Condition=" $(PackageSources) == '' ">@(PackageSource)</PackageSources>
<NuGetCommand Condition=" '$(OS)' == 'Windows_NT'">"$(NuGetExePath)"</NuGetCommand>
<NuGetCommand Condition=" '$(OS)' != 'Windows_NT' ">mono --runtime=v4.0.30319 $(NuGetExePath)</NuGetCommand>
<PackageOutputDir Condition="$(PackageOutputDir) == ''">$(TargetDir.Trim('\\'))</PackageOutputDir>
<RequireConsentSwitch Condition=" $(RequireRestoreConsent) == 'true' ">-RequireConsent</RequireConsentSwitch>
<!-- Commands -->
<RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(RequireConsentSwitch) -o "$(PackagesDir)"</RestoreCommand>
<BuildCommand>$(NuGetCommand) pack "$(ProjectPath)" -p Configuration=$(Configuration) -o "$(PackageOutputDir)" -symbols</BuildCommand>
<!-- Make the build depend on restore packages -->
<BuildDependsOn Condition="$(RestorePackages) == 'true'">
RestorePackages;
$(BuildDependsOn);
</BuildDependsOn>
<!-- Make the build depend on restore packages -->
<BuildDependsOn Condition="$(BuildPackage) == 'true'">
$(BuildDependsOn);
BuildPackage;
</BuildDependsOn>
</PropertyGroup>
<Target Name="CheckPrerequisites">
<!-- Raise an error if we're unable to locate nuget.exe -->
<Error Condition="'$(DownloadNuGetExe)' != 'true' AND !Exists('$(NuGetExePath)')" Text="Unable to locate '$(NuGetExePath)'" />
<SetEnvironmentVariable EnvKey="VisualStudioVersion" EnvValue="$(VisualStudioVersion)" Condition=" '$(VisualStudioVersion)' != '' AND '$(OS)' == 'Windows_NT' " />
<DownloadNuGet OutputFilename="$(NuGetExePath)" Condition=" '$(DownloadNuGetExe)' == 'true' AND !Exists('$(NuGetExePath)')" />
</Target>
<Target Name="RestorePackages" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(RestoreCommand)"
Condition="'$(OS)' != 'Windows_NT' And Exists('$(PackagesConfig)')" />
<Exec Command="$(RestoreCommand)"
LogStandardErrorAsError="true"
Condition="'$(OS)' == 'Windows_NT' And Exists('$(PackagesConfig)')" />
</Target>
<Target Name="BuildPackage" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(BuildCommand)"
Condition=" '$(OS)' != 'Windows_NT' " />
<Exec Command="$(BuildCommand)"
LogStandardErrorAsError="true"
Condition=" '$(OS)' == 'Windows_NT' " />
</Target>
<UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<OutputFilename ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Reference Include="System.Core" />
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Using Namespace="System.Net" />
<Using Namespace="Microsoft.Build.Framework" />
<Using Namespace="Microsoft.Build.Utilities" />
<Code Type="Fragment" Language="cs">
<![CDATA[
try {
OutputFilename = Path.GetFullPath(OutputFilename);
Log.LogMessage("Downloading latest version of NuGet.exe...");
WebClient webClient = new WebClient();
webClient.DownloadFile("https://nuget.org/nuget.exe", OutputFilename);
return true;
}
catch (Exception ex) {
Log.LogErrorFromException(ex);
return false;
}
]]>
</Code>
</Task>
</UsingTask>
<UsingTask TaskName="SetEnvironmentVariable" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<EnvKey ParameterType="System.String" Required="true" />
<EnvValue ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Using Namespace="System" />
<Code Type="Fragment" Language="cs">
<![CDATA[
try {
Environment.SetEnvironmentVariable(EnvKey, EnvValue, System.EnvironmentVariableTarget.Process);
}
catch {
}
]]>
</Code>
</Task>
</UsingTask>
In C#, float
is an alias for System.Single
(a bit like int
is an alias for System.Int32
).
In addition to anyListOf
above, you can always specify generics explicitly using this syntax:
when(mock.process(Matchers.<List<Bar>>any(List.class)));
Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:
when(mock.process(Matchers.any()));
Remember that neither any()
nor anyList()
will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class)
was changed to mean "any instanceof
Foo", but any()
still means "any value including null
".
NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers
. Older versions of Mockito will need to keep using org.mockito.Matchers
as above.
if you looking for a way how to download temporary file, do stuff and delete it try this gem https://github.com/equivalent/pull_tempfile
require 'pull_tempfile'
PullTempfile.transaction(url: 'https://mycompany.org/stupid-csv-report.csv', original_filename: 'dont-care.csv') do |tmp_file|
CSV.foreach(tmp_file.path) do |row|
# ....
end
end
Try this
'''
This is a multiline
comment. I can type here whatever I want.
'''
Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode -- just like #-prepended comments. In effect, it acts exactly like a comment.
On the other hand, if you say this behavior must be documented in the official docs to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.
In any case your editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to an editor that does.
Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.
Not only should the editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.
The PHP function echo() prints out its input to the web server response.
echo("Hello World!");
prints out Hello World! to the web server response.
echo("<prev>");
prints out the tag to the web server response.
echo do not require valid HTML tags. You can use PHP to print XML, images, excel, HTML and so on.
<prev> is not a HTML tag. Is is a valid XML tag, but since I don't know what page you are working in, i cannot tell you what it is. Maybe it is the root tag of a XML page, or a miswritten <pre> tag.
This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.
Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.
$param = isset($_GET['param']) ? $_GET['param'] : 'default';
There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:
$result = $x ?: 'default';
It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset
or a null coalescing operator which is introduced in PHP7:
$param = $_GET['param'] ?? 'default';
By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.
It should be noted that primitive types must have a value. If you used Objects (ie Integer
), you could initialize value to null
and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.
Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.
The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException
, because min/max is undefined in this case.
You can install vim/vi for windows and set windows PATH variable and open it in command line.
I think the simplest way to achieve your goal is this:
var str = 'asd-0.testing';
var regex = /(asd-)(\d)(\.\w+)/;
var anyNumber = 1;
var res = str.replace(regex, `$1${anyNumber}$3`);
With my Android 5 tablet, every time I attempt to use adb, to install a signed release apk, I get the [INSTALL_FAILED_ALREADY_EXISTS]
error.
I have to uninstall the debug package first. But, I cannot uninstall using the device's Application Manager!
If do uninstall the debug version with the Application Manager, then I have to re-run the debug build variant from Android Studio, then uninstall it using adb uninstall com.example.mypackagename
Finally, I can use adb install myApp.apk
to install the signed release apk.
From what I see, people use package.json scripts when they would like to run script in simpler way. For example, to use nodemon
that installed in local node_modules, we can't call nodemon
directly from the cli, but we can call it by using ./node_modules/nodemon/nodemon.js
. So, to simplify this long typing, we can put this...
... scripts: { 'start': 'nodemon app.js' } ...
... then call npm start
to use 'nodemon' which has app.js as the first argument.
What I'm trying to say, if you just want to start your server with the node
command, I don't think you need to use scripts
. Typing npm start
or node app.js
has the same effort.
But if you do want to use nodemon
, and want to pass a dynamic argument, don't use script
either. Try to use symlink instead.
For example using migration with sequelize
. I create a symlink...
ln -s node_modules/sequelize/bin/sequelize sequelize
... And I can pass any arguement when I call it ...
./sequlize -h /* show help */
./sequelize -m /* upgrade migration */
./sequelize -m -u /* downgrade migration */
etc...
At this point, using symlink is the best way I could figure out, but I don't really think it's the best practice.
I also hope for your opinion to my answer.
Leaving an answer for anyone looking to do something similar but in a horizontal direction, like I wanted to.
Tweaking @strider820's answer like below will do the magic:
.fixed-content { //comments showing what I replaced.
left:0; //top: 0;
right:0; //bottom:0;
position:fixed;
overflow-y:hidden; //overflow-y:scroll;
overflow-x:auto; //overflow-x:hidden;
}
That's it. Also check this comment where @train explained using overflow:auto
over overflow:scroll
.
Note that the %
syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:
instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)
This also fixes the error that you happened to have.
I came across another solution to use the Google play services on an emulator. The guys at http://www.genymotion.com/ provide very fast emulators on which you can install Google play services. They just need you to sign up to begin downloading and you need Virtual box installed. At the moment they cater for Android 16 and 17 but more are on the way.
I've just set up a quick benchmarking exercise:
Function time to run 1 million iterations
--------------------------------------------
(int) "123": 0.55029
intval("123"): 1.0115 (183%)
(int) "0": 0.42461
intval("0"): 0.95683 (225%)
(int) int: 0.1502
intval(int): 0.65716 (438%)
(int) array("a", "b"): 0.91264
intval(array("a", "b")): 1.47681 (162%)
(int) "hello": 0.42208
intval("hello"): 0.93678 (222%)
On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.
I'd be interested to know why though.
Update: I've run the tests again, this time with coercion (0 + $var)
| INPUT ($x) | (int) $x |intval($x) | 0 + $x |
|-----------------|------------|-----------|-----------|
| "123" | 0.51541 | 0.96924 | 0.33828 |
| "0" | 0.42723 | 0.97418 | 0.31353 |
| 123 | 0.15011 | 0.61690 | 0.15452 |
| array("a", "b") | 0.8893 | 1.45109 | err! |
| "hello" | 0.42618 | 0.88803 | 0.1691 |
|-----------------|------------|-----------|-----------|
Addendum: I've just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:
$x = "11";
(int) $x; // int(11)
intval($x); // int(11)
$x + 0; // int(11)
$x = "0x11";
(int) $x; // int(0)
intval($x); // int(0)
$x + 0; // int(17) !
$x = "011";
(int) $x; // int(11)
intval($x); // int(11)
$x + 0; // int(11) (not 9)
Tested using PHP 5.3.1
Clone the repository as normal:
git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle
Then checkout the tag you want like so:
git checkout tags/1.1.4
This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".
To retain any changes made, move them to a new branch:
git checkout -b 1.1.4-jspooner
You can get back to the master branch by using:
git checkout master
Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:
git checkout 1.1.4
But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:
warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'
The shorthand can be safely used if the repository does not share names between branches and tags.
String str = "Good";
str = str + " Morning";
In the above code you create 3 String
Objects.
Note: Strings are always immutable. There is no, such thing as a mutable String. str
is just a reference which eventually points to "Good Morning". You are actually, not working on 1
object. you have 3
distinct String
Objects.
StringBuffer str = new StringBuffer("Good");
str.append(" Morning");
StringBuffer
contains an array of characters. It is not same as a String
.
The above code adds characters to the existing array. Effectively, StringBuffer
is mutable, its String
representation isn't.
In my case the issue was, I was referencing a project where I commented out all the .cs
files.
For example ProjectApp references ProjectUtility. In ProjectUtility I only had 1 .cs
file. I wasn't using it anymore so I commented out the whole file. In ProjectApp I wasn't calling any of the code from ProjectUtility, but I had using ProjectUtility;
in one of the ProjectApp .cs
files. The only error I got from the compiler was the CS0006 error.
I uncommented the .cs
file in ProjectUtility and the error went away. So I'm not sure if having no code in a project causes the compiler to create an invalid assembly or not generate the DLL at all. The fix for me was to just remove the reference to ProjectUtility rather than commenting all the code.
In case you were wondering why I commented all the code from the referenced project instead of removing the reference, I did it because I was testing something and didn't want to modify the ProjectApp.csproj
file.
Isn't the "in" clause in the delete ... where, extremely inefficient, if there are going to be a large number of values returned from the subquery? Not sure why you would not just inner (or right) join back against the original table from the subquery on the ID to delete, rather than us the "in (subquery)".?
DELETE T FROM Target AS T
RIGHT JOIN (full subquery already listed for the in() clause in answers above) ` AS TT ON (TT.ID = T.ID)
And maybe it is answered in the "MySQL doesn't allow it", however, it is working fine for me PROVIDED I make sure to fully clarify what to delete (DELETE T FROM Target AS T). Delete with Join in MySQL clarifies the DELETE / JOIN issue.
The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.
This explains the "strange results".
"Better" results can be obtained using the expressions below:
//*[text() = 'qwerty']
The above selects every element in the document that has at least one text-node child with value 'qwerty'.
//*[text() = 'qwerty' and not(text()[2])]
The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.
Passing by reference in the above case is just an alias
for the actual object.
You'll be referring to the actual object just with a different name.
There are many advantages which references
offer compared to pointer references
.
a very common try_files line which can be applied on your condition is
location / {
try_files $uri $uri/ /test/index.html;
}
you probably understand the first part, location /
matches all locations, unless it's matched by a more specific location, like location /test
for example
The second part ( the try_files
) means when you receive a URI that's matched by this block try $uri
first, for example http://example.com/images/image.jpg
nginx will try to check if there's a file inside /images
called image.jpg
if found it will serve it first.
Second condition is $uri/
which means if you didn't find the first condition $uri
try the URI as a directory, for example http://example.com/images/
, ngixn will first check if a file called images
exists then it wont find it, then goes to second check $uri/
and see if there's a directory called images
exists then it will try serving it.
Side note: if you don't have autoindex on
you'll probably get a 403 forbidden error, because directory listing is forbidden by default.
EDIT: I forgot to mention that if you have
index
defined, nginx will try to check if the index exists inside this folder before trying directory listing.
Third condition /test/index.html
is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html
inside the folder test
and serve it if it exists.
If the third condition fails too, then nginx will serve the 404 error page.
Also there's something called named locations, like this
location @error {
}
You can call it with try_files
like this
try_files $uri $uri/ @error;
TIP: If you only have 1 condition you want to serve, like for example inside folder images
you only want to either serve the image or go to 404 error, you can write a line like this
location /images {
try_files $uri =404;
}
which means either serve the file or serve a 404 error, you can't use only $uri
by it self without =404
because you need to have a fallback option.
You can also choose which ever error code you want, like for example:
location /images {
try_files $uri =403;
}
This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..
Setup the window manually,
- (void)applicationDidBecomeActive:(UIApplication *)application
{
if (!application.keyWindow.rootViewController)
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *myViewController= [storyboard instantiateViewControllerWithIdentifier:@"myViewController identifier"];
application.keyWindow.rootViewController = myViewController;
}
}
Here is an elegant library that records video in all supported browsers and supports uploading:
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'
or simply this if you are sure that you have no values like this CKIT002
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_node("D")
G.add_node("E")
G.add_node("F")
G.add_node("G")
G.add_edge("A","B")
G.add_edge("B","C")
G.add_edge("C","E")
G.add_edge("C","F")
G.add_edge("D","E")
G.add_edge("F","G")
print(G.nodes())
print(G.edges())
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edge_color='r', arrows = True)
plt.show()
alternative commands that does same job
tr -d ",$" < infile
awk 'gsub(",$","")' infile
None of the answers so far have given what seems to be the simplest solution.
$('#image_id').load(
function () {
//code here
});
If you want to have the ListView in an AppCompatActivity instead of ListActivity, you can do the following (Modifying @Shardul's answer):
public class ListViewDemoActivity extends AppCompatActivity {
//LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
ArrayList<String> listItems=new ArrayList<String>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
//RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
int clickCounter=0;
private ListView mListView;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_list_view_demo);
if (mListView == null) {
mListView = (ListView) findViewById(R.id.listDemo);
}
adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}
//METHOD WHICH WILL HANDLE DYNAMIC INSERTION
public void addItems(View v) {
listItems.add("Clicked : "+clickCounter++);
adapter.notifyDataSetChanged();
}
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(R.id.listDemo);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}
And in you layout instead of using android:id="@android:id/list"
you can use android:id="@+id/listDemo"
So now you can have a ListView
inside a normal AppCompatActivity
.
JIT compiler only compiles the byte-code to equivalent native code at first execution. Upon every successive execution, the JVM merely uses the already compiled native code to optimize performance.
Without JIT compiler, the JVM interpreter translates the byte-code line-by-line to make it appear as if a native application is being executed.
Assuming array equality means both arrays have equal elements at equal indexes, there is the SequenceEqual
answer and the IStructuralEquatable
answer.
But both have drawbacks, performance wise.
SequenceEqual
current implementation will not shortcut when the arrays have different lengths, and so it may enumerate one of them entirely, comparing each of its elements.
IStructuralEquatable
is not generic and may cause boxing of each compared value. Moreover it is not very straightforward to use and already calls for coding some helper methods hiding it away.
It may be better, performance wise, to use something like:
bool ArrayEquals<T>(T[] first, T[] second)
{
if (first == second)
return true;
if (first == null || second == null)
return false;
if (first.Length != second.Length)
return false;
for (var i = 0; i < first.Length; i++)
{
if (!first[i].Equals(second[i]))
return false;
}
return true;
}
But of course, that is not either some "magic way" of checking array equality.
So currently, no, there is not really an equivalent to Java Arrays.equals()
in .Net.
This solution without timeouts! Real force redraw! For Android and iOS.
var forceRedraw = function(element){
var disp = element.style.display;
element.style.display = 'none';
var trick = element.offsetHeight;
element.style.display = disp;
};
If your project has a CMake configuration it's pretty straight forward to setup VSCode, e.g. setup tasks.json
like below:
{
"version": "0.1.0",
"command": "sh",
"isShellCommand": true,
"args": ["-c"],
"showOutput": "always",
"suppressTaskName": true,
"options": {
"cwd": "${workspaceRoot}/build"
},
"tasks": [
{
"taskName": "cmake",
"args": ["cmake ."]
},
{
"taskName": "make",
"args" : ["make"],
"isBuildCommand": true,
"problemMatcher": {
"owner": "cpp",
"fileLocation": "absolute",
"pattern": {
"regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
}
}
]
}
This assumes that there is a folder build
in the root of the workspace with a CMake configuration.
There's also a CMake integration extension that adds a "CMake build" command to VScode.
PS! The problemMatcher
is setup for clang
-builds. To use GCC I believe you need to change fileLocation
to relative
, but I haven't tested this.
$('#configreset').click(function(){
$('#configform')[0].reset();
});
Put it in JS fiddle. Worked as intended.
So, none of the aforementioned issues are at fault here. Maybe you're having a conflicting ID issue? Is the click actually executing?
Edit: (because I'm a sad sack without proper commenting ability) It's not an issue directly with your code. It works fine when you take it out of the context of the page that you're currently using, so, instead of it being something with the particular jQuery/javascript & attributed form data, it has to be something else. I'd start bisecting the code around it out and try to find where it's going on. I mean, just to 'make sure', i suppose you could...
console.log($('#configform')[0]);
in the click function and make sure it's targeting the right form...
and if it is, it has to be something that's not listed here.
edit part 2: One thing you could try (if it's not targeting it correctly) is use "input:reset" instead of what you are using... also, i'd suggest because it's not the target that's incorrectly working to find out what the actual click is targeting. Just open up firebug/developer tools, whathave you, toss in
console.log($('#configreset'))
and see what pops up. and then we can go from there.
Note one can also get this error if you do this;
while read line; do
echo $line
done << somefile
Because << somefile
should read < somefile
in this case.
I have never done so, but it seems like
MATCH (head, head, body) AGAINST ('some words' IN BOOLEAN MODE)
Should give a double weight to matches found in the head.
Just read this comment on the docs page, Thought it might be of value to you:
Posted by Patrick O'Lone on December 9 2002 6:51am
It should be noted in the documentation that IN BOOLEAN MODE will almost always return a relevance of 1.0. In order to get a relevance that is meaningful, you'll need to:
SELECT MATCH('Content') AGAINST ('keyword1 keyword2') as Relevance
FROM table
WHERE MATCH ('Content') AGAINST('+keyword1+keyword2' IN BOOLEAN MODE)
HAVING Relevance > 0.2
ORDER BY Relevance DESC
Notice that you are doing a regular relevance query to obtain relevance factors combined with a WHERE clause that uses BOOLEAN MODE. The BOOLEAN MODE gives you the subset that fulfills the requirements of the BOOLEAN search, the relevance query fulfills the relevance factor, and the HAVING clause (in this case) ensures that the document is relevant to the search (i.e. documents that score less than 0.2 are considered irrelevant). This also allows you to order by relevance.
This may or may not be a bug in the way that IN BOOLEAN MODE operates, although the comments I've read on the mailing list suggest that IN BOOLEAN MODE's relevance ranking is not very complicated, thus lending itself poorly for actually providing relevant documents. BTW - I didn't notice a performance loss for doing this, since it appears MySQL only performs the FULLTEXT search once, even though the two MATCH clauses are different. Use EXPLAIN to prove this.
So it would seem you may not need to worry about calling the fulltext search twice, though you still should "use EXPLAIN to prove this"
Headers included with #include <> will be searched in all default directories , but you can also add your own location in the search path with -I command line arg.
I saw your edit you could install your headers in default locations usually
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
Confirm with compiler docs though.
The new tests you wrote (directly or indirectly) use classes that log using Log4j.
Log4J needs to be configured for this logging to work properly.
Put a log4j.properties (or log4j.xml) file in the root of your test classpath.
It should have some basic configuration such as
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
# An alternative logging format:
# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n
An appender outputs to the console by default, but you can also explicitly set the target like this:
log4j.appender.A1.Target=System.out
This will redirect all output in a nice format to the console. More info can be found here in the Log4J manual,
Log4J Logging will then be properly configured and this warning will disappear.
A possible solution might be to use the JSON dumps() method, so you can convert the dictionary to a string ---
import json
a={"a":10, "b":20}
b={"b":20, "a":10}
c = [json.dumps(a), json.dumps(b)]
set(c)
json.dumps(a) in c
Output -
set(['{"a": 10, "b": 20}'])
True
What solved my problem was to make sure static
was set to false
.
@ViewChild(ClrForm, {static: false}) clrForm;
With static
turned off, the @ViewChild
reference gets updated by Angular when the *ngIf
directive changes.
You can create dummy variables to handle the categorical data
# Creating dummy variables for categorical datatypes
trainDfDummies = pd.get_dummies(trainDf, columns=['Col1', 'Col2', 'Col3', 'Col4'])
This will drop the original columns in trainDf and append the column with dummy variables at the end of the trainDfDummies dataframe.
It automatically creates the column names by appending the values at the end of the original column name.
This also happens if the paths are correct, but the service account is not the owner of the data files (yet it still has enough rights for read/write access). This can occur if the permissions for the files were reset to match the permissions of the folder (of course, while the service was stopped).
The easiest solution in this case is to detach each database and attach it again (because when attaching the owner is changed to be the service account).
Also you can use killall -r my_pattern
. -r
Interpret process name pattern as an extended regular expression.
killall -r my_pattern
See my answer to a similar question here.
It sounds like you want a background-image to keep it's own aspect ratio while expanding to 100% width and getting cropped off on the top and bottom. If that's the case, do something like this:
.chapter {
position: relative;
height: 1200px;
z-index: 1;
}
#chapter1 {
background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center top;
background-attachment: fixed;
}
jsfiddle: http://jsfiddle.net/ndKWN/3/
The problem with this approach is that you have the container elements at a fixed height, so there can be space below if the screen is small enough.
If you want the height to keep the image's aspect ratio, you'll have to do something like what I wrote in an edit to the answer I linked to above. Set the container's height
to 0 and set the padding-bottom
to the percentage of the width:
.chapter {
position: relative;
height: 0;
padding-bottom: 75%;
z-index: 1;
}
#chapter1 {
background-image: url(http://omset.files.wordpress.com/2010/06/homer-simpson-1-264a0.jpg);
background-repeat: no-repeat;
background-size: 100% auto;
background-position: center top;
background-attachment: fixed;
}
jsfiddle: http://jsfiddle.net/ndKWN/4/
You could also put the padding-bottom
percentage into each #chapter
style if each image has a different aspect ratio. In order to use different aspect ratios, divide the height of the original image by it's own width, and multiply by 100 to get the percentage value.
CSS has a clamp() function that holds the value between the upper and lower bound. The clamp() function enables the selection of the middle value in the range of values between the defined minimum and maximum values.
It simply takes three dimensions:
try with the code below, and check the window resize, which will change the font size you see in the console. i set maximum value 150px
and minimum value 100px
.
$(window).resize(function(){_x000D_
console.log($('#element').css('font-size'));_x000D_
});_x000D_
console.log($('#element').css('font-size'));
_x000D_
h1{_x000D_
font-size: 10vw; /* Browsers that do not support "MIN () - MAX ()" and "Clamp ()" functions will take this value.*/_x000D_
font-size: max(100px, min(10vw, 150px)); /* Browsers that do not support the "clamp ()" function will take this value. */_x000D_
font-size: clamp(100px, 10vw, 150px);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<center>_x000D_
<h1 id="element">THIS IS TEXT</h1>_x000D_
</center>
_x000D_
Change the Aux.js to another name, like Sig.js.
The source tree still shows it as a binary file, but you can stage(add) it and commit.
You can check this like below :
if varDate = "#01/01/0001#" then
' blank date. do something.
else
' Date is not blank. Do some other thing
end if
pointer1 = pointer2
, you give pointer1 the address of pointer2.but! if you do that within a function, and you want the result to persist after the function is done, you need do some extra work. you need a new pointer3 just to point to pointer1. pass pointer3 to the function.
here is an example. look at the output below first, to understand.
#include <stdio.h>
int main()
{
int c = 1;
int d = 2;
int e = 3;
int * a = &c;
int * b = &d;
int * f = &e;
int ** pp = &a; // pointer to pointer 'a'
printf("\n a's value: %x \n", a);
printf("\n b's value: %x \n", b);
printf("\n f's value: %x \n", f);
printf("\n can we change a?, lets see \n");
printf("\n a = b \n");
a = b;
printf("\n a's value is now: %x, same as 'b'... it seems we can, but can we do it in a function? lets see... \n", a);
printf("\n cant_change(a, f); \n");
cant_change(a, f);
printf("\n a's value is now: %x, Doh! same as 'b'... that function tricked us. \n", a);
printf("\n NOW! lets see if a pointer to a pointer solution can help us... remember that 'pp' point to 'a' \n");
printf("\n change(pp, f); \n");
change(pp, f);
printf("\n a's value is now: %x, YEAH! same as 'f'... that function ROCKS!!!. \n", a);
return 0;
}
void cant_change(int * x, int * z){
x = z;
printf("\n ----> value of 'a' is: %x inside function, same as 'f', BUT will it be the same outside of this function? lets see\n", x);
}
void change(int ** x, int * z){
*x = z;
printf("\n ----> value of 'a' is: %x inside function, same as 'f', BUT will it be the same outside of this function? lets see\n", *x);
}
Here is the output: (read this first)
a's value: bf94c204
b's value: bf94c208
f's value: bf94c20c
can we change a?, lets see
a = b
a's value is now: bf94c208, same as 'b'... it seems we can, but can we do it in a function? lets see...
cant_change(a, f);
----> value of 'a' is: bf94c20c inside function, same as 'f', BUT will it be the same outside of this function? lets see
a's value is now: bf94c208, Doh! same as 'b'... that function tricked us.
NOW! lets see if a pointer to a pointer solution can help us... remember that 'pp' point to 'a'
change(pp, f);
----> value of 'a' is: bf94c20c inside function, same as 'f', BUT will it be the same outside of this function? lets see
a's value is now: bf94c20c, YEAH! same as 'f'... that function ROCKS!!!.
press Ctrl + H . Then choose "File Search" tab.
additional search options
search for resources: Ctrl + Shift + R
search for Java types: Ctrl + Shift + T
You cannot start a container from a Dockerfile.
The process goes like this:
Dockerfile =[
docker build
]=> Docker image =[docker run
]=> Docker container
To start (or run) a container you need an image. To create an image you need to build the Dockerfile[1].
[1]: you can also docker import
an image from a tarball or again docker load
.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.actionbar));
}
Put this code in your Activity's onCreate
method. This helped me.
You can do it like this in Lodash 4.x
var data = [{_x000D_
"name": "jim",_x000D_
"color": "blue",_x000D_
"age": "22"_x000D_
}, {_x000D_
"name": "Sam",_x000D_
"color": "blue",_x000D_
"age": "33"_x000D_
}, {_x000D_
"name": "eddie",_x000D_
"color": "green",_x000D_
"age": "77"_x000D_
}];_x000D_
_x000D_
console.log(_x000D_
_.chain(data)_x000D_
// Group the elements of Array based on `color` property_x000D_
.groupBy("color")_x000D_
// `key` is group's name (color), `value` is the array of objects_x000D_
.map((value, key) => ({ color: key, users: value }))_x000D_
.value()_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
_x000D_
Original Answer
var result = _.chain(data)
.groupBy("color")
.pairs()
.map(function(currentItem) {
return _.object(_.zip(["color", "users"], currentItem));
})
.value();
console.log(result);
Note: Lodash 4.0 onwards, the .pairs
function has been renamed to _.toPairs()
Changing anything in build.gradle file will re-sync everything again and the error will be gone.For me i changed the minSdkVersion and it worked. Don't worry this could happen if the system crashed or Android Studio was not shut properly.
POJO stands for Plain Old Java Object, and would be used to describe the same things as a "Normal Class" whereas a JavaBean follows a set of rules. Most commonly Beans use getters and setters to protect their member variables, which are typically set to private and have a no-argument public constructor. Wikipedia has a pretty good rundown of JavaBeans: http://en.wikipedia.org/wiki/JavaBeans
POJO is usually used to describe a class that doesn't need to be a subclass of anything, or implement specific interfaces, or follow a specific pattern.
What about this for a catch all...
if (string.IsNullOrEmpty(x.Trim())
{
}
This will trim all the spaces if they are there avoiding the performance penalty of IsWhiteSpace, which will enable the string to meet the "empty" condition if its not null.
I also think this is clearer and its generally good practise to trim strings anyway especially if you are putting them into a database or something.
In desktop apps (I know, only us dinosaurs write these anymore!) they are essential for getting relatively unchanging global application settings - the user language, path to help files, user preferences etc which would otherwise have to propogate into every class and every dialog.
Edit - of course these should be read-only !
instead of using time try timedelta:
from datetime import timedelta
t1 = timedelta(hours=7, minutes=36)
t2 = timedelta(hours=11, minutes=32)
t3 = timedelta(hours=13, minutes=7)
t4 = timedelta(hours=21, minutes=0)
arrival = t2 - t1
lunch = (t3 - t2 - timedelta(hours=1))
departure = t4 - t3
print(arrival, lunch, departure)
As Bevan said, but keep in mind, that the list-index is 0-based. If you want to move an element to the front of the list, you have to insert it at index 0 (not 1 as shown in your example).
I think the query you want is this:
SELECT BrandId, SUM(ICount),
SUM(sum(ICount)) over () as TotalCount,
100.0 * SUM(ICount) / SUM(sum(Icount)) over () as Percentage
FROM Table
WHERE DateId = 20130618
group by BrandId;
This does the group by
for brand. And it calculates the "Percentage". This version should produce a number between 0 and 100.
Create Sequence.
CREATE SEQUENCE user_role_id_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 3
CACHE 1;
ALTER TABLE user_role_id_seq
OWNER TO postgres;
and alter table
ALTER TABLE user_roles ALTER COLUMN user_role_id SET DEFAULT nextval('user_role_id_seq'::regclass);
I had some difficulty using the solutions already suggested for my specific use case, but figured it out eventually. I don't think my specific case is worthy of a new question, so I am posting my solution here for reference. (This is very closely related to the question and provides a solution for anyone else with a similar case to mine).
The code I ended up with looks like this:
public class HideableControl<T>: Control where T: class
{
private string _propertyName;
private PropertyInfo _propertyInfo;
public string PropertyName
{
get { return _propertyName; }
set
{
_propertyName = value;
_propertyInfo = typeof(T).GetProperty(value);
}
}
protected override bool GetIsVisible(IRenderContext context)
{
if (_propertyInfo == null)
return false;
var model = context.Get<T>();
if (model == null)
return false;
return (bool)_propertyInfo.GetValue(model, null);
}
protected void SetIsVisibleProperty(Expression<Func<T, bool>> propertyLambda)
{
var expression = propertyLambda.Body as MemberExpression;
if (expression == null)
throw new ArgumentException("You must pass a lambda of the form: 'vm => vm.Property'");
PropertyName = expression.Member.Name;
}
}
public interface ICompanyViewModel
{
string CompanyName { get; }
bool IsVisible { get; }
}
public class CompanyControl: HideableControl<ICompanyViewModel>
{
public CompanyControl()
{
SetIsVisibleProperty(vm => vm.IsVisible);
}
}
The important part for me is that in the CompanyControl
class the compiler will only allow me to choose a boolean property of ICompanyViewModel
which makes it easier for other developers to get it right.
The main difference between my solution and the accepted answer is that my class is generic and I only want to match properties from the generic type that are boolean.
For multiple files; note the newer "multiple" attribute for input:
Form:
@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"}))
{
<label for="files">Filename:</label>
<input type="file" name="files" multiple="true" id="files" />
<input type="submit" />
}
Controller:
[HttpPost]
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files)
{
return View();
}
It depends on what you are developing.
A content-oriented website will have its content changing frequently and a Website is better for that.
An application tends to have its data stored in a database and its pages and code change rarely. In this case it's better to have a Web application where deployment of assemblies is much more controlled and has better support for unit testing.
Is it standard behaviour for browsers to only send the checkbox input value data if it is checked upon form submission?
Yes, because otherwise there'd be no solid way of determining if the checkbox was actually checked or not (if it changed the value, the case may exist when your desired value if it were checked would be the same as the one that it was swapped to).
And if no value data is supplied, is the default value always "on"?
Other answers confirm that "on" is the default. However, if you are not interested in the value, just use:
if (isset($_POST['the_checkbox'])){
// name="the_checkbox" is checked
}
body.addEventListener("load", init(), false);
That init() is saying run this function now and assign whatever it returns to the load event.
What you want is to assign the reference to the function, not the result. So you need to drop the ().
body.addEventListener("load", init, false);
Also you should be using window.onload and not body.onload
addEventListener
is supported in most browsers except IE 8.
I tried everything, nothing worked.then I tried the following steps and it worked
close Android studio
go to "My Documents"
delete the following folders a).android, b).androidstudio1.5, c).gradle
start Android studio and enjoy...
It seems stupid but works...
In my case ASP.NET State Service
was stopped. Changing the Startup type
to Automatic
and starting the service manually for the first time solved the issue.
A multiple select is really just a select with a multiple
attribute. With that in mind, it should be as easy as...
Form::select('sports[]', $sports, null, array('multiple'))
The first parameter is just the name, but post-fixing it with the []
will return it as an array when you use Input::get('sports')
.
The second parameter is an array of selectable options.
The third parameter is an array of options you want pre-selected.
The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple
property to the actual select element..
I know this is an old question but the most up to date answer is to use the Android Support Design library that will make your life easy.
You've done twice the checking when you create
${someObject.someProperty != null} ? ${someObject.someProperty}
You should do it clean and simple as below.
<td th:text="${someObject.someProperty} ? ${someObject.someProperty} : 'null value!'"></td>
-> Go to pom.xml
-> Add this Dependency :
-> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
->Wait for Rebuild or manually rebuild the project
->if Maven is not auto build in your machine then manually follow below points to rebuild
right click on your project structure->Maven->Update Project->check "force update of snapshots/Releases"
As per the above this will fix server side validation of an Email Address:
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
However...
If you are using JQuery client side validation you should know that the Email validates differently server side (model validation) to client side (JQuery validation). In that test@example (a top level domain email address) would fail server side but would validate fine on the client side.
To fix this disparity you can override the default client side email validation as follows:
$.validator.methods.email = function (value, element) {
return this.optional(element) || /^[a-z0-9._]+@[a-z]+\.[a-z.]+/.test(value);
}
The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.
For example:
var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}
//that will not work.
delete myObj.test.keyToDelete
instead you would need to use:
delete myObj.test[keyToDelete];
Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.
With Perl you can use the HTML::TableExtract
module to extract the data from the table and then use Text::CSV_XS
to create a CSV file or Spreadsheet::WriteExcel
to create an Excel file.
thanks to Jim Petkus that did gave me a wonderful answer . but i was trying to solve my own script not to changing it to another plugin . My main focus was not using an independent plugin and do what i wanted just by using the jquery core !
and guess what i did find the problem .
var title = $("em").attr("title");
$("div").text(title);
this is what i add to my script and the blew codes to my html part :
<td> <em title=\"$weight\">$weight</em></td>
and found each row $weight value
thanks again to Jim Petkus
No, it's seriously not worth changing. The sort of improvements you're going to get when fiddling with micro-optimisations like this will not be worth it. Even the method call cost will be removed if the min
function is called enough.
If you have a problem with your algorithm, your best bet is to look into macro-optimisations ("big picture" stuff like algorithm selection or tuning) - you'll generally get much better performance improvements there.
And your comment that removing Math.pow
gave improvements may well be correct but that's because it's a relatively expensive operation. Math.min
will not even be close to that in terms of cost.
Give this a try
$indo=$_GET['id'];
$result = mysql_query("SELECT * FROM student WHERE IDNO='$indo'");
I think this works..
Direct download:
Go to the project repository from the dashboard of bitbucket. Select downloads from the left menu. Choose Download repository.
If you have it available, I would consider using numpy. It's very fast for these types of operations:
>>> import numpy
>>> numpy.array([1,2,3]) + 2
array([3, 4, 5])
This is assuming your real application is doing mathematical operations (that can be vectorized).
Neither is good.
Behaviour should be configured independent of the actual markup. For instance, in jQuery you might do something like
$('#the-element').click(function () { /* perform action here */ });
in a separate <script>
block.
The advantage of this is that it
Furthermore, it degrades gracefully (but so would using the onclick
event) since you can provide the link tags with a href
in case the user doesn’t have JavaScript enabled.
Of course, these arguments still count if you’re not using jQuery or another JavaScript library (but why do that?).
JUnit has built-in support for this, with an "expected" attribute.
! is a logical NOT operator, it's a boolean operator that will invert something to its opposite.
Although you can bypass the parentheses of the invoked function by using the BANG (!) before the function, it will still invert the return, which might not be what you wanted. As in the case of an IEFE, it would return undefined, which when inverted becomes the boolean true.
Instead, use the closing parenthesis and the BANG (!) if needed.
// I'm going to leave the closing () in all examples as invoking the function with just ! and () takes away from what's happening.
(function(){ return false; }());
=> false
!(function(){ return false; }());
=> true
!!(function(){ return false; }());
=> false
!!!(function(){ return false; }());
=> true
Other Operators that work...
+(function(){ return false; }());
=> 0
-(function(){ return false; }());
=> -0
~(function(){ return false; }());
=> -1
Combined Operators...
+!(function(){ return false; }());
=> 1
-!(function(){ return false; }());
=> -1
!+(function(){ return false; }());
=> true
!-(function(){ return false; }());
=> true
~!(function(){ return false; }());
=> -2
~!!(function(){ return false; }());
=> -1
+~(function(){ return false; }());
+> -1
In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:
db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);
If you don't, unless there's some Join()
override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):
db.Services.Join(db.ServiceAssignments,
s => s.Id,
sa => sa.ServiceId,
(s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);
Why not write a piece of code like:
int max_neg = ~(1 << 31);
int all_ones = -1;
int max_pos = all_ones & max_neg;
Here's another solution. It's compact and reasonably efficient:
std::vector<std::string> split(const std::string &text, char sep) {
std::vector<std::string> tokens;
std::size_t start = 0, end = 0;
while ((end = text.find(sep, start)) != std::string::npos) {
tokens.push_back(text.substr(start, end - start));
start = end + 1;
}
tokens.push_back(text.substr(start));
return tokens;
}
It can easily be templatised to handle string separators, wide strings, etc.
Note that splitting ""
results in a single empty string and splitting ","
(ie. sep) results in two empty strings.
It can also be easily expanded to skip empty tokens:
std::vector<std::string> split(const std::string &text, char sep) {
std::vector<std::string> tokens;
std::size_t start = 0, end = 0;
while ((end = text.find(sep, start)) != std::string::npos) {
if (end != start) {
tokens.push_back(text.substr(start, end - start));
}
start = end + 1;
}
if (end != start) {
tokens.push_back(text.substr(start));
}
return tokens;
}
If splitting a string at multiple delimiters while skipping empty tokens is desired, this version may be used:
std::vector<std::string> split(const std::string& text, const std::string& delims)
{
std::vector<std::string> tokens;
std::size_t start = text.find_first_not_of(delims), end = 0;
while((end = text.find_first_of(delims, start)) != std::string::npos)
{
tokens.push_back(text.substr(start, end - start));
start = text.find_first_not_of(delims, end);
}
if(start != std::string::npos)
tokens.push_back(text.substr(start));
return tokens;
}
Use that Code
$('#button').submit(function(e) {
e.preventDefault();
// Coding
$('#IDModal').modal('toggle'); //or $('#IDModal').modal('hide');
return false;
});
The difference between:
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
and
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
is thus:
myscript.py
=> debug is 7 (from default) in the first case and "None" in the second
myscript.py --debug
=> debug is 1 in each case
myscript.py --debug 2
=> debug is 2 in each case
easiest method is songdetails..
for read data
import songdetails
song = songdetails.scan("blah.mp3")
if song is not None:
print song.artist
similarly for edit
import songdetails
song = songdetails.scan("blah.mp3")
if song is not None:
song.artist = u"The Great Blah"
song.save()
Don't forget to add u before name until you know chinese language.
u can read and edit in bulk using python glob module
ex.
import glob
songs = glob.glob('*') # script should be in directory of songs.
for song in songs:
# do the above work.
I recently posted a free software library for this: "html5csv.js" -- GitHub
It is intended to help streamline the creation of small simulator apps in Javascript that might need to import or export csv files, manipulate, display, edit the data, perform various mathematical procedures like fitting, etc.
After loading "html5csv.js" the problem of scanning a table and creating a CSV is a one-liner:
CSV.begin('#PrintDiv').download('MyData.csv').go();
Here is a JSFiddle demo of your example with this code.
Internally, for Firefox/Chrome this is a data URL oriented solution, similar to that proposed by @italo, @lepe, and @adeneo (on another question). For IE
The CSV.begin()
call sets up the system to read the data into an internal array. That fetch then occurs. Then the .download()
generates a data URL link internally and clicks it with a link-clicker. This pushes a file to the end user.
According to caniuse IE10 doesn't support <a download=...>
. So for IE my library calls navigator.msSaveBlob()
internally, as suggested by @Manu Sharma
It should be pretty obvious from your question that you're actually just asking about the difference between git merge
and git rebase
.
So let's suppose you're in the common case - you've done some work on your master branch, and you pull from origin's, which also has done some work. After the fetch, things look like this:
- o - o - o - H - A - B - C (master)
\
P - Q - R (origin/master)
If you merge at this point (the default behavior of git pull), assuming there aren't any conflicts, you end up with this:
- o - o - o - H - A - B - C - X (master)
\ /
P - Q - R --- (origin/master)
If on the other hand you did the appropriate rebase, you'd end up with this:
- o - o - o - H - P - Q - R - A' - B' - C' (master)
|
(origin/master)
The content of your work tree should end up the same in both cases; you've just created a different history leading up to it. The rebase rewrites your history, making it look as if you had committed on top of origin's new master branch (R
), instead of where you originally committed (H
). You should never use the rebase approach if someone else has already pulled from your master branch.
Finally, note that you can actually set up git pull
for a given branch to use rebase instead of merge by setting the config parameter branch.<name>.rebase
to true. You can also do this for a single pull using git pull --rebase
.
Use the -ss
option:
ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
For JPEG output use -q:v
to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.
The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.
Placing -ss
before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg
cli tool documentation:
-ss
position (input/output)When used as an input option (before
-i
), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, soffmpeg
will seek to the closest seek point before position. When transcoding and-accurate_seek
is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when-noaccurate_seek
is used, it will be preserved.When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.
position may be either in seconds or in
hh:mm:ss[.xxx]
form.
The easiest way to do this is to give each of your objects its own unique toString
method:
(function() {
var id = 0;
/*global MyObject */
MyObject = function() {
this.objectId = '<#MyObject:' + (id++) + '>';
this.toString= function() {
return this.objectId;
};
};
})();
I had the same problem and this solved it perfectly for me with minimal fuss, and was a lot easier that re-implementing some fatty Java style Hashtable
and adding equals()
and hashCode()
to your object classes. Just make sure that you don't also stick a string '<#MyObject:12> into your hash or it will wipe out the entry for your exiting object with that id.
Now all my hashes are totally chill. I also just posted a blog entry a few days ago about this exact topic.
T[]
int
constant or int
expression, see n
below)T[]
has one read-only field: length
and an index operator [int]
for reading/writing data at certain indices.1.
String[] array= new String[]{};
what is the use of { } here ?
It initializes the array with the values between { }
. In this case 0 elements, so array.length == 0
and array[0] throws IndexOutOfBoundsException: 0
.
2. what is the diff between
String array=new String[];
andString array=new String[]{};
The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[]
not just String
. Ignoring that (probably just a typo) the difference is:
new String[] // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0] // size is known, it has 0 elements, explicitly sized
3. when am writing
String array=new String[10]{};
got error why ?
(Again, ignoring the missing []
before array
) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}
.
Just make up your mind and use one of those - Java thinks.
help me i am confused
String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2
(Here, "same as" means it will construct the same array.)
Perhaps is way too late to respond but, make sure your session is initialized before destroying it.
session_start() ;
session_destroy() ;
i.e. you cannot destroy a session in logout.php if you initialized your session in index.php. You must start the session in logout.php before destroying it.
If you can use Java NIO (JDK 1.4 or greater), then I think you're looking for java.nio.channels.FileChannel.lock()
This answer may help some. The adb.exe has problems with virtual devices when you are using your phone for tethering. If you turn off tethering it will correct the problem.
Since there's no Request context in the pipeline during app start anymore, I can't imagine there's any way to guess what server/port the next actual request might come in on. You have to so it on Begin_Session.
Here's what I'm using when not in Classic Mode. The overhead is negligible.
/// <summary>
/// Class is called only on the first request
/// </summary>
private class AppStart
{
static bool _init = false;
private static Object _lock = new Object();
/// <summary>
/// Does nothing after first request
/// </summary>
/// <param name="context"></param>
public static void Start(HttpContext context)
{
if (_init)
{
return;
}
//create class level lock in case multiple sessions start simultaneously
lock (_lock)
{
if (!_init)
{
string server = context.Request.ServerVariables["SERVER_NAME"];
string port = context.Request.ServerVariables["SERVER_PORT"];
HttpRuntime.Cache.Insert("basePath", "http://" + server + ":" + port + "/");
_init = true;
}
}
}
}
protected void Session_Start(object sender, EventArgs e)
{
//initializes Cache on first request
AppStart.Start(HttpContext.Current);
}
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
You can try this method:
</p><br /><br />
<p>ng-class="{test: obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}<br /><br /><br />
ng-class="{test: obj.value1 == 'someothervalue' || obj.value2 == 'somethingelse'}
You can get complete details from here.
After the post from Gabor Grothendieck post at the r-help mailing list
years<-c("20 years old", "1 years old")
library(gsubfn)
pat <- "[-+.e0-9]*\\d"
sapply(years, function(x) strapply(x, pat, as.numeric)[[1]])
Here's a working sample of NSNumberFormatter reading localized number String (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks such as "8,765.4 ", this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)
NSString *tempStr = @"8,765.4";
// localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
// next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial
NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(@"string '%@' gives NSNumber '%@' with intValue '%i'",
tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release]; // good citizen
if in string:
string yourVar = yourTextBoxname.Text;
if in numbers:
int yourVar = int.Parse(yourTextBoxname.Text);
It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==
, the following should work:
byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);
This will output: YWJjZGVmPT0=
which is abcdef==
encoded in Base64.
Edit:
To decode a Base64 string, simply use Convert.FromBase64String()
. E.g.
string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);
At this point, bytes
will be a byte[]
(not a string
). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
This will output the original input string, abcdef==
in this case.
I use maven for my java builds which has a plugin called the maven assembly plugin.
It does what your asking, but like some of the other suggestions describe - essentially exploding all the dependent jars and recombining them into a single jar
Yes its possible! and you can use as many colors and images as you desire, here is the right way:
body{_x000D_
/* Its, very important to set the background repeat to: no-repeat */_x000D_
background-repeat:no-repeat; _x000D_
_x000D_
background-image: _x000D_
/* 1) An image */ url(http://lorempixel.com/640/100/nature/John3-16/), _x000D_
/* 2) Gradient */ linear-gradient(to right, RGB(0, 0, 0), RGB(255, 255, 255)), _x000D_
/* 3) Color(using gradient) */ linear-gradient(to right, RGB(110, 175, 233), RGB(110, 175, 233));_x000D_
_x000D_
background-position:_x000D_
/* 1) Image position */ 0 0, _x000D_
/* 2) Gradient position */ 0 100px,_x000D_
/* 3) Color position */ 0 130px;_x000D_
_x000D_
background-size: _x000D_
/* 1) Image size */ 640px 100px,_x000D_
/* 2) Gradient size */ 100% 30px, _x000D_
/* 3) Color size */ 100% 30px;_x000D_
}
_x000D_
You are calling the one.start()
method in the run
method of your Thread. But the run
method will only be called when a thread is already started. Do this instead:
one = new Thread() {
public void run() {
try {
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
} catch(InterruptedException v) {
System.out.println(v);
}
}
};
one.start();
Simply Use
FragmentManager fm = getActivity().getSupportFragmentManager();
Remember always when accessing fragment inflating in MainLayout use
Casting or getActivity()
.
I have added line
$this->_productCollection->addAttributeToSelect('releasedate');
in
app/code/core/Mage/Catalog/Block/Product/List.php on line 95
in function _getProductCollection()
and then call it in
app/design/frontend/default/hellopress/template/catalog/product/list.phtml
By writing code
<div><?php echo $this->__('Release Date: %s', $this->dateFormat($_product->getReleasedate())) ?>
</div>
Now it is working in Magento 1.4.x
As Benjamin said in his answer, TC39 explicitly decided not to include this feature at least for ES2015. However, the consensus seems to be that they will add it in ES2016.
The syntax hasn't been decided yet, but there's a preliminary proposal for ES2016 that will allow you to declare static properties on a class.
Thanks to the magic of babel, you can use this today. Enable the class properties transform according to these instructions and you're good to go. Here's an example of the syntax:
class foo {
static myProp = 'bar'
someFunction() {
console.log(this.myProp)
}
}
This proposal is in a very early state, so be prepared to tweak your syntax as time goes on.
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
In the latter case, if obj is null you won't get a NullPointerException but a false.
$eval
and $parse
don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.
Q: What exactly is $eval doing? Why does it need its own mini parsing language?
From the docs:
Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.
It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).
Q: Why isn't plain old javascript "eval" being used?
Because it's not actually evaluating JavaScript. As the docs say:
If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.
The docs linked to above have a lot more information.
For serializable deep clone, with Type Information is,
export function clone<T>(a: T): T {
return JSON.parse(JSON.stringify(a));
}
Even though this question asked is old, note that changing a UUID on a virtual HDD in a windows system will make windows treat it as a not activated machine (as it notices the disk change) and will ask for reactivation !
SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).
The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).
Use a HashSet<T>
. For example:
var items = "A B A D A C".Split(' ');
var unique_items = new HashSet<string>(items);
foreach (string s in unique_items)
Console.WriteLine(s);
prints
A B D C
It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment environment;
....
this.environment.getActiveProfiles();
Popen.communicate
will set the returncode
attribute when it's done(*). Here's the relevant documentation section:
Popen.returncode
The child return code, set by poll() and wait() (and indirectly by communicate()).
A None value indicates that the process hasn’t terminated yet.
A negative value -N indicates that the child was terminated by signal N (Unix only).
So you can just do (I didn't test it but it should work):
import subprocess as sp
child = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE)
streamdata = child.communicate()[0]
rc = child.returncode
(*) This happens because of the way it's implemented: after setting up threads to read the child's streams, it just calls wait
.
On a MAC, you need to use nm *.o | c++filt
, as there is no -C
option in nm
.
It is basically a header file that also includes every standard library and STL include file. The only purpose I can see for it would be for testing and education.
Se e.g. GCC 4.8.0 /bits/stdc++.h source.
Using it would include a lot of unnecessary stuff and increases compilation time.
Edit: As Neil says, it's an implementation for precompiled headers. If you set it up for precompilation correctly it could, in fact, speed up compilation time depending on your project. (https://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html)
I would, however, suggest that you take time to learn about each of the sl/stl headers and include them separately instead, and not use "super headers" except for precompilation purposes.
Commenting just so people can have a solution to the intended question.
You can do what you are wanting but it isn't quite as nice as Notepad++ but it may work for small solutions decently enough.
In sublime if you hold ctrl, or mac equiv., and select the word/characters you want on a single line with the mouse and still holding ctrl go to another line and select the word/characters you want on that line it will be additive and you will build your selection. I mainly use notepadd++ as my extractor and data cleanup and sublime for actual development.
The other way is if your columns are in perfect alignment you can simply middle click on windows or option + click on mac and this enables you to select text in a square like fashion, Columns, inside the lines of text.
Another simple solution too
arr = [0,4,8,2,5,0,2,6]
arr.sum(0.0) / arr.size
I just encountered the same issue, my system is Win7. just use the command on terminal like: netstat -na|findstr port, you will see the port has been used. So if you want to start the server without this message, you can change other port that not been used.
I found a tool called ttyplot
in homebrew. It's good. https://github.com/tenox7/ttyplot
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/white" />
<corners android:radius="4dp" />
</shape>
In kotlin:
override fun onBackPressed() {
when {
webView.canGoBack() -> webView.goBack()
else -> super.onBackPressed()
}
}
webView - id of the webview component in xml, if using synthetic reference.
Easy. Just follow the code below and enjoy.
//SwipeGestureMethodUsing
func SwipeGestureMethodUsing ()
{
//AddSwipeGesture
[UISwipeGestureRecognizerDirection.right,
UISwipeGestureRecognizerDirection.left,
UISwipeGestureRecognizerDirection.up,
UISwipeGestureRecognizerDirection.down].forEach({ direction in
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
swipe.direction = direction
window?.addGestureRecognizer(swipe)
})
}
//respondToSwipeGesture
func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer
{
switch swipeGesture.direction
{
case UISwipeGestureRecognizerDirection.right:
print("Swiped right")
case UISwipeGestureRecognizerDirection.down:
print("Swiped down")
case UISwipeGestureRecognizerDirection.left:
print("Swiped left")
case UISwipeGestureRecognizerDirection.up:
print("Swiped up")
default:
break
}
}
}
This little library may help you. But be aware that browser detection is not always the solution.
Because my edits to the above were rejected (did any of you actually try?), here's what you really need to make this work:
Windows (And Mac Office 2011+):
(Excel Timestamp - 25569) * 86400
(Unix Timestamp / 86400) + 25569
MAC OS X (pre Office 2011):
(Excel Timestamp - 24107) * 86400
(Unix Timestamp / 86400) + 24107
<a onclick="yourfunction()">
this will work fine . no need to add href="#"
Execute chmod 777 -R scripts/
, it worked fine for me ;)
TimeSpan.FromTicks(28000000000).TotalMinutes;
As other people have pointed out, relying on the parent pid to become 1 when the parent exits is non-portable. Instead of waiting for a specific parent process ID, just wait for the ID to change:
pit_t pid = getpid();
switch (fork())
{
case -1:
{
abort(); /* or whatever... */
}
default:
{
/* parent */
exit(0);
}
case 0:
{
/* child */
/* ... */
}
}
/* Wait for parent to exit */
while (getppid() != pid)
;
Add a micro-sleep as desired if you don't want to poll at full speed.
This option seems simpler to me than using a pipe or relying on signals.
STR_TO_DATE allows you to do this, and it has a format argument.
notify()
- Selects a random thread from the wait set of the object and puts it in the BLOCKED
state. The rest of the threads in the wait set of the object are still in the WAITING
state.
notifyAll()
- Moves all the threads from the wait set of the object to BLOCKED
state. After you use notifyAll()
, there are no threads remaining in the wait set of the shared object because all of them are now in BLOCKED
state and not in WAITING
state.
BLOCKED
- blocked for lock acquisition.
WAITING
- waiting for notify ( or blocked for join completion ).
Another one:
def local_maxima_mask(vec):
"""
Get a mask of all points in vec which are local maxima
:param vec: A real-valued vector
:return: A boolean mask of the same size where True elements correspond to maxima.
"""
mask = np.zeros(vec.shape, dtype=np.bool)
greater_than_the_last = np.diff(vec)>0 # N-1
mask[1:] = greater_than_the_last
mask[:-1] &= ~greater_than_the_last
return mask
via Facebook's Platform Updates:
Change in Session Redirect Behavior
This week, we started adding a fragment #____=____ to the redirect_uri when this field is left blank. Please ensure that your app can handle this behavior.
To prevent this, set the redirect_uri in your login url request like so: (using Facebook php-sdk)
$facebook->getLoginUrl(array('redirect_uri' => $_SERVER['SCRIPT_URI'],'scope' => 'user_about_me'));
UPDATE
The above is exactly as the documentation says to fix this. However, Facebook's documented solution does not work. Please consider leaving a comment on the Facebook Platform Updates blog post and follow this bug to get a better answer. Until then, add the following to your head tag to resolve this issue:
<script type="text/javascript">
if (window.location.hash && window.location.hash == '#_=_') {
window.location.hash = '';
}
</script>
Or a more detailed alternative (thanks niftylettuce):
<script type="text/javascript">
if (window.location.hash && window.location.hash == '#_=_') {
if (window.history && history.pushState) {
window.history.pushState("", document.title, window.location.pathname);
} else {
// Prevent scrolling by storing the page's current scroll offset
var scroll = {
top: document.body.scrollTop,
left: document.body.scrollLeft
};
window.location.hash = '';
// Restore the scroll offset, should be flicker free
document.body.scrollTop = scroll.top;
document.body.scrollLeft = scroll.left;
}
}
</script>
As of yet there are no parent selectors (or as Shaun Inman calls them, qualified selectors), so you will have to apply styles to the child list items to override the styles on the parent list items.
Cascading is sort of the whole point of Cascading Style Sheets, hence the name.
You should almost always use a return value. 'out
' parameters create a bit of friction to a lot of APIs, compositionality, etc.
The most noteworthy exception that springs to mind is when you want to return multiple values (.Net Framework doesn't have tuples until 4.0), such as with the TryParse
pattern.
where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS')
should work.
I don't know if/where it's published, but you can get the latest release by omitting the minor and build numbers.
Latest 1.8.x:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
Latest 1.x:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
However, do keep in mind that these links have a much shorter cache timeout than with the full version number, so your users may be downloading them more than you'd like. See The crucial .0 in Google CDN references to jQuery 1.x.0 for more information.
Don't know, if it's a good idea or not: After trying all other solutions without success, I just renamed /usr/local/lib/dtrace, linked node and re-renamed the directory again. After that, node worked as expected.
You can take a look here for a longer list of screen sizes and respective media queries.
Or go for Bootstrap media queries:
/* Large desktop */
@media (min-width: 1200px) { ... }
/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }
/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }
/* Landscape phones and down */
@media (max-width: 480px) { ... }
Additionally you might wanty to take a look at Foundation's media queries with the following default settings:
// Media Queries
$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;
Perhaps you should check your IDE case sensitive properties. I had the same problem, and solved it by making Idea case-sensitive (for my filesystem is case sensitive): https://confluence.jetbrains.com/display/IDEADEV/Filesystem+Case-Sensitivity+Mismatch
String dataIWant = mydata.replaceFirst(".*'(.*?)'.*", "$1");
Another option would be to abandon the syntactic sugar and decorate in the __init__
of the class.
def countdown(number):
def countdown_decorator(func):
def func_wrapper():
for index in reversed(range(1, number+1)):
print(index)
func()
return func_wrapper
return countdown_decorator
class MySuperClass():
def __init__(self, number):
self.number = number
self.do_thing = countdown(number)(self.do_thing)
def do_thing(self):
print('im doing stuff!')
myclass = MySuperClass(3)
myclass.do_thing()
which would print
3
2
1
im doing stuff!
I was going to post the steps
-timed polyfill, but then I remembered that I really don’t want to ever see this effect, so…
function blink(element, interval) {
var visible = true;
setInterval(function() {
visible = !visible;
element.style.visibility = visible ? "visible" : "hidden";
}, interval || 1000);
}
In Windows, you can use /
in your path just like Linux or macOS in all places as long as you use PowerShell as your command-line interface. It comes pre-installed on Windows and it supports many Linux commands like ls
command.
If you use Windows Command Prompt (the one that appears when you type cmd
in Windows Start Menu), you need to specify paths with \
just inside it. You can use /
paths in all other places (code editor, Python interactive mode, etc.).
cin.get()
seems to flush it automatically oddly enough (probably not preferred though, since this is confusing and probably temperamental).
I use a slightly more concise version:
expect(() => {
// Code block that should throw error
}).toThrow(TypeError) // Or .toThrow('expectedErrorMessage')
Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.
you have an array of int
which is a primitive type, primitive type doesn't have the method add. You should look for Collections
.
Provided both machines are in the same workgroup, open cmd.exe
on the machine you want to connect to, type ipconfig
and note the IP at the IPv4 Address
line.
Then, on the machine you want to connect with, use http:// + the IP of the target machine
.
That should do it.
It contains your local IntelliJ IDE configs. I recommend adding this folder to your .gitignore
file:
# intellij configs
.idea/
For basic out of the box python with bs4 installed then you can process your xml with
soup = BeautifulSoup(html, "html5lib")
If however you want to use formatter='xml' then you need to
pip3 install lxml
soup = BeautifulSoup(html, features="xml")
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();
i think u miss understand about table relation..
users : scores = 1 : *
just join
is not a solution.
is this your intention?
SELECT users.username, avg(scores.point), avg(scores.avg_time)
FROM scores, users
WHERE scores.user_id = users.id
GROUP BY users.username
ORDER BY avg(scores.point) DESC, avg(scores.avg_time)
LIMIT 0, 20
(this query to get each users average point and average avg_time by desc point, asc )avg_time
if you want to get each scores ranking? use left outer join
SELECT users.username, scores.point, scores.avg_time
FROM scores left outer join users on scores.user_id = users.id
ORDER BY scores.point DESC, scores.avg_time
LIMIT 0, 20
You could also have embed all of your template views into your main html file. For Example:
<body ng-app="testApp">
<h1>Test App</h1>
<div ng-view></div>
<script type = "text/ng-template" id = "index.html">
<h1>Index Page</h1>
<p>{{message}}</p>
</script>
<script type = "text/ng-template" id = "home.html">
<h1>Home Page</h1>
<p>{{message}}</p>
</script>
</body>
This way if each template requires a different controller then you can still use the angular-router. See this plunk for a working example http://plnkr.co/edit/9X0fT0Q9MlXtHVVQLhgr?p=preview
This way once the application is sent from the server to your client, it is completely self contained assuming that it doesn't need to make any data requests, etc.
To Trigger OnChange in ObservableCollection List
Example:
int index = NotificationDetails.IndexOf(notificationDetails);
NotificationDetails.Remove(notificationDetails);
NotificationDetails.Insert(index, notificationDetails);
If you use a Language Resource file to set the labels in your application you need to set the its value:
CultureInfo customCulture = new CultureInfo("en-US");
Languages.Culture = customCulture;
@RequestMapping(path="/apps/add", method=RequestMethod.POST)
public String addApps(String appUrl, Model model, final RedirectAttributes redirectAttrs) {
if (!validate(appUrl)) {
redirectAttrs.addFlashAttribute("error", "Validation failed");
}
return "redirect:/apps/add"
}
@RequestMapping(path="/apps/add", method=RequestMethod.GET)
public String addAppss(Model model) {
String error = model.asMap().get("error");
}
npm start
runs a script that the app maker built for easy starting of the app
npm install
installs all the packages in package.json
run npm install
first
then run npm start
using fragment
writing code in onCreateView()
RecyclerView recyVideo = view.findViewById(R.id.recyVideoFag);
using activity
writing code in onCreate() RecyclerView recyVideo = findViewById(R.id.recyVideoFag);
In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before
css to match yours.
In case if it is IE10 then using below css3 it is possible
select::-ms-expand {
display: none;
}
However if you're interested in jQuery plugin, try Chosen.js
or you can create your own in js.
If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.
I was able to figure this out; it was a lot simpler then I thought. Under the WHM manager go to: Home >> Software >> EasyApache (Apache Update) >> There you have two options "Build Profile" or "Customize Based On Profile". I went Customize to keep my current config then followed the instructions on the page.
Eventually there was a place to add and remove php modules. There you will find ever module under the sun. Just select the one you want and rebuild the profile. It was really that simple.
For those who found this question hoping to find an answer that doesn't involve jQuery, you hook into the window
"scroll" event using normal event listening. Say we want to add scroll listening to a number of CSS-selector-able elements:
// what should we do when scrolling occurs
var runOnScroll = function(evt) {
// not the most exciting thing, but a thing nonetheless
console.log(evt.target);
};
// grab elements as array, rather than as NodeList
var elements = document.querySelectorAll("...");
elements = Array.prototype.slice.call(elements);
// and then make each element do something on scroll
elements.forEach(function(element) {
window.addEventListener("scroll", runOnScroll, {passive: true});
});
(Using the passive attribute to tell the browser that this event won't interfere with scrolling itself)
For bonus points, you can give the scroll handler a lock mechanism so that it doesn't run if we're already scrolling:
// global lock, so put this code in a closure of some sort so you're not polluting.
var locked = false;
var lastCall = false;
var runOnScroll = function(evt) {
if(locked) return;
if (lastCall) clearTimeout(lastCall);
lastCall = setTimeout(() => {
runOnScroll(evt);
// you do this because you want to handle the last
// scroll event, even if it occurred while another
// event was being processed.
}, 200);
// ...your code goes here...
locked = false;
};
git diff <local branch> <remote>/<remote branch>
For example git diff main origin/main
, or git diff featureA origin/next
Of course to have said remote-tracking branch you need to git fetch
first; and you need it to have up to date information about branches in remote repository.
you can also do in this way using input-group
<div class="input-group">
<input class="form-control"
placeholder="I can help you to find anything you want!">
<div class="input-group-addon" ><i class="fa fa-search"></i></div>
</div>
Another possible solution is:
const link = document.createElement('a');
link.target = '_blank';
link.href = 'https://www.google.es';
link.setAttribute('visibility', 'hidden');
link.click();
Select Preferences -> Workspace Settings and add the following code, If you have Hot reload enabled, then the changes reflect immediately in the browser
{
"files.exclude": {
"**/.git": true,
"**/.DS_Store": true,
"**/*.js.map": true,
"**/*.js": {"when": "$(basename).ts"}
},
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 1000
}
Works Fine for App Notification settings on IOS 10 (tested)
if(&UIApplicationOpenSettingsURLString != nil){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
For anyone using AngularJS, a simple solution is to filter the value with the date API, which converts milliseconds to a string based on the requested format. Example:
<div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>
Note that this expects milliseconds, so you may want to multiply timeRemaining by 1000 if you are converting from seconds (as the original question was formulated).
Yes it is wise to use a version control system for your project. Anyway, focusing on your installation warning issue you can try to launch npm install command starting from your root project folder instead of outside of it, so the installation steps will only update the existing package-lock.json file instead of creating a new one. Hope this helps.
setFixedLengthStreamingMode(int) with contentLength parameters could set the fixed length of a HTTP request body.
For SSMS 18 (specifically 18.6), I found my backup here C:\Windows\SysWOW64\Visual Studio 2017\Backup Files\Solution1
.
Kudos to Matthew Lock for giving me the idea to just search across my whole machine!
On macOS High Sierra, this solved my issue:
sudo gem update --system -n /usr/local/bin/gem
One other way:
char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = string.Join("", chars);
//we get "a string"
// or for fun:
string s = string.Join("_", chars);
//we get "a_ _s_t_r_i_n_g"
If you want to show time on textview then better use Chronometer or TextClock
Using Chronometer:This was added in API 1. It has lot of option to customize it.
Your xml
<Chronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" />
Your activity
Chronometer mChronometer=(Chronometer) findViewById(R.id.chronometer);
mChronometer.setBase(SystemClock.elapsedRealtime());
mChronometer.start();
Using TextClock: This widget is introduced in API level 17. I personally like Chronometer.
Your xml
<TextClock
android:id="@+id/textClock"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:format12Hour="hh:mm:ss a"
android:gravity="center_horizontal"
android:textColor="#d41709"
android:textSize="44sp"
android:textStyle="bold" />
Thats it, you are done.
You can use any of these two widgets. This will make your life easy.
Try to using application/* instead. And use JSON.maybeJson() to check the data structure in the controller.
This is my solution:
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
// alert( pattern.test(emailAddress) );
return pattern.test(emailAddress);
};
Found that RegExp over here: http://mdskinner.com/code/email-regex-and-validation-jquery
I find the existing explanations too gobbledygook. Here's my explanation in plain English:
STA: If a thread creates a COM object that's set to STA (when calling CoCreateXXX you can pass a flag that sets the COM object to STA mode), then only this thread can access this COM object (that's what STA means - Single Threaded Apartment), other thread trying to call methods on this COM object is under the hood silently turned into delivering messages to the thread that creates(owns) the COM object. This is very much like the fact that only the thread that created a UI control can access it directly. And this mechanism is meant to prevent complicated lock/unlock operations.
MTA: If a thread creates a COM object that's set to MTA, then pretty much every thread can directly call methods on it.
That's pretty much the gist of it. Although technically there're some details I didn't mention, such as in the 'STA' paragraph, the creator thread must itself be STA. But this is pretty much all you have to know to understand STA/MTA/NA.
If using MVC 5 read this solution!
I know the question specifically called for MVC 3, but I stumbled upon this page with MVC 5 and wanted to post a solution for anyone else in my situation. I tried the above solutions, but they did not work for me, the Action Filter was never reached and I couldn't figure out why. I am using version 5 in my project and ended up with the following action filter:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
namespace SydHeller.Filters
{
public class ValidateJSONAntiForgeryHeader : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
string clientToken = filterContext.RequestContext.HttpContext.Request.Headers.Get(KEY_NAME);
if (clientToken == null)
{
throw new HttpAntiForgeryException(string.Format("Header does not contain {0}", KEY_NAME));
}
string serverToken = filterContext.HttpContext.Request.Cookies.Get(KEY_NAME).Value;
if (serverToken == null)
{
throw new HttpAntiForgeryException(string.Format("Cookies does not contain {0}", KEY_NAME));
}
System.Web.Helpers.AntiForgery.Validate(serverToken, clientToken);
}
private const string KEY_NAME = "__RequestVerificationToken";
}
}
-- Make note of the using System.Web.Mvc
and using System.Web.Mvc.Filters
, not the http
libraries (I think that is one of the things that changed with MVC v5. --
Then just apply the filter [ValidateJSONAntiForgeryHeader]
to your action (or controller) and it should get called correctly.
In my layout page right above </body>
I have @AntiForgery.GetHtml();
Finally, in my Razor page, I do the ajax call as follows:
var formForgeryToken = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
type: "POST",
url: serviceURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: requestData,
headers: {
"__RequestVerificationToken": formForgeryToken
},
success: crimeDataSuccessFunc,
error: crimeDataErrorFunc
});
Spent a few hours facing this issue this morning. I am likely to be the least technical person on these forums. Like the requester, I endured every reminder to set %JAVA_HOME%, biting my tongue each time I saw this non luminary advice. Finally I pondered whether my laptop's JRE was versions ahead of my JDK (as JREs are regularly updated automatically) and I installed the latest JDK. The difference was minor, emanating from a matter of weeks of different versions. I started with this error on jdk v 1.0865. The JRE was 1.0866. After installation, I had jdk v1.0874 and the equivalent JRE. At that point, I directed the Eclipse JRE to focus on my JDK and all was well. My println of java.home even reflected the correct JRE.
So much feedback repeated the wrong responses. I would strongly request that people read the feedback from others to avoid useless redundancy. Take care all, SG
Yes, it does, specially for very large SPA.
In some scenario, RequireJS is a must. For example, I develop PhoneGap applications using AngularJS that also uses Google Map API. Without AMD loader like RequireJS, the app would simply crash upon launch when offline as it cannot source the Google Map API scripts. An AMD loader gives me a chance to display an error message to the user.
However, integration between AngularJS and RequireJS is a bit tricky. I created angularAMD to make this a less painful process:
Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:
CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm
.PHONY: all
all: client
.PHONY: clean
clean:
$(RM) *~ *.o client
OBJECTS=client.o
client: $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)
In the line defining the client target change the order of $(LDFLAGS) as needed.
exit 1
is all you need. The 1
is a return code, so you can change it if you want, say, 1
to mean a successful run and -1
to mean a failure or something like that.
Don't just run the docker prune
command. It will delete all the docker networks, containers, and images. So you might end up losing the important data as well.
The error shows that "No space left on device" so we just need to free up some space.
The easiest way to free some space is to remove dangling images.
When the old created images are not being used those images are referred to as dangling images or there are some cache images as well which you can remove.
Use the below commands. To list all dangling images image id.
docker images -f "dangling=true" -q
to remove the images by image id.
docker rmi IMAGE_ID
This way you can free up some space and start hacking with docker again :)
Objective-c:
NSString *day = [@"10/04/2011" componentsSeparatedByString:@"/"][0];
Swift:
var day: String = "10/04/2011".componentsSeparatedByString("/")[0]
If you need to call the base constructor but not right away because your new (derived) class needs to do some data manipulation, the best solution is to resort to factory method. What you need to do is to mark private your derived constructor, then make a static method in your class that will do all the necessary stuff and later call the constructor and return the object.
public class MyClass : BaseClass
{
private MyClass(string someString) : base(someString)
{
//your code goes in here
}
public static MyClass FactoryMethod(string someString)
{
//whatever you want to do with your string before passing it in
return new MyClass(someString);
}
}
Are you looking for the following?
File.open(yourfile, 'w') { |file| file.write("your text") }
First you need to create a mock m_contractsDao and set it up. Assuming that the class is ContractsDao:
ContractsDao mock_contractsDao = mock(ContractsDao.class);
when(mock_contractsDao.save(any(String.class))).thenReturn("Some result");
Then inject the mock into m_orderSvc and call your method.
m_orderSvc.m_contractsDao = mock_contractsDao;
m_prog = new ProcessOrdersWorker(m_orderSvc, m_opportunitySvc, m_myprojectOrgSvc);
m_prog.work();
Finally, verify that the mock was called properly:
verify(mock_contractsDao, times(1)).save("Parameter I'm expecting");
If your post keys have to be parsed and the keys are sequences with data, you can try this:
Post data example: Storeitem|14=data14
foreach($_POST as $key => $value){
$key=Filterdata($key); $value=Filterdata($value);
echo($key."=".$value."<br>");
}
then you can use strpos to isolate the end of the key separating the number from the key.