I uninstalled puppeteer, mocha and chai
using
npm uninstall puppeteer mocha chai
from the command line and then reinstalled using
npm install puppeteer mocha chai
and the error message simply never showed up
you're missing group nested controls with formGroupName
directive
<div class="panel-body" formGroupName="address">
<div class="form-group">
<label for="address" class="col-sm-3 control-label">Business Address</label>
<div class="col-sm-8">
<input type="text" class="form-control" formControlName="street" placeholder="Business Address">
</div>
</div>
<div class="form-group">
<label for="website" class="col-sm-3 control-label">Website</label>
<div class="col-sm-8">
<input type="text" class="form-control" formControlName="website" placeholder="website">
</div>
</div>
<div class="form-group">
<label for="telephone" class="col-sm-3 control-label">Telephone</label>
<div class="col-sm-8">
<input type="text" class="form-control" formControlName="mobile" placeholder="telephone">
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-3 control-label">Email</label>
<div class="col-sm-8">
<input type="text" class="form-control" formControlName="email" placeholder="email">
</div>
</div>
<div class="form-group">
<label for="page id" class="col-sm-3 control-label">Facebook Page ID</label>
<div class="col-sm-8">
<input type="text" class="form-control" formControlName="pageId" placeholder="facebook page id">
</div>
</div>
<div class="form-group">
<label for="about" class="col-sm-3 control-label"></label>
<div class="col-sm-3">
<!--span class="btn btn-success form-control" (click)="openGeneralPanel()">Back</span-->
</div>
<label for="about" class="col-sm-2 control-label"></label>
<div class="col-sm-3">
<button class="btn btn-success form-control" [disabled]="companyCreatForm.invalid" (click)="openContactInfo()">Continue</button>
</div>
</div>
</div>
When you upload your p8 file in Firebase, in the box that reads App ID Prefix(required) , you should enter your team ID. You can get it from https://developer.apple.com/account/#/membership and copy/paste the Team ID as shown below.
I suggest using pubnub. I tried using ServiceWorkers and PushNotification from the browser however, however when I tried it webviews did not support this.
https://www.pubnub.com/docs/web-javascript/pubnub-javascript-sdk
Follow the steps given below as I also had the same problem:
$ git pull origin master --allow-unrelated-histories
(To see if local branch can be easily merged with remote one)
$ git push -u origin master
(Now push entire content of local git repository to your online repository)
If all those kill process commands don't work for you, my suggestion is to check if you were using any other packages to run your node process.
I had the similar issue, and it was due to I was running my node process using PM2(a NPM package). The kill [processID]
command disables the process but keeps the port occupied. Hence I had to go into PM2 and dump all node process to free up the port again.
The element.getBoundingClientRect()
method will return the proper coordinates of an element relative to the viewport regardless of whether the svg has been scaled and/or translated.
While getBBox() works for an untransformed space, if scale and translation have been applied to the layout then it will no longer be accurate. The getBoundingClientRect() function has worked well for me in a force layout project when pan and zoom are in effect, where I wanted to attach HTML Div elements as labels to the nodes instead of using SVG Text elements.
Please check it this:
This is working in chrome and all browser.
<a href="mailto:[email protected]">Test</a>
try and working in great.
I had the exact same problem you describe above (Galaxy Nexus on t-mobile USA) it is because mobile data is turned off.
In Jelly Bean it is: Settings > Data Usage > mobile data
Note that I have to have mobile data turned on PRIOR to sending an MMS OR receiving one. If I receive an MMS with mobile data turned off, I will get the notification of a new message and I will receive the message with a download button. But if I do not have mobile data on prior, the incoming MMS attachment will not be received. Even if I turn it on after the message was received.
For some reason when your phone provider enables you with the ability to send and receive MMS you must have the Mobile Data enabled, even if you are using Wifi, if the Mobile Data is enabled you will be able to receive and send MMS, even if Wifi is showing as your internet on your device.
It is a real pain, as if you do not have it on, the message can hang a lot, even when turning on Mobile Data, and might require a reboot of the device.
A bit late to the party, but JQuery change inner text but preserve html has at least one approach not mentioned here:
var $td = $("#demoTable td");
$td.html($td.html().replace('Tap on APN and Enter', 'new text'));
Without fixing the text, you could use (snother)[https://stackoverflow.com/a/37828788/1587329]:
var $a = $('#demoTable td'); var inner = ''; $a.children.html().each(function() { inner = inner + this.outerHTML; }); $a.html('New text' + inner);
This is the best possible way that I have tried out. If it should help anyone...
+ (UIViewController*) topMostController
{
UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topController.presentedViewController) {
topController = topController.presentedViewController;
}
return topController;
}
Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?
By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...
-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications
If you are running you should be able to access any of those system properties to see if they have been set:
if (System.getProperty("com.sun.management.jmxremote") == null) {
System.out.println("JMX remote is disabled");
} else [
String portString = System.getProperty("com.sun.management.jmxremote.port");
if (portString != null) {
System.out.println("JMX running on port "
+ Integer.parseInt(portString));
}
}
Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts
or if it is set to an incorrect interface address then you can override it with the following:
-Djava.rmi.server.hostname=<IP address>
As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port
is actually the RMI port. This tells the client what port the JMX server is running on.
The problem you'll face is that there's two types of PEM formatted keys: PKCS8 and SSLeay. It doesn't help that OpenSSL seems to use both depending on the command:
The usual openssl genrsa
command will generate a SSLeay format PEM. An export from an PKCS12 file with openssl pkcs12 -in file.p12
will create a PKCS8 file.
The latter PKCS8 format can be opened natively in Java using PKCS8EncodedKeySpec
. SSLeay formatted keys, on the other hand, can not be opened natively.
To open SSLeay private keys, you can either use BouncyCastle provider as many have done before or Not-Yet-Commons-SSL have borrowed a minimal amount of necessary code from BouncyCastle to support parsing PKCS8 and SSLeay keys in PEM and DER format: http://juliusdavies.ca/commons-ssl/pkcs8.html. (I'm not sure if Not-Yet-Commons-SSL will be FIPS compliant)
By inference from the OpenSSL man pages, key headers for two formats are as follows:
PKCS8 Format
Non-encrypted: -----BEGIN PRIVATE KEY-----
Encrypted: -----BEGIN ENCRYPTED PRIVATE KEY-----
SSLeay Format
-----BEGIN RSA PRIVATE KEY-----
(These seem to be in contradiction to other answers but I've tested OpenSSL's output using PKCS8EncodedKeySpec
. Only PKCS8 keys, showing ----BEGIN PRIVATE KEY-----
work natively)
Generally if something works on various computers but fails on only one computer, then there's something wrong with that computer. Here are a few things to check:
(1) Are you running the same stuff on that computer -- OS including patches, etc.
(2) Does the computer report problems? Where to look depends on the OS, but it looks like you're using linux, so check syslog
(3) Run hardware diagnostics, e.g. the ones recommended here. Start with memory and disk checks in particular.
If you can't turn up any issues, then search for a similar issue in the bug parade for whichever VM you're using. Unfortunately if you're already on the latest version of the VM, then you won't necessarily find a fix.
Finally, one more option is simply to try another VM -- e.g. OpenJDK or JRockit, instead of Oracle's standard.
Steps:
This gives you three files:
PushChatKey.p12
)aps_development.cer
Go to the folder where you downloaded the files, in my case the Desktop:
$ cd ~/Desktop/
Convert the .cer file into a .pem file:
$ openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem
Convert the private key’s .p12 file into a .pem file:
$ openssl pkcs12 -nocerts -out PushChatKey.pem -in PushChatKey.p12
Enter Import Password:
MAC verified OK
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
You first need to enter the passphrase for the .p12 file so that openssl can read it. Then you need to enter a new passphrase that will be used to encrypt the PEM file. Again for this tutorial I used “pushchat” as the PEM passphrase. You should choose something more secure. Note: if you don’t enter a PEM passphrase, openssl will not give an error message but the generated .pem file will not have the private key in it.
Finally, combine the certificate and key into a single .pem file:
$ cat PushChatCert.pem PushChatKey.pem > ck.pem
Its reaily good and working solution for push.
Please try it
I removed the text-transform: uppercase;
and then set it to bold
/bolder
, and this seemed to work.
Building on another answer on this page,
public static String getCurrentUrlFromRequest(ServletRequest request)
{
if (! (request instanceof HttpServletRequest))
return null;
return getCurrentUrlFromRequest((HttpServletRequest)request);
}
public static String getCurrentUrlFromRequest(HttpServletRequest request)
{
StringBuffer requestURL = request.getRequestURL();
String queryString = request.getQueryString();
if (queryString == null)
return requestURL.toString();
return requestURL.append('?').append(queryString).toString();
}
Full working implementation of how to detect orientation change in Swift 3.0.
I chose to use this implementation because phone orientations of face up
and face down
were important to me, and I wanted the view to change only once I knew the orientation was in the specified position.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//1
NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
deinit {
//3
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
func deviceOrientationDidChange() {
//2
switch UIDevice.current.orientation {
case .faceDown:
print("Face down")
case .faceUp:
print("Face up")
case .unknown:
print("Unknown")
case .landscapeLeft:
print("Landscape left")
case .landscapeRight:
print("Landscape right")
case .portrait:
print("Portrait")
case .portraitUpsideDown:
print("Portrait upside down")
}
}
}
The important pieces to note are:
unknown
orientation at times.Hope someone finds this helpful.
for (int i = 0; i < list.size(); i++) {
if (i < list.size() - 1) {
if (list.get(i) > list.get(i + 1)) {
int j = list.get(i);
list.remove(i);
list.add(i, list.get(i));
list.remove(i + 1);
list.add(j);
i = -1;
}
}
}
Hashtable<String, Object>
It is better than java.util.Properties
which is by fact an extension of Hashtable<Object, Object>
.
Send the passwordbox control as a parameter to your login command.
<Button Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=PasswordBox}"...>
Then you can call CType(parameter, PasswordBox).Password
in your viewmodel.
OR is slightly tricky, but not overly so. Here is an example
set var1=%~1
set var2=%~2
::
set or_=
if "%var1%"=="Stack" set or_=true
if "%var2%"=="Overflow" set or_=true
if defined or_ echo Stack OR Overflow
To subtract timevals:
gettimeofday(&t0, 0);
/* ... */
gettimeofday(&t1, 0);
long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;
This is assuming you'll be working with intervals shorter than ~2000 seconds, at which point the arithmetic may overflow depending on the types used. If you need to work with longer intervals just change the last line to:
long long elapsed = (t1.tv_sec-t0.tv_sec)*1000000LL + t1.tv_usec-t0.tv_usec;
I assume that you have a .cer file containing PKCS#7-encoded certificate data and you want to convert it to PEM-encoded certificate data (typically a .crt or .pem file). For instance, a .cer file containing PKCS#7-encoded data looks like this:
-----BEGIN PKCS7----- MIIW4gYJKoZIhvcNAQcCoIIW0zCCFs8CAQExADALBgkqhkiG9w0BBwGggha1MIIH ... POI9n9cd2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G +bKhADEA -----END PKCS7-----
PEM certificate data looks like this:
-----BEGIN CERTIFICATE----- MIIHNjCCBh6gAwIBAgIQAlBxtqKazsxUSR9QdWWxaDANBgkqhkiG9w0BAQUFADBm ... nv72c/OV4nlyrvBLPoaS5JFUJvFUG8RfAEY= -----END CERTIFICATE-----
There is an OpenSSL command that will convert .cer files (with PKCS#7 data) to the PEM data you may be expecting to encounter (the BEGIN CERTIFICATE
block in the example above). You can coerce PKCS#7 data into PEM format by this command on a file we'll call certfile.cer:
openssl pkcs7 -text -in certfile.cer -print_certs -outform PEM -out certfile.pem
Note that a .cer or .pem file might contain one or more certificates (possibly the entire certificate chain).
If M2_HOME
is configured to point to the Maven home directory then:
File -> Settings
Maven
Runner
Insert in the field VM Options
the following string:
Dmaven.multiModuleProjectDirectory=$M2_HOME
Click Apply
and OK
I needed a more general solution to account for the possibility of multiple dictionaries in the list having the key value, and a straightforward implementation using list comprehension:
dict_indices = [i for i, d in enumerate(dict_list) if d[dict_key] == key_value]
From the documentation:
get cookie from response
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies
{'example_cookie_name': 'example_cookie_value'}
give cookie back to server on subsequent request
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)`
All cookies expire as per the cookie specification, so this is not a PHP limitation.
Use a far future date. For example, set a cookie that expires in ten years:
setcookie(
"CookieName",
"CookieValue",
time() + (10 * 365 * 24 * 60 * 60)
);
Note that if you set a date past 2038 in 32-bit PHP, the number will wrap around and you'll get a cookie that expires instantly.
control-shift-L should open the log(s) for you. this will by default be the messages log, but if you create the item that is creating the error the Compiler Log will show up (for me the box shows up in the bottom middle left).
if the messages log is the only log that shows up, simply re-execute the item that was causing the failure and the compiler log will show up
for instance, hit Control-shift-L then execute this
CREATE OR REPLACE FUNCTION TEST123() IS
BEGIN
VAR := 2;
end TEST123;
and you will see the message "Error(1,18): PLS-00103: Encountered the symbol ")" when expecting one of the following: current delete exists prior "
(You can also see this in "View--Log")
One more thing, if you are having a problem with a (function || package || procedure) if you do the coding via the SQL Developer interface (by finding the object in question on the connections tab and editing it the error will be immediately displayed (and even underlined at times)
This format is used to get current timestamp and stored in mysql
$date = date("Y-m-d H:i:s");
$update_query = "UPDATE db.tablename SET insert_time=".$date." WHERE username='" .$somename . "'";
Use flex. Much simpler and will work regardless of your div
size:
.center-screen {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
text-align: center;_x000D_
min-height: 100vh;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div class="center-screen">_x000D_
I'm in the center_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
To kill the puma process first run
lsof -wni tcp:3000
to show what is using port 3000. Then use the PID that comes with the result to run the kill process.
For example after running lsof -wni tcp:3000 you might get something like
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
ruby 3366 dummy 8u IPv4 16901 0t0 TCP 127.0.0.1:3000 (LISTEN)
Now run the following to kill the process. (where 3366 is the PID)
kill -9 3366
Should resolve the issue
Go to the first line from which you would like to delete, and press the keys dG
If you just need to test some of the concrete methods without touching any of the abstracts, you can use CALLS_REAL_METHODS
(see Morten's answer), but if the concrete method under test calls some of the abstracts, or unimplemented interface methods, this won't work -- Mockito will complain "Cannot call real method on java interface."
(Yes, it's a lousy design, but some frameworks, e.g. Tapestry 4, kind of force it on you.)
The workaround is to reverse this approach -- use the ordinary mock behavior (i.e., everything's mocked/stubbed) and use doCallRealMethod()
to explicitly call out the concrete method under test. E.g.
public abstract class MyClass {
@SomeDependencyInjectionOrSomething
public abstract MyDependency getDependency();
public void myMethod() {
MyDependency dep = getDependency();
dep.doSomething();
}
}
public class MyClassTest {
@Test
public void myMethodDoesSomethingWithDependency() {
MyDependency theDependency = mock(MyDependency.class);
MyClass myInstance = mock(MyClass.class);
// can't do this with CALLS_REAL_METHODS
when(myInstance.getDependency()).thenReturn(theDependency);
doCallRealMethod().when(myInstance).myMethod();
myInstance.myMethod();
verify(theDependency, times(1)).doSomething();
}
}
Updated to add:
For non-void methods, you'll need to use thenCallRealMethod()
instead, e.g.:
when(myInstance.myNonVoidMethod(someArgument)).thenCallRealMethod();
Otherwise Mockito will complain "Unfinished stubbing detected."
Construct the first parameter as an instance of Action
, e.g.
var inputID = 123;
var col = new BlockingDataCollection();
var task = Task.Factory.StartNew(
() => CheckFiles(inputID, col),
cancelCheckFile.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
Looking into https://mochajs.org/#usage we see that simply use
mocha test/myfile
will work. You can omit the '.js' at the end.
Location permission privacy change in Android 10 or Android Q.
We have to define additional ACCESS_BACKGROUND_LOCATION
permission if user wants to access their current location in background so user needs to granted permission runtime also in requestPermission()
If we are using lower than Android 10 device then ACCESS_BACKGROUND_LOCATION
permission allow automatically with ACCESS_FINE_LOCATION
or ACCESS_COARSE_LOCATION
permission
This tabular format might be easy to understand what if we don't specify ACCESS_BACKGROUND_LOCATION
in manifest file.
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /> // here we defined ACCESS_BACKGROUND_LOCATION for Android 10 device
MainActivity.java
Call checkRunTimePermission()
in onCreate()
or onResume()
public void checkRunTimePermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED||
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
gpsTracker = new GPSTracker(context);
} else {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
10);
}
} else {
gpsTracker = new GPSTracker(context); //GPSTracker is class that is used for retrieve user current location
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 10) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
gpsTracker = new GPSTracker(context);
} else {
if (!ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.ACCESS_FINE_LOCATION)) {
// If User Checked 'Don't Show Again' checkbox for runtime permission, then navigate user to Settings
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("Permission Required");
dialog.setCancelable(false);
dialog.setMessage("You have to Allow permission to access user location");
dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package",
context.getPackageName(), null));
//i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(i, 1001);
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
//code for deny
}
}
}
@Override
public void startActivityForResult(Intent intent, int requestCode) {
super.startActivityForResult(intent, requestCode);
switch (requestCode) {
case 1001:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED) {
gpsTracker = new GPSTracker(context);
if (gpsTracker.canGetLocation()) {
latitude = gpsTracker.getLatitude();
longitude = gpsTracker.getLongitude();
}
} else {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_BACKGROUND_LOCATION},10);
}
}
break;
default:
break;
}
}
build.gradle (app level)
android {
compileSdkVersion 29 //should be >= 29
buildToolsVersion "29.0.2"
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "com.example.runtimepermission"
minSdkVersion 21
targetSdkVersion 29 //should be >= 29
versionCode 1
versionName "1.0"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
}
Here you can find GPSTracker.java
file code
_msize(array)
in Windows or malloc_usable_size(array)
in Linux should work for the dynamic array
Both are located within malloc.h and both return a size_t
You should not attempt to parse HTML with regex. HTML is not a regular language, so any regex you come up with will likely fail on some esoteric edge case. Please refer to the seminal answer to this question for specifics. While mostly formatted as a joke, it makes a very good point.
The following examples are Java, but the regex will be similar -- if not identical -- for other languages.
String target = someString.replaceAll("<[^>]*>", "");
Assuming your non-html does not contain any < or > and that your input string is correctly structured.
If you know they're a specific tag -- for example you know the text contains only <td>
tags, you could do something like this:
String target = someString.replaceAll("(?i)<td[^>]*>", "");
Edit: Omega brought up a good point in a comment on another post that this would result in multiple results all being squished together if there were multiple tags.
For example, if the input string were <td>Something</td><td>Another Thing</td>
, then the above would result in SomethingAnother Thing
.
In a situation where multiple tags are expected, we could do something like:
String target = someString.replaceAll("(?i)<td[^>]*>", " ").replaceAll("\\s+", " ").trim();
This replaces the HTML with a single space, then collapses whitespace, and then trims any on the ends.
Another trick is to use
.class {
position: absolute;
visibility:hidden;
display:none;
}
This is not likely to mess up your flow (because it takes it out of flow) and makes sure that the user can't see it, and then if display:none
works later on it will be working. Keep in mind that visibility:hidden
may not remove it from screen readers.
In HTML5 better use this:
{
//...
canvas.width = img.naturalWidth; //img.width;
canvas.height = img.naturalHeight; //img.height;
//...
}
I encountered this error with the Eclipse 4.10 installer. We had failed to complete the install correctly due to platform security settings and attempted to uninstall but had to do it by hand since no uninstaller was introduced during the failed install. We suspected this corrupted the end result - even after re-installing.
The solution was to use the JVM to launch Eclipse and bypass the launcher executable entirely. The following command successfully launches Eclipse 4.10 (some parameters will change based on the version of Eclipse):
%JDK190%\bin\javaw.exe -jar C:\<fully_qualified_path_to_eclipse>\Eclipse410\plugins\org.eclipse.equinox.launcher_1.5.200.v20180922-1751.jar -clean -showsplash
After using this command/shortcut to launch Eclipse we had no further errors with Eclipse itself but we weren't able to use the EXE launcher in the future. Even after a year of using this version, the launcher continues to display this same error.
To be clear, you'll have to modify your javaw.exe
command to match your system specifications on MS Windows.
Was having this issue testing long doubles, and alas, I came across a fix! You have to compile your project with -D__USE_MINGW_ANSI_STDIO:
Jason Huntley@centurian /home/developer/dependencies/Python-2.7.3/test $ gcc main.c
Jason Huntley@centurian /home/developer/dependencies/Python-2.7.3/test $ a.exe c=0.000000
Jason Huntley@centurian /home/developer/dependencies/Python-2.7.3/test $ gcc main.c -D__USE_MINGW_ANSI_STDIO
Jason Huntley@centurian /home/developer/dependencies/Python-2.7.3/test $ a.exe c=42.000000
Code:
Jason Huntley@centurian /home/developer/dependencies/Python-2.7.3/test
$ cat main.c
#include <stdio.h>
int main(int argc, char **argv)
{
long double c=42;
c/3;
printf("c=%Lf\n",c);
return 0;
}
In my case, for some reason, vendor
folder was disabled on VS Code settings:
"intelephense.files.exclude": [
"**/.git/**",
"**/.svn/**",
"**/.hg/**",
"**/CVS/**",
"**/.DS_Store/**",
"**/node_modules/**",
"**/bower_components/**",
"**/vendor/**", <-- remove this line!
"**/resources/views/**"
],
By removing the line containing vendor
folder it works ok on version Intelephense 1.5.4
Efficiency aside, I rarely find myself wishing for declarative collection creation outside of unit tests. I do believe that the double brace syntax is very readable.
Another way to achieve the declarative construction of lists specifically is to use Arrays.asList(T ...)
like so:
List<String> aList = Arrays.asList("vanilla", "strawberry", "chocolate");
The limitation of this approach is of course that you cannot control the specific type of list to be generated.
DESCRIBE <table>;
This is acutally a shortcut for:
SHOW COLUMNS FROM <table>;
In any case, there are three possible values for the "Key" attribute:
PRI
UNI
MUL
The meaning of PRI
and UNI
are quite clear:
PRI
=> primary keyUNI
=> unique keyThe third possibility, MUL
, (which you asked about) is basically an index that is neither a primary key nor a unique key. The name comes from "multiple" because multiple occurrences of the same value are allowed. Straight from the MySQL documentation:
If
Key
isMUL
, the column is the first column of a nonunique index in which multiple occurrences of a given value are permitted within the column.
There is also a final caveat:
If more than one of the Key values applies to a given column of a table, Key displays the one with the highest priority, in the order
PRI
,UNI
,MUL
.
As a general note, the MySQL documentation is quite good. When in doubt, check it out!
1.You can make overload functions.
SomeF(strin s){}
SomeF(string s, string s2){}
SomeF(string s1, string s2, string s3){}
More info: http://csharpindepth.com/Articles/General/Overloading.aspx
2.or you may create one function with params
SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like
More info: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params
3.or you can use simple array
Main(string[] args){}
How to get rid of a header(first row) and an index(first column).
To write to CSV file:
df = pandas.DataFrame(your_array)
df.to_csv('your_array.csv', header=False, index=False)
To read from CSV file:
df = pandas.read_csv('your_array.csv')
a = df.values
If you want to read a CSV file that doesn't contain a header, pass additional parameter header
:
df = pandas.read_csv('your_array.csv', header=None)
They are both going to have the same effect.
However, as pointed out in the comments: $(window).scrollTop()
is supported by more web browsers than $('html').scrollTop()
.
Command line arguments are accessible via String[] args
parameter of main
method.
For first argument you can check args[0]
entire code would look like
public static void main(String[] args) {
if ("a".equals(args[0])) {
// do something
}
}
I know this is a little bit too late but it might just help someone.
In my case I already had a method to make the Object from a json Object and make json from the object. with this you can simply create a new instance of the object and use it to restore. For instance in a function parsing a final object
public void update(final Object object){ _x000D_
final Object original = Object.makeFromJSON(object.toJSON()); _x000D_
// the original is not affected by changes made to object _x000D_
}
_x000D_
This might be overkill - but be careful doing anything which relies on the extension of PHP files being .php
- what if someone comes along later and adds handlers for .php4
or even .html
so they're handled by PHP. You might be better off serving files out of those directories from a different instance of Apache or something, which only serves static content.
In C++ (without error checking):
std::string blob = ...; // assume blob is in the string
std::string query = "INSERT INTO foo (blob_column) VALUES (?);";
sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, query, query.size(), &stmt, nullptr);
sqlite3_bind_blob(stmt, 1, blob.data(), blob.size(),
SQLITE_TRANSIENT);
That can be SQLITE_STATIC
if the query will be executed before blob
gets destructed.
What is it?
WAI-ARIA stands for “Web Accessibility Initiative – Accessible Rich Internet Applications”. It is a set of attributes to help enhance the semantics of a web site or web application to help assistive technologies, such as screen readers for the blind, make sense of certain things that are not native to HTML. The information exposed can range from something as simple as telling a screen reader that activating a link or button just showed or hid more items, to widgets as complex as whole menu systems or hierarchical tree views.
This is achieved by applying roles and state attributes to HTML 4.01 or later markup that has no bearing on layout or browser functionality, but provides additional information for assistive technologies.
One corner stone of WAI-ARIA is the role attribute. It tells the browser to tell the assistive technology that the HTML element used is not actually what the element name suggests, but something else. While it originally is only a div element, this div element may be the container to a list of auto-complete items, in which case a role of “listbox” would be appropriate to use. Likewise, another div that is a child of that container div, and which contains a single option item, should then get a role of “option”. Two divs, but through the roles, totally different meaning. The roles are modeled after commonly used desktop application counterparts.
An exception to this are document landmark roles, which don’t change the actual meaning of the element in question, but provide information about this particular place in a document.
The second corner stone are WAI-ARIA states and properties. They define the state of certain native or WAI-ARIA elements such as if something is collapsed or expanded, a form element is required, something has a popup menu attached to it or the like. These are often dynamic and change their values throughout the lifecycle of a web application, and are usually manipulated via JavaScript.
What is it not?
WAI-ARIA is not intended to influence browser behavior. Unlike a real button element, for example, a div which you pour the role of “button” onto does not give you keyboard focusability, an automatic click handler when Space or Enter are being pressed on it, and other properties that are indiginous to a button. The browser itself does not know that a div with role of “button” is a button, only its accessibility API portion does.
As a consequence, this means that you absolutely have to implement keyboard navigation, focusability and other behavioural patterns known from desktop applications yourself. You can find some Advanced ARIA techniques Here.
When should I not use it?
Yes, that’s correct, this section comes first! Because the first rule of using WAI-ARIA is: Don’t use it unless you absolutely have to! The less WAI-ARIA you have, and the more you can count on using native HTML widgets, the better! There are some more rules to follow, you can check them out here.
Yes, you can use Type.InvokeMember()
:
using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, obj, "Value");
This will throw an exception if obj
doesn't have a property called Name
, or it can't be set.
Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:
using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
prop.SetValue(obj, "Value", null);
}
replace:
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];
with:
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];
if (isset($_POST['newsletter'])) {
$checkBoxValue = "yes";
} else {
$checkBoxValue = "no";
}
then replace this line of code:
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter"
with:
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter";
The getimagesize() should be the most definite way of working out whether the file is an image:
if(@is_array(getimagesize($mediapath))){
$image = true;
} else {
$image = false;
}
because this is a sample getimagesize() output:
Array (
[0] => 800
[1] => 450
[2] => 2
[3] => width="800" height="450"
[bits] => 8
[channels] => 3
[mime] => image/jpeg)
Adding to @Vityata 's answer, below is the function I use to convert a row / column vector in a 1D array:
Function convertVecToArr(ByVal rng As Range) As Variant
'convert two dimension array into a one dimension array
Dim arr() As Variant, slicedArr() As Variant
arr = rng.value 'arr = rng works too (https://bettersolutions.com/excel/cells-ranges/vba-working-with-arrays.htm)
If UBound(arr, 1) > UBound(arr, 2) Then
slicedArr = Application.WorksheetFunction.Transpose(arr)
Else
slicedArr = Application.WorksheetFunction.index(arr, 1, 0) 'If you set row_num or column_num to 0 (zero), Index returns the array of values for the entire column or row, respectively._
'To use values returned as an array, enter the Index function as an array formula in a horizontal range of cells for a row,_
'and in a vertical range of cells for a column.
'https://usefulgyaan.wordpress.com/2013/06/12/vba-trick-of-the-week-slicing-an-array-without-loop-application-index/
End If
convertVecToArr = slicedArr
End Function
generally filter
is slightly faster if using a builtin function.
I would expect the list comprehension to be slightly faster in your case
Following solution worked for me
//Parent class
@OneToMany(mappedBy = 'parent',
cascade= CascadeType.ALL, orphanRemoval = true)
@OrderBy(value="ordinal ASC")
List<Child> children = new ArrayList<>()
//Updated setter of children
public void setChildren(List<Children> children) {
this.children.addAll(children);
for (Children child: children)
child.setParent(this);
}
//Child class
@ManyToOne
@JoinColumn(name="Parent_ID")
private Parent parent;
You can use the Firefox/Chrome developer toolbar:
@precastic's answer above is, imo, the right idea.
Worth noting that in IDEA 2018.2 (and surely other nearby versions) there are default keyboard shortcuts for this: (showing Mac, see Code > Folding > Expand All to Level for your system):
Cmd+Option+Keypad *, 1 - expand all to level 1
Cmd+Option+Keypad *, 2 - expand all to level 2
...
Cmd+Option+Keypad *, 5 - expand all to level 5
Note: these are "second stroke" shortcuts. First press Cmd+Option+*, then release, then hit the number you want.
I got this error for a stupid mistake, the variable name in the @PathVariable wasn't matching the one in the @RequestMapping
For example
@RequestMapping(value = "/whatever/{**contentId**}", method = RequestMethod.POST)
public … method(@PathVariable Integer **contentID**){
}
It may help others
Make sure that your code is returning a value of given return-type irrespective of conditional statements
This code snippet was showing the same error
int search(char arr[], int start, int end, char value)
{
int i;
for(i=start; i<=end; i++)
{
if(arr[i] == value)
return i;
}
}
This is the working code after little changes
int search(char arr[], int start, int end, char value)
{
int i;
int index=-1;
for(i=start; i<=end; i++)
{
if(arr[i] == value)
index=i;
}
return index;
}
MediaPlayer mp=new MediaPlayer();
mp.setDataSource(path);
mp.setScreenOnWhilePlaying(true);
mp.setDisplay(holder);
mp.prepare();
mp.start();
If you're looking for a shortcut in Android studio and can't quite remember the command, simply click Ctrl+Shift+A to launch the command search. From here, you can search for any shortcut you want.
Merry coding!
My advice would be this:
/garages
Returns list of garages (think JSON array here)
/garages/yyy
Returns specific garage
/garage/yyy/cars
Returns list of cars in garage
/garages/cars
Returns list of all cars in all garages (may not be practical of course)
/cars
Returns list of all cars
/cars/xxx
Returns specific car
/cars/colors
Returns lists of all posible colors for cars
/cars/colors/red,blue,green
Returns list of cars of the specific colors (yes commas are allowed :) )
Edit:
/cars/colors/red,blue,green/doors/2
Returns list of all red,blue, and green cars with 2 doors.
/cars/type/hatchback,coupe/colors/red,blue,green/
Same idea as the above but a lil more intuitive.
/cars/colors/red,blue,green/doors/two-door,four-door
All cars that are red, blue, green and have either two or four doors.
Hopefully that gives you the idea. Essentially your Rest API should be easily discoverable and should enable you to browse through your data. Another advantage with using URLs and not query strings is that you are able to take advantage of the native caching mechanisms that exist on the web server for HTTP traffic.
Here's a link to a page describing the evils of query strings in REST: http://web.archive.org/web/20070815111413/http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful
I used Google's cache because the normal page wasn't working for me here's that link as well: http://rest.blueoxen.net/cgi-bin/wiki.pl?QueryStringsConsideredHarmful
It is possible by using the legend tag. Refer to http://www.w3schools.com/html5/tag_legend.asp
I think it is better if you just created it like this:
var arr = [];
arr = {
key1: 'value1',
key2:'value2'
};
For more info, take a look at this:
You could also create an ssh tunnel.
docker-compose.yml
:
---
version: '2'
services:
kibana:
image: "kibana:4.5.1"
links:
- elasticsearch
volumes:
- ./config/kibana:/opt/kibana/config:ro
elasticsearch:
build:
context: .
dockerfile: ./docker/Dockerfile.tunnel
entrypoint: ssh
command: "-N elasticsearch -L 0.0.0.0:9200:localhost:9200"
docker/Dockerfile.tunnel
:
FROM buildpack-deps:jessie
RUN apt-get update && \
DEBIAN_FRONTEND=noninteractive \
apt-get -y install ssh && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*
COPY ./config/ssh/id_rsa /root/.ssh/id_rsa
COPY ./config/ssh/config /root/.ssh/config
COPY ./config/ssh/known_hosts /root/.ssh/known_hosts
RUN chmod 600 /root/.ssh/id_rsa && \
chmod 600 /root/.ssh/config && \
chown $USER:$USER -R /root/.ssh
config/ssh/config
:
# Elasticsearch Server
Host elasticsearch
HostName jump.host.czerasz.com
User czerasz
ForwardAgent yes
IdentityFile ~/.ssh/id_rsa
This way the elasticsearch
has a tunnel to the server with the running service (Elasticsearch, MongoDB, PostgreSQL) and exposes port 9200 with that service.
The simplest and most elegant way is as follows:
all(x==myList[0] for x in myList)
(Yes, this even works with the empty list! This is because this is one of the few cases where python has lazy semantics.)
Regarding performance, this will fail at the earliest possible time, so it is asymptotically optimal.
A cleaner way to do this:
class Book {
public Title: string;
public Price: number;
public Description: string;
constructor(public BookId: number, public Author: string){}
}
Then
var bks: Book[] = [
new Book(1, "vamsee")
];
VS Command Shell Command shell in the Output pane. Far from perfect, but often very, very useful. Faster and easier to get to than a separate cmd and has easier copy/paste support.
If you're not using Homebrew, this is what I just did on MAC OS X Lion (10.7.5):
Get the latest version of the ZSH sourcecode
Untar the download into its own directory then install: ./configure && make && make test && sudo make install
This installs the the zsh binary at /usr/local/bin/zsh
.
You can now use the shell by loading up a new terminal and executing the binary directly, but you'll want to make it your default shell...
To make it your default shell you must first edit /etc/shells
and add the new path. Then you can either run chsh -s /usr/local/bin/zsh
or go to System Preferences > Users & Groups > right click your user > Advanced Options... > and then change "Login shell".
Load up a terminal and check you're now in the correct version with echo $ZSH_VERSION
. (I wasn't at first, and it took me a while to figure out I'd configured iTerm to use a specific shell instead of the system default).
If you use gradle build, use this: BuildConfig.APPLICATION_ID
to get the package name of the application.
This worked for me (I added an "if sheet visible" because in my case I wanted to skip hidden sheets)
Sub Create_new_file()
Application.DisplayAlerts = False
Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Dim pname, parea As String
Set wb = ThisWorkbook
Workbooks.Add
Set wbNew = ActiveWorkbook
For Each sh In wb.Worksheets
pname = sh.Name
If sh.Visible = True Then
sh.Copy After:=wbNew.Sheets(Sheets.Count)
wbNew.Sheets(Sheets.Count).Cells.ClearContents
wbNew.Sheets(Sheets.Count).Cells.ClearFormats
wb.Sheets(sh.Name).Activate
Range(sh.PageSetup.PrintArea).Select
Selection.Copy
wbNew.Sheets(pname).Activate
Range("A1").Select
With Selection
.PasteSpecial (xlValues)
.PasteSpecial (xlFormats)
.PasteSpecial (xlPasteColumnWidths)
End With
ActiveSheet.Name = pname
End If
Next
wbNew.Sheets("Hoja1").Delete
Application.DisplayAlerts = True
End Sub
change
public class LinqHelper
to
public static class LinqHelper
Following points need to be considered when creating an extension method:
non-generic
, static
and non-nested
static
methodthis
keyword. If you are creating the TableModel automatically from a set of values (with "new JTable(Vector, Vector)"), perhaps it is easier to remove editors from columns:
JTable table = new JTable(my_rows, my_header);
for (int c = 0; c < table.getColumnCount(); c++)
{
Class<?> col_class = table.getColumnClass(c);
table.setDefaultEditor(col_class, null); // remove editor
}
Without editors, data will be not editable.
<script type="text/javascript">
function returnwasset(){
alert('return sent');
$.ajax({
type: "POST",
url: "process.php",
data: somedata;
dataType:'text'; //or HTML, JSON, etc.
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
</script>
Use a margin to space around an element.
.box {
margin: top right bottom left;
}
.box {
margin: 10px 5px 10px 5px;
}
This adds space outside of the element. So background colours, borders etc will not be included.
If you want to add spacing within an element use padding instead. It can be called in the same way as above.
A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.
Since Java 1.1, anonymous inner class have provided this facility in a highly verbose manner. They also have a restriction of only being able to use final
(and definitely assigned) local variables. (Note, even non-final
local variables are in scope, but cannot be used.)
Java SE 8 is intended to have a more concise version of this for single-method interfaces*, called "lambdas". Lambdas have much the same restrictions as anonymous inner classes, although some details vary randomly.
Lambdas are being developed under Project Lambda and JSR 335.
*Originally the design was more flexible allowing Single Abstract Methods (SAM) types. Unfortunately the new design is less flexible, but does attempt to justify allowing implementation within interfaces.
I would accept ldav1s' answer if I were you, but I just want to point out that 'else if' can be written in terms of 'else's and 'if's in any language:
if HAVE_CLIENT
libtest_LIBS = $(top_builddir)/libclient.la
else
if HAVE_SERVER
libtest_LIBS = $(top_builddir)/libserver.la
else
libtest_LIBS =
endif
endif
(The indentation is for clarity. Don't indent the lines, they won't work.)
I am using gradle with eclipse and faced the same challenge today and tried a number of ways to resolve but the only way which helped me was to run command gradlew clean
.
P.S. => Don't combine the "build" with the above mentioned command.
Helped me, try your luck.
You could assign the comparison of the property to "1"
obj["isChecked"] = (obj["isChecked"]==="1");
This only evaluates for a String value of "1"
though. Other variables evaulate to false like an actual typeof number
would be false. (i.e. obj["isChecked"]=1
)
If you wanted to be indiscrimate about "1"
or 1
, you could use:
obj["isChecked"] = (obj["isChecked"]=="1");
console.log(obj["isChecked"]==="1"); // true
console.log(obj["isChecked"]===1); // false
console.log(obj["isChecked"]==1); // true
console.log(obj["isChecked"]==="0"); // false
console.log(obj["isChecked"]==="Elephant"); // false
Same concept in PHP
$obj["isChecked"] = ($obj["isChecked"] == "1");
The same operator limitations as stated above for JavaScript apply.
The 'double not' also works. It's confusing when people first read it but it works in both languages for integer/number type values. It however does not work in JavaScript for string type values as they always evaluate to true:
!!"1"; //true
!!"0"; //true
!!1; //true
!!0; //false
!!parseInt("0",10); // false
echo !!"1"; //true
echo !!"0"; //false
echo !!1; //true
echo !!0; //false
You have to Import the Scanner and Timer Package Properly using the java.util classes.
import java.util.Scanner;
import java.util.Timer;
A lot of people, including me, use sqlfiddle.com to test SQL.
''.join(filter(str.isdigit, "+123-456-7890"))
try with this code...
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>/social.properties</value>
</list>
</property>
</bean>
Using "limit" and "top" will not work with all SQL servers (for example with Oracle). You can try a more complex query in pure sql:
select mt1.id, mt1."name", mt1.score, mt1."date" from mytable mt1
where mt1.id=2
and mt1."date"= (select min(mt2."date") from mytable mt2 where mt2.id=2)
PLEASE do not use object as a class name:
public class MyObject //better to choose an appropriate name
{
string id;
DateTime date;
public string ID
{
get { return id; }
set { id = value; }
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
}
You should implement INotifyPropertyChanged
for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.
Your Viewmodel class/ dialogbox class should have a Property
of your MyObject
list. ObservableCollection<MyObject>
is the way to go:
public ObservableCollection<MyObject> MyList
{
get...
set...
}
In your xaml
you should set the Itemssource
to your collection of MyObject
. (the Datacontext
have to be your dialogbox class!)
<DataGrid ItemsSource="{Binding Source=MyList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
</DataGrid.Columns>
</DataGrid>
table { width: 100%; }
Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.
$("#tableid").width($(window).width());
If not, use this snippet
<style>
body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
<tr>
<td>Just a Test
</td>
</tr>
</table>
You will notice that the width is perfectly covering the page.
The main thing is too nullify the margin
and padding
as I have shown at the body, then you are set.
Have a look at this picture: Graphical Projections
The glOrtho
command produces an "Oblique" projection that you see in the bottom row. No matter how far away vertexes are in the z direction, they will not recede into the distance.
I use glOrtho every time I need to do 2D graphics in OpenGL (such as health bars, menus etc) using the following code every time the window is resized:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, windowWidth, windowHeight, 0.0f, 0.0f, 1.0f);
This will remap the OpenGL coordinates into the equivalent pixel values (X going from 0 to windowWidth and Y going from 0 to windowHeight). Note that I've flipped the Y values because OpenGL coordinates start from the bottom left corner of the window. So by flipping, I get a more conventional (0,0) starting at the top left corner of the window rather.
Note that the Z values are clipped from 0 to 1. So be careful when you specify a Z value for your vertex's position, it will be clipped if it falls outside that range. Otherwise if it's inside that range, it will appear to have no effect on the position except for Z tests.
Do not always use Redirect permanent
(or why it may cause issues in future)
If there is a chance that you will add subdomains later, do not use redirect permanent
.
Because if a client has used a subdomain that wasn't registred as VirtualHost
he may also never reach this subdomain even when it is registred later.
redirect permanent
sends an HTTP 301 Moved Permanently
to the client (browser) and a lot of them cache this response for ever (until cache is cleared [manually]). So using that subdomain will always autoredirect to www.*** without requesting the server again.
see How long do browsers cache HTTP 301s?
So just use Redirect
<VirtualHost *:80>
ServerName example.com
Redirect / http://www.example.com/
</VirtualHost>
You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree
option for single commands, or the GIT_WORK_TREE
environment variable. There is also the core.worktree
configuration option but it will not work in a bare repository (check the man page for what it does).
# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status
You can simply use echo -n "|$COMMAND|"
.
FYI - I had this issue as well and it turned out that my html listed the .jpg file with a .JPG in caps, but the file itself was lowercase .jpg. That rendered fine locally and using Codekit, but when it was pushed to the web it wouldn't load. Simply changing the file names to have a lowercase .jpg extension to match the html did the trick.
This worked for me in case you want to change the AUTO_INCREMENT-attribute for a not-empty-table:
1.)Exported the whole table as .sql file
2.)Deleted the table after export
2.)Did needed change in CREATE_TABLE command
3.)Executed the CREATE_TABLE and INSERT_INTO commands from the .sql-file
...et viola
"[a-zA-Z]"
matches only one character. To match multiple characters, use "[a-zA-Z]+"
.
Since a dot is a joker for any character, you have to mask it: "abc\."
To make the dot optional, you need a question mark:
"abc\.?"
If you write the Pattern as literal constant in your code, you have to mask the backslash:
System.out.println ("abc".matches ("abc\\.?"));
System.out.println ("abc.".matches ("abc\\.?"));
System.out.println ("abc..".matches ("abc\\.?"));
Combining both patterns:
System.out.println ("abc.".matches ("[a-zA-Z]+\\.?"));
Instead of a-zA-Z, \w is often more appropriate, since it captures foreign characters like äöüßø and so on:
System.out.println ("abc.".matches ("\\w+\\.?"));
Are you sure you can't alter the HTML in the popup window?
If you can, add a <script>
tag at the end of the popup's HTML, and call window.print()
inside it. Then it won't be called until the HTML has loaded.
Static libraries are archives that contain the object code for the library, when linked into an application that code is compiled into the executable. Shared libraries are different in that they aren't compiled into the executable. Instead the dynamic linker searches some directories looking for the library(s) it needs, then loads that into memory. More then one executable can use the same shared library at the same time, thus reducing memory usage and executable size. However, there are then more files to distribute with the executable. You need to make sure that the library is installed onto the uses system somewhere where the linker can find it, static linking eliminates this problem but results in a larger executable file.
This solution is for those users who use GitHub desktop.
Rename your repository from setting on GitHub.com
Now from your desktop click on sync.
Done.
Single line- There are two ways, you can simply change.
1- Pragmatically (Swift 3)
Just add the following code
yourLabel.numberOfLines = 1;
yourLabel.minimumScaleFactor = 0.7;
yourLabel.adjustsFontSizeToFitWidth = true;
2 - Using UILabel Attributes inspector
i- Select your label- Set number of lines 1.
ii- Autoshrink- Select Minimum Font Scale from drop down
iii- Set Minimum Font Scale value as you wish , I have set 0.7 as in below image. (default is 0.5)
1D array of primitives does copy elements when it is cloned. This tempts us to clone 2D array(Array of Arrays).
Remember that 2D array clone doesn't work due to shallow copy implementation of clone()
.
public static void main(String[] args) {
int row1[] = {0,1,2,3};
int row2[] = row1.clone();
row2[0] = 10;
System.out.println(row1[0] == row2[0]); // prints false
int table1[][]={{0,1,2,3},{11,12,13,14}};
int table2[][] = table1.clone();
table2[0][0] = 100;
System.out.println(table1[0][0] == table2[0][0]); //prints true
}
To get the new Microsoft Edge based on a Mozilla core add:
else if ((verOffset=nAgt.indexOf("Edg"))!=-1) {
browserName = "Microsoft Edge";
fullVersion = nAgt.substring(verOffset+5);
}
before
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
Important step for Event binding on Ajax loading content...
01. First of all unbind or off the event on selector
$(".SELECTOR").off();
02. Add event listener on document level
$(document).on("EVENT", '.SELECTOR', function(event) {
console.log("Selector event occurred");
});
Generally speaking:
all
and any
are functions that take some iterable and return True
, if
all()
, no values in the iterable are falsy;any()
, at least one value is truthy.A value x
is falsy iff bool(x) == False
.
A value x
is truthy iff bool(x) == True
.
Any non-booleans in the iterable will be fine — bool(x)
will coerce any x
according to these rules: 0
, 0.0
, None
, []
, ()
, []
, set()
, and other empty collections will yield False
, anything else True
. The docstring for bool
uses the terms 'true'/'false' for 'truthy'/'falsy', and True
/False
for the concrete boolean values.
In your specific code samples:
You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:
if any(foobars) == big_foobar:
...because any(foobars)
would first be evaluated to either True
or False
, and then that boolean value would be compared to big_foobar
, which generally always gives you False
(unless big_foobar
coincidentally happened to be the same boolean value).
Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.
What you want instead is:
if any(x == big_foobar for x in foobars):
which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars
, it compares the item to big_foobar
and emits the resulting boolean into the resulting sequence:
tmp = (x == big_foobar for x in foobars)
then any
walks over all items in tmp
and returns True
as soon as it finds the first truthy element. It's as if you did the following:
In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']
In [2]: big_foobar = 'big'
In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])
Out[3]: True
Note: As DSM pointed out, any(x == y for x in xs)
is equivalent to y in xs
but the latter is more readable, quicker to write and runs faster.
Some examples:
In [1]: any(x > 5 for x in range(4))
Out[1]: False
In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True
In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True
In [4]: all([True, True, True, False, True])
Out[4]: False
See also: http://docs.python.org/2/library/functions.html#all
The line
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
would do the same as
when(someObject.doSomething(Matchers.any())).thenReturn(true);
So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.
And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.
Check if below are enabled
bz, mbstring, intl, ioncube_loader and Json extension.
Being impatient, I created a new App Pool with the same settings and used that.
In XML, element names are defined by the developer. This often results in a conflict when trying to mix XML documents from different XML applications. A user or an XML application will not know how to handle these differences. Name conflicts in XML can easily be avoided using a name prefix. When using prefixes in XML, a namespace for the prefix must be defined.The namespace can be defined by an xmlns attribute in the start tag of an element.The namespace declaration has the following syntax. xmlns:prefix="URI".
You can combine tuple and XOR swaps: x, y = x ^ x ^ y, x ^ y ^ y
x, y = 10, 20
print('Before swapping: x = %s, y = %s '%(x,y))
x, y = x ^ x ^ y, x ^ y ^ y
print('After swapping: x = %s, y = %s '%(x,y))
or
x, y = 10, 20
print('Before swapping: x = %s, y = %s '%(x,y))
print('After swapping: x = %s, y = %s '%(x ^ x ^ y, x ^ y ^ y))
Using lambda:
x, y = 10, 20
print('Before swapping: x = %s, y = %s' % (x, y))
swapper = lambda x, y : ((x ^ x ^ y), (x ^ y ^ y))
print('After swapping: x = %s, y = %s ' % swapper(x, y))
Output:
Before swapping: x = 10 , y = 20
After swapping: x = 20 , y = 10
if you really want to use CSS, use following property which will make field non-editable.
pointer-events: none;
In order to get access to the post data we have to use body-parser
. Basically what the body-parser
is which allows express to read the body and then parse that into a Json
object that we can understand.
I had this problem. My solution is: change same password of other in windowns. Restart Service (check logon in tab Service SQL).
This isn't the cleanest/quickest/easiest/most elegant solution, but it is a brute force one that I created to get the job done in a similar scenario:
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();
// Create new DataColumns for dtSpecificOrders that are the same as in "dt"
DataColumn dcID = new DataColumn("ID", typeof(int));
DataColumn dcName = new DataColumn("Name", typeof(string));
dtSpecificOrders.Columns.Add(dtID);
dtSpecificOrders.Columns.Add(dcName);
DataRow[] orderRows = dt.Select("CustomerID = 2");
foreach (DataRow dr in orderRows)
{
DataRow myRow = dtSpecificOrders.NewRow(); // <-- create a brand-new row
myRow[dcID] = int.Parse(dr["ID"]);
myRow[dcName] = dr["Name"].ToString();
dtSpecificOrders.Rows.Add(myRow); // <-- this will add the new row
}
The names in the DataColumns must match those in your original table for it to work. I just used "ID" and "Name" as examples.
I had this problem and the solution was namespaces. The included file was included in its own namespace. Obvious thing, easy to overlook.
You can use something like this:
List<Object[]> list = em.createQuery("SELECT p.field1, p.field2 FROM Entity p").getResultList();
then you can iterate over it:
for (Object[] obj : list){
System.out.println(obj[0]);
System.out.println(obj[1]);
}
BUT if you have only one field in query, you get a list of the type not from Object[]
If ds is the DataSet, you can access the CustomerID column of the first row in the first table with something like:
DataRow dr = ds.Tables[0].Rows[0];
Console.WriteLine(dr["CustomerID"]);
It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.
Let's say you have something like this in your code:
$str = "test";
echo($str{0});
since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:
$str = "test";
echo($str[0]);
Fixing the code in the question will look something like this:
public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
$records = $this->listRecords($zoneID, $type, $name);
if (isset($records->result[0]->id)) {
return $records->result[0]->id;
}
return false;
}
ps -elf doesn't seem to show the PID. I recommend using instead:
ps -ld | grep foo
gdb -p PID
Here's my version of @andy-shin sequently with arguments in array instead of index:
function run(funcs, args) {
var i = 0;
var recursive = function() {
funcs[i](function() {
i++;
if (i < funcs.length)
recursive();
}, args[i]);
};
recursive();
}
I do it like this, to launch the SendFreeTextActivity from a (custom) menu fragment that appears in multiple activities:
In the MenuFragment class:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu, container, false);
final Button sendFreeTextButton = (Button) view.findViewById(R.id.sendFreeTextButton);
sendFreeTextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "sendFreeTextButton clicked");
Intent intent = new Intent(getActivity(), SendFreeTextActivity.class);
MenuFragment.this.startActivity(intent);
}
});
...
Well the code you've shown doesn't actually include adding any Integers to the ArrayList
- but if you do know that you've got integers, you can use:
sum = (double) ((Integer) marks.get(i)).intValue();
That will convert it to an int
, which can then be converted to double
. You can't just cast directly between the boxed classes.
Note that if you can possibly use generics for your ArrayList
, your code will be clearer.
This displays files with its permisions
stat -c '%a - %n' directory/*
For the first rule,
Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.
For the second,
Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.
For the third,
Same as the second, except your formula is =".8*" rather than .9.
Found this example... Will test...
import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
public static void main(String [] args)
{
int x=1;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(x));
}
}
Tested this and:
String.format("%05d",number);
Both work, for my purposes I think String.Format is better and more succinct.
CSS and Desktop only solution
@media (min-width: 992px) {
.dropdown:hover>.dropdown-menu {
display: block;
}
}
I like to use the program Artistic Style. According to their website:
Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages.
It runs in Window, Linux and Mac. It will do things like indenting, replacing tabs with spaces or vice-versa, putting spaces around operations however you like (converting if(x<2)
to if ( x<2 )
if that's how you like it), putting braces on the same line as function definitions, or moving them to the line below, etc. All the options are controlled by command line parameters.
In order to use it in vim, just set the formatprg option to it, and then use the gq command. So, for example, I have in my .vimrc:
autocmd BufNewFile,BufRead *.cpp set formatprg=astyle\ -T4pb
so that whenever I open a .cpp file, formatprg is set with the options I like. Then, I can type gg to go to the top of the file, and gqG to format the entire file according to my standards. If I only need to reformat a single function, I can go to the top of the function, then type gq][ and it will reformat just that function.
The options I have for astyle, -T4pb
, are just my preferences. You can look through their docs, and change the options to have it format the code however you like.
Here's a demo. Before astyle:
int main(){if(x<2){x=3;}}
float test()
{
if(x<2)
x=3;
}
After astyle (gggqG):
int main()
{
if (x < 2)
{
x = 3;
}
}
float test()
{
if (x < 2)
x = 3;
}
Hope that helps.
cast it to a char pointer an increment your pointer forward x bytes ahead.
Through the following steps you can do it .
In Eclipse window , Right Click on your Project from Package Explorer. 1. Select Properties, 2. Select Android from Properties, 3. Check "Is Library" check box, 4. If it is checked then Unchecked "Is Library" check box. 5. Click Apply and than OK.
This is the correct answer. It worked!!
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome("E:\\Python\\selenium\\webdriver\\chromedriver.exe")
driver.get("https://www.tatacliq.com/global-desi-navy-embroidered-kurta/p-mp000000000876745")
driver.set_page_load_timeout(45)
driver.maximize_window()
driver.implicitly_wait(2)
driver.get_screenshot_as_file("E:\\Python\\Tatacliq.png")
print ("Executed Successfully")
driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").click()
SpecialPrice = driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").text
print(SpecialPrice)
When specifying your cron values you'll need to make sure that your values fall within the ranges. For instance, some cron's use a 0-7 range for the day of week where both 0 and 7 represent Sunday. We do not(check below).
Seconds: 0-59
Minutes: 0-59
Hours: 0-23
Day of Month: 1-31
Months: 0-11
Day of Week: 0-6
reference: https://github.com/ncb000gt/node-cron
You could use Universal Encoding Detector, but be aware that it will just give you best guess, not the actual encoding, because it's impossible to know encoding of a string "abc" for example. You will need to get encoding information elsewhere, eg HTTP protocol uses Content-Type header for that.
The string representation of a DateTime can be parsed by the Time class.
> Time.parse(DateTime.now.to_s).utc
=> 2015-10-06 14:53:51 UTC
You don't have to convert the object to a MyClass object because it already is. Wnat you really want to do is to cast it, but since the class name is not known at compile time, you can't do that, since you can't declare a variable of that class. My guess is that you want/need something like "duck typing", i.e. you don't know the class name but you know the method name at compile time. Interfaces, as proposed by Gregory, are your best bet to do that.
let url = ("https://firebasestorage.googleapis.com/v0/b/qualityaudit-678a4.appspot.com/o/profile_images%2FBFA28EDD-9E15-4CC3-9AF8-496B91E74A11.png?alt=media&token=b4518b07-2147-48e5-93fb-3de2b768412d")
self.myactivityindecator.startAnimating()
let urlString = url
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url)
{
(data, response, error) in
if error != nil {
print("Failed fetching image:", error!)
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
print("error")
return
}
DispatchQueue.main.async {
let image = UIImage(data: data!)
let myimageview = UIImageView(image: image)
print(myimageview)
self.imgdata.image = myimageview.image
self.myactivityindecator.stopanimating()
}
}.resume()
This means that a TCP RST was received and the connection is now closed. This occurs when a packet is sent from your end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.
This can happen if the other side crashes and then comes back up or if it calls close()
on the socket while there is data from you in transit, and is an indication to you that some of the data that you previously sent may not have been received.
It is up to you whether that is an error; if the information you were sending was only for the benefit of the remote client then it may not matter that any final data may have been lost. However you should close the socket and free up any other resources associated with the connection.
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
You have to initialize the vector of vectors to the appropriate size before accessing any elements. You can do it like this:
// assumes using std::vector for brevity
vector<vector<int>> matrix(RR, vector<int>(CC));
This creates a vector of RR
size CC
vectors, filled with 0
.
Just loop...
foreach(var table in DataSet1.Tables) {
foreach(var col in table.Columns) {
...
}
foreach(var row in table.Rows) {
object[] values = row.ItemArray;
...
}
}
In your 'encrypt' method, you should either get rid of the try/catch and instead add a try/catch around where you call encrypt (inside 'actionPerformed') or return null inside the catch within encrypt (that's the second error.
You may want to distinguish between unset variables and variables that are set and empty:
is_empty() {
local var_name="$1"
local var_value="${!var_name}"
if [[ -v "$var_name" ]]; then
if [[ -n "$var_value" ]]; then
echo "set and non-empty"
else
echo "set and empty"
fi
else
echo "unset"
fi
}
str="foo"
empty=""
is_empty str
is_empty empty
is_empty none
Result:
set and non-empty
set and empty
unset
BTW, I recommend using set -u
which will cause an error when reading unset variables, this can save you from disasters such as
rm -rf $dir
You can read about this and other best practices for a "strict mode" here.
For those searching this error, another thing that can trigger AtributeError: can't set attribute
is if you try to set a decorated @property
that has no setter method. Not the problem in the OP's question, but I'm putting it here to help any searching for the error message directly. (if you don't like it, go edit the question's title :)
class Test:
def __init__(self):
self._attr = "original value"
# This will trigger an error...
self.attr = "new value"
@property
def attr(self):
return self._attr
Test()
I don't think you can, apart from response.setContentType(..)
This is ancient history but I just ran into this issue and the fix for me was recycling the application pool of the website in IIS. Easy fix, for once.
In an HTML Document - VOID ELEMENTS do not need a "closing tag" at all!
In xhtml, everything is Generic, therefore they all need termination e.g. a "closing tag"; Including br, a simple line-break, as <br></br>
or its shorthand <br />
.
However, a Script Element is never a void or a parametric Element, because script tag before anything else, is a Browser Instruction, not a Data Description declaration.
Principally, a Semantic Termination Instruction e.g., a "closing tag" is only needed for processing instructions who's semantics cannot be terminated by a succeeding tag. For instance:
<H1>
semantics cannot be terminated by a following <P>
because it doesn't carry enough of its own semantics to override and therefore terminate the previous H1 instruction set. Although it will be able to break the stream into a new paragraph line, it is not "strong enough" to override the present font size & style line-height pouring down the stream, i.e leaking from H1 (because P doesn't have it).
This is how and why the "/" (termination) signalling has been invented.
A generic no-description termination Tag like < />
, would have sufficed for any single fall off the encountered cascade, e.g.: <H1>Title< />
but that's not always the case, because we also want to be capable of "nesting", multiple intermediary tagging of the Stream: split into torrents before wrapping / falling onto another cascade. As a consequence a generic terminator such as < />
would not be able to determine the target of a property to terminate. For example: <b>
bold <i>
bold-italic < />
italic </>
normal. Would undoubtedly fail to get our intention right and would most probably interpret it as bold bold-itallic bold normal.
This is how the notion of a wrapper ie., container was born. (These notions are so similar that it is impossible to discern and sometimes the same element may have both. <H1>
is both wrapper and container at the same time. Whereas <B>
only a semantic wrapper). We'll need a plain, no semantics container. And of course the invention of a DIV Element came by.
The DIV element is actually a 2BR-Container. Of course the coming of CSS made the whole situation weirder than it would otherwise have been and caused a great confusion with many great consequences - indirectly!
Because with CSS you could easily override the native pre&after BR behavior of a newly invented DIV, it is often referred to, as a "do nothing container". Which is, naturally wrong! DIVs are block elements and will natively break the line of the stream both before and after the end signalling. Soon the WEB started suffering from page DIV-itis. Most of them still are.
The coming of CSS with its capability to fully override and completely redefine the native behavior of any HTML Tag, somehow managed to confuse and blur the whole meaning of HTML existence...
Suddenly all HTML tags appeared as if obsolete, they were defaced, stripped of all their original meaning, identity and purpose. Somehow you'd gain the impression that they're no longer needed. Saying: A single container-wrapper tag would suffice for all the data presentation. Just add the required attributes. Why not have meaningful tags instead; Invent tag names as you go and let the CSS bother with the rest.
This is how xhtml was born and of course the great blunt, paid so dearly by new comers and a distorted vision of what is what, and what's the damn purpose of it all. W3C went from World Wide Web to What Went Wrong, Comrades?!!
The purpose of HTML is to stream meaningful data to the human recipient.
To deliver Information.
The formal part is there to only assist the clarity of information delivery. xhtml doesn't give the slightest consideration to the information. - To it, the information is absolutely irrelevant.
The most important thing in the matter is to know and be able to understand that xhtml is not just a version of some extended HTML, xhtml is a completely different beast; grounds up; and therefore it is wise to keep them separate.
The difference is :
"If you use !=
, it returns sub-second. If you use <>
, it takes 7 seconds to return. Both return the right answer."
Oracle not equals (!=) SQL operator
Regards
You can download ip-tables from MaxMind:
http://www.maxmind.com/app/geolite
Import the CSV to your database (make sure to create an index for ip_long_from + ip_long_to). Then you can simply do:
$iplong = ip2long($_SERVER['REMOTE_ADDR']);
// should use mysqli with prepared statements etc, but just an example
mysql_query("
SELECT country
FROM ip_table
WHERE $iplong BETWEEN ip_long_from AND ip_long_to
LIMIT 1
");
A standard http GET request should do it. Then you can use JSON.parse() to make it into a json object.
function Get(yourUrl){
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET",yourUrl,false);
Httpreq.send(null);
return Httpreq.responseText;
}
then
var json_obj = JSON.parse(Get(yourUrl));
console.log("this is the author name: "+json_obj.author_name);
that's basically it
View Custmv;
private void initViews() {
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Custmv = inflater.inflate(R.layout.id_number_edit_text_custom, this, true);
editText = (EditText) findViewById(R.id.id_number_custom);
loadButton = (ImageButton) findViewById(R.id.load_data_button);
loadButton.setVisibility(RelativeLayout.INVISIBLE);
loadData();
}
private void loadData(){
loadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText firstName = (EditText) Custmv.getParent().findViewById(R.id.display_name);
firstName.setText("Some Text");
}
});
}
try like this.
There's no "step-by-step" here. When initialization is performed with constant expressions, the process is essentially performed at compile time. Of course, if the array is declared as a local object, it is allocated locally and initialized at run-time, but that can be still thought of as a single-step process that cannot be meaningfully subdivided.
Designated initializers allow you to supply an initializer for a specific member of struct object (or a specific element of an array). All other members get zero-initialized. So, if my_data
is declared as
typedef struct my_data {
int a;
const char *name;
double x;
} my_data;
then your
my_data data[]={
{ .name = "Peter" },
{ .name = "James" },
{ .name = "John" },
{ .name = "Mike" }
};
is simply a more compact form of
my_data data[4]={
{ 0, "Peter", 0 },
{ 0, "James", 0 },
{ 0, "John", 0 },
{ 0, "Mike", 0 }
};
I hope you know what the latter does.
/\{([^}]+)\}/
/ - delimiter
\{ - opening literal brace escaped because it is a special character used for quantifiers eg {2,3}
( - start capturing
[^}] - character class consisting of
^ - not
} - a closing brace (no escaping necessary because special characters in a character class are different)
+ - one or more of the character class
) - end capturing
\} - the closing literal brace
/ - delimiter
Until Safari implements Service Worker and follows the direction set by Chrome and Firefox, there is no way to add your app programatically to the home screen, or to have the browser prompt the user
However, there is a small library that prompts the user to do it and even points to the right spot. Works a treat.
This is a python script that I saved as rand.py in my home folder:
#!/bin/python
import sys
import random
if __name__ == '__main__':
with open(sys.argv[1], 'r') as f:
flist = f.readlines()
random.shuffle(flist)
for line in flist:
print line.strip()
On Mac OSX sort -R
and shuf
are not available so you can alias this in your bash_profile as:
alias shuf='python rand.py'
I wanted to use this in an Angular (6) library today and it took me a while to get this to work as expected.
In order for my library to use declarations I had to use the d.ts
extention for the file that declares the new properties of the global object.
So in the end, the file ended up with something like:
/path-to-angular-workspace/angular-workspace/projects/angular-library/src/globals.d.ts
Once created, don't forget to expose it in your public_api.ts
.
That did it for me. Hope this helps.
Your best bet is to look up php_gd2. It's a fairly decent image library that comes with PHP (just disabled in php.ini), and not only can you output your finished images in a couple formats, it's got enough functions that you should be able to do up a good graph fairly easily.
EDIT: it might help if I gave you a couple useful links:
http://www.libgd.org/ - You can get the latest php_gd2
here
http://ca3.php.net/gd - The php_gd
manual.
public static void main(String args[]) {
char Char;
int count;
String a = "Hi my name is Rahul";
a = a.toLowerCase();
for (Char = 'a'; Char <= 'z'; Char++) {
count = 0;
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == Char) {
count++;
}
}
System.out.println("Number of occurences of " + Char + " is " + count);
}
}
Here is an example of what I would do. I hope it's what you're looking for.
char_array = c("foo_bar","bar_foo","apple","beer")
a = data.frame("data"=char_array,"data2"=1:4)
a$data = substr(a$data,1,nchar(a$data)-3)
a should now contain:
data data2
1 foo_ 1
2 bar_ 2
3 ap 3
4 b 4
To use the standard sleep function add the following in your .cpp file:
#include <unistd.h>
As of Qt version 4.8, the following sleep functions are available:
void QThread::msleep(unsigned long msecs)
void QThread::sleep(unsigned long secs)
void QThread::usleep(unsigned long usecs)
To use them, simply add the following in your .cpp file:
#include <QThread>
Reference: QThread (via Qt documentation): http://doc.qt.io/qt-4.8/qthread.html
Otherwise, perform these steps...
Modify the project file as follows:
CONFIG += qtestlib
Note that in newer versions of Qt you will get the following error:
Project WARNING: CONFIG+=qtestlib is deprecated. Use QT+=testlib instead.
... so, instead modify the project file as follows:
QT += testlib
Then, in your .cpp file, be sure to add the following:
#include <QtTest>
And then use one of the sleep functions like so:
usleep(100);
Using Python 3 and Python 2.6+ syntax:
with open(filepath, 'w') as file_handler:
for item in the_list:
file_handler.write("{}\n".format(item))
This is platform-independent. It also terminates the final line with a newline character, which is a UNIX best practice.
Starting with Python 3.6, "{}\n".format(item)
can be replaced with an f-string: f"{item}\n"
.
The best solution for your browser load time would be to use a server side script to join them all together into one big .js file. Make sure to gzip/minify the final version. Single request - nice and compact.
Alternatively, you can use DOM to create a <script>
tag and set the src property on it then append it to the <head>
. If you need to wait for that functionality to load, you can make the rest of your javascript file be called from the load
event on that script tag.
This function is based on the functionality of jQuery $.getScript()
function loadScript(src, f) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = src;
var done = false;
script.onload = script.onreadystatechange = function() {
// attach to both events for cross browser finish detection:
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
if (typeof f == 'function') f();
// cleans up a little memory:
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
// example:
loadScript('/some-other-script.js', function() {
alert('finished loading');
finishSetup();
});
The C++ standard library has almost exactly that function call nth_element
, although it does modify your data. It has expected linear run-time, O(N), and it also does a partial sort.
const int N = ...;
double a[N];
// ...
const int m = ...; // m < N
nth_element (a, a + m, a + N);
// a[m] contains the mth element in a
I had this problem in VS2013 (Update 5) and there can be two reasons for that, both of which you can find by enabling "Detailed" build output under "Tools"->"Projects and Solutions"->"Build and Run".
"Forcing recompile of all source files due to missing PDB "..."
This happens when you disable debug information output in your compiler options (Under Project settings: „C/C++“->“Debug Information Format“ to „None“ and „Linker“->“Generate Debug Info“ to „No“: ). If you have left „C/C++“->“Program Database File Name“ at the default (which is „$(IntDir)vc$(PlatformToolsetVersion).pdb“), VS will not find the file due to a bug (https://connect.microsoft.com/VisualStudio/feedback/details/833494/project-with-debug-information-disabled-always-rebuilds).
To fix it, simply clear the file name to "" (empty field).
"Forcing rebuild of all source files due to a change in the command line since the last build."
This seems to be a known VS bug too (https://connect.microsoft.com/VisualStudio/feedback/details/833943/forcing-rebuild-of-all-source-files-due-to-a-change-in-the-command-line-since-the-last-build) and seems to be fixed in newer versions (but not VS2013). I known of no workaround, but if you do, by all means, post it here.
by_type_year_tag_filtered <- by_type_year_tag %>%
dplyr:: filter(tag_name %in% c("dplyr", "ggplot2"))
And as an addendum to all answers, FYI: override
is not a keyword, but a special kind of identifier! It has meaning only in the context of declaring/defining virtual functions, in other contexts it's just an ordinary identifier. For details read 2.11.2 of The Standard.
#include <iostream>
struct base
{
virtual void foo() = 0;
};
struct derived : base
{
virtual void foo() override
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
int main()
{
base* override = new derived();
override->foo();
return 0;
}
Output:
zaufi@gentop /work/tests $ g++ -std=c++11 -o override-test override-test.cc
zaufi@gentop /work/tests $ ./override-test
virtual void derived::foo()
I had this issue on a Windows machine and installing node.js was the solution that finally worked for me. This came after trying multiple other routes including trying to get 'therubyracer' working. Though the github for node.js suggests that installation on windows is still unstable, the website at http://nodejs.org/ had a Windows installer which worked perfectly.
In typeScript I test with angular, and it's doing OK
deepCopy(obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = this.deepCopy(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = this.deepCopy(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
On android 2.2 you can input multiple language and switch by sliding on the spacebar. Go in the settings under "language and keyboard" and then "Android Keyboard", "Input language".
Hope this helps.
What about this?
var Restaurant = (function() {
var _id = 0;
var privateVars = [];
function Restaurant(name) {
this.id = ++_id;
this.name = name;
privateVars[this.id] = {
cooked: []
};
}
Restaurant.prototype.cook = function (food) {
privateVars[this.id].cooked.push(food);
}
return Restaurant;
})();
Private variable lookup is impossible outside of the scope of the immediate function. There is no duplication of functions, saving memory.
The downside is that the lookup of private variables is clunky privateVars[this.id].cooked
is ridiculous to type. There is also an extra "id" variable.
Here's a simple one that I often use:
# Set up logging to include a file record of the output
# Note: the file is always created, even if there is
# no actual output.
log4j.rootLogger=error, stdout, R
# Log format to standard out
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern= %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n
# File based log output
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=owls_conditions.log
log4j.appender.R.MaxFileSize=10000KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern= %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n
The format of the log is as follows:
ERROR [2009-09-13 09:56:01,760] [main] (RDFDefaultErrorHandler.java:44)
http://www.xfront.com/owl/ontologies/camera/#(line 1 column 1): Content is not allowed in prolog.
Such a format is defined by the string %5p\t[%d] [%t] (%F:%L)\n \t%m%n\n
. You can read the meaning of conversion characters in log4j javadoc for PatternLayout
.
Included comments should help in understanding what it does. Further notes:
owls_conditions.log
: change it according to your needs;Clojure can be used, but it's slow.
See also: Clojure fork for Android, and a tutorial.
You have to allocate the buffer with mallock, and give the read write the pointer to it.
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
ssize_t nrd;
int fd;
int fd1;
char* buffer = malloc(100*sizeof(char));
fd = open("bli.txt", O_RDONLY);
fd1 = open("bla.txt", O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,sizeof(buffer))) {
write(fd1,buffer,nrd);
}
close(fd);
close(fd1);
free(buffer);
return 0;
}
Make sure that the rad file exists and contains something. It's not perfect but it works.
In my case, I was getting this error because I had an input named x
and I was creating (without realizing it) a local variable called x
. I thought I was trying to access an element of the input x
(which was an array), while I was actually trying to access an element of the local variable x
(which was a scalar).
Sometimes, you have methods that operate on its parameters that define a symmetric operation:
a.f(b); <-> b.f(a);
If you know b can never be null, you can just swap it. It is most useful for equals:
Instead of foo.equals("bar");
better do "bar".equals(foo);
.
The problem was that the ID column wasn't getting any value. I saw on @Martin Smith SQL Fiddle that he declared the ID column with DEFAULT newid
and I didn't..
Since HTML does not have an "include" directive, I can think only of three workarounds
A little comment on each of the methods.
Frames can be either standard frames or iFrames. Either way, you will have to specify a fixed height for them, so this might not be the solution you are looking for.
Javascript is a pretty broad subject and there probably exist many ways how one might use it to achieve the desired effect. Off the top of my head however I can think of two ways:
<script type="text/javascript" src="header.js">
which has something like this in it: document.write('My header goes here');
Doing it via CSS would be really an abuse. CSS has the content
property which allows you to insert some HTML content, although it's not really intended to be used like this. Also I'm not sure about browser support for this construct.
The best solution is using DATE() function and extracting yy, mm, and dd from the string with RIGHT(), MID() and LEFT() functions, the final will be some DATE(LEFT(),MID(),RIGHT()), details here
It just needs to be in the classpath (aka make sure it ends up under /WEB-INF/classes in the .war as part of the build).
Move semantics allows for a straightforward way to release memory, by simply applying the assignment (=) operator from an empty rvalue:
std::vector<uint32_t> vec(100, 0);
std::cout << vec.capacity(); // 100
vec = vector<uint32_t>(); // Same as "vector<uint32_t>().swap(vec)";
std::cout << vec.capacity(); // 0
It is as much efficient as the "swap()"-based method described in other answers (indeed, both are conceptually doing the same thing). When it comes to readability, however, the assignment version makes a better job at expressing the programmer's intention while being more concise.
just a simple class that benchmark the codeblock :
using namespace std::chrono;
class benchmark {
public:
time_point<high_resolution_clock> t0, t1;
unsigned int *d;
benchmark(unsigned int *res) : d(res) {
t0 = high_resolution_clock::now();
}
~benchmark() { t1 = high_resolution_clock::now();
milliseconds dur = duration_cast<milliseconds>(t1 - t0);
*d = dur.count();
}
};
// simple usage
// unsigned int t;
// { // put the code in a block
// benchmark bench(&t);
// // ...
// // code to benchmark
// }
// HERE the t contains time in milliseconds
// one way to use it can be :
#define BENCH(TITLE,CODEBLOCK) \
unsigned int __time__##__LINE__ = 0; \
{ benchmark bench(&__time__##__LINE__); \
CODEBLOCK \
} \
printf("%s took %d ms\n",(TITLE),__time__##__LINE__);
int main(void) {
BENCH("TITLE",{
for(int n = 0; n < testcount; n++ )
int a = n % 3;
});
return 0;
}
If you are starting with something that has a .Length
or .Count
(such as ICollection<T>
, IList<T>
, List<T>
, etc) - then this will be the fastest option, since it doesn't need to go through the GetEnumerator()
/MoveNext()
/Dispose()
sequence required by Any()
to check for a non-empty IEnumerable<T>
sequence.
For just IEnumerable<T>
, then Any()
will generally be quicker, as it only has to look at one iteration. However, note that the LINQ-to-Objects implementation of Count()
does check for ICollection<T>
(using .Count
as an optimisation) - so if your underlying data-source is directly a list/collection, there won't be a huge difference. Don't ask me why it doesn't use the non-generic ICollection
...
Of course, if you have used LINQ to filter it etc (Where
etc), you will have an iterator-block based sequence, and so this ICollection<T>
optimisation is useless.
In general with IEnumerable<T>
: stick with Any()
;-p
If you are trying to parse apart a human name in PHP, I recommend Keith Beckman's nameparse.php script.
Copy in case site goes down:
<?
/*
Name: nameparse.php
Version: 0.2a
Date: 030507
First: 030407
License: GNU General Public License v2
Bugs: If one of the words in the middle name is Ben (or St., for that matter),
or any other possible last-name prefix, the name MUST be entered in
last-name-first format. If the last-name parsing routines get ahold
of any prefix, they tie up the rest of the name up to the suffix. i.e.:
William Ben Carey would yield 'Ben Carey' as the last name, while,
Carey, William Ben would yield 'Carey' as last and 'Ben' as middle.
This is a problem inherent in the prefix-parsing routines algorithm,
and probably will not be fixed. It's not my fault that there's some
odd overlap between various languages. Just don't name your kids
'Something Ben Something', and you should be alright.
*/
function norm_str($string) {
return trim(strtolower(
str_replace('.','',$string)));
}
function in_array_norm($needle,$haystack) {
return in_array(norm_str($needle),$haystack);
}
function parse_name($fullname) {
$titles = array('dr','miss','mr','mrs','ms','judge');
$prefices = array('ben','bin','da','dal','de','del','der','de','e',
'la','le','san','st','ste','van','vel','von');
$suffices = array('esq','esquire','jr','sr','2','ii','iii','iv');
$pieces = explode(',',preg_replace('/\s+/',' ',trim($fullname)));
$n_pieces = count($pieces);
switch($n_pieces) {
case 1: // array(title first middles last suffix)
$subp = explode(' ',trim($pieces[0]));
$n_subp = count($subp);
for($i = 0; $i < $n_subp; $i++) {
$curr = trim($subp[$i]);
$next = trim($subp[$i+1]);
if($i == 0 && in_array_norm($curr,$titles)) {
$out['title'] = $curr;
continue;
}
if(!$out['first']) {
$out['first'] = $curr;
continue;
}
if($i == $n_subp-2 && $next && in_array_norm($next,$suffices)) {
if($out['last']) {
$out['last'] .= " $curr";
}
else {
$out['last'] = $curr;
}
$out['suffix'] = $next;
break;
}
if($i == $n_subp-1) {
if($out['last']) {
$out['last'] .= " $curr";
}
else {
$out['last'] = $curr;
}
continue;
}
if(in_array_norm($curr,$prefices)) {
if($out['last']) {
$out['last'] .= " $curr";
}
else {
$out['last'] = $curr;
}
continue;
}
if($next == 'y' || $next == 'Y') {
if($out['last']) {
$out['last'] .= " $curr";
}
else {
$out['last'] = $curr;
}
continue;
}
if($out['last']) {
$out['last'] .= " $curr";
continue;
}
if($out['middle']) {
$out['middle'] .= " $curr";
}
else {
$out['middle'] = $curr;
}
}
break;
case 2:
switch(in_array_norm($pieces[1],$suffices)) {
case TRUE: // array(title first middles last,suffix)
$subp = explode(' ',trim($pieces[0]));
$n_subp = count($subp);
for($i = 0; $i < $n_subp; $i++) {
$curr = trim($subp[$i]);
$next = trim($subp[$i+1]);
if($i == 0 && in_array_norm($curr,$titles)) {
$out['title'] = $curr;
continue;
}
if(!$out['first']) {
$out['first'] = $curr;
continue;
}
if($i == $n_subp-1) {
if($out['last']) {
$out['last'] .= " $curr";
}
else {
$out['last'] = $curr;
}
continue;
}
if(in_array_norm($curr,$prefices)) {
if($out['last']) {
$out['last'] .= " $curr";
}
else {
$out['last'] = $curr;
}
continue;
}
if($next == 'y' || $next == 'Y') {
if($out['last']) {
$out['last'] .= " $curr";
}
else {
$out['last'] = $curr;
}
continue;
}
if($out['last']) {
$out['last'] .= " $curr";
continue;
}
if($out['middle']) {
$out['middle'] .= " $curr";
}
else {
$out['middle'] = $curr;
}
}
$out['suffix'] = trim($pieces[1]);
break;
case FALSE: // array(last,title first middles suffix)
$subp = explode(' ',trim($pieces[1]));
$n_subp = count($subp);
for($i = 0; $i < $n_subp; $i++) {
$curr = trim($subp[$i]);
$next = trim($subp[$i+1]);
if($i == 0 && in_array_norm($curr,$titles)) {
$out['title'] = $curr;
continue;
}
if(!$out['first']) {
$out['first'] = $curr;
continue;
}
if($i == $n_subp-2 && $next &&
in_array_norm($next,$suffices)) {
if($out['middle']) {
$out['middle'] .= " $curr";
}
else {
$out['middle'] = $curr;
}
$out['suffix'] = $next;
break;
}
if($i == $n_subp-1 && in_array_norm($curr,$suffices)) {
$out['suffix'] = $curr;
continue;
}
if($out['middle']) {
$out['middle'] .= " $curr";
}
else {
$out['middle'] = $curr;
}
}
$out['last'] = $pieces[0];
break;
}
unset($pieces);
break;
case 3: // array(last,title first middles,suffix)
$subp = explode(' ',trim($pieces[1]));
$n_subp = count($subp);
for($i = 0; $i < $n_subp; $i++) {
$curr = trim($subp[$i]);
$next = trim($subp[$i+1]);
if($i == 0 && in_array_norm($curr,$titles)) {
$out['title'] = $curr;
continue;
}
if(!$out['first']) {
$out['first'] = $curr;
continue;
}
if($out['middle']) {
$out['middle'] .= " $curr";
}
else {
$out['middle'] = $curr;
}
}
$out['last'] = trim($pieces[0]);
$out['suffix'] = trim($pieces[2]);
break;
default: // unparseable
unset($pieces);
break;
}
return $out;
}
?>
In my case, I was inserting the values in the Child Table in the wrong order
For Table with 2 columns- Column1 and Column2, i got this error when I mistakenly entered:
Insert into Table values('value for column2''value for column1')
Error resolved when I used below format :-
Insert into Table (column1, column2) values('value for column2''value for column1')
In case you want to use it globally on all custom inputs use following jQuery code:
$(document).ready(function () {
$('.custom-file-input').on('change', function (e) {
e.target.nextElementSibling.innerHTML = e.target.files[0].name;
});
});
While using the previously mentioned childForm.ShowDialog(this) will disable your main form, it still doesent look very disabled. However if you call Enabled = false before ShowDialog() and Enable = true after you call ShowDialog() the main form will even look like it is disabled.
var childForm = new Form();
Enabled = false;
childForm .ShowDialog(this);
Enabled = true;
Try this.
Dim Workbk as workbook
Set Workbk = thisworkbook
Now everything you program will apply just for your containing macro workbook.
In ES5 supported (or shimmed) browsers...
var keys = Object.keys(myHash);
var values = keys.map(function(v) { return myHash[v]; });
Shims from MDN...
Yes, you can, but your parse will probably fail (there is no standard).
To parse it you should remove those comments, or by hand, or using a regular expression:
It replaces any comments, like:
/****
* Hey
*/
/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/
It replaces any comments, like:
// Hey
/\/\/.*/
In JavaScript, you could do something like this:
jsonString = jsonString.replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/, "").replace(/\/\/.*/,"")
var object = JSON.parse(jsonString);
You can use Calendar.
Calendar rightNow = Calendar.getInstance();
Date4j alternative to Date, Calendar, and related Java classes
I was having the same problem. Turned out I was missing the ./Views/Web.config
file, because I created the project from an empty ASP.NET application instead of using an ASP.NET MVC template.
For ASP.NET MVC 5, a vanilla ./Views/Web.config
file contains the following:
<?xml version="1.0"?>
<!-- https://stackoverflow.com/a/19899269/178082 -->
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.web>
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
</httpHandlers>
<!--
Enabling request validation in view pages would cause validation to occur
after the input has already been processed by the controller. By default
MVC performs request validation before a controller processes the input.
To change this behavior apply the ValidateInputAttribute to a
controller or action.
-->
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
Adding a ./Views/Web.config
file containing this content fixed this problem for me.
size_t
is the unsigned integer type of the result of the sizeof operator (ISO C99 Section 7.17.)
The sizeof
operator yields the size (in bytes) of its operand, which may be an
expression or the parenthesized name of a type. The size is determined from the type of
the operand. The result is an integer. The value of the result is implementation-de?ned, and
its type (an unsigned integer type) is size_t
(ISO C99 Section 6.5.3.4.)
Just add @Transactional
annotation on top of your test:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"testContext.xml"})
@Transactional
public class StudentSystemTest {
By default Spring will start a new transaction surrounding your test method and @Before
/@After
callbacks, rolling back at the end. It works by default, it's enough to have some transaction manager in the context.
From: 10.3.5.4 Transaction management (bold mine):
In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener. Note that
TransactionalTestExecutionListener
is configured by default, even if you do not explicitly declare@TestExecutionListeners
on your test class. To enable support for transactions, however, you must provide aPlatformTransactionManager
bean in the application context loaded by@ContextConfiguration
semantics. In addition, you must declare@Transactional
either at the class or method level for your tests.
Another option is to rename using a regular expression:
import pandas as pd
import re
df = pd.DataFrame({'$a':[1,2], '$b':[3,4], '$c':[5,6]})
df = df.rename(columns=lambda x: re.sub('\$','',x))
>>> df
a b c
0 1 3 5
1 2 4 6
Reassigning the path Xcode is configured with worked for me.
sudo xcode-select -switch /Applications/Xcode.app
You'll then likely be prompted (after trying a command) to agree to the license agreement.
Recursively add subfolders,
for i in `find . -name "*.java" -type f`; do
echo "$i"
done
sed -ie 's/old_link/new_link/g' *
Works on both BSD & Linux with gnu sed
Performance is almost always about good design and optimized database interactions. Ruby does what most web sites need quite fast, especially more recent versions; and the speed of development and ease of maintenance provides a large payoff in costs and in keeping customers happy. I find JAVA to have slow execution performance for some tasks, and given the difficulty of developing in JAVA, many developers create slow applications regardless of the theoretical speed capability as demonstrated in benchmarks (benchmarks are generally contrived to show a specific and narrow capability). When I need intensive processing that isn't well suited to my database's capabilities, I choose C or Objective-C or some other truly high performance compiled language for those tasks depending on the platform. If I need to create a databased web application, I use RoR or sometimes C# ASP.NET depending on other requirements; because all platforms have strengths and weaknesses. Execution speed of the things your application does is important, but after all, if execution performance of one narrow aspect of a language is all that counts; then I might still be using Assembler language for everything.
I've encountered this kind of problem before. I was using the Windows x64 operating system, so I was getting an error in openssl. Later I realized that the path to the OpenSSL installation file was "C: \ OpenSSL win32". Finally, I deleted the OpenSSL program and installed it to "C: \ Program Files (x86)" and used it smoothly.
To clone your class object you can use the Object.MemberwiseClone method,
just add this function to your class :
public class yourClass
{
// ...
// ...
public yourClass DeepCopy()
{
yourClass othercopy = (yourClass)this.MemberwiseClone();
return othercopy;
}
}
then to perform a deep independant copy, just call the DeepCopy method :
yourClass newLine = oldLine.DeepCopy();
NSDictionary *dict = [NSDictionary dictionaryWithObject: @"String" forKey: @"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];
[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: @"Another String" forKey: @"another test"];
NSLog(@"Dictionary: %@, Mutable Dictionary: %@", dict, anotherDict);
// now we can save these to a file
NSString *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];
//and restore them
NSMutableDictionary *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];
REVISED - please see Andrew_1510's answer below, as IPython has been updated.
...
It was a bit hard figure out how to get there from a dusty bug report, but:
It ships with IPython now!
import ipy_autoreload
%autoreload 2
%aimport your_mod
# %autoreload? for help
... then every time you call your_mod.dwim()
, it'll pick up the latest version.
Pure Bash, without an extra process:
for (( COUNTER=0; COUNTER<=10; COUNTER+=2 )); do
echo $COUNTER
done
I'm going to expand on user5609829's answer a little bit as I believe the other solutions here are too complicated/too much work. Applying a margin-right: -4px
to the inline block elements will remove the spacing and is supported by all browsers. See the updated fiddle here. For those concerned with using negative margins, try giving this a read.
The same thing happened to me recently, you just need to download the "punkt" package and it should work.
When you execute "list" (l) after having "downloaded all the available things", is everything marked like the following line?:
[*] punkt............... Punkt Tokenizer Models
If you see this line with the star, it means you have it, and nltk should be able to load it.
Use jackson-bom which will have all the three jackson versions.i.e.jackson-annotations, jackson-core and jackson-databind. This will resolve the dependencies related to those versions
I was getting ó in $mail->Subject /w PHPMailer.
So for me the complete solution is:
// Your Subject with tildes. Example.
$someSubjectWithTildes = 'Subscripción España';
$mailer->CharSet = 'UTF-8';
$mailer->Encoding = 'quoted-printable';
$mailer->Subject = html_entity_decode($someSubjectWithTildes);
Hope it helps.
No, Bootstrap does not introduce special considerations for disabling a drop-down.
<select id="xxx" name="xxx" class="input-medium" disabled>
or
<select id="xxx" name="xxx" class="input-medium" disabled="disabled">
will work. I prefer to give attributes values (as in the second form; in XHTML, attributes must have a value), but the HTML spec says:
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
The key differences between read-only and disabled:*
The Disabled attribute
The Read Only Attribute
<SELECT>
, <OPTION>
, and <BUTTON>
elements do not have readonly attributes (although thy both have disabled attributes)*-blatant plagiarism from http://kreotekdev.wordpress.com/2007/11/08/disabled-vs-readonly-form-fields/
- Can someone give a simple definition of what
Record
is?
A Record<K, T>
is an object type whose property keys are K
and whose property values are T
. That is, keyof Record<K, T>
is equivalent to K
, and Record<K, T>[K]
is (basically) equivalent to T
.
- Is
Record<K,T>
merely a way of saying "all properties on this object will have typeT
"? Probably not all objects, sinceK
has some purpose...
As you note, K
has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>
, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }
.
- Does the
K
generic forbid additional keys on the object that are notK
, or does it allow them and just indicate that their properties are not transformed toT
?
It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:
declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'
and it would treat them as excess properties which are sometimes rejected:
declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties
and sometimes accepted:
const y = {a: "hey", b: "you"};
acceptR(y); // okay
With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
Yes!
Hope that helps. Good luck!
If you'd like a hardware solution, Netgear has a series of cheap ($50 or so) switches that do bandwidth limiting. Netgear Prosafe GS105E and similar switches are worth investigating.
@SpringBootApplication
annotation missing in your spring boot starter class.
web application type
in properties file:In application.properties
:
spring.main.web-application-type=none
If you use application.yml
then add:
spring:
main:
web-application-type: none
*SpringBootServletInitializer*
in main class.@SpringBootApplication
public class YourAppliationName extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(YourAppliationName.class, args);
}
}
If you use spring-boot-starter-webflux
then also add spring-boot-starter-web
as dependency.
var ids = [];
$(document).ready(function($) {
$(".color_cell").bind('click', function() {
alert('Test');
ids.push(this.id);
});
});
The query below will result in dd-mmm-yy format.
select
cast(DAY(getdate()) as varchar)+'-'+left(DATEname(m,getdate()),3)+'-'+
Right(Year(getdate()),2)