A common cause for Chrome to crash during startup is running Chrome as
root
user (administrator
) on Linux. While it is possible to work around this issue by passing--no-sandbox
flag when creating your WebDriver session, such a configuration is unsupported and highly discouraged. You need to configure your environment to run Chrome as a regular user instead.
This error message...
org.openqa.selenium.WebDriverException: unknown error: DevToolsActivePort file doesn't exist
...implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.
Your code trials and the versioning information of all the binaries would have given us some hint about what's going wrong.
However as per Add --disable-dev-shm-usage to default launch flags seems adding the argument --disable-dev-shm-usage
will temporary solve the issue.
If you desire to initiate/span a new Chrome Browser session you can use the following solution:
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized"); // open Browser in maximized mode
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-gpu"); // applicable to windows os only
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox"); // Bypass OS security model
WebDriver driver = new ChromeDriver(options);
driver.get("https://google.com");
As per base_switches.cc disable-dev-shm-usage
seems to be valid only on Linux OS:
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
// The /dev/shm partition is too small in certain VM environments, causing
// Chrome to fail or crash (see http://crbug.com/715363). Use this flag to
// work-around this issue (a temporary directory will always be used to create
// anonymous shared memory files).
const char kDisableDevShmUsage[] = "disable-dev-shm-usage";
#endif
In the discussion Add an option to use /tmp instead of /dev/shm David mentions:
I think it would depend on how are /dev/shm and /tmp mounted. If they are both mounted as tmpfs I'm assuming there won't be any difference. if for some reason /tmp is not mapped as tmpfs (and I think is mapped as tmpfs by default by systemd), chrome shared memory management always maps files into memory when creating an anonymous shared files, so even in that case shouldn't be much difference. I guess you could force telemetry tests with the flag enabled and see how it goes.
As for why not use by default, it was a pushed back by the shared memory team, I guess it makes sense it should be useing /dev/shm for shared memory by default.
Ultimately all this should be moving to use memfd_create, but I don't think that's going to happen any time soon, since it will require refactoring Chrome memory management significantly.
You can find a couple of detailed discussions in:
Here is the link to the Sandbox story.
it simple way in xml:
android:maxLength="@{length}"
for setting it programmatically you can use the following function
public static void setMaxLengthOfEditText(EditText editText, int length) {
InputFilter[] filters = editText.getFilters();
List arrayList = new ArrayList();
int i2 = 0;
if (filters != null && filters.length > 0) {
int filtersSize = filters.length;
int i3 = 0;
while (i2 < filtersSize) {
Object obj = filters[i2];
if (obj instanceof LengthFilter) {
arrayList.add(new LengthFilter(length));
i3 = 1;
} else {
arrayList.add(obj);
}
i2++;
}
i2 = i3;
}
if (i2 == 0) {
arrayList.add(new LengthFilter(length));
}
if (!arrayList.isEmpty()) {
editText.setFilters((InputFilter[]) arrayList.toArray(new InputFilter[arrayList.size()]));
}
}
pip when used with virtualenv will generally install packages in the path <virtualenv_name>/lib/<python_ver>/site-packages
.
For example, I created a test virtualenv named venv_test with Python 2.7, and the django
folder is in venv_test/lib/python2.7/site-packages/django
.
list comprehension
.Half line solution:
common_elements = [x for x in list1 if x in list2]
If that helped, consider upvoting my answer.
Use array or common container for objects only if they have default and copy constructors.
Store pointers otherwise (or smart pointers, but may meet some issues in this case).
PS: Always define own default and copy constructors otherwise auto-generated will be used
You can use the Partial
mapped type as explained in the documentation:
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html
In your example, you'll have:
interface IX {
a: string;
b: any;
c: AnotherType;
}
let x: Partial<IX> = {
a: 'abc'
}
Via Type.GetType you can get the type information. You can use this class to get the method information and then invoke the method (for static methods, leave the first parameter null).
You might also need the Assembly name to correctly identify the type.
If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.
Sergey is correct, but if you need to get a response from your home-spun dialog(s) for evaluation in the same block of code that invoked it, you should use .showAndWait(), not .show(). Here's my rendition of a couple of the dialog types that are provided in Swing's OptionPane:
public class FXOptionPane {
public enum Response { NO, YES, CANCEL };
private static Response buttonSelected = Response.CANCEL;
private static ImageView icon = new ImageView();
static class Dialog extends Stage {
public Dialog( String title, Stage owner, Scene scene, String iconFile ) {
setTitle( title );
initStyle( StageStyle.UTILITY );
initModality( Modality.APPLICATION_MODAL );
initOwner( owner );
setResizable( false );
setScene( scene );
icon.setImage( new Image( getClass().getResourceAsStream( iconFile ) ) );
}
public void showDialog() {
sizeToScene();
centerOnScreen();
showAndWait();
}
}
static class Message extends Text {
public Message( String msg ) {
super( msg );
setWrappingWidth( 250 );
}
}
public static Response showConfirmDialog( Stage owner, String message, String title ) {
VBox vb = new VBox();
Scene scene = new Scene( vb );
final Dialog dial = new Dialog( title, owner, scene, "res/Confirm.png" );
vb.setPadding( new Inset(10,10,10,10) );
vb.setSpacing( 10 );
Button yesButton = new Button( "Yes" );
yesButton.setOnAction( new EventHandler<ActionEvent>() {
@Override public void handle( ActionEvent e ) {
dial.close();
buttonSelected = Response.YES;
}
} );
Button noButton = new Button( "No" );
noButton.setOnAction( new EventHandler<ActionEvent>() {
@Override public void handle( ActionEvent e ) {
dial.close();
buttonSelected = Response.NO;
}
} );
BorderPane bp = new BorderPane();
HBox buttons = new HBox();
buttons.setAlignment( Pos.CENTER );
buttons.setSpacing( 10 );
buttons.getChildren().addAll( yesButton, noButton );
bp.setCenter( buttons );
HBox msg = new HBox();
msg.setSpacing( 5 );
msg.getChildren().addAll( icon, new Message( message ) );
vb.getChildren().addAll( msg, bp );
dial.showDialog();
return buttonSelected;
}
public static void showMessageDialog( Stage owner, String message, String title ) {
showMessageDialog( owner, new Message( message ), title );
}
public static void showMessageDialog( Stage owner, Node message, String title ) {
VBox vb = new VBox();
Scene scene = new Scene( vb );
final Dialog dial = new Dialog( title, owner, scene, "res/Info.png" );
vb.setPadding( new Inset(10,10,10,10) );
vb.setSpacing( 10 );
Button okButton = new Button( "OK" );
okButton.setAlignment( Pos.CENTER );
okButton.setOnAction( new EventHandler<ActionEvent>() {
@Override public void handle( ActionEvent e ) {
dial.close();
}
} );
BorderPane bp = new BorderPane();
bp.setCenter( okButton );
HBox msg = new HBox();
msg.setSpacing( 5 );
msg.getChildren().addAll( icon, message );
vb.getChildren().addAll( msg, bp );
dial.showDialog();
}
}
I needed to explicitly add POST in the CURL command:
curl -X POST http://<user>:<token>@<server>/safeRestart
I also have the SafeRestart Plugin installed, in case that makes a difference.
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.
When using SwiftUI, SDWebImageSwiftUI is the best option.
Add the dependancy via XCode's Swift Package Manager: https://github.com/SDWebImage/SDWebImageSwiftUI.git
Then just use WebImage()
instead of Image()
WebImage(url: URL(string: "https://nokiatech.github.io/heif/content/images/ski_jump_1440x960.heic"))
Try using the "%h"
modifier:
scanf("%hu", &length);
^
ISO/IEC 9899:201x - 7.21.6.1-7
Specifies that a following d , i , o , u , x , X , or n conversion specifier applies to an argument with type pointer to short or unsigned short.
Encapsulation:
Hiding something, sort of like medicine capsule. We don't know what is in the capsule, we just take it. Same as in programming - we just hide some special code of method or property and it only gives output, same as capsule. In short, encapsulation hides data.
Abstraction:
Abstraction means hiding logic or implementation. For example, we take tablets and see their color and but don't know what is the purpose of this and how it works with the body.
This is because width
when provided a %
doesn't account for padding
/margin
s. You will need to reduce the amount to possibly 24%
or 24.5%
. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.
What you might like to do is look up CSS grid based layouts. This layout method involves specifying some CSS classes to align the page contents to a grid structure. It's more closely related to print-bsed layout than web-based, but it's a technique used on a lot of websites to layout the content into a structure without having to resort to tables.
Try this for starters from Smashing Magazine.
Select multiple lines by clicking first line then holding shift and clicking last line. Then press:
CTRL+SHIFT+L
or on MAC: CMD+SHIFT+L (as per comments)
Alternatively you can select lines and go to SELECTION MENU >> SPLIT INTO LINES.
Now you can edit multiple lines, move cursors etc. for all selected lines.
Another way to rename the database or taking image of the database is by using Reverse engineering option in the database tab. It will create a ERR diagram for the database. Rename the schema there.
after that go to file menu and go to export and forward engineer the database.
Then you can import the database.
The object for the list:
public class InstalledProgram
{
public string DisplayName { get; set; }
public string Version { get; set; }
public string InstalledDate { get; set; }
public string Publisher { get; set; }
public string UnninstallCommand { get; set; }
public string ModifyPath { get; set; }
}
The call for creating the list:
List<InstalledProgram> installedprograms = new List<InstalledProgram>();
string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
{
foreach (string subkey_name in key.GetSubKeyNames())
{
using (RegistryKey subkey = key.OpenSubKey(subkey_name))
{
if (subkey.GetValue("DisplayName") != null)
{
installedprograms.Add(new InstalledProgram
{
DisplayName = (string)subkey.GetValue("DisplayName"),
Version = (string)subkey.GetValue("DisplayVersion"),
InstalledDate = (string)subkey.GetValue("InstallDate"),
Publisher = (string)subkey.GetValue("Publisher"),
UnninstallCommand = (string)subkey.GetValue("UninstallString"),
ModifyPath = (string)subkey.GetValue("ModifyPath")
});
}
}
}
}
from manual:
: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.
As this returns always zero therefore is is similar to be used as true
Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?
Mu. No correct way exists, not even one that's consistent across browsers.
This is a problem that comes from the HTTP specification (section 15.6):
Existing HTTP clients and user agents typically retain authentication information indefinitely. HTTP/1.1. does not provide a method for a server to direct clients to discard these cached credentials.
On the other hand, section 10.4.2 says:
If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information.
In other words, you may be able to show the login box again (as @Karsten says), but the browser doesn't have to honor your request - so don't depend on this (mis)feature too much.
On Kotlin you can set width and height of any view directly using their virtual properties:
someView.layoutParams.width = 100
someView.layoutParams.height = 200
An alternative way is to use MySql Workbench. Go to Administration -> Users and privileges -> and change 'localhost' with '%' in 'Limit to Host Matching' (From host) attribute for users you wont to give remote access Or create new user ( Add account button ) with '%' on this attribute instead localhost.
Try this:
foreach($array as $k => $obj) {
$obj->{'newKey'} = "value";
}
I finally tracked this down to .NET Code Access Security. I have some internally-developed binary modules that are stored on and executed from a network share. To get .NET 2.0/PowerShell 2.0 to load them, I had added a URL rule to the Intranet
code group to trust that directory:
PS> & "$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\caspol.exe" -machine -listgroups
Microsoft (R) .NET Framework CasPol 2.0.50727.5420
Copyright (c) Microsoft Corporation. All rights reserved.
Security is ON
Execution checking is ON
Policy change prompt is ON
Level = Machine
Code Groups:
1. All code: Nothing
1.1. Zone - MyComputer: FullTrust
1.1.1. StrongName - ...: FullTrust
1.1.2. StrongName - ...: FullTrust
1.2. Zone - Intranet: LocalIntranet
1.2.1. All code: Same site Web
1.2.2. All code: Same directory FileIO - 'Read, PathDiscovery'
1.2.3. Url - file://Server/Share/Directory/WindowsPowerShell/Modules/*: FullTrust
1.3. Zone - Internet: Internet
1.3.1. All code: Same site Web
1.4. Zone - Untrusted: Nothing
1.5. Zone - Trusted: Internet
1.5.1. All code: Same site Web
Note that, depending on which versions of .NET are installed and whether it's 32- or 64-bit Windows, caspol.exe
can exist in the following locations, each with their own security configuration (security.config
):
$Env:SystemRoot\Microsoft.NET\Framework\v2.0.50727\
$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\
$Env:SystemRoot\Microsoft.NET\Framework\v4.0.30319\
$Env:SystemRoot\Microsoft.NET\Framework64\v4.0.30319\
After deleting group 1.2.3.
...
PS> & "$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\caspol.exe" -machine -remgroup 1.2.3.
Microsoft (R) .NET Framework CasPol 2.0.50727.9136
Copyright (c) Microsoft Corporation. All rights reserved.
The operation you are performing will alter security policy.
Are you sure you want to perform this operation? (yes/no)
yes
Removed code group from the Machine level.
Success
...I am left with the default CAS configuration and local scripts now work again. It's been a while since I've tinkered with CAS, and I'm not sure why my rule would seem to interfere with those granting FullTrust
to MyComputer
, but since CAS is deprecated as of .NET 4.0 (on which PowerShell 3.0 is based), I guess it's a moot point now.
In a nutshell answer.
As commented, just in case the link I posted there broke, try this:
Add a Name(any valid name) in Excel's Name Manager under Formula tab in the Ribbon.
Then assign a formula using GET.CELL function.
=GET.CELL(63,INDIRECT("rc",FALSE))
63 stands for backcolor.
Let's say we name it Background so in any cell with color type:
=Background
Result:
Notice that Cells A2, A3 and A4 returns 3, 4, and 5 respectively which equates to the cells background color index. HTH.
BTW, here's a link on Excel's Color Index
For adding argument to delay function.
First setup a dictionary then add it as the userInfo. Unwrap the info with the timer as the argument.
let arg : Int = 42
let infoDict : [String : AnyObject] = ["argumentInt", arg]
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHereWithArgument:", userInfo: infoDict, repeats: false)
Then in the called function
func functionHereWithArgument (timer : NSTimer)
{
if let userInfo = timer.userInfo as? Dictionary<String, AnyObject>
{
let argumentInt : Int = (userInfo[argumentInt] as! Int)
}
}
You could also try this:
SELECT DISTINCT (DATE(dateadded)) AS unique_date, COUNT(*) AS amount
FROM table
GROUP BY unique_date
ORDER BY unique_date ASC
I just put an index.html file in /htdocs and type in http://127.0.0.1/index.html - and up comes the html.
Add a folder "named Forum" and type in 127.0.0.1/forum/???.???
You can save the best model using keras.callbacks.ModelCheckpoint()
Example:
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model_checkpoint_callback = keras.callbacks.ModelCheckpoint("best_Model.h5",save_best_only=True)
history = model.fit(x_train,y_train,
epochs=10,
validation_data=(x_valid,y_valid),
callbacks=[model_checkpoint_callback])
This will save the best model in your working directory.
There is a way to make youtube autoplay, and complete playlists play through. Get Adblock browser for Android, and then go to the youtube website, and and configure it for the desktop version of the page, close Adblock browser out, and then reopen, and you will have the desktop version, where autoplay will work.
Using the desktop version will also mean that AdBlock will work. The mobile version invokes the standalone YouTube player, which is why you want the desktop version of the page, so that autoplay will work, and so ad blocking will work.
You can use JSON.parse for that:
JSON.parse("true"); //returns boolean true
To add some clarification and directly address the question above, there are several classes of characters that cause problems for URLs and URIs.
There are some characters that are disallowed and should never appear in a URL/URI, reserved characters (described below), and other characters that may cause problems in some cases, but are marked as "unwise" or "unsafe". Explanations for why the characters are restricted are clearly spelled out in RFC-1738 (URLs) and RFC-2396 (URIs). Note the newer RFC-3986 (update to RFC-1738) defines the construction of what characters are allowed in a given context but the older spec offers a simpler and more general description of which characters are not allowed with the following rules.
Excluded US-ASCII Characters disallowed within the URI syntax:
control = <US-ASCII coded characters 00-1F and 7F hexadecimal>
space = <US-ASCII coded character 20 hexadecimal>
delims = "<" | ">" | "#" | "%" | <">
The character "#" is excluded because it is used to delimit a URI from a fragment identifier. The percent character "%" is excluded because it is used for the encoding of escaped characters. In other words, the "#" and "%" are reserved characters that must be used in a specific context.
List of unwise characters are allowed but may cause problems:
unwise = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"
Characters that are reserved within a query component and/or have special meaning within a URI/URL:
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","
The "reserved" syntax class above refers to those characters that are allowed within a URI, but which may not be allowed within a particular component of the generic URI syntax. Characters in the "reserved" set are not reserved in all contexts. The hostname, for example, can contain an optional username so it could be something like ftp://user@hostname/
where the '@' character has special meaning.
Here is an example of a URL that has invalid and unwise characters (e.g. '$', '[', ']') and should be properly encoded:
http://mw1.google.com/mw-earth-vectordb/kml-samples/gp/seattle/gigapxl/$[level]/r$[y]_c$[x].jpg
Some of the character restrictions for URIs and URLs are programming language-dependent. For example, the '|' (0x7C) character although only marked as "unwise" in the URI spec will throw a URISyntaxException in the Java java.net.URI constructor so a URL like http://api.google.com/q?exp=a|b
is not allowed and must be encoded instead as http://api.google.com/q?exp=a%7Cb
if using Java with a URI object instance.
It tells the compiler that you're in a Single Thread Apartment model. This is an evil COM thing, it's usually used for Windows Forms (GUI's) as that uses Win32 for its drawing, which is implemented as STA. If you are using something that's STA model from multiple threads then you get corrupted objects.
This is why you have to invoke onto the Gui from another thread (if you've done any forms coding).
Basically don't worry about it, just accept that Windows GUI threads must be marked as STA otherwise weird stuff happens.
Something like this should work (it did for me). The reason for wanting to use -Filter
instead of -Include
is that include takes a huge performance hit compared to -Filter
.
Below just loops each file type and multiple servers/workstations specified in separate files.
##
## This script will pull from a list of workstations in a text file and search for the specified string
## Change the file path below to where your list of target workstations reside
## Change the file path below to where your list of filetypes reside
$filetypes = gc 'pathToListOffiletypes.txt'
$servers = gc 'pathToListOfWorkstations.txt'
##Set the scope of the variable so it has visibility
set-variable -Name searchString -Scope 0
$searchString = 'whatYouAreSearchingFor'
foreach ($server in $servers)
{
foreach ($filetype in $filetypes)
{
## below creates the search path. This could be further improved to exclude the windows directory
$serverString = "\\"+$server+"\c$\Program Files"
## Display the server being queried
write-host “Server:” $server "searching for " $filetype in $serverString
Get-ChildItem -Path $serverString -Recurse -Filter $filetype |
#-Include "*.xml","*.ps1","*.cnf","*.odf","*.conf","*.bat","*.cfg","*.ini","*.config","*.info","*.nfo","*.txt" |
Select-String -pattern $searchstring | group path | select name | out-file f:\DataCentre\String_Results.txt
$os = gwmi win32_operatingsystem -computer $server
$sp = $os | % {$_.servicepackmajorversion}
$a = $os | % {$_.caption}
## Below will list again the server name as well as its OS and SP
## Because the script may not be monitored, this helps confirm the machine has been successfully scanned
write-host $server “has completed its " $filetype "scan:” “|” “OS:” $a “SP:” “|” $sp
}
}
#end script
Use list comprehensions when the result needs to be iterated over multiple times, or where speed is paramount. Use generator expressions where the range is large or infinite.
See Generator expressions and list comprehensions for more info.
There is another approach to solve this problem, using slice
in JavaScript.
var d = new Date();
var datestring = d.getFullYear() + "-" + ("0"+(d.getMonth()+1)).slice(-2) +"-"+("0" + d.getDate()).slice(-2);
the datestring
return date with format as you expect: 2019-09-01
another approach is using dateformat
library: https://github.com/felixge/node-dateformat
Robustness diagrams are written after use cases and before class diagrams. They help to identify the roles of use case steps. You can use them to ensure your use cases are sufficiently robust to represent usage requirements for the system you're building.
They involve:
Whereas the Model-View-Controller pattern is used for user interfaces, the Entity-Control-Boundary Pattern (ECB) is used for systems. The following aspects of ECB can be likened to an abstract version of MVC, if that's helpful:
Entities (model)
Objects representing system data, often from the domain model.
Boundaries (view/service collaborator)
Objects that interface with system actors (e.g. a user or external service). Windows, screens and menus are examples of boundaries that interface with users.
Controls (controller)
Objects that mediate between boundaries and entities. These serve as the glue between boundary elements and entity elements, implementing the logic required to manage the various elements and their interactions. It is important to understand that you may decide to implement controllers within your design as something other than objects – many controllers are simple enough to be implemented as a method of an entity or boundary class for example.
Four rules apply to their communication:
Communication allowed:
Entity Boundary Control
Entity X X
Boundary X
Control X X X
Something like this might be the easiest way.
<a href="mailto:?subject=I wanted you to see this site&body=Check out this site http://www.website.com."
title="Share by Email">
<img src="http://png-2.findicons.com/files/icons/573/must_have/48/mail.png">
</a>
You could find another email image and add that if you wanted.
To browse .NET code dependencies, you can use the capabilities of the tool NDepend. The tool proposes:
For example such query can look like:
from m in Methods
let depth = m.DepthOfIsUsing("NHibernate.NHibernateUtil.Entity(Type)")
where depth >= 0 && m.IsUsing("System.IDisposable")
orderby depth
select new { m, depth }
And its result looks like: (notice the code metric depth, 1 is for direct callers, 2 for callers of direct callers...) (notice also the Export to Graph button to export the query result to a Call Graph)
The dependency graph looks like:
The dependency matrix looks like:
The dependency matrix is de-facto less intuitive than the graph, but it is more suited to browse complex sections of code like:
Disclaimer: I work for NDepend
Angular 2+
I found this while searching for Angular 2+, so here is the way:
$window.location.reload();
An Error "indicates serious problems that a reasonable application should not try to catch."
while
An Exception "indicates conditions that a reasonable application might want to catch."
Error along with RuntimeException
& their subclasses are unchecked
exceptions. All other Exception classes are checked
exceptions.
Checked exceptions are generally those from which a program can recover & it might be a good idea to recover from such exceptions programmatically. Examples include FileNotFoundException
, ParseException
, etc. A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller
On the other hand we have unchecked exceptions. These are those exceptions that might not happen if everything is in order, but they do occur. Examples include ArrayIndexOutOfBoundException
, ClassCastException
, etc. Many applications will use try-catch
or throws
clause for RuntimeExceptions
& their subclasses but from the language perspective it is not required to do so. Do note that recovery from a RuntimeException
is generally possible but the guys who designed the class/exception deemed it unnecessary for the end programmer to check for such exceptions.
Errors are also unchecked exception & the programmer is not required to do anything with these. In fact it is a bad idea to use a try-catch
clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError
, StackOverflowError
, etc.
Do note that although Errors are unchecked exceptions, we shouldn't try to deal with them, but it is ok to deal with RuntimeExceptions
(also unchecked exceptions) in code. Checked exceptions should be handled by the code.
This is like user3076252's answer, but you'll be choosing a different set of options:
It should find your unbound JRE, but this time with all the numbers in it's name (rather than unbound), and you can select it. It will take a while to search the drive, but you can stop it at any time, and it will save the results, if any.
I had the same problem, but setting windowSoftInputMode
did not help, and I did not want to change the upper view to have isScrollContainer="false"
because I wanted it to scroll.
My solution was to define the top location of the navigation tools instead of the bottom. I'm using Titanium, so I'm not sure exactly how this would translate to android. Defining the top location of the navigation tools view prevented the soft keyboard from pushing it up, and instead covered the nav controls like I wanted.
you can use
^[\w.-]+$
the +
is to make sure it has at least 1 character. Need the ^
and $
to denote the begin and end, otherwise if the string has a match in the middle, such as @@@@xyz%%%%
then it is still a match.
\w
already includes alphabets (upper and lower case), numbers, and underscore. So the rest .
, -
, are just put into the "class" to match. The +
means 1 occurrence or more.
P.S. thanks for the note in the comment
Offical Bitmapdrawable documentation
This is sample on how to convert bitmap to drawable
Bitmap bitmap;
//Convert bitmap to drawable
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
imageView.setImageDrawable(drawable);
Tips of using OS-dependent function to terminate C++ thread:
std::thread::native_handle()
only can get the thread’s valid native handle type before calling join()
or detach()
. After that, native_handle()
returns 0 - pthread_cancel()
will coredump.
To effectively call native thread termination function(e.g. pthread_cancel()
), you need to save the native handle before calling std::thread::join()
or std::thread::detach()
. So that your native terminator always has a valid native handle to use.
More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .
Just do delete
. This is from the SQLite documentation:
"When the WHERE is omitted from a DELETE statement and the table being deleted has no triggers, SQLite uses an optimization to erase the entire table content without having to visit each row of the table individually. This "truncate" optimization makes the delete run much faster. Prior to SQLite version 3.6.5, the truncate optimization also meant that the sqlite3_changes() and sqlite3_total_changes() interfaces and the count_changes pragma will not actually return the number of deleted rows. That problem has been fixed as of version 3.6.5."
Simple solution:
<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>
This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.
You can set the spring profile by supplying -Dspring.profiles.active=<env>
For java files in source(src) directory, you can use by
System.getProperty("spring.profiles.active")
For java files in test directory you can supply
SPRING_PROFILES_ACTIVE
to <env>
OR
Since, "environment", "jvmArgs" and "systemProperties" are ignored for the "test" task. In root build.gradle
add a task to set jvm property and environment variable.
test {
def profile = System.properties["spring.profiles.active"]
systemProperty "spring.profiles.active",profile
environment "SPRING.PROFILES_ACTIVE", profile
println "Running ${project} tests with profile: ${profile}"
}
I want to share a simple approach for downloading files with JavaScript (ES6), React and a Spring Boot backend:
- Spring boot Rest Controller
Resource from org.springframework.core.io.Resource
@SneakyThrows
@GetMapping("/files/{filename:.+}/{extraVariable}")
@ResponseBody
public ResponseEntity<Resource> serveFile(@PathVariable String filename, @PathVariable String extraVariable) {
Resource file = storageService.loadAsResource(filename, extraVariable);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
- React, API call using AXIOS
Set the responseType to arraybuffer to specify the type of data contained in the response.
export const DownloadFile = (filename, extraVariable) => {
let url = 'http://localhost:8080/files/' + filename + '/' + extraVariable;
return axios.get(url, { responseType: 'arraybuffer' }).then((response) => {
return response;
})};
Final step > downloading
with the help of js-file-download you can trigger browser to save data to file as if it was downloaded.
DownloadFile('filename.extension', 'extraVariable').then(
(response) => {
fileDownload(response.data, filename);
}
, (error) => {
// ERROR
});
If you simply want to go to another page, then what you might need is a link that looks like a button with a href like so:
<a href="/#/somepage.html" class="button">Back to Listings</a>
Hope this helps.
You also can get it from any ContainerAware (f.i. Controller) class from the request service:
If you are using apache as a webserver (I suppose for other
webservers the solution would be similar) and are using
virtualhosting (your urls look like this - localhost/app.php
then you can use:
$container->get('request')->server->get('DOCUMENT_ROOT');
// in controller:
$this->getRequest()->server->get('DOCUMENT_ROOT');
Else (your urls look like this - localhost/path/to/Symfony/web/app.php
:
$container->get('request')->getBasePath();
// in controller:
$this->getRequest()->getBasePath();
\b(?=\w)(?!(ma|(t){1}))\b(\w*)
this is for the given regex.
the \b is to find word boundary.
the positive look ahead (?=\w) is here to avoid spaces.
the negative look ahead over the original regex is to prevent matches of it.
and finally the (\w*) is to catch all the words that are left.
the group that will hold the words is group 3.
the simple (?!pattern) will not work as any sub-string will match
the simple ^(?!(?:m{2}|t)$).*$ will not work as it's granularity is full lines
I have also tried this combination within both the single quotes and double quotes. But none has worked. Instead of using \n
better use <br/>
in the double quotes. Like this..
$variable = "and";
echo "part 1 $variable part 2<br/>";
echo "part 1 ".$variable." part 2";
You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
I might be wrong but "find -name __" works fine for me. (Maybe it's just my phone.) If you just want to list all files, you can try
adb shell ls -R /
You probably need the root permission though.
Edit:
As other answers suggest, use ls
with grep
like this:
adb shell ls -Ral yourDirectory | grep -i yourString
eg.
adb shell ls -Ral / | grep -i myfile
-i
is for ignore-case. and /
is the root directory.
As you didn't give us very much information, I'm assuming the language you're writing the code in is C#. First of all: Prefer System.Collections.Generic.List over an ArrayList. Secondly: One way would be to loop through every item in the list and check whether it contains "How". Another way would be to use LINQ. Here's a quick example that filters out every item which doesn't contain "How":
var list = new List<string>();
list.AddRange(new string[] {
"How are you?",
"How you doing?",
"Joe",
"Mike", });
foreach (string str in list.Where(s => s.Contains("How")))
{
Console.WriteLine(str);
}
Console.ReadLine();
If you are using ajax, you may want to get updated value of select right after the selection.
//Part 1
$(".element").select2(/*Your code*/)
//Part 2 - continued
$(".element").on("select2:select", function (e) {
var select_val = $(e.currentTarget).val();
console.log(select_val)
});
Credits: Steven-Johnston
function setWidth(width) {
var canvas = document.getElementById("myCanvas");
canvas.width = width;
}
I had this problem on devices running iOS. I made a shop that is embeddable in a normal website using an iframe. Somehow, on every pageload the user got a new sessionid, resulting in users getting stuck halfway the process because some values weren't present in the session.
I tried some of the solutions given on this page, but popups don't work very well on an iPad and I needed the most transparent solution.
I resolved it using a redirect. The website that embeds my site must first redirect the user to my site, so the top frame contains the url to my site, where I set a cookie and redirect the user to the proper page on the website that embeds my site, that is passed through in the url.
Example PHP code
Remote website redirects user to
http://clientname.example.com/init.php?redir=http://www.domain.com/shop/frame
init.php
<?php
// set a cookie for a year
setcookie('initialized','1',time() + 3600 * 24 * 365, '/', '.domain.com', false, false);
header('location: ' . $_GET['redir']);
die;
The user ends up on http://www.domain.com/shop/frame
where my site is embedded, storing sessions as it should and eating cookies.
Hope this helps someone.
yes
$oneweekfromnow = strtotime("+1 week", strtotime("<date-from-db>"));
on another note, why do you have your date in the database like that?
brew install caskroom/cask/brew-cask
brew tap caskroom/versions
brew cask install sublime-text
Weird how I will struggle with this for days, post on StackOverflow, then figure out my own answer in 20 seconds.
[edited to reflect that the package name is now just sublime-text
, not sublime-text3
]
The answers here got me close, but in 2016, I was able to write the following LINQ:
List<ObjectType> objectList = similarTypeList.Select(o =>
new ObjectType
{
PropertyOne = o.PropertyOne,
PropertyTwo = o.PropertyTwo,
PropertyThree = o.PropertyThree
}).ToList();
You can try this in your Action:
return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
And this in your Ajax success:
success: function (resultDateString) {
var date = new Date(resultDateString);
}
Or this in your View: (Javascript plus C#)
var date = new Date('@DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")');
They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.
If you're experiencing a different behaviour, it's time to change for another DBMS.
Okay, it is going to be extremely late answer to this question. But here is just one sample if you want to do it in Kotlin.
val intent = Intent(Intent.ACTION_DIAL)
intent.data = Uri.parse("tel:<number>")
startActivity(intent)
Thought it might help someone.
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
Make use of $"string".
In this example, it would be,
dbload=$"load data local infile \"'gfpoint.csv'\" into table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY \"'\n'\" IGNORE 1 LINES"
Note(from the man page):
A double-quoted string preceded by a dollar sign ($"string") will cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted.
My approach to delete all rows from a table i DynamoDb is just to pull all rows out from the table, using DynamoDbs ScanAsync and then feed the result list to DynamoDbs AddDeleteItems. Below code in C# works fine for me.
public async Task DeleteAllReadModelEntitiesInTable()
{
List<ReadModelEntity> readModels;
var conditions = new List<ScanCondition>();
readModels = await _context.ScanAsync<ReadModelEntity>(conditions).GetRemainingAsync();
var batchWork = _context.CreateBatchWrite<ReadModelEntity>();
batchWork.AddDeleteItems(readModels);
await batchWork.ExecuteAsync();
}
Note: Deleting the table and then recreating it again from the web console may cause problems if using YAML/CloudFormation to create the table.
Try this.
20 4 * * *
Check the below Screenshot
Referred URL - https://www.lenar.io/jenkins-schedule-build-periodically/
You can use CSS gradient - although there are not consistent across browsers so You would have to code it for every one
Like that: CSS3 Transparency + Gradient
Gradient should be more transparent on top or on top right corner (depending on capabilities)
The (un)safe way to do this - if you are ok with not using option explicit - is...
Not TypeName(myObj) = "Empty"
This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...
Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ true, the object exists - TypeName is Object
'Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ false, the object has not been declared
This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.
The exception you get is telling you filedialog
is not in your namespace.
filedialog
(and btw messagebox
) is a tkinter module, so it is not imported just with from tkinter import *
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>>
you should use for example:
>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>
or
>>> import tkinter.filedialog as fdialog
or
>>> from tkinter.filedialog import askopenfilename
So this would do for your browse button:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()
I have not tried this, so I am not guarantueeing anything, however
foreach Bar f in filterBars
{
search(f)
}
Foo search(Bar b)
{
fooSelect = (from f in fooBunch
where !(from b in f.BarList select b.BarId).Contains(b.ID)
select f).ToList();
return fooSelect;
}
git clone --depth 1 --branch <tag_name> <repo_url>
--depth 1
is optional but if you only need the state at that one revision, you probably want to skip downloading all the history up to that revision.
In my IBM AIX Server (OS version: AIX 5.2), use:
find ./ -type f -print -exec grep -n -i "stringYouWannaFind" {} \;
this will print out path/file name and relative line number in the file like:
./inc/xxxx_x.h
2865: /** Description : stringYouWannaFind */
anyway,it works for me : )
You can also use barcodefragmentlib which is an extension of zxing but provides barcode scanning as fragment library, so can be very easily integrated.
Here is the supporting documentation for usage of library
BhupeshC and murat , this is what I was looking for. However @SQL varchar(4000) wasn't big enough. So, small change
DECLARE @cmd varchar(4000)
DECLARE MY_CURSOR CURSOR
LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR
select 'ALTER TABLE ['+s.name+'].['+t.name+'] DROP CONSTRAINT [' + RTRIM(f.name) +'];' FROM sys.Tables t INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id INNER JOIN sys.schemas s ON s.schema_id = f.schema_id
OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @cmd
WHILE @@FETCH_STATUS = 0
BEGIN
-- EXEC (@cmd)
PRINT @cmd
FETCH NEXT FROM MY_CURSOR INTO @cmd
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR
GO
Suppose you have following lines of code
MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)
If you are receiving following error message
AttributeError: module 'urllib' has no attribute 'urlretrieve'
Then you should try following code to fix the issue:
import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)
I recently had a similar problem in latest Eclipse (Kepler) and fixed it by disabling the option "Honour all XML schema locations" in Preferences > XML > XML Files > Validation. It disables validation for references to the same namespaces that point to different schema locations, only taking the first found generally in the XML file being validated. This option comes from the Xerces library.
WTP Doc: http://www.eclipse.org/webtools/releases/3.1.0/newandnoteworthy/sourceediting.php
Xerces Doc: http://xerces.apache.org/xerces2-j/features.html#honour-all-schemaLocations
I came to this post when i was searching for the same issue but in android
.
I don't say this is the best way to get sorted files by last modified date, but its the easiest way I found yet.
Below code may be helpful to someone-
File downloadDir = new File("mypath");
File[] list = downloadDir.listFiles();
for (int i = list.length-1; i >=0 ; i--) {
//use list.getName to get the name of the file
}
Thanks
(ANSWER IS IN DOT NET 4.5 and in java, there must be a similar approach exist)
I am from West Bengal in INDIA.
As I understand your problem is ...
You want to produce similar to ' ? ' (It is a letter in Bengali language)
which has Unicode HEX : 0X0985
.
Now if you know this value in respect of your language then how will you produce that language specific Unicode symbol right ?
In Dot Net it is as simple as this :
int c = 0X0985;
string x = Char.ConvertFromUtf32(c);
Now x is your answer. But this is HEX by HEX convert and sentence to sentence conversion is a work for researchers :P
#multiple-background{_x000D_
box-sizing: border-box;_x000D_
width: 123px;_x000D_
height: 30px;_x000D_
font-size: 12pt;_x000D_
border-radius: 7px; _x000D_
background: url("https://cdn0.iconfinder.com/data/icons/woocons1/Checkbox%20Full.png"), linear-gradient(to bottom, #4ac425, #4ac425);_x000D_
background-repeat: no-repeat, repeat;_x000D_
background-position: 5px center, 0px 0px;_x000D_
background-size: 18px 18px, 100% 100%;_x000D_
color: white; _x000D_
border: 1px solid #e4f6df;_x000D_
box-shadow: .25px .25px .5px .5px black;_x000D_
padding: 3px 10px 0px 5px;_x000D_
text-align: right;_x000D_
}
_x000D_
<div id="multiple-background"> Completed </div>
_x000D_
The Stack is an area of memory for keeping temporary data. Stack is used by the CALL instruction to keep the return address for procedures The return RET instruction gets this value from the stack and returns to that offset. The same thing happens when an INT instruction calls an interrupt. It stores in the Stack the flag register, code segment and offset. The IRET instruction is used to return from interrupt call.
The Stack is a Last In First Out (LIFO) memory. Data is placed onto the Stack with a PUSH instruction and removed with a POP instruction. The Stack memory is maintained by two registers: the Stack Pointer (SP) and the Stack Segment (SS) register. When a word of data is PUSHED onto the stack the the High order 8-bit Byte is placed in location SP-1 and the Low 8-bit Byte is placed in location SP-2. The SP is then decremented by 2. The SP addds to the (SS x 10H) register, to form the physical stack memory address. The reverse sequence occurs when data is POPPED from the Stack. When a word of data is POPPED from the stack the the High order 8-bit Byte is obtained in location SP-1 and the Low 8-bit Byte is obtained in location SP-2. The SP is then incremented by 2.
rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"
OR
rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"
You can also add the option //e:vbscript
to make sure the scripting engine will recognize your script as a vbscript.
Windows/DOS batch files doesn't require escaping \
like *nix.
You can still use "C:\Users\guest\Desktop\123\MyScript.vbs"
, but this requires the user has *.vbs
associated to wscript
.
Some people argue that a method should have a single point of exit (e.g., only one return
). Personally, I think that trying to stick to that rule produces code that's harder to read. In your example, as soon as you find what you were looking for, return it immediately, it's clear and it's efficient.
The original significance of having a single entry and single exit for a function is that it was part of the original definition of StructuredProgramming as opposed to undisciplined goto SpaghettiCode, and allowed a clean mathematical analysis on that basis.
Now that structured programming has long since won the day, no one particularly cares about that anymore, and the rest of the page is largely about best practices and aesthetics and such, not about mathematical analysis of structured programming constructs.
the am giving you is the code for trigger for INSERT, UPDATE and DELETE this works fine on Microsoft SQL SERVER 2008 and onwards database i am using is Northwind
/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
EmpID int,
Activity varchar(20),
DoneBy varchar(50),
Date_Time datetime NOT NULL DEFAULT GETDATE()
);
select * from Emp_Audit*/
create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
SET @activity = 'UPDATE';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from inserted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end
If exists (Select * from inserted) and not exists(Select * from deleted)
begin
SET @activity = 'INSERT';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from inserted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end
If exists(select * from deleted) and not exists(Select * from inserted)
begin
SET @activity = 'DELETE';
SET @user = SYSTEM_USER;
SELECT @EmpID = EmployeeID from deleted i;
INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end
In my case, Get specific version, even checking both check boxes and undoing all pending changes didn't work.
Checked the work spaces. Edit current workspace. Check all paths. The solution path was incorrect and was pointing to a deleted folder.
Fixed the path and get latest worked fine.
You can use the mktime(hour, minute, seconds, month, day, year) function
$paymentDate = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
$contractDateBegin = mktime(0, 0, 0, 1, 1, 2001);
$contractDateEnd = mktime(0, 0, 0, 1, 1, 2012);
if ($paymentDate >= $contractDateBegin && $paymentDate <= $contractDateEnd){
echo "is between";
}else{
echo "NO GO!";
}
For this example you will need to create your own type, that would be an array. Then you create a bigger array which elements are of type you have just created.
To run my example you will need to fill columns A and B in Sheet1 with some values. Then run test(). It will read first two rows and add the values to the BigArr. Then it will check how many rows of data you have and read them all, from the place it has stopped reading, i.e., 3rd row.
Tested in Excel 2007.
Option Explicit
Private Type SmallArr
Elt() As Variant
End Type
Sub test()
Dim x As Long, max_row As Long, y As Long
'' Define big array as an array of small arrays
Dim BigArr() As SmallArr
y = 2
ReDim Preserve BigArr(0 To y)
For x = 0 To y
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Write what has been read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
'' Get the number of the last not empty row
max_row = Range("A" & Rows.Count).End(xlUp).Row
'' Change the size of the big array
ReDim Preserve BigArr(0 To max_row)
Debug.Print "new size of BigArr with old data = " & UBound(BigArr)
'' Check haven't we lost any data
For x = 0 To y
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
For x = y To max_row
'' We have to change the size of each Elt,
'' because there are some new for,
'' which the size has not been set, yet.
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Check what we have read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
End Sub
From the matplotlib docs on scatter 1:
cmap is only used if c is an array of floats
So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.
How does this work for you?
import matplotlib.pyplot as plt
cm = plt.cm.get_cmap('RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)
plt.colorbar(sc)
plt.show()
The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection
The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().
Select columns by namedata <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr [ 4]: carrier, tailnum, origin, dest
#> dbl [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#> plane year month day dep_time sched_dep_time dep_delay arr_time
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 N142… 2013 1 1 517 515 2 830
#> 2 N242… 2013 1 1 533 529 4 850
#> 3 N619… 2013 1 1 542 540 2 923
#> 4 N804… 2013 1 1 544 545 -1 1004
#> 5 N668… 2013 1 1 554 600 -6 812
#> 6 N394… 2013 1 1 554 558 -4 740
#> 7 N516… 2013 1 1 555 600 -5 913
#> 8 N829… 2013 1 1 557 600 -3 709
#> 9 N593… 2013 1 1 557 600 -3 838
#> 10 N3AL… 2013 1 1 558 600 -2 753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> # arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> # dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> # time_hour <dttm>
Here you go.
<div id="menu">
<div class="fader">
<div class="text">
<p>Yay!</p>
</div>
<a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
<img class ="blog" src="http://s18.postimg.org/il7hbk7i1/image.png" alt="">
</a>
</div>
<div class="fader">
<div class="text">
<p>Yay!</p>
</div>
<a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
<img class ="blog" src="http://s18.postimg.org/4st2fxgqh/image.png" alt="">
</a>
</div>
<div class="fader">
<div class="text">
<p>Yay!</p>
</div>
<a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
<img class ="projects" src="http://s18.postimg.org/sxtrxn115/image.png" alt="">
</a>
</div>
<div class="fader">
<div class="text">
<p>Yay!</p>
</div>
<a href="http://stackoverflow.com/questions/15732643/jquery-masonry-and-css3/">
<img class ="blog" src="http://s18.postimg.org/5xn4lb37d/image.png" alt="">
</a>
</div>
</div>
#menu {
text-align: center; }
.fader {
/* Giving equal sizes to each element */
width: 250px;
height: 375px;
/* Positioning elements in lines */
display: inline-block;
/* This is necessary for position:absolute to work as desired */
position: relative;
/* Preventing zoomed images to grow outside their elements */
overflow: hidden; }
.fader img {
/* Stretching the images to fill whole elements */
width: 100%;
height: 100%;
/* Preventing blank space below the image */
line-height: 0;
/* A one-second transition was to disturbing for me */
-webkit-transition: all 0.3s ease;
-moz-transition: all 0.3s ease;
-o-transition: all 0.3s ease;
-ms-transition: all 0.3s ease;
transition: all 0.3s ease; }
.fader img:hover {
/* Making images appear bigger and transparent on mouseover */
opacity: 0.5;
width: 120%;
height: 120%; }
.fader .text {
/* Placing text behind images */
z-index: -10;
/* Positioning text top-left conrner in the middle of elements */
position: absolute;
top: 50%;
left: 50%; }
.fader .text p {
/* Positioning text contents 50% left and top relative
to text container's top left corner */
margin-top: -50%;
margin-left: -50%; }
Instead of .fader { inline-block; }
consider using some grid system. Based on your technology of preference, you can go Foundation, Susy, Masonry or their alternatives.
Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.
You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.
Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.
So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".
That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.
SOAP:
SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.
REST:
REST is a design concept.
The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.
It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)
Flickr's REST API goes further and lets you return images as well.
JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.
You can use Decode
as well:
SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item
You use the ajaxStop to execute code when the ajax are completed:
$(document).ajaxStop(function(){
setTimeout("window.location = 'otherpage.html'",100);
});
I found a way to do it (dont know if it is the best but it works)
string oldFile = "oldFile.pdf";
string newFile = "newFile.pdf";
// open the reader
PdfReader reader = new PdfReader(oldFile);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);
// open the writer
FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
// the pdf content
PdfContentByte cb = writer.DirectContent;
// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252,BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 8);
// write the text in the pdf content
cb.BeginText();
string text = "Some random blablablabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 520, 640, 0);
cb.EndText();
cb.BeginText();
text = "Other random blabla...";
// put the alignment and coordinates here
cb.ShowTextAligned(2, text, 100, 200, 0);
cb.EndText();
// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
// close the streams and voilá the file should be changed :)
document.Close();
fs.Close();
writer.Close();
reader.Close();
I hope this can be usefull for someone =) (and post here any errors)
def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
print("Your SP balance is now 0.")
attributeConfirmation()
elif strength < 0:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif strength > balance:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
print("That is an invalid input. Restarting attribute selection.")
attributeSelection()
you need to IMPORT your project R file
import <YOUR-PROJECT-PACKGENAME>.R;
I've made a generalized diff that compare 2 objects of any kind and can run a modification handler gist.github.com/bortunac "diff.js" an ex of using :
old_obj={a:1,b:2,c:[1,2]}
now_obj={a:2 , c:[1,3,5],d:55}
so property a is modified, b is deleted, c modified, d is added
var handler=function(type,pointer){
console.log(type,pointer,this.old.point(pointer)," | ",this.now.point(pointer));
}
now use like
df=new diff();
df.analize(now_obj,old_obj);
df.react(handler);
the console will show
mdf ["a"] 1 | 2
mdf ["c", "1"] 2 | 3
add ["c", "2"] undefined | 5
add ["d"] undefined | 55
del ["b"] 2 | undefined
There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
To shorten it up a little:
geocoder = new google.maps.Geocoder();
function codeAddress() {
//In this case it gets the address from an element on the page, but obviously you could just pass it to the method instead
var address = document.getElementById( 'address' ).value;
geocoder.geocode( { 'address' : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
//In this case it creates a marker, but you can get the lat and lng from the location.LatLng
map.setCenter( results[0].geometry.location );
var marker = new google.maps.Marker( {
map : map,
position: results[0].geometry.location
} );
} else {
alert( 'Geocode was not successful for the following reason: ' + status );
}
} );
}
The above error is a linker error... the linker a program that takes one or more objects generated by a compiler and combines them into a single executable program.
You must add -lboost_system
to you linker flags which indicates to the linker that it must look for symbols like boost::system::system_category()
in the library libboost_system.so
.
If you have main.cpp, either:
g++ main.cpp -o main -lboost_system
OR
g++ -c -o main.o main.cpp
g++ main.o -lboost_system
Going with what you've started:
row = [[]]
crimefile = open(fileName, 'r')
for line in crimefile.readlines():
tmp = []
for element in line[0:-1].split(','):
tmp.append(element)
row.append(tmp)
One extremely ugly way to resolve this is have the user manually type the directory into a text box, and add this back to the front of the file value in the JavaScript.
Messy... but it depends on the level of user you are working with, and gets around the security issue.
<form>
<input type="text" id="file_path" value="C:/" />
<input type="file" id="file_name" />
<input type="button" onclick="ajax_restore();" value="Restore Database" />
</form>
JavaScript
var str = document.getElementById('file_path').value;
var str = str + document.getElementById('file_name').value;
If you are looking for retrieving remote user IDSID/Username, use:
echo gethostbyaddr($_SERVER['REMOTE_ADDR']);
You will get something like iamuser1-mys.corp.company.com
Filter the rest of the domain behind, and you are able to get the idsid only.
For more information visit http://lostwithin.net/how-to-get-users-ip-and-computer-name-using-php/
Visual studio command prompt is nothing but the regular command prompt where few environment variables are set by default. This variables are set in the batch script : C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat . So basically to get a visual studio command prompt for a particular version, just open regular command prompt and run this batch script : C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\VsDevCmd.bat (Change the visual studio version based on your installed version). Voila you have got the visual studio command prompt. You can write a script to run the batch file and open cmd.exe.
Screenshot:
SizedBox.fromSize(
size: Size(56, 56), // button width and height
child: ClipOval(
child: Material(
color: Colors.orange, // button color
child: InkWell(
splashColor: Colors.green, // splash color
onTap: () {}, // button pressed
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.call), // icon
Text("Call"), // text
],
),
),
),
),
)
The following definition might be more efficient than the first solution proposed
def new_list_from_intervals(original_list, *intervals):
n = sum(j - i for i, j in intervals)
new_list = [None] * n
index = 0
for i, j in intervals :
for k in range(i, j) :
new_list[index] = original_list[k]
index += 1
return new_list
then you can use it like below
new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))
I checked all above said project version, module version, project bytecode version, target bytecode version settings in IntelliJ Idea
, but all were the same as I scratched.
I face this error Error:java: invalid source release: 1.8
in IntelliJ Idea 2017.2.6
because I upgraded the dependency version Maven
pom file, which(dependency) were supposed to build for JDK 1.8 application and I were building my application on and with maven compiler source and target JDK 1.7.
Hence I again downgrade the dependency version to earlier one in Maven
pom, and the error gone after project Rebuild Module 'xyz_project'.
The quickest solution is: set environment variable RANDFILE to path where the 'random state' file can be written (of course check the file access permissions), eg. in your command prompt:
set RANDFILE=C:\MyDir\.rnd
openssl genrsa -out my-prvkey.pem 1024
More explanations: OpenSSL on Windows tries to save the 'random state' file in the following order:
I'm pretty sure that in your case it ends up trying to save it in C:\.rnd (and it fails because lack of sufficient access rights). Unfortunately OpenSSL does not print the path that is actually tries to use in any error messages.
I have the same problem, but you know why? because I didn't put .txt in the end of my File and so it was File not a textFile, you shoud do just two things:
Its Working Properly
EditText et_mobile= (EditText) findViewById(R.id.edittxt);
et_mobile.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
if (et_mobile.getText().toString().trim().length() == 0) {
CommonMethod.showAlert("Please enter name", FeedbackSubmtActivity.this);
}
}
}
});
public static void showAlert(String message, Activity context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
$("option[value*='2']").attr('selected', 'selected');
// 2 for example, add * for every option
A super fast miracle command, which recursively traverses files to count the number of images in a directory and organize the output by image extension:
find . -type f | sed -e 's/.*\.//' | sort | uniq -c | sort -n | grep -Ei '(tiff|bmp|jpeg|jpg|png|gif)$'
If your .NET version is newer than 3.0 you can try using System.Xml.Linq.XDocument
instead of XmlDocument
. It is easier to process data with XDocument
.
If you landed here looking for solution that works with React Router and AWS Amplify Console - you already know that you can't use CloudFront redirection rules directly since Amplify Console does not expose CloudFront Distribution for the app.
Solution, however, is very simple - you just need to add a redirect/rewrite rule in Amplify Console like this:
See the following links for more info (and copy-friendly rule from the screenshot):
As noted, you could also place the legend in the plot, or slightly off it to the edge as well. Here is an example using the Plotly Python API, made with an IPython Notebook. I'm on the team.
To begin, you'll want to install the necessary packages:
import plotly
import math
import random
import numpy as np
Then, install Plotly:
un='IPython.Demo'
k='1fw3zw2o13'
py = plotly.plotly(username=un, key=k)
def sin(x,n):
sine = 0
for i in range(n):
sign = (-1)**i
sine = sine + ((x**(2.0*i+1))/math.factorial(2*i+1))*sign
return sine
x = np.arange(-12,12,0.1)
anno = {
'text': '$\\sum_{k=0}^{\\infty} \\frac {(-1)^k x^{1+2k}}{(1 + 2k)!}$',
'x': 0.3, 'y': 0.6,'xref': "paper", 'yref': "paper",'showarrow': False,
'font':{'size':24}
}
l = {
'annotations': [anno],
'title': 'Taylor series of sine',
'xaxis':{'ticks':'','linecolor':'white','showgrid':False,'zeroline':False},
'yaxis':{'ticks':'','linecolor':'white','showgrid':False,'zeroline':False},
'legend':{'font':{'size':16},'bordercolor':'white','bgcolor':'#fcfcfc'}
}
py.iplot([{'x':x, 'y':sin(x,1), 'line':{'color':'#e377c2'}, 'name':'$x\\\\$'},\
{'x':x, 'y':sin(x,2), 'line':{'color':'#7f7f7f'},'name':'$ x-\\frac{x^3}{6}$'},\
{'x':x, 'y':sin(x,3), 'line':{'color':'#bcbd22'},'name':'$ x-\\frac{x^3}{6}+\\frac{x^5}{120}$'},\
{'x':x, 'y':sin(x,4), 'line':{'color':'#17becf'},'name':'$ x-\\frac{x^5}{120}$'}], layout=l)
This creates your graph, and allows you a chance to keep the legend within the plot itself. The default for the legend if it is not set is to place it in the plot, as shown here.
For an alternative placement, you can closely align the edge of the graph and border of the legend, and remove border lines for a closer fit.
You can move and re-style the legend and graph with code, or with the GUI. To shift the legend, you have the following options to position the legend inside the graph by assigning x and y values of <= 1. E.g :
{"x" : 0,"y" : 0}
-- Bottom Left {"x" : 1, "y" : 0}
-- Bottom Right {"x" : 1, "y" : 1}
-- Top Right {"x" : 0, "y" : 1}
-- Top Left {"x" :.5, "y" : 0}
-- Bottom Center {"x": .5, "y" : 1}
-- Top CenterIn this case, we choose the upper right, legendstyle = {"x" : 1, "y" : 1}
, also described in the documentation:
In most cases the solution of CD.. will work perfectly fine. However I had a bit more twisted situation:
@(String.IsNullOrEmpty(Model.MaidenName) ? " " : Model.MaidenName)
This would print me " " in my page, respectively generate the source &nbsp;
. Now there is a function Html.Raw(" ")
which is supposed to let you write source code, except in this constellation it throws a compiler error:
Compiler Error Message: CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Web.IHtmlString' and 'string'
So I ended up writing a statement like the following, which is less nice but works even in my case:
@if (String.IsNullOrEmpty(Model.MaidenName)) { @Html.Raw(" ") } else { @Model.MaidenName }
Note: interesting thing is, once you are inside the curly brace, you have to restart a Razor block.
SELECT ID,
Name,
DATEDIFF(yy,CONVERT(DATETIME, DOB),GETDATE()) AS AGE,
DOB
FROM MyTable
Your mistake is looking for range
, which gives you the range
of a vector, for example:
range(c(10, -5, 100))
gives
-5 100
Instead, look at the :
operator to give sequences (with a step size of one):
1:100
or you can use the seq
function to have a bit more control. For example,
##Step size of 2
seq(1, 100, by=2)
or
##length.out: desired length of the sequence
seq(1, 100, length.out=5)
I want to mention here a very, VERY, interesting technique that is being used in huge projects like jQuery and Modernizr for concatenate things.
Both of this projects are entirely developed with requirejs modules (you can see that in their github repos) and then they use the requirejs optimizer as a very smart concatenator. The interesting thing is that, as you can see, nor jQuery neither Modernizr needs on requirejs to work, and this happen because they erase the requirejs syntatic ritual in order to get rid of requirejs in their code. So they end up with a standalone library that was developed with requirejs modules! Thanks to this they are able to perform cutsom builds of their libraries, among other advantages.
For all those interested in concatenation with the requirejs optimizer, check out this post
Also there is a small tool that abstracts all the boilerplate of the process: AlbanilJS
This could be complicated way of doing
String newString = new String(oldString);
This shortens the String is the underlying char[] used is much longer.
However more specifically it will be checking that every character can be UTF-8 encoded.
There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?
Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'
String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));
prints
false
A function that allows iterating over both stdout
and stderr
concurrently, in realtime, line by line
In case you need to get the output stream for both stdout
and stderr
at the same time, you can use the following function.
The function uses Queues to merge both Popen pipes into a single iterator.
Here we create the function read_popen_pipes()
:
from queue import Queue, Empty
from concurrent.futures import ThreadPoolExecutor
def enqueue_output(file, queue):
for line in iter(file.readline, ''):
queue.put(line)
file.close()
def read_popen_pipes(p):
with ThreadPoolExecutor(2) as pool:
q_stdout, q_stderr = Queue(), Queue()
pool.submit(enqueue_output, p.stdout, q_stdout)
pool.submit(enqueue_output, p.stderr, q_stderr)
while True:
if p.poll() is not None and q_stdout.empty() and q_stderr.empty():
break
out_line = err_line = ''
try:
out_line = q_stdout.get_nowait()
except Empty:
pass
try:
err_line = q_stderr.get_nowait()
except Empty:
pass
yield (out_line, err_line)
read_popen_pipes()
in use:
import subprocess as sp
with sp.Popen(my_cmd, stdout=sp.PIPE, stderr=sp.PIPE, text=True) as p:
for out_line, err_line in read_popen_pipes(p):
# Do stuff with each line, e.g.:
print(out_line, end='')
print(err_line, end='')
return p.poll() # return status-code
2017 Update - since WooCommerce 3:
global $product;
$id = $product->get_id();
Woocommerce doesn't like you accessing those variables directly. This will get rid of any warnings from woocommerce if your wp_debug is true.
With this code you can obtain any controller:
var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext,
controller);
Since C++11, you can also use a lambda expression instead of defining a comparator struct:
auto comp = [](const string& a, const string& b) { return a.length() < b.length(); };
map<string, string, decltype(comp)> my_map(comp);
my_map["1"] = "a";
my_map["three"] = "b";
my_map["two"] = "c";
my_map["fouuur"] = "d";
for(auto const &kv : my_map)
cout << kv.first << endl;
Output:
1
two
three
fouuur
I'd like to repeat the final note of Georg's answer: When comparing by length you can only have one string of each length in the map as a key.
The full command is:
dir /b /a-d
Let me break it up;
Basically the /b
is what you look for.
/a-d
will exclude the directory names.
For more information see dir /?
for other arguments that you can use with the dir
command.
This post is high up when you google that error message, which I got when installing security patch KB4505224 on SQL Server 2017 Express i.e. None of the above worked for me, but did consume several hours trying.
The solution for me, partly from here was:
And all was well.
Streams are often accessed by threads that periodically empty their content and, for example, display it on the screen, send it to a socket or write it to a file. This is done for performance reasons. Flushing an output stream means that you want to stop, wait for the content of the stream to be completely transferred to its destination, and then resume execution with the stream empty and the content sent.
Try this:
$parts = explode('.', $file_name);
$file_extension = end($parts);
The reason is that the argument for end
is passed by reference, since end
modifies the array by advancing its internal pointer to the final element. If you're not passing a variable in, there's nothing for a reference to point to.
See end
in the PHP manual for more info.
(originally posted by leepowers in his question)
The error message is confusing for one big reason:
Primitive type names are not reserved in PHP
The following are all valid class declarations:
class string { }
class int { }
class float { }
class double { }
My mistake was in thinking that the error message was referring solely to the string primitive type - the word 'instance' should have given me pause. An example to illustrate further:
class string { }
$n = 1234;
$s1 = (string)$n;
$s2 = new string();
$a = array('no', 'yes');
printf("\$s1 - primitive string? %s - string instance? %s\n",
$a[is_string($s1)], $a[is_a($s1, 'string')]);
printf("\$s2 - primitive string? %s - string instance? %s\n",
$a[is_string($s2)], $a[is_a($s2, 'string')]);
Output:
$s1 - primitive string? yes - string instance? no
$s2 - primitive string? no - string instance? yes
In PHP it's possible for a string
to be a string
except when it's actually a string
. As with any language that uses implicit type conversion, context is everything.
The question is about VS 2008 Express.
Microsoft's web page for registering Visual Studio 2008 Express has been dead (404) for some time, so registering it is not possible.
Instead, as a workaround, you can temporarily remove the requirement to register VS2008Exp by deleting (or renaming) the registry key:
HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration
To ensure that this is working beforehand, click Help -> register product within VS2008.
You should see text like
"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 10 more days before you will be required to register it."
Close the application, delete that key, reopen, click help->register product.
The text should now say
"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 30 more days before you will be required to register it."
So you have two options - delete that key manually every 30 days, or run it from a batch file that also contains a line like:
reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f
[Edit: User @i486 confirms on testing that this workaround works even after the expiration period has expired]
[Edit2: User @Wyatt8740 has a much more elegant way to prevent the value from reappearing.]
Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.
In your class, do something like this:
public void setSqlResource(Resource sqlResource) {
this.sqlResource = sqlResource;
}
And then in your application context file, in the bean definition, just set a property:
<bean id="someBean" class="...">
<property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>
And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.
You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.
Just here to show my implementation for @herman solution
ZoneId americaLaPazZone = ZoneId.of("UTC-04:00");
static Date firstDateOfMonth(Date date) {
LocalDate localDate = convertToLocalDateWithTimezone(date);
YearMonth baseMonth = YearMonth.from(localDate);
LocalDateTime initialDate = baseMonth.atDay(firstDayOfMonth).atStartOfDay();
return Date.from(initialDate.atZone(americaLaPazZone).toInstant());
}
static Date lastDateOfMonth(Date date) {
LocalDate localDate = convertToLocalDateWithTimezone(date);
YearMonth baseMonth = YearMonth.from(localDate);
LocalDateTime lastDate = baseMonth.atEndOfMonth().atTime(23, 59, 59);
return Date.from(lastDate.atZone(americaLaPazZone).toInstant());
}
static LocalDate convertToLocalDateWithTimezone(Date date) {
return LocalDateTime.from(date.toInstant().atZone(americaLaPazZone)).toLocalDate();
}
GOOGLEFINANCE can have a 20 minutes delay, so refreshing every minute would not really help.
Instead of GOOGLEFINANCE you can use different source. I'm using this RealTime stock prices(I tried a couple but this is the easiest by-far to implement. They have API that retuen JSON { Name: CurrentPrice }
Here's a little script you can use in Google Sheets(Tools->Script Editor)
function GetStocksPrice() {
var url = 'https://financialmodelingprep.com/api/v3/stock/real-time-
price/AVP,BAC,CHK,CY,GE,GPRO,HIMX,IMGN,MFG,NIO,NMR,SSSS,UCTT,UMC,ZNGA';
var response = UrlFetchApp.fetch(url);
// convert json string to json object
var jsonSignal = JSON.parse(response);
// define an array of all the object keys
var headerRow = Object.keys(jsonSignal);
// define an array of all the object values
var values = headerRow.map(function(key){ return jsonSignal[key]});
var data = values[0];
// get sheet by ID -
// you can get the sheet unqiue ID from the your current sheet url
var jsonSheet = SpreadsheetApp.openById("Your Sheet UniqueID");
//var name = jsonSheet.getName();
var sheet = jsonSheet.getSheetByName('Sheet1');
// the column to put the data in -> Y
var letter = "F";
// start from line
var index = 4;
data.forEach(function( row, index2 ) {
var keys = Object.keys(row);
var value2 = row[keys[1]];
// set value loction
var cellXY = letter + index;
sheet.getRange(cellXY).setValue(value2);
index = index + 1;
});
}
Now you need to add a trigger that will execute every minute.
And your set :)
Ruby has no pre/post increment/decrement operator. For instance,
x++
orx--
will fail to parse. More importantly,++x
or--x
will do nothing! In fact, they behave as multiple unary prefix operators:-x == ---x == -----x == ......
To increment a number, simply writex += 1
.
Taken from "Things That Newcomers to Ruby Should Know " (archive, mirror)
That explains it better than I ever could.
EDIT: and the reason from the language author himself (source):
- ++ and -- are NOT reserved operator in Ruby.
- C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
- self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.
I have the same problem. None of the options suggested above worked for me. However I find, that if I lets say manually add groupid/artifact/version for org.springframework.spring-core version 4.3.4.RELEASE and save the pom.xml, the dependencies download automatically and the search works for the jars already present in the repository. However if I now search for org.springframework.spring-context , which isnt in the current dependencies, this search still doesn't work.
The \s
metacharacter matches whitespace characters.
the "display/offsetHeight" hack didn't work in my case, at least when it was applied to the element being animated.
i had a dropdown menu that was being open/closed over the page content. the artifacts were being left on the page content after the menu had closed (only in webkit browsers). the only way the "display/offsetHeight" hack worked is if i applied it to the body, which seems nasty.
however, i did find another solution:
this is still pretty hacky (it uses a CSS3 property to force hardware rendering), but at least it only affects the element in question, and worked for me on both safari and chrome on PC and Mac.
If you want to escape user input in a variable you can do like below within SQL
Set @userinput = replace(@userinput,'''','''''')
The @userinput will be now escaped with an extra single quote for every occurance of a quote
I had similar problem extracting certificates from a file. This might not be the most best way to do it but it worked for me.
openssl pkcs7 -inform DER -print_certs -in <path of the file> | awk 'split_after==1{n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1} {print > "cert" n ".pem"}'
If you only got one IP on the server, there is no chance to do that. DNS is a simple name to number (IP) resolver. If you have two IPs on the server, you can point each subdomain to each of the IP-addresses and run both servers on the default port on each IP.
one.example.com -> 127.0.0.1 (server: 127.0.0.1:25565)
two.example.com -> 127.0.0.2 (server: 127.0.0.2:25565)
You may try this one
$this->db->where('field1',$filed1);
$this->db->where('filed2',$filed2);
$result = $this->db->get('table_name')->num_rows();
In rails 4 you can now use a css and sass helper image-url:
div.logo {background-image: image-url("logo.png");}
If your background images aren't showing up consider looking at how you're referencing them in your stylesheets.
Try either
sudo apt-get install php-zip
orsudo apt-get install php5.6-zip
Then, you might have to restart your web server.
sudo service apache2 restart
orsudo service nginx restart
If you are installing on centos or fedora OS then use yum in place of apt-get. example:-
sudo yum install php-zip
or
sudo yum install php5.6-zip
and
sudo service httpd restart
Here is a better way to loop over files as it handles spaces and newlines in file names:
#!/bin/bash
find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
echo "$line"
ls -l "$line"
done
I am using this code, which I find more practical than the accepted answer above:
List<Thing> thingList = new ArrayList<>(thingSet);
thingList.sort((thing1, thing2) -> thing1.getName().compareToIgnoreCase(thing2.getName()));
$(document).on('change','.radio-button', function(){
const radio = $(this);
if (radio.is(':checked')) {
console.log(radio)
}
});
It is a kind of an interface naming convention which matches with functional programming
//Runnable
interface Runnable {
void run();
}
//Action - throws exception
interface Action {
void run() throws Exception;
}
//Consumer - consumes a value/values, throws exception
interface Consumer1<T> {
void accept(T t) throws Exception;
}
//Callable - return result, throws exception
interface Callable<R> {
R call() throws Exception;
}
//Supplier - returns result, throws exception
interface Supplier<R> {
R get() throws Exception;
}
//Predicate - consumes a value/values, returns true or false, throws exception
interface Predicate1<T> {
boolean test(T t) throws Exception;
}
//Function - consumes a value/values, returns result, throws exception
public interface Function1<T, R> {
R apply(T t) throws Exception;
}
...
I had same issue using different dependancy what helped me is to set scope to compile.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>compile</scope>
</dependency>
sup, sub {
vertical-align: baseline;
position: relative;
top: -0.4em;
}
sub {
top: 0.4em;
}
Use this:
static int RandomNumber(int min, int max)
{
Random random = new Random(); return random.Next(min, max);
}
This is example for you to modify and use in your application.
Test for presence using the in
operator, then apply the remove
method.
if thing in some_list: some_list.remove(thing)
The remove
method will remove only the first occurrence of thing
, in order to remove all occurrences you can use while
instead of if
.
while thing in some_list: some_list.remove(thing)
This shoot-first-ask-questions-last attitude is common in Python. Instead of testing in advance if the object is suitable, just carry out the operation and catch relevant Exceptions:
try:
some_list.remove(thing)
except ValueError:
pass # or scream: thing not in some_list!
except AttributeError:
call_security("some_list not quacking like a list!")
Off course the second except clause in the example above is not only of questionable humor but totally unnecessary (the point was to illustrate duck-typing for people not familiar with the concept).
If you expect multiple occurrences of thing:
while True:
try:
some_list.remove(thing)
except ValueError:
break
However, with contextlib's suppress() contextmanager (introduced in python 3.4) the above code can be simplified to this:
with suppress(ValueError, AttributeError):
some_list.remove(thing)
Again, if you expect multiple occurrences of thing:
with suppress(ValueError):
while True:
some_list.remove(thing)
Around 1993, Python got lambda
, reduce()
, filter()
and map()
, courtesy of a Lisp hacker who missed them and submitted working patches*. You can use filter
to remove elements from the list:
is_not_thing = lambda x: x is not thing
cleaned_list = filter(is_not_thing, some_list)
There is a shortcut that may be useful for your case: if you want to filter out empty items (in fact items where bool(item) == False
, like None
, zero, empty strings or other empty collections), you can pass None as the first argument:
cleaned_list = filter(None, some_list)
filter(function, iterable)
used to be equivalent to [item for item in iterable if function(item)]
(or [item for item in iterable if item]
if the first argument is None
); in Python 3.x, it is now equivalent to (item for item in iterable if function(item))
. The subtle difference is that filter used to return a list, now it works like a generator expression - this is OK if you are only iterating over the cleaned list and discarding it, but if you really need a list, you have to enclose the filter()
call with the list()
constructor.filter
- along with companions map
and reduce
(they are not gone yet but reduce
was moved into the functools module, which is worth a look if you like high order functions).List comprehensions became the preferred style for list manipulation in Python since introduced in version 2.0 by PEP 202. The rationale behind it is that List comprehensions provide a more concise way to create lists in situations where map()
and filter()
and/or nested loops would currently be used.
cleaned_list = [ x for x in some_list if x is not thing ]
Generator expressions were introduced in version 2.4 by PEP 289. A generator expression is better for situations where you don't really need (or want) to have a full list created in memory - like when you just want to iterate over the elements one at a time. If you are only iterating over the list, you can think of a generator expression as a lazy evaluated list comprehension:
for item in (x for x in some_list if x is not thing):
do_your_thing_with(item)
!=
instead of is not
(the difference is important)As already answered, you can create an ArrayList of String Arrays as @Péter Török written;
//Declaration of an ArrayList of String Arrays
ArrayList<String[]> listOfArrayList = new ArrayList<String[]>();
When assigning different String Arrays to this ArrayList, each String Array's length will be different.
In the following example, 4 different Array of String added, their lengths are varying.
String Array #1: len: 3
String Array #2: len: 1
String Array #3: len: 4
String Array #4: len: 2
The Demonstration code is as below;
import java.util.ArrayList;
public class TestMultiArray {
public static void main(String[] args) {
//Declaration of an ArrayList of String Arrays
ArrayList<String[]> listOfArrayList = new ArrayList<String[]>();
//Assignment of 4 different String Arrays with different lengths
listOfArrayList.add( new String[]{"line1: test String 1","line1: test String 2","line1: test String 3"} );
listOfArrayList.add( new String[]{"line2: test String 1"} );
listOfArrayList.add( new String[]{"line3: test String 1","line3: test String 2","line3: test String 3", "line3: test String 4"} );
listOfArrayList.add( new String[]{"line4: test String 1","line4: test String 2"} );
// Printing out the ArrayList Contents of String Arrays
// '$' is used to indicate the String elements of String Arrays
for( int i = 0; i < listOfArrayList.size(); i++ ) {
for( int j = 0; j < listOfArrayList.get(i).length; j++ )
System.out.printf(" $ " + listOfArrayList.get(i)[j]);
System.out.println();
}
}
}
And the output is as follows;
$ line1: test String 1 $ line1: test String 2 $ line1: test String 3
$ line2: test String 1
$ line3: test String 1 $ line3: test String 2 $ line3: test String 3 $ line3: test String 4
$ line4: test String 1 $ line4: test String 2
Also notify that you can initialize a new Array of Sting as below;
new String[]{ str1, str2, str3,... }; // Assuming str's are String objects
So this is same with;
String[] newStringArray = { str1, str2, str3 }; // Assuming str's are String objects
I've written this demonstration just to show that no theArrayList object, all the elements are references to different instantiations of String Arrays, thus the length of each String Arrays are not have to be the same, neither it is important.
One last note: It will be best practice to use the ArrayList within a List interface, instead of which that you've used in your question.
It will be better to use the List interface as below;
//Declaration of an ArrayList of String Arrays
List<String[]> listOfArrayList = new ArrayList<String[]>();
You can also do like this ....
<?php $countryname = $all_meta_for_user['country']; ?>
<select id="mycountry" name="country" class="user">
<?php $myrows = $wpdb->get_results( "SELECT * FROM wp_countries order by country_name" );
foreach($myrows as $rows){
if( $countryname == $rows->id ){
echo "<option selected = 'selected' value='".$rows->id."'>".$rows->country_name."</option>";
} else{
echo "<option value='".$rows->id."'>".$rows->country_name."</option>";
}
}
?>
</select>
Format specifier in printf
should be %f
for doubl
datatypes since float
datatyles eventually convert to double
datatypes inside printf
.
There is no provision to print float
data. Please find the discussion here : Correct format specifier for double in printf
A variation when using xpath in Java using count():
int numberofbodies = Integer.parseInt((String) xPath.evaluate("count(/html/body)", doc));
if( numberofbodies==0) {
// body node missing
}
Most times, you won't need to "convert"; VBA will do safe implicit type conversion for you, without the use of converters like CStr
.
The below code works without any issues, because the variable is of Type String, and implicit type conversion is done for you automatically!
Dim myVal As String
Dim myNum As Integer
myVal = "My number is: "
myVal = myVal & myNum
Result:
"My number is: 0"
You don't even have to get that fancy, this works too:
Dim myString as String
myString = 77
"77"
The only time you WILL need to convert is when the variable Type is ambiguous (e.g., Type Variant, or a Cell's Value
(which is Variant)).
Even then, you won't have to use CStr
function if you're compounding with another String variable or constant. Like this:
Sheet1.Range("A1").Value = "My favorite number is " & 7
"My favorite number is 7"
So, really, the only rare case is when you really want to store an integer value, into a variant or Cell value, when not also compounding with another string (which is a pretty rare side case, I might add):
Dim i as Integer
i = 7
Sheet1.Range("A1").Value = i
7
Dim i as Integer
i = 7
Sheet1.Range("A1").Value = CStr(i)
"7"
The top post has 'as TextView' appended on the end. You might get other compiler errors if you leave this on. The following should be fine.
val text: TextView = findViewById(R.id.android_text) as TextView
Where 'android_text' is the ID of your textView
This solution work on my case i am using ubuntu 16.04, VirtualBox 2.7.2 and genymotion 2.7.2 Same error come in my system i have followed simple step and my problem was solve
1. $ LD_LIBRARY_PATH=/usr/local/lib64/:$LD_LIBRARY_PATH
2. $ export LD_LIBRARY_PATH
3. $ sudo apt-add-repository ppa:ubuntu-toolchain-r/test
4. $ sudo apt-get update
5. $ sudo apt-get install gcc-4.9 g++-4.9
I hope this will work for you
Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.
function myFunction() {_x000D_
var selchbox = [];_x000D_
var inputfields = document.getElementsByName("myCheck");_x000D_
var ar_inputflds = inputfields.length;_x000D_
_x000D_
for (var i = 0; i < ar_inputflds; i++) {_x000D_
if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
selchbox.push(inputfields[i].value);_x000D_
}_x000D_
return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
var selchb = myFunction();_x000D_
console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
yes, its possible, run this command:
lets say you have user called thoko
grant select any table, insert any table, delete any table, update any table to thoko;
note: worked on oracle database
If you are using python3, you need to install python3-dev
. This fixed my problem sudo apt-get install python3-dev
.
You can pass in the element to the controller, just like the scope:
function someControllerFunc($scope, $element){
}
It seems Yahoo server does some heuristic based on User-Agent
in a case Accept
header is set to */*
.
Accept: text/html
did the trick for me.
e.g.
wget --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" http://yahoo.com
Note: if you don't declare Accept
header then wget
automatically adds Accept:*/*
which means give me anything you have.
The method you're using to read the http body response returns a byte slice:
func ReadAll(r io.Reader) ([]byte, error)
You can convert []byte
to a string by using
body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)
I do like this and its working fine.
constructor() {
super();
this.state ={
status:true
}
}
render() {
return(
{ this.state.status === true ?
<TouchableHighlight onPress={()=>this.hideView()}>
<View style={styles.optionView}>
<Text>Ok Fine :)</Text>
</View>
</TouchableHighlight>
:
<Text>Ok Fine.</Text>
}
);
}
hideView(){
this.setState({
home:!this.state.status
});
}
For anyone attempting something similar using a Dockerfile...
Running in detached mode won't help. The container will always exit (stop running) if the command is non-blocking, this is the case with bash.
In this case, a workaround would be: 1. Commit the resulting image: (container_name = the name of the container you want to base the image off of, image_name = the name of the image to be created docker commit container_name image_name 2. Use docker run to create a new container using the new image, specifying the command you want to run. Here, I will run "bash": docker run -it image_name bash
This would get you the interactive login you're looking for.
Based on @Vlad Bezden answer I use this slightly modified code because I prefer named placeholders:
String.prototype.format = function(placeholders) {
var s = this;
for(var propertyName in placeholders) {
var re = new RegExp('{' + propertyName + '}', 'gm');
s = s.replace(re, placeholders[propertyName]);
}
return s;
};
usage:
"{greeting} {who}!".format({greeting: "Hello", who: "world"})
String.prototype.format = function(placeholders) {_x000D_
var s = this;_x000D_
for(var propertyName in placeholders) {_x000D_
var re = new RegExp('{' + propertyName + '}', 'gm');_x000D_
s = s.replace(re, placeholders[propertyName]);_x000D_
} _x000D_
return s;_x000D_
};_x000D_
_x000D_
$("#result").text("{greeting} {who}!".format({greeting: "Hello", who: "world"}));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="result"></div>
_x000D_
I think it's best to create 1px nine-patch image, and use showDividers attribute in TableRow and TableLayout since they are both LinearLayouts
this short code worked for me:
Configuration wConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup wServiceSection = ServiceModelSectionGroup.GetSectionGroup(wConfig);
ClientSection wClientSection = wServiceSection.Client;
wClientSection.Endpoints[0].Address = <your address>;
wConfig.Save();
Of course you have to create the ServiceClient proxy AFTER the config has changed. You also need to reference the System.Configuration and System.ServiceModel assemblies to make this work.
Cheers
One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.
assert type(A) is type(""), "requires a string"
You need to add sudo . I did the following to get it installed :
sudo apt-get install libsm6 libxrender1 libfontconfig1
and then did that (optional! maybe you won't need it)
sudo python3 -m pip install opencv-contrib-python
FINALLY got it done !
I think, it should be like this:
class foo():
input = get_input(__qualname__)
Static constructor
called only the first instance of the class created.
like this:
static class YourClass
{
static YourClass()
{
//initialization
}
}
push is an Array method, for json object you may need to define it
this should do it:
library[title] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};
Download and include this plugin
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js"></script>
and use like
if(CryptoJS.MD5($("#txtOldPassword").val())) != oldPassword) {
}
//Following lines shows md5 value
//var hash = CryptoJS.MD5("Message");
//alert(hash);
I was having problems getting a commandField Delete button to honor the 'return false' response to when a user clicked cancel on the 'Are you sure' pop-up that one gets with using the javascript confirm() function. I didn't want to change it to a template field.
The problem, as I see it, was that these commandField Buttons already have some Javascript associated with them to perform the postback. No amount of simply appending the confirm() function was effective.
Here's how I solved it:
Using JQuery, I first found each delete button on the page (there are several), then manipulated the button's associated Javascript based on whether the visitor agreed or canceled the confirming pop-up.
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('input[type="button"]').each(function() {
if ($(this).val() == "Delete") {
var curEvent = $(this).attr('onclick');
var newContent = "if(affirmDelete() == true){" + curEvent + "};"
$(this).attr('onclick',newContent);
}
});
}
function affirmDelete() {
return confirm('Are you sure?');
}
</script>
You are missing an equality:
var query = (from p in tblPersoon where p.id == 5 select p).Single();
where
clause must result in a boolean.
OR you should not be using where
at all:
var query = (from p in tblPersoon select p).Single();
Another approach would be to have an array of objects, with each individual object holding the properties of a column. This slightly changes the structure of "myMappings", but makes it easy to work with:
var myMappings = [
{ title: "Name", width: "10%" },
{ title: "Phone", width: "10%" },
{ title: "Address", width: "50%" },
{ title: "Zip", width: "10%" },
{ title: "Comments", width: "20%" }
];
Then you could easily iterate through all your "columns" with a for loop:
for (var i = 0; i < myMappings.length; i += 1) {
// myMappings[i].title ...
// myMappings[i].width ...
}
These are known as postfix and prefix operators. Both will add 1 to the variable but there is a difference in the result of the statement.
int x = 0;
int y = 0;
y = ++x; // result: y=1, x=1
int x = 0;
int y = 0;
y = x++; // result: y=0, x=1
Toni
's answer is very useful, but I thought a quick start for total beginners to test coverage assessment (like I am).
As already mentioned, Visual Studio Professional and Community Editions do not have built-in test coverage support. However, it can be obtained quite easily. I will write step-by-step configuration for use with NUnit tests within Visual Studion 2015 Professional.
Install OpenCover NUGet component using NuGet interface
Get OpenCoverUI extension. This can be installed directly from Visual Studio by using Tools -> Extensions and Updates
Configure OpenCoverUI to use the appropriate executables, by accessing Tools -> Options -> OpenCover.UI Options -> General
NUnit Path: must point to the `nunit-console.exe file. This can be found only within NUnit 2.xx version, which can be downloaded from here.
OpenCover Path: this should point to the installed package, usually <solution path>\packages\OpenCover.4.6.519\tools\OpenCover.Console.exe
Install ReportGenerator NUGet package
Access OpenCover Test Explorer
from OpenCover menu. Try discovering tests from there. If it fails, check Output windows for more details.
Check OpenCover Results (within OpenCover menu) for more details. It will output details such as Code Coverage in a tree based view. You can also highlight code that is or is not covered (small icon in the top-left).
NOTE: as mentioned, OpenCoverUI does not support latest major version of NUnit (3.xx). However, if nothing specific to this version is used within tests, it will work with no problems, regardless of having installed NUnit 3.xx version.
This covers the quick start. As already mentioned in the comments, for more advanced configuration and automation check this article.
If you want to content to be scrollable, set the position of the content to absolute:
content {
position: absolute;
...
}
I don't know if this was just for me, but if not that's the fix!
Also since the background is fixed, it means you have a "parallax" effect! So now, not only did this person teach you how to make a blurry background, but it is also a parallax background effect!
Sure!
#file -- test.py --
myvar = 42
def test_func():
print("Hello!")
Now, this file ("test.py") is in python terminology a "module". We can import it (as long as it can be found in our PYTHONPATH
) Note that the current directory is always in PYTHONPATH
, so if use_test
is being run from the same directory where test.py
lives, you're all set:
#file -- use_test.py --
import test
test.test_func() #prints "Hello!"
print (test.myvar) #prints 42
from test import test_func #Only import the function directly into current namespace
test_func() #prints "Hello"
print (myvar) #Exception (NameError)
from test import *
test_func() #prints "Hello"
print(myvar) #prints 42
There's a lot more you can do than just that through the use of special __init__.py
files which allow you to treat multiple files as a single module), but this answers your question and I suppose we'll leave the rest for another time.
If you want the file to be opened with the default application, I mean without specifying Acrobat or Reader, you can't open the file in the specified page.
On the other hand, if you are Ok with specifying Acrobat or Reader, keep reading:
You can do it without telling the full Acrobat path, like this:
Process myProcess = new Process();
myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path
myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\example.pdf";
myProcess.Start();
If you don't want the pdf to open with Reader but with Acrobat, chage the second line like this:
myProcess.StartInfo.FileName = "Acrobat.exe";
You can query the registry to identify the default application to open pdf files and then define FileName on your process's StartInfo accordingly.
Follow this question for details on doing that: Finding the default application for opening a particular file type on Windows
Short answer (valid as of 2015-04-16): removeAtIndex(myString.endIndex.predecessor())
Example:
var howToBeHappy = "Practice compassion, attention and gratitude. And smile!!"
howToBeHappy.removeAtIndex(howToBeHappy.endIndex.predecessor())
println(howToBeHappy)
// "Practice compassion, attention and gratitude. And smile!"
Meta:
The language continues its rapid evolution, making the half-life for many formerly-good S.O. answers dangerously brief. It's always best to learn the language and refer to real documentation.
File.Create
returns a FileStream
object that you can call Close()
on.
If you simply want to watch a state property and then act within the component accordingly to the changes of that property then see the example below.
In store.js
:
export const state = () => ({
isClosed: false
})
export const mutations = {
closeWindow(state, payload) {
state.isClosed = payload
}
}
In this scenario, I am creating a boolean
state property that I am going to change in different places in the application like so:
this.$store.commit('closeWindow', true)
Now, if I need to watch that state property in some other component and then change the local property I would write the following in the mounted
hook:
mounted() {
this.$store.watch(
state => state.isClosed,
(value) => {
if (value) { this.localProperty = 'edit' }
}
)
}
Firstly, I am setting a watcher on the state property and then in the callback function I use the value
of that property to change the localProperty
.
I hope it helps!
This worked for me - ( from mongo shell )
var file = cat('./new.json'); # file name
use testdb # db name
var o = JSON.parse(file); # convert string to JSON
db.forms.insert(o) # collection name
public static class DateTimeExtensions
{
public static DateTime LastDayOfMonth(this DateTime date)
{
return date.AddDays(1-(date.Day)).AddMonths(1).AddDays(-1);
}
}
I ran into this problem debugging play framework version 2.x, turned out the server hadn't been started even though the play debug run command was issued. After a first request to the webserver which caused the play framework to really start the application at port 9000, I was able to connect properly to the debug port 9999 from eclipse.
[info] play - Application started (Dev)
The text above was shown in the console when the message above appeared, indicating why eclipse couldn't connect before first http request.
I feel like all of these answers are slightly incomplete, so here's the proper way to add a viewController's view as a subview of another viewController's view:
[self addChildViewController:viewControllerToAdd];
[self.view addSubview:viewControllerToAdd.view];
[viewControllerToAdd didMoveToParentViewController:self];
If you'd like, you can copy this into your code as a snippet. SO doesn't seem to understand code replacement formatting, but they will show up clean in Xcode:
[self addChildViewController:<#viewControllerToAdd#>];
[self.view addSubview:<#viewControllerToAdd#>.view];
[<#viewControllerToAdd#> didMoveToParentViewController:self];
willMove is called automatically w/ addChild. Thanks @iOSSergey
When your custom container calls the addChildViewController: method, it automatically calls the willMoveToParentViewController: method of the view controller to be added as a child before adding it.
Your pointer is pointing to local variable of the function. So as soon as you return from the function, memory gets deallocated. You have to assign memory on heap in order to use it in other functions.
Instead
char *rtnPtr = word;
do this
char *rtnPtr = malloc(length);
So that it is available in the main function. After it is used free the memory.
Eclipse used to need a column mode plugin to be able to select a rectangular selection.
Since Eclipse 3.5, you just need to type Alt+Shift+A: see its News and Noteworthy section. (On OS X it's Option-Command-A.)
Or activate the '
Editor Presentation
' action set ( Window > Customize Perspective menu) to get a tool bar button for toggling the block selection mode.
AmbroseChapel adds in the comments:
This is a toggle.
Columnar selection is a mode you enter and leave: in other words, Eclipse switches into a mode where all mouse selections have to be columnar and you stay in that mode until you switch back (by using the same command again).
It's not like other editors where columnar selections are enabled only while certain keys are down.
Assuming your array called 'string' already exists, try
string[0] = '\0';
\0
is the explicit NUL terminator, required to mark the end of string.
I found this example
https://github.com/square/retrofit/issues/1557
Here we set custom url client connection client before before we build API rest service implementation.
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import retrofit.Endpoint
import retrofit.RestAdapter
import retrofit.client.Request
import retrofit.client.UrlConnectionClient
import retrofit.converter.GsonConverter
class ClientBuilder {
public static <T> T buildClient(final Class<T> client, final String serviceUrl) {
Endpoint mCustomRetrofitEndpoint = new CustomRetrofitEndpoint()
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(mCustomRetrofitEndpoint)
.setConverter(new GsonConverter(gson))
.setClient(new MyUrlConnectionClient())
RestAdapter restAdapter = builder.build()
return restAdapter.create(client)
}
}
public final class MyUrlConnectionClient extends UrlConnectionClient {
@Override
protected HttpURLConnection openConnection(Request request) {
HttpURLConnection connection = super.openConnection(request);
connection.setConnectTimeout(15 * 1000);
connection.setReadTimeout(30 * 1000);
return connection;
}
}
Exact comparison of floating point values is know to not always work due to the rounding and internal representation issue.
Try imprecise comparison:
if (x >= 0.099 && x <= 0.101)
{
}
The other alternative is to use the decimal data type.