This happened to me when I registered a new domain name, e.g., "new" for example.com (new.example.com). The name could not be resolved temporarily in my location for a couple of hours, while it could be resolved abroad. So I used a proxy to test the website where I saw net::ERR_HTTP2_PROTOCOL_ERROR
in chrome console for some AJAX posts. Hours later, when the name could be resloved locally, those error just dissappeared.
I think the reason for that error is those AJAX requests were not redirected by my proxy, it just visit a website which had not been resolved by my local DNS resolver.
All of the files in %USERPROFILE%\AppData\Local\Microsoft\WindowsApps
are placeholders that point to files that are actually located somewhere in C:\Program Files\WindowsApps
, which happens to be denied permissions completely.
It appears I was on the right track with my statement made in my duplicate of this problem:
"Seems like they didn't really think about the distribution method screwing with permissions!"
Source: Cannot install pylint in Git Bash on Windows (Windows Store)
Permissions are screwed up royally because of the WindowsApps distribution method:
Interestingly it says that the "Users" group can read and execute files, as well as my specific user, but the Administrators group can only List folder contents for some hilariously unfathomable reason. And when trying to access the folder in File Explorer, it refuses to even show the folder contents, so there's something fishy about that as well.
Interestingly, even though executing python
in CMD works just fine, the "WindowsApps" folder does not show up when listing the files in the directory it resides in, and attempting to navigate into the folder generates a "Permission denied" error:
Attempting to change the permissions requires changing the owner first, so I changed the owner to the Administrators group. After that, I attempted to change the permissions for the Administrators group to include Full control, but it was unable to change this, because "access was denied" (duh, Micro$ucks, that's what we're trying to change!).
This permission error happened for so many files that I used Alt+C to quickly click "Continue" on repeat messages, but this still took too long, so I canceled the process, resulting in this warning message popping up:
And now I am unable to set the TrustedInstaller user back as the owner of the WindowsApps folder, because it doesn't show up in the list of Users/Groups/Built-in security principles/Other objects. *
*Actually, according to this tutorial, you can swap the owner back to TrustedInstaller by typing NT Service\TrustedInstaller
into the object name text box.
There is no solution. Basically, we are completely screwed. Classy move, Microsoft.
this work for me
compile 'com.android.support:appcompat-v7:26.0.0'
change 26.0.0 to 26.0.1
compile 'com.android.support:appcompat-v7:26.0.1'
After upgrading some dependency I found solutions. We should use latest play service version. In build.gradle[app] dependency.
compile 'com.android.support:multidex:1.0.2'
compile 'com.google.android.gms:play-services:11.8.0'
compile 'com.google.firebase:firebase-core:11.8.0'
In build.gradle[project], we should use latest Google plug-in.
classpath 'com.google.gms:google-services:3.1.1'
I am also sharing below code for better understanding.
android {
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "com.***.user"
minSdkVersion 17
targetSdkVersion 26
versionCode 26
versionName "1.0.20"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
vectorDrawables.useSupportLibrary = true
aaptOptions {
cruncherEnabled = false
}
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
You can use the built-in forEach
function for arrays.
Like this:
//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
element.product_desc = element.product_desc.substring(0,10);
});
Your version wasn't wrong though. It should look more like this:
for(let i=0; i<data.products.length; i++){
console.log(data.products[i].product_desc); //use i instead of 0
}
If you want to reload the page , you can easily go to your component then do :
location.reload();
I did this:
click SDk Manager:
Change in updates to Canary Channel, check and update it...
After go in build.gradle and change the compile version to 26.0.0-beta2:
After go in gradle/build.gradle and change dependencies classpath 'com.android.tools.build:gradle:3.0.0-alpha7':
After sync the project... It works to me! I hope I've helped... tks!
If you are using AS 3.1 the new build graphical console isn't very helpful for finding out the source of the problem.
you need to click on toggle view and see the logs in text format to see the error and if needed to Run with --stacktrace
Make sure you have the following condition:
[key]
if your primary key name is not Id
or ID
. public
keyword. Example:
public class MyEntity {
[key]
public Guid Id {get; set;}
}
If your object could contain any key/value pairs, you could declare an interface called keyable
like :
interface keyable {
[key: string]: any
}
then use it as follows :
let countryProviders: keyable[];
or
let countryProviders: Array<keyable>;
It happen the same thing to me. See on Gradle -> Build Gradle -> and make sure that the compatibility matches in both compile "app compat" and "support design" lines, they should have the same version.
Then to be super sure, that it will launch with no problem, go to File -> Project Structure ->app and check on tab propertie the build Tools version, it should be the same as your support compile line, just in case i put the target SDK version as 25 as well on the tab Flavors.
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-
core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
*compile 'com.android.support:appcompat-v7:25.3.1'*
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
*compile 'com.android.support:design:25.3.1'*
}
Thats what I did and worked. Good luck!
function enumKeys(_enum) {
const entries = Object.entries(_enum).filter(e => !isNaN(Number(e[0])));
if (!entries.length) {
// enum has string values so we can use Object.keys
return Object.keys(_enum);
}
return entries.map(e => e[1]);
}
Update Android Studio and Gradle. Changing the respective updated gradle version in build.gradle file worked for me.
I have faced this problem with Maven build earlier. It was occurring because I was working in a restricted office network. You need to import required certificate in your keystore.
Follow Steps in the answer of below question "unable to find valid certification path to requested target", but browser says it's OK
(use double quotes for fienames/pathnames)
Note: I am not able to find now exact source from where I solved problem, if I get it, I will update it
Use support-v13 instead of support-v4
compile 'com.android.support:support-v13:25.2.0'
The target
you tried to add in InputProps
is not the same target
you wanted which is in React.FormEvent
So, the solution I could come up with was, extending the event related types to add your target type, as:
interface MyEventTarget extends EventTarget {
value: string
}
interface MyFormEvent<T> extends React.FormEvent<T> {
target: MyEventTarget
}
interface InputProps extends React.HTMLProps<Input> {
onChange?: React.EventHandler<MyFormEvent<Input>>;
}
Once you have those classes, you can use your input component as
<Input onChange={e => alert(e.target.value)} />
without compile errors. In fact, you can also use the first two interfaces above for your other components.
I too faced the same issue and finally solved it by disabling Instant Run
in an android studio.
Settings ? Build, Execution, Deployment ? Instant Run and uncheck Enable Instant Run
Update:
There is no Instant Run option available in latest Android Studio 3.5+. It should be applicable only for older versions.
You are mixing the deprecated mysql extension with mysqli.
Try something like:
$sql = mysqli_query($success, "SELECT * FROM login WHERE username = '".$_POST['username']."' and password = '".md5($_POST['password'])."'");
$row = mysqli_num_rows($sql);
Django 1.10 no longer allows you to specify views as a string (e.g. 'myapp.views.home'
) in your URL patterns.
The solution is to update your urls.py
to include the view callable. This means that you have to import the view in your urls.py
. If your URL patterns don't have names, then now is a good time to add one, because reversing with the dotted python path no longer works.
from django.conf.urls import include, url
from django.contrib.auth.views import login
from myapp.views import home, contact
urlpatterns = [
url(r'^$', home, name='home'),
url(r'^contact/$', contact, name='contact'),
url(r'^login/$', login, name='login'),
]
If there are many views, then importing them individually can be inconvenient. An alternative is to import the views module from your app.
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from myapp import views as myapp_views
urlpatterns = [
url(r'^$', myapp_views.home, name='home'),
url(r'^contact/$', myapp_views.contact, name='contact'),
url(r'^login/$', auth_views.login, name='login'),
]
Note that we have used as myapp_views
and as auth_views
, which allows us to import the views.py
from multiple apps without them clashing.
See the Django URL dispatcher docs for more information about urlpatterns
.
For other beginners like me, who didn't find any suitable solution for this error, check the node version installed (x32, x64, x86). I have a 64-bit CPU and I've installed x86 node version, which caused the CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
error.
Just a simple solution is here...it worked for me:
1.
Add the applicationId to the application's build.gradle:
android {
...
defaultConfig {
applicationId "com.example.my.app"
...
}
}
And than Clean Project -> Build or Rebuild Project
2. If your minSdkVersion <= 20 (https://developer.android.com/studio/build/multidex)
Use Multidex correctly.
application's build.gradle
android {
...
defaultConfig {
....
multiDexEnabled true
}
...
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
...
}
manifest.xml
<application
...
android:name="android.support.multidex.MultiDexApplication" >
...
3.
If you use a custom Application class
public class MyApplication extends MultiDexApplication {
@Override
protected void attachBaseContext(Context context) {
super.attachBaseContext(context);
MultiDex.install(this);
}
}
manifest.xml
<application
...
android:name="com.example.my.app.MyApplication" >
...
This error appear because the compiler could not found "my-upload-key.keystore" file in your project
After you have generated the file you need to paste it into project's andorid/app folder
this worked for me!
For Android Studio 3.2.1 Update your
Gradle Version 4.6
Android plugin version 3.2.1
gradle-wrapper.properties
Change this line:
distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
with
distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip
build.gradle
(Project: your_app_name)Change this line
classpath 'com.android.tools.build:gradle:XXX'
to this
classpath 'com.android.tools.build:gradle:2.0.0-alpha3'
or
classpath 'com.android.tools.build:gradle:1.5.0'
Sync Now
File -> Invalidate Caches/Restart...
Invalidate and Restart
Android Studio would restart. After this, it should work normally
Hope it help
"client": [
{
"client_info": {
"mobilesdk_app_id": "9:99999999:android:9ccdbb6c1ae659b8",
"android_client_info": {
"package_name": "[packagename]"
}
}
package_name
must match what's in your manifest file. you can find the google-services.json
file if you look in the example photo below.
I had similar issue with below error:
Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'.
It started when I added below dependency in Gradle:
implementation 'com.google.android.gms:play-services-tagmanager:11.0.4'
I fixed it by upgrading the dependency version as below:
implementation 'com.google.android.gms:play-services-tagmanager:17.0.0'
In My case, I First Clean
the project then i press Make Project
button as below image, then it start working. Rebuild
doesn't work for me.
And I also updating Google Repository is must.
according to @jreback here https://github.com/conda/conda/issues/1166
conda config --set ssl_verify false
will turn off this feature, e.g. here
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
I tried to install only LocalDB, which was missed in my VS 2015 installation. Followed below URL & selectively download the LocalDB (2012) installer which is only 33mb in size :)
https://www.microsoft.com/en-us/download/details.aspx?id=29062
If you are looking for the SQL Server Data Tool for Visual Studio 2015 Integration, then Please download that from :
The results might seem similar, but that is just because of the Taylor expansion for the logarithm. Since log(1 + x) ~ x, the results can be similar.
However,
I am using the following code to get logarithmic returns, but it gives the exact same values as the pct.change() function.
is not quite correct.
import pandas as pd
df = pd.DataFrame({'p': range(10)})
df['pct_change'] = df.pct_change()
df['log_stuff'] = \
np.log(df['p'].astype('float64')/df['p'].astype('float64').shift(1))
df[['pct_change', 'log_stuff']].plot();
The SIMPLEST answer is to put "data" into a pair of square brackets (i.e. [data]):
$.getJSON("json/products.json").done(function (data) {
var allProducts = [data].map(function (item) {
return new getData(item);
});
});
Here, [data] is an array, and the ".map" method can be used on it. It works for me!
using (var client = new HttpClient(handler))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, apiEndPoint)).ConfigureAwait(false);
await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
This worked for me
Go to Jenkins -> Manage Jenkins -> Configure System -> Global properties Check the box 'Environment variables' and add the JAVA_HOME path = "C:\Program Files\Java\jdk-10.0.1"
*Don't write bin at the end
When I got this error, it was because the protocols (TLS versions) and/or cipher suites supported by the server were not enabled on (and possibly not even supported by) the device. For API 16-19, TLSv1.1 and TLSv1.2 are supported but not enabled by default. Once I enabled them for these versions, I still got the error because these versions don't support any of the ciphers on our instance of AWS CloudFront.
Since it's not possible to add ciphers to Android, we had to switch our CloudFront version from TLSv1.2_2018 to TLSv1.1_2016 (which still supports TLSv1.2; it just doesn't require it), which has four of the ciphers supported by the earlier Android versions, two of which are still considered strong.
At that point, the error disappeared and the calls went through (with TLSv1.2) because there was at least one protocol and at least one cipher that the device and server shared.
Refer to the tables on this page to see which protocols and ciphers are supported by and enabled on which versions of Android.
Now was Android really trying to use SSLv3 as implied by the "sslv3 alert handshake failure" part of the error message? I doubt it; I suspect this is an old cobweb in the SSL library that hasn't been cleaned out but I can't say for sure.
In order to enable TLSv1.2 (and TLSv1.1), I was able to use a much simpler SSLSocketFactory
than the ones seen elsewhere (like NoSSLv3SocketFactory
). It simply makes sure that the enabled protocols include all the supported protocols and that the enabled ciphers include all the supported ciphers (the latter wasn't necessary for me but it could be for others) - see configure()
at the bottom. If you'd rather enable only the latest protocols, you can replace socket.supportedProtocols
with something like arrayOf("TLSv1.1", "TLSv1.2")
(likewise for the ciphers):
class TLSSocketFactory : SSLSocketFactory() {
private val socketFactory: SSLSocketFactory
init {
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(null, null, null)
socketFactory = sslContext.socketFactory
}
override fun getDefaultCipherSuites(): Array<String> {
return socketFactory.defaultCipherSuites
}
override fun getSupportedCipherSuites(): Array<String> {
return socketFactory.supportedCipherSuites
}
override fun createSocket(s: Socket, host: String, port: Int, autoClose: Boolean): Socket {
return configure(socketFactory.createSocket(s, host, port, autoClose) as SSLSocket)
}
override fun createSocket(host: String, port: Int): Socket {
return configure(socketFactory.createSocket(host, port) as SSLSocket)
}
override fun createSocket(host: InetAddress, port: Int): Socket {
return configure(socketFactory.createSocket(host, port) as SSLSocket)
}
override fun createSocket(host: String, port: Int, localHost: InetAddress, localPort: Int): Socket {
return configure(socketFactory.createSocket(host, port, localHost, localPort) as SSLSocket)
}
override fun createSocket(address: InetAddress, port: Int, localAddress: InetAddress, localPort: Int): Socket {
return configure(socketFactory.createSocket(address, port, localAddress, localPort) as SSLSocket)
}
private fun configure(socket: SSLSocket): SSLSocket {
socket.enabledProtocols = socket.supportedProtocols
socket.enabledCipherSuites = socket.supportedCipherSuites
return socket
}
}
The problem was actually in the version Android Studio 1.3
updated from the canary channel. I updated my studio
to 1.3 and got the same error but reverting back to studio 1.2.1
made my project run fine.
the output is from NonFinalPluginExpiry.java
example 2.4.0-alpha7
either need to:
make a automation script to generate env var and set it daily
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(String.format(
"%1$s:%2$s:%3$s",
now.getYear(),
now.getMonthValue() -1,
now.getDayOfMonth())
.getBytes("utf8"));
String overrideValue = new BigInteger(1, crypt.digest()).toString(16);
EXAMPLE APP IN JAVA (sources + JAR):
https://github.com/c3ph3us/ado
https://github.com/c3ph3us/ado/releases
example bash function to export env and start idea / or studio:
// eval export & start idea :)
function sti() {
export `java -jar AndroidDailyOverride.jar p`
idea.sh
}
I have some additions to above mentioned answers Its infact a hack mentioned by Jesse Wilson from okhttp, square here. According to this hack, i had to rename my SSLSocketFactory variable to
private SSLSocketFactory delegate;
This is my TLSSocketFactory class
public class TLSSocketFactory extends SSLSocketFactory {
private SSLSocketFactory delegate;
public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
delegate = context.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return delegate.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return delegate.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(delegate.createSocket());
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(delegate.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(delegate.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(delegate.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(delegate.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
}
return socket;
}
}
and this is how i used it with okhttp and retrofit
OkHttpClient client=new OkHttpClient();
try {
client = new OkHttpClient.Builder()
.sslSocketFactory(new TLSSocketFactory())
.build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
I got this same error when I was trying to import an Eclipse NDK project into Android Studio. It turns out, for NDK support in Android Studio, you need to use a new gradle and android plugin (and gradle version 2.5+ for that matter). This plugin, requires changes in the module's build.gradle file. Specifically the "android{...}" object should be inside "model{...}" object like this:
apply plugin: 'com.android.model.application'
model {
android {
....
}
}
So if you have updated your gradle configuration to use the new gradle plugin, and the new android plugin, but didn't change the module's build.gradle syntax, you could get "Gradle DSL method not found: 'android()'" error.
I prepared a patch file here that has some further explanations in the comments: https://gist.github.com/shumoapp/91d815de6e01f5921d1f These are the changes I had to do after importing the native-audio ndk project into Android Studio.
I had same issue. I have tried many things but nothing worked Until I try following:
gradle-[version]-all
within C:\Users\<username>\.gradle\wrapper\dists\
. If you encounter a "File in use" error (or similar), terminate any running Java executables..gradle
directory.I came across the same issue. I tried adding the server in "Server Runtime" but unfortunately that didn't work for me.
What worked for me is, I added javax.servlet-api-3.0.1.jar
file in build path. On the other hand If It's a Maven project add dependency for this jar file. This would definitely work.
The problem for me was that I read the response twice as follows:
System.out.println(response.body().string());
getSucherResponse = objectMapper.readValue(response.body().string(), GetSucherResponse.class);
However, the response can only be read once as it is a stream.
I had the same issue and it was caused because cyberoam was blocking my following URL
Caused by: org.gradle.api.resources.ResourceException: Unable to load Maven meta-data from https://maven.fabric.io/public/io/fabric/tools/gradle/maven-metadata.xml.
If adding google()
into your build.gradle
doesn't work try adding it at first place in your repositories section of node_modules/YOUR_PACKAGE/android/build.gradle
file.
not Error:
JSONObject json1 = getJsonX();
Error:
JSONObject json2 = null;
if(x == y)
json2 = getJSONX();
Error: Local variable statement defined in an enclosing scope must be final or effectively final.
But you can write:
JSONObject json2 = (x == y) ? json2 = getJSONX() : null;
I had this issue when animating some views and the app would go into background mode and come back. I handled it by setting a flag isActive. I set it to NO in
- (void)applicationWillResignActive:(UIApplication *)application
and YES in
- (void)applicationDidBecomeActive:(UIApplication *)application
and animate or not animate my views accordingly. Took care of the issue.
Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16
iOS8 requires these images
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)Your server tells you exactly what you need : [Hint: SSLProxyEngine]
You need to add that directive to your VirtualHost
before the Proxy
directives :
SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/
This issue happened when I accidently renamed the line
apply plugin: 'com.android.application'
on file app/build.gradle
to some other name. So, I fixed it by changing it to what it was.
Tomcat can work in 2 modes:
Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol
parameter in the server.xml
file.
HTTP/1.1
or org.apache.coyote.http11.Http11Protocol
org.apache.coyote.http11.Http11NioProtocol
If you're using BIO then I believe they should be more or less the same.
If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.
In iOS9 UIPopoverController is depreciated. So can use the below code for Objective-C version above iOS9.x,
- (IBAction)onclickPopover:(id)sender {
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
UIViewController *viewController = [sb instantiateViewControllerWithIdentifier:@"popover"];
viewController.modalPresentationStyle = UIModalPresentationPopover;
viewController.popoverPresentationController.sourceView = self.popOverBtn;
viewController.popoverPresentationController.sourceRect = self.popOverBtn.bounds;
viewController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
[self presentViewController:viewController animated:YES completion:nil]; }
The only problem I can see in your code is that you are using CurrentContext
instead of OverCurrentContext
.
So, replace this:
self.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
self.navigationController.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
for this:
self.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
self.navigationController.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
The reason rd /s
refuses to delete certain files is most likely due to READONLY file attributes on files in the directory.
The proper way to fix this, is to make sure you reset the attributes on all files first:
attrib -r %directory% /s /d
rd /s %directory%
There could be others such as hidden or system files, so if you want to play it safe:
attrib -h -r -s %directory% /s /d
rd /s %directory%
@Override
public void onPause() {
super.onPause();
if(pDialog != null)
pDialog .dismiss();
pDialog = null;
}
refer this.
If you want to find how many processors (or CPUs) a machine has the same way %NUMBER_OF_PROCESSORS%
shows you the number of cores, save the following script in a batch file, for example, GetNumberOfCores.cmd
:
@echo off
for /f "tokens=*" %%f in ('wmic cpu get NumberOfCores /value ^| find "="') do set %%f
And then execute like this:
GetNumberOfCores.cmd
echo %NumberOfCores%
The script will set a environment variable named %NumberOfCores%
and it will contain the number of processors.
I also faced the same problem and the problem was that the libraries were missing in some of the following files.
settings.gradle, app/build.gradle, package.json, MainApplication.java
Suppose the library is react-native-vector-icons then it should be mentioned in following files;
compile project(':react-native-vector-icons')
include ':react-native-vector-icons' project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
Import the dependency: import com.oblador.vectoricons.VectorIconsPackage;
and then add: new VectorIconsPackage() in getPackages() method.
the solution that solved my problem for this is
goto references->right click Newtonsoft.json--goto properties and check the version
this same version should be in
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-YourDllVersion" newVersion="YourDllVersion" />
</dependentAssembly>
Your module name must be camelCase eg. pdfLib. I had same issue because I my module name was 'PdfLib' and after renaming it to 'pdfLib'. It worked. The issue was not in my device but in jenkins server. So, check and see if you have such modulenames
I had similar experience and it took me time to solve the problem. Though, my own case was ASP.Net MVC Core
and Core
framework. Setting Trusted_Connection=False;
solved my problem.
Inside appsettings.json
file
"ConnectionStrings": {
"DefaultConnection": "Server=servername; Database=databasename; User Id=userid; Password=password; Trusted_Connection=False; MultipleActiveResultSets=true",
},
Instead of looking for ways to decode a5 (Yen ¥
) or 96 (en-dash –
), tell MySQL that your client is encoded "latin1", but you want "utf8" in the database.
See details in Trouble with UTF-8 characters; what I see is not what I stored
Fill in the service layer with the model and then send it to the view. For example: ViewItem=ModelItem.ToString().Substring(0,100);
I have solved the issue using below code in my DBContext
public partial class Q4Sandbox : DbContext { public Q4Sandbox() : base("name=Q4Sandbox") { } public virtual DbSet Employees { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance; } }
Thanks to a SO member.
Alternatively, this solution works with both Apache2 version < 2.4 as well as >= 2.4. Make sure that the "version" module is enabled:
a2enmod version
And then use this code instead:
<IfVersion < 2.4>
Allow from all
</IfVersion>
<IfVersion >= 2.4>
Require all granted
</IfVersion>
Adding dependencies didn't fix the issue at my end.
The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.
I removed the additional fields from the @Entity class and it worked.
If you would like to stay in spring boot space just set the pom packaging to jar
<packaging>jar</packaging>
and add the spring-boot-maven-plugin to you build properties in the pom.xml file:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
then a simple mvn package command will create a complete executable jar file.
See the very good spring reference doc for more details (doing it gradle style also) spring reference doc
To make a translation in the controller you could use $translate
service:
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope
event: $translateChangeSuccess
and do the same translation there:
$rootScope.$on('$translateChangeSuccess', function () {
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
});
Of course, you could encapsulate the $translate
service in a method and call it in the controller and in the $translateChangeSucess
listener.
I got this error when starting my ASP.NET application and in my case the problem was that the SQL Server service was not running. Starting that cleared it up.
I am not sure if this will still help someone, but I've done all of the solutions above (and from some other posts) to no avail.
What fixed the issue on my end was to put a backslash to the end of RedirectUri value in the web.config (crazy, I know!). RedirectUri is a parameter in UseOpenIdConnectAuthentication.
So, instead of:
<add key="ida:RedirectUri" value="https://www.bogussite.com/home" />
Do this:
<add key="ida:RedirectUri" value="https://www.bogussite.com/home/" />
And updated the Reply URL on the Azure App Settings as well.
That somehow made the Startup to run as expected (probably cleared some cache), and the breakpoints are now firing.
FYI. I was modelling my code from here: https://github.com/microsoftgraph/aspnet-connect-sample
In my case the issue didn't resolve by following any of the above methods. I had all the paths in my package config correct and the dll's were in place as referred, I was still getting run time error for System.Web.WebPages.Razor. I changed the localhost port number and this worked
I am not sure of why I had the issue and why changing the port number resolved it. Just posting this as I feel this might be useful for someone out there.
Try this:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
try
{
cn.Open();
SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
cmd.ExecuteNonQuery();
lblAlert.Text = "SucessFully Connected";
cn.Close();
}
catch (Exception eq)
{
lblAlert.Text = eq.ToString();
}
}
Hi the getOptimalPreview() that is here didn't worked for me so I want to share my version:
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
if (sizes==null) return null;
Camera.Size optimalSize = null;
double ratio = (double)h/w;
double minDiff = Double.MAX_VALUE;
double newDiff;
for (Camera.Size size : sizes) {
newDiff = Math.abs((double)size.width/size.height - ratio);
if (newDiff < minDiff) {
optimalSize = size;
minDiff = newDiff;
}
}
return optimalSize;
}
var uniq = allvalues.GroupBy(x => x.Id).Select(y=>y.First()).Distinct();
Easy and simple
The issue isn't actually a syntax error, the Hive ParseException is just caused by a reserved keyword in Hive (in this case, end
).
The solution: use backticks around the offending column name:
CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
"dynamodb.column.mapping" = "cid:cid,end:end,category:category");
With the added backticks around end
, the query works as expected.
IF, HAVING, WHERE, SELECT, UNIQUEJOIN, JOIN, ON, TRANSFORM, MAP, REDUCE, TABLESAMPLE, CAST, FUNCTION, EXTENDED, CASE, WHEN, THEN, ELSE, END, DATABASE, CROSS
Source: This Hive ticket from the Facebook Phabricator tracker
If it's a new google account, you have to send an email (the first one) through the regular user interface. After that you can use your application/robot to send messages.
This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command
start -> run -> %temp%
There is comma missing in your tuple.
insert the comma between the tuples as shown:
pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))
Do the same for all
There's also a cute little trick that lets you specify a single host on the command line (or multiple hosts, I guess), without an intermediary inventory:
ansible-playbook -i "imac1-local," user.yml
Note the comma (,) at the end; this signals that it's a list, not a file.
Now, this won't protect you if you accidentally pass a real inventory file in, so it may not be a good solution to this specific problem. But it's a handy trick to know!
The error you have is because -credential
without -computername
can't exist.
You can try this way:
Invoke-Command -Credential $migratorCreds -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME
I think this topic is totally overdiscussed/overcomplicated. Using an IDE is THE way to go to completely avoid any syntax errors. I would even say that working without an IDE is kind of unprofessional. Why? Because modern IDEs check your syntax after every character you type. When you code and your entire line turns red, and a big warning notice shows you the exact type and the exact position of the syntax error, then there's absolutely no need to search for another solution.
You'll (effectively) never run into syntax errors again, simply because you see them right as you type. Seriously.
Excellent IDEs with syntax check (all of them are available for Linux, Windows and Mac):
In addition to Kassim's answer:
As Peter says, they won't be in Maven Central
Either use maven-android-sdk-deployer to deploy the libraries to your local repository
Or from Android SDK Manager download the Android Support Repository (in Extras) and an M2 repo of the support libraries will be downloaded to your Android SDK directory
I also had to update the "Local Maven repository for Support Libraries" in Android SDK Manager.
You can solve the issue by clearing value of address in endpoint tag in web.config:
<endpoint address="" name="wsHttpEndpoint" ....... />
Just adding a bit of extra information here in case someone has the same issue as me.
I use namespaces in my code and I had a class with a function that throws an Exception.
However my try/catch code in another class file was completely ignored and the normal PHP error for an uncatched exception was thrown.
Turned out I forgot to add "use \Exception;" at the top, adding that solved the error.
Works for me this way (similar to @Amey and @user4642224 code, but shorter a bit):
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
prox = Proxy()
prox.proxy_type = ProxyType.MANUAL
prox.http_proxy = "ip_addr:port"
prox.socks_proxy = "ip_addr:port"
prox.ssl_proxy = "ip_addr:port"
capabilities = webdriver.DesiredCapabilities.CHROME
prox.add_to_capabilities(capabilities)
driver = webdriver.Chrome(desired_capabilities=capabilities)
Check your server config file /etc/mysql/my.cnf
- verify bind_address
is not set to 127.0.0.1
. Set it to 0.0.0.0
or comment it out then restart server with:
sudo service mysql restart
I have done this in a project a long time ago. The code given below write a whole rows bold with specific column names and all of these columns are written in bold format.
private void WriteColumnHeaders(DataColumnCollection columnCollection, int row, int column)
{
// row represent particular row you want to bold its content.
for (i = 0; i < columnCollection.Count; i++)
{
DataColumn col = columnCollection[i];
xlWorkSheet.Cells[row, column + i + 1] = col.Caption;
// Some Font Styles
xlWorkSheet.Cells[row, column + i + 1].Style.Font.Bold = true;
xlWorkSheet.Cells[row, column + i + 1].Interior.Color = Color.FromArgb(192, 192, 192);
//xlWorkSheet.Columns[i + 1].ColumnWidth = xlWorkSheet.Columns[i+1].ColumnWidth + 10;
}
}
You must pass value of row 0 so that first row of your excel sheets have column headers with bold font size. Just change DataColumnCollection
to your columns name and change col.Caption
to specific column name.
Alternate
You may do this to cell of excel sheet you want bold.
xlWorkSheet.Cells[row, column].Style.Font.Bold = true;
Assuming your controller's action method is something like this:
public ActionResult AllCategories(int id = 0)
{
return View(db.Categories.Include(p => p.Products).ToList());
}
Modify your models to be something like this:
public class Product
{
[Key]
public int ID { get; set; }
public int CategoryID { get; set; }
//new code
public virtual Category Category { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Path { get; set; }
//remove code below
//public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
[Key]
public int CategoryID { get; set; }
public string Name { get; set; }
//new code
public virtual ICollection<Product> Products{ get; set; }
}
Then your since now the controller takes in a Category as Model (instead of a Product):
foreach (var category in Model)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in Model.Products)
{
// cut for brevity, need to add back more code from original
<li>@product.Title</li>
}
</ul>
</div>
}
UPDATED: Add ToList() to the controller return statement.
You may be victim of a garbage collection problem.
When your application requires memory and it's getting low on what it's configured to use the garbage collector will run often which consume a lot of CPU cycles. If it can't collect anything your memory will stay low so it will be run again and again. When you redeploy your application the memory is cleared and the garbage collection won't happen more than required so the CPU utilization stays low until it's full again.
You should check that there is no possible memory leak in your application and that it's well configured for memory (check the -Xmx
parameter, see What does Java option -Xmx stand for?)
Also, what are you using as web framework? JSF relies a lot on sessions and consumes a lot of memory, consider being stateless at most!
For me, the problem was a ContextRefreshedEvent handler. I was doing some data initilization but at that point in the application the Authentication had not been set. It was a catch 22 since the system needed an authentication to authorize and it needed authorization to get the authentication details :). I ended up loosening the authorization from a class level to a method level.
In my case it was simply an error in the web.config.
I had:
<endpoint address="http://localhost/WebService/WebOnlineService.asmx"
It should have been:
<endpoint address="http://localhost:10593/WebService/WebOnlineService.asmx"
The port number (:10593) was missing from the address.
Try to add this:
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
I was searching for similar solution. The replies here and the Tutorial on top is informative. I studied posts/blogs referred here to build mine successful. I am posting complete CMakeLists.txt worked for me. I guess, this would be helpful as a basic template for beginners.
"CMakeLists.txt"
cmake_minimum_required(VERSION 3.10.2)
# Target Project
project (ClientProgram)
# Begin: Including Sources and Headers
include_directories(include)
file (GLOB SOURCES "src/*.c")
# End: Including Sources and Headers
# Begin: Generate executables
add_executable (ClientProgram ${SOURCES})
# End: Generate executables
# This Project Depends on External Project(s)
include (ExternalProject)
# Begin: External Third Party Library
set (libTLS ThirdPartyTlsLibrary)
ExternalProject_Add (${libTLS}
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
# Begin: Download Archive from Web Server
URL http://myproject.com/MyLibrary.tgz
URL_HASH SHA1=<expected_sha1sum_of_above_tgz_file>
DOWNLOAD_NO_PROGRESS ON
# End: Download Archive from Web Server
# Begin: Download Source from GIT Repository
# GIT_REPOSITORY https://github.com/<project>.git
# GIT_TAG <Refer github.com releases -> Tags>
# GIT_SHALLOW ON
# End: Download Source from GIT Repository
# Begin: CMAKE Comamnd Argiments
CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/${libTLS}
CMAKE_ARGS -DUSE_SHARED_LIBRARY:BOOL=ON
# End: CMAKE Comamnd Argiments
)
# The above ExternalProject_Add(...) construct wil take care of \
# 1. Downloading sources
# 2. Building Object files
# 3. Install under DCMAKE_INSTALL_PREFIX Directory
# Acquire Installation Directory of
ExternalProject_Get_Property (${libTLS} install_dir)
# Begin: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# Include PATH that has headers required by Target Project
include_directories (${install_dir}/include)
# Import librarues from External Project required by Target Project
add_library (lmytls SHARED IMPORTED)
set_target_properties (lmytls PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmytls.so)
add_library (lmyxdot509 SHARED IMPORTED)
set_target_properties(lmyxdot509 PROPERTIES IMPORTED_LOCATION ${install_dir}/lib/libmyxdot509.so)
# End: Importing Headers & Library of Third Party built using ExternalProject_Add(...)
# End: External Third Party Library
# Begin: Target Project depends on Third Party Component
add_dependencies(ClientProgram ${libTLS})
# End: Target Project depends on Third Party Component
# Refer libraries added above used by Target Project
target_link_libraries (ClientProgram lmytls lmyxdot509)
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
this.requestWindowFeature(getWindow().FEATURE_NO_TITLE);
Session class has been removed on SDK 4.0. The login magement is done through the class LoginManager. So:
mLoginManager = LoginManager.getInstance();
mLoginManager.logOut();
As the reference Upgrading to SDK 4.0 says:
Session Removed - AccessToken, LoginManager and CallbackManager classes supercede and replace functionality in the Session class.
Simply reference or browser the EF dll - EntityFramework.SqlServer.dll
I had this exact same problem with a site (Kentico CMS), starting development in 4.5, finding out the production server only supports 4.0, tried going back down to target framework of 4.0. Compiling the other posts in this thread (specifically changing target framework to .Net 4 and .Net 4.5 still being referenced). I searched through my solution and found that a handful of the NuGet packages were still using libraries with targetFramework="net45".
packages.config (before):
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="AutoMapper" version="3.1.0" targetFramework="net45" />
<package id="EntityFramework" version="5.0.0" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.0.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" />
</packages>
I changed the projects target framework back to 4.5, removed all NuGet libraries, went back down to 4.0 and re-added the libraries (had to use some previous versions that were not dependent on 4.5).
packages.config (after):
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="AutoMapper" version="3.1.1" targetFramework="net40" />
<package id="EntityFramework" version="6.0.2" targetFramework="net40" />
<package id="Microsoft.AspNet.WebApi.Client" version="4.0.30506.0" targetFramework="net40" />
<package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net40" />
<package id="Newtonsoft.Json" version="4.5.11" targetFramework="net40" />
</packages>
You will need to include the dll with your project and add a reference to it as well.
Here is a link to a similar issue already on Stack: MVC3 Deployment Dependency Problems
I have a files only website. Added MVC 5 to webforms application (targeting net45). I had to modify the packages.config
package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45"
to
package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" developmentDependency="true"
in order for it to startup on local box in debug mode (previously had the top described error). Running VS 2017 on Windows 7...opened through File > Open > Web Site > File (chose root directory outside of IIS).
According to this article on sqlserverstudymaterial;
Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).
If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.
If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
I found that, I am using a different InstallUtil from my target .NET Framework. I am building a .NET Framework 4.5, meanwhile the error occured if I am using the .NET Framework 2.0 release. Having use the right InstallUtil for my target .NET Framework, solved this problem!
Instead of .each, another (perhaps more concise) approach to getting all those prices might be:
var prices = $(products).children("li").map(function() {
return $(this).prop("data-price");
}).get();
additionally you may want to consider filtering the array to get rid of empty or non-numeric array values in case they should exist:
prices = prices.filter(function(n){ return(!isNaN(parseFloat(n))) });
then use Sergey's solution above:
var max = Math.max.apply(Math,prices);
var min = Math.min.apply(Math,prices);
edit: I guess it's now starting to be safe to use the native JSON.stringify() method, supported by most browsers (yes, even IE8+ if you're wondering).
As simple as:
JSON.stringify(yourData)
You should encode you data in JSON before sending it, you can't just send an object like this as POST data.
I recommand using the jQuery json plugin to do so. You can then use something like this in jQuery:
$.post(_saveDeviceUrl, {
data : $.toJSON(postData)
}, function(response){
//Process your response here
}
);
Your regex is good altough I would replace it with the empty string
String resultString = subjectString.replaceAll("[\t\n\r]", "");
You expect a space between "text." and "And" right?
I get that space when I try the regex by copying your sample
"This is my text. "
So all is well here. Maybe if you just replace it with the empty string it will work. I don't know why you replace it with \s. And the alternation | is not necessary in a character class.
I downgraded via NuGet to MVC 4 and then upgraded again to 5.2.7 and it fixed this issue
For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);
If you want it to download and install from your own server then use the following code
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
startActivity(intent);
I have never ever come across such a strange problem like this! o.O
Do you know what the problem was? $ isn't working. I tried the same code with jQuery like jQuery("#tblEntAttributes tbody").append(newRowContent);
and it works like a charm!
No idea why this strange problem occurs!
Thanks a lot for your link to the requests module. It's just perfect. Below the solution to my problem.
import requests
import json
url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned'
payload = {
"Host": "www.mywbsite.fr",
"Connection": "keep-alive",
"Content-Length": 129,
"Origin": "https://www.mywbsite.fr",
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",
"Content-Type": "application/json",
"Accept": "*/*",
"Referer": "https://www.mywbsite.fr/data/mult.aspx",
"Accept-Encoding": "gzip,deflate,sdch",
"Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",
"Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
}
# Adding empty header as parameters are being sent in payload
headers = {}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.content)
Try this:
// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg),
Base64.NO_WRAP);
If you are thinking that previously it was running properly and now on it started showing the particular issue. Then it is just a hit and trial method to solve. so to get better solution you could follow below steps
Hyperlink
is not a control, it is a flow content element, you can only use it in controls which support flow content, like a TextBlock
. TextBoxes
only have plain text.
You can do the following (I guessed on table fields,etc)
SELECT s.studentname
, s.studentid
, s.studentdesc
, h.hallname
FROM students s
INNER JOIN hallprefs hp
on s.studentid = hp.studentid
INNER JOIN halls h
on hp.hallid = h.hallid
Based on your request for multiple halls you could do it this way. You just join on your Hall table multiple times for each room pref id:
SELECT s.StudentID
, s.FName
, s.LName
, s.Gender
, s.BirthDate
, s.Email
, r.HallPref1
, h1.hallName as Pref1HallName
, r.HallPref2
, h2.hallName as Pref2HallName
, r.HallPref3
, h3.hallName as Pref3HallName
FROM dbo.StudentSignUp AS s
INNER JOIN RoomSignUp.dbo.Incoming_Applications_Current AS r
ON s.StudentID = r.StudentID
INNER JOIN HallData.dbo.Halls AS h1
ON r.HallPref1 = h1.HallID
INNER JOIN HallData.dbo.Halls AS h2
ON r.HallPref2 = h2.HallID
INNER JOIN HallData.dbo.Halls AS h3
ON r.HallPref3 = h3.HallID
Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.
For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).
Greets
Try put this before send e-mail
ServicePointManager.ServerCertificateValidationCallback =
delegate(object s, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors) { return true; };
Remenber to add the using libs!
Also, another solution is ensuring your controls are created in UI thread, not by a background worker thread for example.
Swift version : This presents a ViewController which is embedded in a Navigation Controller.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Identify the bundle by means of a class in that bundle.
let storyboard = UIStoryboard(name: "Storyboard", bundle: NSBundle(forClass: SettingsViewController.self))
// Instance of ViewController that is in the storyboard.
let settingViewController = storyboard.instantiateViewControllerWithIdentifier("SettingsVC")
let navController = UINavigationController(rootViewController: settingViewController)
presentViewController(navController, animated: true, completion: nil)
}
You haven't shown your Car
type, but assuming you'd want the price of the first car, you could use:
public static void processCars(ArrayList<Car> cars) {
Car car = cars.get(0);
System.out.println(car.getPrice());
}
Note that I've changed the name of the list from car
to cars
- this is a list of cars, not a single car. (I've changed the method name in a similar way.)
If you only want the method to process a single car, you should change the parameter to be of type Car
:
public static void processCar(Car car)
and then call it like this:
// In the main method
processCar(cars.get(0));
If you do leave it as processing the whole list, it would be worth generalizing the parameter to List<Car>
- it's unlikely that you'll really require that it's an ArrayList<Car>
.
int countRow = dt.Rows.Count;
int countCol = dt.Columns.Count;
for (int iCol = 0; iCol < countCol; iCol++)
{
DataColumn col = dt.Columns[iCol];
for (int iRow = 0; iRow < countRow; iRow++)
{
object cell = dt.Rows[iRow].ItemArray[iCol];
}
}
Have you tried to set the value of the static DefaultConnectionLimit property programmatically?
Here is a good source of information about that true headache... ASP.NET Thread Usage on IIS 7.5, IIS 7.0, and IIS 6.0, with updates for framework 4.0.
For errors like this you should involve oracle support. Unfortunately you do not mention what oracle release you are using. The error can be related to optimizer bind peeking. Depending on the oracle version different workarounds apply.
You have two ways to address this:
_optim_peek_user_binds = false
Of course underscore parameters should only be set if advised by oracle support
Change the node to and create a file, packages.xsd, in the same folder (and include it in the project) with the following contents:
<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
targetNamespace="urn:packages" xmlns="urn:packages">
<xs:element name="packages">
<xs:complexType>
<xs:sequence>
<xs:element name="package" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="id" type="xs:string" use="required" />
<xs:attribute name="version" type="xs:string" use="required" />
<xs:attribute name="targetFramework" type="xs:string" use="optional" />
<xs:attribute name="allowedVersions" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
I have also come across this issue whilst upgrading from Java 1.6_29 to 1.7.
Alarmingly, my customer has discovered a setting in the Java control panel which resolves this.
In the Advanced Tab you can check 'Use SSL 2.0 compatible ClientHello format'.
This seems to resolve the issue.
We are using Java applets in an Internet Explorer browser.
Hope this helps.
I just had a similar error using the openssl.exe from the Apache for windows bin folder. I had the -config flag specified by had a typo in the path of the openssl.cnf file. I think you'll find that
openssl req -config C:\OpenSSL\bin\openssl.conf -x509 -days 365 -newkey rsa:1024 -keyout hostkey.pem -nodes -out hostcert.pem
should be
openssl req -config "C:\OpenSSL\bin\openssl.cnf" -x509 -days 365 -newkey rsa:1024 -keyout hostkey.pem -nodes -out hostcert.pem
Note: the conf should probably be cnf.
Even if there aren't much properties to change, but you can achieve following style only with css:
.options {
border: 1px solid #e5e5e5;
padding: 10px;
}
select {
font-size: 14px;
border: none;
width: 100%;
background: white;
}
_x000D_
<div class="options">
<select>
<option value="">Apple</option>
<option value="">Banana</option>
<option value="">Orange</option>
<option value="">Mango</option>
</select>
</div>
_x000D_
I use SQLYog at home and work. It turns out they DO have a free open-source version, though sadly they've been trying to hide that fact for the last few years.
You can download the open-source version from https://github.com/webyog/sqlyog-community - just click the "Download SQLyog Community Version" link.
Just use finish() on back key press onKeypressed()
We tried several things before arriving at an acceptable solution:
xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
root# grep -ibH "df" /usr/bin/xxd
Binary file /usr/bin/xxd matches
xxd -u /usr/bin/xxd | grep -H 'DF'
(standard input):00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
Then found we could get usable results with
xxd -u /usr/bin/xxd > /tmp/xxd.hex ; grep -H 'DF' /tmp/xxd
Note that using a simple search target like 'DF' will incorrectly match characters that span across byte boundaries, i.e.
xxd -u /usr/bin/xxd | grep 'DF'
00017b0: 4010 8D05 0DFF FF0A 0300 53E3 0610 A003 @.........S.....
--------------------^^
So we use an ORed regexp to search for ' DF' OR 'DF ' (the searchTarget preceded or followed by a space char).
The final result seems to be
xxd -u -ps -c 10000000000 DumpFile > DumpFile.hex
egrep ' DF|DF ' Dumpfile.hex
0001020: 0089 0424 8D95 D8F5 FFFF 89F0 E8DF F6FF ...$............
-----------------------------------------^^
0001220: 0C24 E871 0B00 0083 F8FF 89C3 0F84 DF03 .$.q............
--------------------------------------------^^
The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.
In your .Debug/.Release files, you need to add the following parameter in your connection string fields:
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"
This will cause each connection string line to find the matching name and update the attributes accordingly.
Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.
Here's an example from one of my apps. Here's the web.config file section:
<connectionStrings>
<add name="EAF" connectionString="[Test Connection String]" />
</connectionString>
And here's the web.config.release section doing the proper transform:
<connectionStrings>
<add name="EAF" connectionString="[Prod Connection String]"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)" />
</connectionStrings>
One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.
For more details you can see the MSDN documentation
https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx
PHP7, in php.ini file, remove the ";" before extension=openssl
You are trying to to an Insert (with ExecuteNonQuery()
) on a SQL connection that is used by this reader already:
while (myReader.Read())
Either read all the values in a list first, close the reader and then do the insert, or use a new SQL connection.
That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).
You could use this:
string path = @"c:\projects\roott\wsdlproj\devlop\beta2\text";
string lastDirectory = path.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).Last();
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[columnIndex].Visible = false;
}
HeaderText
for the GridViewColumn
and then find the column using that HeaderText
.
protected void UsersGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
((DataControlField)UsersGrid.Columns
.Cast<DataControlField>()
.Where(fld => fld.HeaderText == "Email")
.SingleOrDefault()).Visible = false;
}
This solution will work for all versions of Android. You can use reflection in Java to make it work for all Android devices:
Basically you should create a reflection wrapper to call the Android 2.2 setDisplayOrientation, instead of calling the specific method.
The method:
protected void setDisplayOrientation(Camera camera, int angle){
Method downPolymorphic;
try
{
downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
if (downPolymorphic != null)
downPolymorphic.invoke(camera, new Object[] { angle });
}
catch (Exception e1)
{
}
}
And instead of using camera.setDisplayOrientation(x) use setDisplayOrientation(camera, x) :
if (Integer.parseInt(Build.VERSION.SDK) >= 8)
setDisplayOrientation(mCamera, 90);
else
{
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
p.set("orientation", "portrait");
p.set("rotation", 90);
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
p.set("orientation", "landscape");
p.set("rotation", 90);
}
}
On SQL Server 2008+ it is possible to use Table Valued Parameters to pass in a table variable to a dynamic SQL statement as long as you don't need to update the values in the table itself.
So from the code you posted you could use this approach for @TSku
but not for @RelPro
Example syntax below.
CREATE TYPE MyTable AS TABLE
(
Foo int,
Bar int
);
GO
DECLARE @T AS MyTable;
INSERT INTO @T VALUES (1,2), (2,3)
SELECT *,
sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
FROM @T
EXEC sp_executesql
N'SELECT *,
sys.fn_PhysLocFormatter(%%physloc%%) AS [physloc]
FROM @T',
N'@T MyTable READONLY',
@T=@T
The physloc
column is included just to demonstrate that the table variable referenced in the child scope is definitely the same one as the outer scope rather than a copy.
// I would make it a little bit more simple
var products = new List<List<product>> {item1, item2, item3 }.SelectMany(id => id).ToList();
This way it is a multi dimensional List and the .SelectMany() will flatten it into a IEnumerable of product then I use the .ToList() method after.
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
Running Windows Server 2008 R2 64bit and .net framework 4.5, ran this command from this location, and was successful:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis -i
output:
Microsoft (R) ASP.NET RegIIS version 4.0.30319.0
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation. All rights reserved.
Start installing ASP.NET (4.0.30319.0).
.....
Finished installing ASP.NET (4.0.30319.0).
I was looking for a similar solution and this is what I would suggest. In the OnTouch method, record the time for MotionEvent.ACTION_DOWN event and then for MotionEvent.ACTION_UP, record the time again. This way you can set your own threshold also. After experimenting few times you will know the max time in millis it would need to record a simple touch and you can use this in move or other method as you like.
Hope this helped. Please comment if you used a different method and solved your problem.
You need to clear the old array out before you push the new data in. There are many ways to accomplish this but I used this one:
options.series[0].data.length = 0;
So your code should look like this:
options.series[0].data.length = 0;
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var data = {};
$.each(items, function(itemNo, item) {
if (itemNo === 0) {
data.name = item;
} else {
data.y = parseFloat(item);
}
});
options.series[0].data.push(data);
});
Now when the button is clicked the old data is purged and only the new data should show up. Hope that helps.
This error was somewhat misleading - I was loading some DLLs that required x64 architecture to be specified. In the .csproj
file:
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release-ABC|AnyCPU'">
<OutputPath>bin\Release-ABC</OutputPath>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
A missing PlatformTarget
caused this error.
The problem is that "i" is incremented, so by the time the click event is executed the value of i equals len. One possible solution is to capture the value of i inside a function:
var len = menuitems.length;
for (var i = 0; i < len; i++){
(function(i) {
$('<li/>',{
'html':'<img src="'+menuitems[i].icon+'">'+menuitems[i].name,
'click':function(){
menuitems[i].action();
},
'class':o.itemClass
}).appendTo('.'+o.listClass);
})(i);
}
In the above sample, the anonymous function creates a new scope which captures the current value of i, so that when the click event is triggered the local variable is used instead of the i from the for loop.
I'm using the following function for that; it's an adaptation from one of the man entries in the fputscsv comments. And you'll probably want to flatten that array; not sure what happens if you pass in a multi-dimensional one.
/**
* Formats a line (passed as a fields array) as CSV and returns the CSV as a string.
* Adapted from http://us3.php.net/manual/en/function.fputcsv.php#87120
*/
function arrayToCsv( array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
$delimiter_esc = preg_quote($delimiter, '/');
$enclosure_esc = preg_quote($enclosure, '/');
$output = array();
foreach ( $fields as $field ) {
if ($field === null && $nullToMysqlNull) {
$output[] = 'NULL';
continue;
}
// Enclose fields containing $delimiter, $enclosure or whitespace
if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
$output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
}
else {
$output[] = $field;
}
}
return implode( $delimiter, $output );
}
I would just not add it in the first place:
var sb = new StringBuilder();
bool first = true;
foreach (var foo in items) {
if (first)
first = false;
else
sb.Append('&');
// for example:
var escapedValue = System.Web.HttpUtility.UrlEncode(foo);
sb.Append(key).Append('=').Append(escapedValue);
}
var s = sb.ToString();
you can use getopt to handle parameters in your bash script. there are not many explanations for getopt out there. here is an example:
#!/bin/sh
OPTIONS=$(getopt -o hf:gb -l help,file:,foo,bar -- "$@")
if [ $? -ne 0 ]; then
echo "getopt error"
exit 1
fi
eval set -- $OPTIONS
while true; do
case "$1" in
-h|--help) HELP=1 ;;
-f|--file) FILE="$2" ; shift ;;
-g|--foo) FOO=1 ;;
-b|--bar) BAR=1 ;;
--) shift ; break ;;
*) echo "unknown option: $1" ; exit 1 ;;
esac
shift
done
if [ $# -ne 0 ]; then
echo "unknown option(s): $@"
exit 1
fi
echo "help: $HELP"
echo "file: $FILE"
echo "foo: $FOO"
echo "bar: $BAR"
see also:
man getopt
It's 2020 and stuffs had greatly evolved with php 7.4 and opcache.
Here is the OP^ benchmark, ran as unix CLI, without the echo and html parts.
Test ran locally on a regular computer.
php -v
PHP 7.4.6 (cli) (built: May 14 2020 10:02:44) ( NTS )
Modified benchmark script:
<?php
## preperations; just a simple environment state
$test_iterations = 100;
$test_arr_size = 1000;
// a shared function that makes use of the loop; this should
// ensure no funny business is happening to fool the test
function test($input)
{
//echo '<!-- '.trim($input).' -->';
}
// for each test we create a array this should avoid any of the
// arrays internal representation or optimizations from getting
// in the way.
// normal array
$test_arr1 = array();
$test_arr2 = array();
$test_arr3 = array();
// hash tables
$test_arr4 = array();
$test_arr5 = array();
for ($i = 0; $i < $test_arr_size; ++$i)
{
mt_srand();
$hash = md5(mt_rand());
$key = substr($hash, 0, 5).$i;
$test_arr1[$i] = $test_arr2[$i] = $test_arr3[$i] = $test_arr4[$key] = $test_arr5[$key]
= $hash;
}
## foreach
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr1 as $k => $v)
{
test($v);
}
}
echo 'foreach '.(microtime(true) - $start)."\n";
## foreach (using reference)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr2 as &$value)
{
test($value);
}
}
echo 'foreach (using reference) '.(microtime(true) - $start)."\n";
## for
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
$size = count($test_arr3);
for ($i = 0; $i < $size; ++$i)
{
test($test_arr3[$i]);
}
}
echo 'for '.(microtime(true) - $start)."\n";
## foreach (hash table)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
foreach ($test_arr4 as $k => $v)
{
test($v);
}
}
echo 'foreach (hash table) '.(microtime(true) - $start)."\n";
## for (hash table)
$start = microtime(true);
for ($j = 0; $j < $test_iterations; ++$j)
{
$keys = array_keys($test_arr5);
$size = sizeOf($test_arr5);
for ($i = 0; $i < $size; ++$i)
{
test($test_arr5[$keys[$i]]);
}
}
echo 'for (hash table) '.(microtime(true) - $start)."\n";
Output:
foreach 0.0032877922058105
foreach (using reference) 0.0029420852661133
for 0.0025191307067871
foreach (hash table) 0.0035080909729004
for (hash table) 0.0061779022216797
As you can see the evolution is insane, about 560 time faster than reported in 2012.
On my machines and servers, following my numerous experiments, basics for loops are the fastest. This is even clearer using nested loops ($i $j $k..)
It is also the most flexible in usage, and has a better readability from my view.
You don't show the code for display_data
, but here's what you need to do:
print "$%0.02f" %amount
This is a format specifier for the variable amount
.
Since this is beginner topic, I won't get into floating point rounding error, but it's good to be aware that it exists.
The other answers here adequately explain the security caveats which are also mentioned in the subprocess
documentation. But in addition to that, the overhead of starting a shell to start the program you want to run is often unnecessary and definitely silly for situations where you don't actually use any of the shell's functionality. Moreover, the additional hidden complexity should scare you, especially if you are not very familiar with the shell or the services it provides.
Where the interactions with the shell are nontrivial, you now require the reader and maintainer of the Python script (which may or may not be your future self) to understand both Python and shell script. Remember the Python motto "explicit is better than implicit"; even when the Python code is going to be somewhat more complex than the equivalent (and often very terse) shell script, you might be better off removing the shell and replacing the functionality with native Python constructs. Minimizing the work done in an external process and keeping control within your own code as far as possible is often a good idea simply because it improves visibility and reduces the risks of -- wanted or unwanted -- side effects.
Wildcard expansion, variable interpolation, and redirection are all simple to replace with native Python constructs. A complex shell pipeline where parts or all cannot be reasonably rewritten in Python would be the one situation where perhaps you could consider using the shell. You should still make sure you understand the performance and security implications.
In the trivial case, to avoid shell=True
, simply replace
subprocess.Popen("command -with -options 'like this' and\\ an\\ argument", shell=True)
with
subprocess.Popen(['command', '-with','-options', 'like this', 'and an argument'])
Notice how the first argument is a list of strings to pass to execvp()
, and how quoting strings and backslash-escaping shell metacharacters is generally not necessary (or useful, or correct).
Maybe see also When to wrap quotes around a shell variable?
If you don't want to figure this out yourself, the shlex.split()
function can do this for you. It's part of the Python standard library, but of course, if your shell command string is static, you can just run it once, during development, and paste the result into your script.
As an aside, you very often want to avoid Popen
if one of the simpler wrappers in the subprocess
package does what you want. If you have a recent enough Python, you should probably use subprocess.run
.
check=True
it will fail if the command you ran failed.stdout=subprocess.PIPE
it will capture the command's output.text=True
(or somewhat obscurely, with the synonym universal_newlines=True
) it will decode output into a proper Unicode string (it's just bytes
in the system encoding otherwise, on Python 3).If not, for many tasks, you want check_output
to obtain the output from a command, whilst checking that it succeeded, or check_call
if there is no output to collect.
I'll close with a quote from David Korn: "It's easier to write a portable shell than a portable shell script." Even subprocess.run('echo "$HOME"', shell=True)
is not portable to Windows.
I think the common approach is to SELECT * FROM INFORMATION_SCHEMA.TABLES
for each database using sp_MSforeachdb
I created a snippet in VS Code that I think it might be helpful.
IF OBJECT_ID('tempdb..#alltables', 'U') IS NOT NULL DROP TABLE #alltables;
SELECT * INTO #alltables FROM INFORMATION_SCHEMA.TABLES;
TRUNCATE TABLE #alltables;
EXEC sp_MSforeachdb 'USE [?];INSERT INTO #alltables SELECT * from INFORMATION_SCHEMA.TABLES';
SELECT * FROM #alltables WHERE TABLE_NAME LIKE '%<TABLE_NAME_TO_SEARCH>%';
GO
{
"List all tables": {
"prefix": "sqlListTable",
"body": [
"IF OBJECT_ID('tempdb..#alltables', 'U') IS NOT NULL DROP TABLE #alltables;",
"SELECT * INTO #alltables FROM INFORMATION_SCHEMA.TABLES;",
"TRUNCATE TABLE #alltables;",
"EXEC sp_MSforeachdb 'USE [?];INSERT INTO #alltables SELECT * from INFORMATION_SCHEMA.TABLES';",
"SELECT * FROM #alltables WHERE TABLE_NAME LIKE '%$0%';",
"GO"
]
}
}
Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.
That depends on how you define what is working. Does it replace all occurrences of the target character with '\0'
? Absolutely!
String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"
Everything seems to work fine to me! indexOf
can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.
It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!
String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;
It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):
In the Java programming language, unlike C, an array of
char
is not aString
, and neither aString
nor an array ofchar
is terminated by '\u0000' (the NUL character).
Would this be the culprit to the funky characters?
Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.
That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.
Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the replace(CharSequence, CharSequence)
overload.
System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU
The replaceAll
solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.
I found an even elegant and simple solution to clearing cache
WebView obj;
obj.clearCache(true);
http://developer.android.com/reference/android/webkit/WebView.html#clearCache%28boolean%29
I have been trying to figure out the way to clear the cache, but all we could do from the above mentioned methods was remove the local files, but it never clean the RAM.
The API clearCache, frees up the RAM used by the webview and hence mandates that the webpage be loaded again.
I experienced the same issue when sending high volume email. Setting the deliveryMethod
property to PickupDirectoryFromIis
fixed it for me.
Also don't create a new SmtpClient everytime.
Here you've got a copy-paste code:
class NameToBackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value.ToString() == "System")
{
return new SolidColorBrush(System.Windows.Media.Colors.Aqua);
}else
{
return new SolidColorBrush(System.Windows.Media.Colors.Blue);
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
Just
$("#your_item").trigger("click");
using .trigger() you can simulate many type of events, just passing it as the parameter.
You can create your own custom config section in the app.config file. There are quite a few tutorials around to get you started. Ultimately, you could have something like this:
<configSections>
<section name="backupDirectories" type="TestReadMultipler2343.BackupDirectoriesSection, TestReadMultipler2343" />
</configSections>
<backupDirectories>
<directory location="C:\test1" />
<directory location="C:\test2" />
<directory location="C:\test3" />
</backupDirectories>
To complement Richard's answer, this is the C# you could use with his sample configuration:
using System.Collections.Generic;
using System.Configuration;
using System.Xml;
namespace TestReadMultipler2343
{
public class BackupDirectoriesSection : IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
List<directory> myConfigObject = new List<directory>();
foreach (XmlNode childNode in section.ChildNodes)
{
foreach (XmlAttribute attrib in childNode.Attributes)
{
myConfigObject.Add(new directory() { location = attrib.Value });
}
}
return myConfigObject;
}
}
public class directory
{
public string location { get; set; }
}
}
Then you can access the backupDirectories configuration section as follows:
List<directory> dirs = ConfigurationManager.GetSection("backupDirectories") as List<directory>;
Check the Initial Catalog parameter in your connection string. It may be that your code is looking in the wrong database for the Projects object.
For example, if you have database syncing setup in such a way that only a subset of the master-database's tables are transferred, you can encounter this error if Linq to SQL is expecting all tables to be in the database pointed to by the connection string.
var table = Tables[0]; //get first table from Dataset
foreach (DataRow row in table.Rows)
{
foreach (var item in row.ItemArray)
{
console.Write("Value:"+item);
}
}
Try this link <-- MORE SOURCE CODE HERE
/** Include the Pear Library for Zip */
include ('Archive/Zip.php');
/** Create a Zipping Object...
* Name of zip file to be created..
* You can specify the path too */
$obj = new Archive_Zip('test.zip');
/**
* create a file array of Files to be Added in Zip
*/
$files = array('black.gif',
'blue.gif',
);
/**
* creating zip file..if success do something else do something...
* if Error in file creation ..it is either due to permission problem (Solution: give 777 to that folder)
* Or Corruption of File Problem..
*/
if ($obj->create($files)) {
// echo 'Created successfully!';
} else {
//echo 'Error in file creation';
}
?>; // We'll be outputting a ZIP
header('Content-type: application/zip');
// It will be called test.zip
header('Content-Disposition: attachment; filename="test.zip"');
//read a file and send
readfile('test.zip');
?>;
I ran into this problem recently - the issue was that I had included the jQuery UI files in the head tag, but the Telerik library I was using included jQuery at the bottom of the body tag (thus apparently re-initializing jQuery and unloading the UI plugins previously loaded).
The solution was to find out where jQuery was actually being included, and including the jQuery UI scripts after that.
You can use ISNULL()
.
SELECT ISNULL(SUM(Price), 0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
That should do the trick.
I resolved this problem writing function instead of procedure and using CROSS APPLY in SQL statement. This solution works on SQL 2005 and later versions.
I found the actual solution...There is a problem in invoking your service from the client.. check the following things.
Make sure all [datacontract], [datamember] attribute are placed properly i.e. make sure WCF is error free
The WCF client, either web.config or any window app config, make sure config entries are properly pointing to the right ones.. binding info, url of the service..etc..etc
Then above problem : tempuri issue is resolved.. it has nothing to do with namespace.. though you are sure you lived with default,
Hope it saves your number of hours!
For what it is worth, an additional consideration when using .NET 4.0 is that if a valid endpoint is not found in your configuration, a default endpoint will be automatically created and used.
The default endpoint will use all default values so if you think you have a valid service configuration with a large value for maxReceivedMessageSize etc., but there is something wrong with the configuration, you would still get the 400 Bad Request since a default endpoint would be created and used.
This is done silently so it is hard to detect. You will see messages to this effect (e.g. 'No Endpoint found for Service, creating Default Endpoint' or similar) if you turn on tracing on the server but there is no other indication (to my knowledge).
I had the same problem, but it didn't have anything to do with JavaScript. Consider this code:
<input id="hdnTest" type="hidden" value='<%= hdnValue %>' />
<asp:PlaceHolder ID="phWrapper" runat="server"></asp:PlaceHolder>
<asp:PlaceHolder ID="phContent" runat="server" Visible="false">
<b>test content</b>
</asp:PlaceHolder>
In this situation you'll get the same error even though PlaceHolders don't have any harmful code blocks, it happens because of the non-server control hdnTest uses code blocks.
Just add runat=server to the hdnTest and the problem is solved.
here is the solution that I decided to use.
ServicePointManager.ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
string name = certificate.Subject;
DateTime expirationDate = DateTime.Parse(certificate.GetExpirationDateString());
if (sslPolicyErrors == SslPolicyErrors.None || (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch && name.EndsWith(".acceptabledomain.com") && expirationDate > DateTime.Now))
{
return true;
}
return false;
};
To get the id of the parent div:
$(buttonSelector).parents('div:eq(0)').attr('id');
Also, you can refactor your code quite a bit:
$('button').click( function() {
var correct = Number($(this).attr('rel'));
validate(Number($(this).siblings('input').val()), correct);
$(this).parents('div:eq(0)').html(feedback);
});
Now there is no need for a button-class
explanation
eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
$(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
Thus: $(selector).parents('div:eq(0)'); will match the first parent div of the elements matched by selector.
You should have a look at the jQuery docs, particularly selectors and traversing:
If the transfer mode is Buffered then make sure that the values of MaxReceivedMessageSize and MaxBufferSize is same. I just resolved the faulted state issue this way after grappling with it for hours and thought i'll post it here if it helps someone.
You may be able to replace the:
VirtualHost ipaddress:443
with
VirtualHost *:443
You probably need todo this on all of your virt hosts.
It will probably clear up that message. Let the ServerName directive worry about routing the message request.
Again, you may not be able to do this if you have multiple ip's aliases to the same machine.
There isn't direct support for COUNT(DISTINCT {x}))
, but you can simulate it from an IGrouping<,>
(i.e. what group by
returns); I'm afraid I only "do" C#, so you'll have to translate to VB...
select new
{
Foo= grp.Key,
Bar= grp.Select(x => x.SomeField).Distinct().Count()
};
Here's a Northwind example:
using(var ctx = new DataClasses1DataContext())
{
ctx.Log = Console.Out; // log TSQL to console
var qry = from cust in ctx.Customers
where cust.CustomerID != ""
group cust by cust.Country
into grp
select new
{
Country = grp.Key,
Count = grp.Select(x => x.City).Distinct().Count()
};
foreach(var row in qry.OrderBy(x=>x.Country))
{
Console.WriteLine("{0}: {1}", row.Country, row.Count);
}
}
The TSQL isn't quite what we'd like, but it does the job:
SELECT [t1].[Country], (
SELECT COUNT(*)
FROM (
SELECT DISTINCT [t2].[City]
FROM [dbo].[Customers] AS [t2]
WHERE ((([t1].[Country] IS NULL) AND ([t2].[Country] IS NULL)) OR (([t1]
.[Country] IS NOT NULL) AND ([t2].[Country] IS NOT NULL) AND ([t1].[Country] = [
t2].[Country]))) AND ([t2].[CustomerID] <> @p0)
) AS [t3]
) AS [Count]
FROM (
SELECT [t0].[Country]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[CustomerID] <> @p0
GROUP BY [t0].[Country]
) AS [t1]
-- @p0: Input NVarChar (Size = 0; Prec = 0; Scale = 0) []
-- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 3.5.30729.1
The results, however, are correct- verifyable by running it manually:
const string sql = @"
SELECT c.Country, COUNT(DISTINCT c.City) AS [Count]
FROM Customers c
WHERE c.CustomerID != ''
GROUP BY c.Country
ORDER BY c.Country";
var qry2 = ctx.ExecuteQuery<QueryResult>(sql);
foreach(var row in qry2)
{
Console.WriteLine("{0}: {1}", row.Country, row.Count);
}
With definition:
class QueryResult
{
public string Country { get; set; }
public int Count { get; set; }
}
Assuming your products LINQ class uses a similar yield for enumerating/iterating, the first version is more efficient because its only yielding one value each time its iterated over.
The second example is converting the enumerator/iterator to a list with the ToList() method. This means it manually iterates over all the items in the enumerator and then returns a flat list.
a profanity filtering system will never be perfect, even if the programmer is cocksure and keeps abreast of all nude developments
that said, any list of 'naughty words' is likely to perform as well as any other list, since the underlying problem is language understanding which is pretty much intractable with current technology
so, the only practical solution is twofold:
ddlCategory.DataSource = ds;
ddlCategory.DataTextField = "CatName";
ddlCategory.DataValueField = "CatID";
Cách 1:
ddlCategory.Items.Add(new ListItem("--please select--", "-1"));
ddlCategory.AppendDataBoundItems = true;
ddlCategory.SelectedIndex = -1;
ddlCategory.DataBind();
Cách 2:
ddlCategory.Items.Insert(0, new ListItem("-- please select --", "0"));
(Tested OK)
As per CodeTrawler's answer, the solution is to enter the following into an explorer window:
%systemroot%\Microsoft.NET\Framework
Then search for:
Mscorlib.dll
...and right-click / go to the version tab for each result.
I think I know what you are asking for. Here is what you can do.
first get the height of the person say h meters.
if you can calculate the height of the camera from ground (using height if the person i.e. h) and get angles A and B using gyroscope or something from android then you can calculate the height of the object using the above formula.
Isn't this what you were looking for???
let me know if you need any explanation.
You need to give a function to be called after the time delay as the second argument to after
:
after(delay_ms, callback=None, *args)
Registers an alarm callback that is called after a given time.
So what you really want to do is this:
tiles_letter = ['a', 'b', 'c', 'd', 'e']
def add_letter():
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
root.after(0, add_letter) # add_letter will run as soon as the mainloop starts.
root.mainloop()
You also need to schedule the function to be called again by repeating the call to after
inside the callback function, since after
only executes the given function once. This is also noted in the documentation:
The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself
Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter
, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter
to make sure the list isn't empty, and just return
if it is:
def add_letter():
if not tiles_letter:
return
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
Live-Demo: repl.it
On Windows, Ctrl+Shift+r would force reload the script in chrome.
Simply, double shift then type Assets Folder
choose it to be created in the correct place
If the purpose of this is to create a unique value from the date
, here is what I would do
DECLARE @ts TIMESTAMP
SET @ts = CAST(getdate() AS TIMESTAMP)
SELECT @ts
This gets the date and declares it as a simple timestamp
Here is how you can do it:
std::string & trim(std::string & str)
{
return ltrim(rtrim(str));
}
And the supportive functions are implemeted as:
std::string & ltrim(std::string & str)
{
auto it2 = std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
str.erase( str.begin() , it2);
return str;
}
std::string & rtrim(std::string & str)
{
auto it1 = std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
str.erase( it1.base() , str.end() );
return str;
}
And once you've all these in place, you can write this as well:
std::string trim_copy(std::string const & str)
{
auto s = str;
return ltrim(rtrim(s));
}
Try this
You can comment section of a script using a conditional.
For example, the following script:
DEBUG=false
if ${DEBUG}; then
echo 1
echo 2
echo 3
echo 4
echo 5
fi
echo 6
echo 7
would output:
6
7
In order to uncomment the section of the code, you simply need to comment the variable:
#DEBUG=false
(Doing so would print the numbers 1 through 7.)
Actually, char* name
is not a pointer to a constant, but a pointer to a variable. You might be talking about this other question.
What is the difference between char * const and const char *?
import java.util.Calendar;
Calendar cal = Calendar.getInstance();
int currentHour = cal.get(Calendar.HOUR);
if (currentHour > 10 && currentHour < 18) {
//then rock on
}
Surprisingly this question doesn't have a definitive documented answer. Perhaps another data point would provide value to others looking for an answer. On my systems running CentOS (6.8,7.3) and Java 8 (build 1.8.0_60-b27, 64-Bit Server):
default memory is 1/4 of physical memory, not limited by 1GB.
Also, -XX:+PrintFlagsFinal
prints to STDERR so command to determine current default memory presented by others above should be tweaked to the following:
java -XX:+PrintFlagsFinal 2>&1 | grep MaxHeapSize
The following is returned on system with 64GB of physical RAM:
uintx MaxHeapSize := 16873684992 {product}
You can use regular expressions. Here is the function with @janm's suggestions.
class String
def is_i?
!!(self =~ /\A[-+]?[0-9]+\z/)
end
end
An edited version according to comment from @wich:
class String
def is_i?
/\A[-+]?\d+\z/ === self
end
end
In case you only need to check positive numbers
if !/\A\d+\z/.match(string_to_check)
#Is not a positive number
else
#Is all good ..continue
end
Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:
*** Phones:
*** Tablets:
Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.
this seems to be the simplified version
Array.from('abc').map((each)=>each.charCodeAt(0).toString(2)).join(" ")
Override service method like this:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
And Voila!
var o = {a:1, b:2};
o.toString=function(){
return 'a='+this.a+', b='+this.b;
};
console.log(o);
console.log('Item: ' + o);
Since Javascript v1.0 works everywhere (even IE) this is a native approach and allows for a very costomised look of your object while debugging and in production https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
Usefull example
var Ship=function(n,x,y){
this.name = n;
this.x = x;
this.y = y;
};
Ship.prototype.toString=function(){
return '"'+this.name+'" located at: x:'+this.x+' y:'+this.y;
};
alert([new Ship('Star Destroyer', 50.001, 53.201),
new Ship('Millennium Falcon', 123.987, 287.543),
new Ship('TIE fighter', 83.060, 102.523)].join('\n'));//now they can battle!
//"Star Destroyer" located at: x:50.001 y:53.201
//"Millennium Falcon" located at: x:123.987 y:287.543
//"TIE fighter" located at: x:83.06 y:102.523
Also, as a bonus
function ISO8601Date(){
return this.getFullYear()+'-'+(this.getMonth()+1)+'-'+this.getDate();
}
var d=new Date();
d.toString=ISO8601Date;//demonstrates altering native object behaviour
alert(d);
//IE6 Fri Jul 29 04:21:26 UTC+1200 2016
//FF&GC Fri Jul 29 2016 04:21:26 GMT+1200 (New Zealand Standard Time)
//d.toString=ISO8601Date; 2016-7-29
Try:
subprocess.call(['sudo', 'apach2ctl', 'restart'])
The subprocess needs to access the real stdin/out/err for it to be able to prompt you, and read in your password. If you set them up as pipes, you need to feed the password into that pipe yourself.
If you don't define them, then it grabs sys.stdout, etc...
If you have a unique column in your table (e.g. tableid) then try this.
SELECT EMAIL FROM TABLE WHERE TABLEID IN
(SELECT MAX(TABLEID), EMAIL FROM TABLE GROUP BY EMAIL)
I have found even better Grunt plugin, that works if you have your index.html and Gruntfile.js in the same directory;
https://npmjs.org/package/grunt-connect-pushstate
After that in your Gruntfile:
var pushState = require('grunt-connect-pushstate/lib/utils').pushState;
connect: {
server: {
options: {
port: 1337,
base: '',
logger: 'dev',
hostname: '*',
open: true,
middleware: function (connect, options) {
return [
// Rewrite requests to root so they may be handled by router
pushState(),
// Serve static files
connect.static(options.base)
];
}
},
}
},
I know this is SUPER old... but just for fun I decided to give this a try:
@Echo OFF
setlocal
set testpath=%path: =#%
FOR /F "tokens=* delims=;" %%P in ("%testpath%") do call :loop %%P
:loop
if '%1'=='' goto endloop
set testpath=%1
set testpath=%testpath:#= %
echo %testpath%
SHIFT
goto :loop
:endloop
pause
endlocal
exit
This doesn't require a count and will go until it finishes. I had the same problem with spaces but it made it through the entire variable. The key to this is the loop labels and the SHIFT
function.
left: initial
This will also set left
back to the browser default.
But important to know property: initial
is not supported in IE.
Olof's answer is good, but it needs one more thing before it's perfect. In the comments below his answer, dacwe (correctly) points out that his implementation violates the Compare/Equals contract for Sets. If you try to call contains or remove on an entry that's clearly in the set, the set won't recognize it because of the code that allows entries with equal values to be placed in the set. So, in order to fix this, we need to test for equality between the keys:
static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
new Comparator<Map.Entry<K,V>>() {
@Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
int res = e1.getValue().compareTo(e2.getValue());
if (e1.getKey().equals(e2.getKey())) {
return res; // Code will now handle equality properly
} else {
return res != 0 ? res : 1; // While still adding all entries
}
}
}
);
sortedEntries.addAll(map.entrySet());
return sortedEntries;
}
"Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface... the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal." (http://docs.oracle.com/javase/6/docs/api/java/util/SortedSet.html)
Since we originally overlooked equality in order to force the set to add equal valued entries, now we have to test for equality in the keys in order for the set to actually return the entry you're looking for. This is kinda messy and definitely not how sets were intended to be used - but it works.
If you are working on development environment(or on for production env. it may be backup your data) then first to clear the data from the DB field or set the value as 0.
UPDATE table_mame SET field_name= 0;
After that to run the below query and after successfully run the query, to the schemamigration and after that run the migrate script.
ALTER TABLE table_mame ALTER COLUMN field_name TYPE numeric(10,0) USING field_name::numeric;
I think it will help you.
You can use simple jQuery jPut plugin
http://plugins.jquery.com/jput/
<script>
$(document).ready(function(){
var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
jsonData:json,
//ajax_url:"youfile.json", if you want to call from a json file
name:"tbody_template",
});
});
</script>
<table jput="t_template">
<tbody jput="tbody_template">
<tr>
<td>{{name}}</td>
<td>{{email}}</td>
</tr>
</tbody>
</table>
<table>
<tbody id="tbody">
</tbody>
</table>
To submit form in MVC NET Core you can submit using INPUT:
<input type="submit" value="Add This Form">
To make it a button I am using Bootstrap for example:
<input type="submit" value="Add This Form" class="btn btn-primary">
To prevent sending duplicate forms in MVC NET Core, you can add onclick event, and use this.disabled = true; to disable the button:
<input type="submit" value="Add This Form" class="btn btn-primary" onclick="this.disabled = true;">
If you want check first if form is valid and then disable the button, add this.form.submit(); first, so if form is valid, then this button will be disabled, otherwise button will still be enabled to allow you to correct your form when validated.
<input type="submit" value="Add This Form" class="btn btn-primary" onclick="this.form.submit(); this.disabled = true;">
You can add text to the disabled button saying you are now in the process of sending form, when all validation is correct using this.value='text';:
<input type="submit" value="Add This Form" class="btn btn-primary" onclick="this.form.submit(); this.disabled = true; this.value = 'Submitting the form';">
I've been trying to deploy a simple Angular 7 application, to an Azure Web App. Everything worked fine, until the point where you refreshed the page. Doing so, was presenting me with an 500 error - moved content. I've read both on the Angular docs and in around a good few forums, that I need to add a web.config file to my deployed solution and make sure the rewrite rule fallback to the index.html file. After hours of frustration and trial and error tests, I've found the error was quite simple: adding a tag around my file markup.
I resolved by removing @Basic(optional = false) property or just update boolean @Basic(optional = true)
I just integrated Robert Foss's TouchImageView: it worked perfectly out of the box! Thanks!
I just modified a bit the code so I could be able to instantiate it from my layout.xml.
Just add two constructors
public TouchImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public TouchImageView(Context context) {
super(context);
init(context);
}
and transform the old constructor into an init method:
private void init(Context context){
//...old code ofconstructor of Robert Moss's code
}
As well as the previous answers are you could always use the Pull attrib as well:
<ol class="row" id="possibilities">
<li class="span6">
<div class="row">
<div class="span3">
<p>some text here</p>
<p>Text Here too</p>
</div>
<figure class="span3 pull-right"><img src="img/screenshots/options.png" alt="Some text" /></figure>
</div>
</li>
<li class="span6">
<div class="row">
<figure class="span3"><img src="img/qrcode.png" alt="Some text" /></figure>
<div class="span3">
<p>Some text</p>
<p>Some text here too.</p>
</div>
</div>
</li>
VS 2017
Tools>NuGet Package Manager>Package Manager Settings>General Click on "Clear All NuGet Cache(s)"
If using latest Git,
git merge --abort
else this will do the job in older git versions
git reset --merge
or
git reset --hard
After stopping the database server, the next step is to gain access to the server through a backdoor by starting the database server and skipping networking and permission tables. This can be done by running the commands below.
sudo mysqld_safe --skip-grant-tables --skip-networking &
Now that the database server is started in safe mode, run the commands below to logon as root without password prompt. To do that, run the commands below
sudo mysql -u root
Then run the commands below to use the mysql database.
use mysql;
Finally, run the commands below to reset the root password.
update user set password=PASSWORD("new_password_here") where User='root';
Replace new_password _here with the new password you want to create for the root account, then press Enter.
After that, run the commands below to update the permissions and save your changes to disk.
flush privileges;
Exit (CTRL + D) and you’re done.
Next start MariaDB normally and test the new password you just created.
sudo systemctl stop mariadb.service
sudo systemctl start mariadb.service
Logon to the database by running the commands below.
sudo mysql -u root -p
source: https://websiteforstudents.com/reset-mariadb-root-password-ubuntu-17-04-17-10/
Robocopy, or "Robust File Copy", is a command-line directory and/or file replication command. Robocopy functionally replaces Xcopy, with more options. It has been available as part of the Windows Resource Kit starting with Windows NT 4.0, and was first introduced as a standard feature in Windows Vista and Windows Server 2008. The command is
robocopy
...
I was having the same problem. When I initially created the java project in Eclipse I specified JRE 8. When I went into the project's build path and edited the JRE System Library, the Java 8 execution environment was selected. When I chose to use an "Alernate JRE" (still java 8) it fixed the error for me.
View -> Datasets (bottom of menu, above Refresh)
in sys too:
import sys
# its win32, maybe there is win64 too?
is_windows = sys.platform.startswith('win')
To reset the auto increment you have to get your sequence name by using following query.
Syntax:
SELECT pg_get_serial_sequence(‘tablename’, ‘ columnname‘);
Example:
SELECT pg_get_serial_sequence('demo', 'autoid');
The query will return the sequence name of autoid as "Demo_autoid_seq" Then use the following query to reset the autoid
Syntax:
ALTER SEQUENCE sequenceName RESTART WITH value;
Example:
ALTER SEQUENCE "Demo_autoid_seq" RESTART WITH 1453;
Because you are talking about your replacement being anything, and also replacing in the middle of an element's children, it becomes more tricky than just inserting a singular element, or directly removing and appending:
function replaceTargetWith( targetID, html ){
/// find our target
var i, tmp, elm, last, target = document.getElementById(targetID);
/// create a temporary div or tr (to support tds)
tmp = document.createElement(html.indexOf('<td')!=-1?'tr':'div'));
/// fill that div with our html, this generates our children
tmp.innerHTML = html;
/// step through the temporary div's children and insertBefore our target
i = tmp.childNodes.length;
/// the insertBefore method was more complicated than I first thought so I
/// have improved it. Have to be careful when dealing with child lists as
/// they are counted as live lists and so will update as and when you make
/// changes. This is why it is best to work backwards when moving children
/// around, and why I'm assigning the elements I'm working with to `elm`
/// and `last`
last = target;
while(i--){
target.parentNode.insertBefore((elm = tmp.childNodes[i]), last);
last = elm;
}
/// remove the target.
target.parentNode.removeChild(target);
}
example usage:
replaceTargetWith( 'idTABLE', 'I <b>can</b> be <div>anything</div>' );
demo:
By using the .innerHTML
of our temporary div this will generate the TextNodes
and Elements
we need to insert without any hard work. But rather than insert the temporary div itself -- this would give us mark up that we don't want -- we can just scan and insert it's children.
...either that or look to using jQuery and it's replaceWith
method.
jQuery('#idTABLE').replaceWith('<blink>Why this tag??</blink>');
As a response to EL 2002's comment above:
It not always possible. For example, when
createElement('div')
and set its innerHTML as<td>123</td>
, this div becomes<div>123</div>
(js throws away inappropriate td tag)
The above problem obviously negates my solution as well - I have updated my code above accordingly (at least for the td
issue). However for certain HTML this will occur no matter what you do. All user agents interpret HTML via their own parsing rules, but nearly all of them will attempt to auto-correct bad HTML. The only way to achieve exactly what you are talking about (in some of your examples) is to take the HTML out of the DOM entirely, and manipulate it as a string. This will be the only way to achieve a markup string with the following (jQuery will not get around this issue either):
<table><tr>123 text<td>END</td></tr></table>
If you then take this string an inject it into the DOM, depending on the browser you will get the following:
123 text<table><tr><td>END</td></tr></table>
<table><tr><td>END</td></tr></table>
The only question that remains is why you would want to achieve broken HTML in the first place? :)
You can also use wget to »untar it inline«. Simply specify stdout as the output file (-O -
):
wget --no-check-certificate https://github.com/pinard/Pymacs/tarball/v0.24-beta2 -O - | tar xz
Instead of casting to float, you can add 0.0 to the sum:
def avg(l):
return sum(l, 0.0) / len(l)
I find using str.format
much more elegant:
>>> '{0: <5}'.format('s')
's '
>>> '{0: <5}'.format('ss')
'ss '
>>> '{0: <5}'.format('sss')
'sss '
>>> '{0: <5}'.format('ssss')
'ssss '
>>> '{0: <5}'.format('sssss')
'sssss'
If you want to align the string to the right use >
instead of <
:
>>> '{0: >5}'.format('ss')
' ss'
Edit 1:
As mentioned in the comments: the 0
in '{0: <5}'
indicates the argument’s index passed to str.format()
.
Edit 2: In python3 one could use also f-strings:
sub_str='s'
for i in range(1,6):
s = sub_str*i
print(f'{s:>5}')
' s'
' ss'
' sss'
' ssss'
'sssss'
or:
for i in range(1,5):
s = sub_str*i
print(f'{s:<5}')
's '
'ss '
'sss '
'ssss '
'sssss'
of note, in some places above, ' '
(single quotation marks) were added to emphasize the width of the printed strings.
Below is Example of simple dropdown using jstl tag
<form:select path="cityFrom">
<form:option value="Ghaziabad" label="Ghaziabad"/>
<form:option value="Modinagar" label="Modinagar"/>
<form:option value="Meerut" label="Meerut"/>
<form:option value="Amristar" label="Amristar"/>
</form:select>
Yeah it suck to get stuck in Scale View.
Host+Home will popup the Virtual machine settings. (by default Host is Right Control)
From there you can change the view settings, as the Menu bar is hidden in Scale View.
Had the same issue, especially when you checked the box not to show the 'Switch to Scale view' dialog.
This you can do while the VM is running.
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
We use Apache Tika via php (command line utility) with -j for json :
<?php
shell_exec( 'java -jar tika-app-1.4.jar -j http://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying' );
?>
This is a sample output from a random guardian article :
{
"Content-Encoding":"UTF-8",
"Content-Length":205599,
"Content-Type":"text/html; charset\u003dUTF-8",
"DC.date.issued":"2013-07-21",
"X-UA-Compatible":"IE\u003dEdge,chrome\u003d1",
"application-name":"The Guardian",
"article:author":"http://www.guardian.co.uk/profile/nicholaswatt",
"article:modified_time":"2013-07-21T22:42:21+01:00",
"article:published_time":"2013-07-21T22:00:03+01:00",
"article:section":"Politics",
"article:tag":[
"Lynton Crosby",
"Health policy",
"NHS",
"Health",
"Healthcare industry",
"Society",
"Public services policy",
"Lobbying",
"Conservatives",
"David Cameron",
"Politics",
"UK news",
"Business"
],
"content-id":"/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
"dc:title":"Tory strategist Lynton Crosby in new lobbying row | Politics | The Guardian",
"description":"Exclusive: Firm he founded, Crosby Textor, advised private healthcare providers how to exploit NHS \u0027failings\u0027",
"fb:app_id":180444840287,
"keywords":"Lynton Crosby,Health policy,NHS,Health,Healthcare industry,Society,Public services policy,Lobbying,Conservatives,David Cameron,Politics,UK news,Business,Politics",
"msapplication-TileColor":"#004983",
"msapplication-TileImage":"http://static.guim.co.uk/static/a314d63c616d4a06f5ec28ab4fa878a11a692a2a/common/images/favicons/windows_tile_144_b.png",
"news_keywords":"Lynton Crosby,Health policy,NHS,Health,Healthcare industry,Society,Public services policy,Lobbying,Conservatives,David Cameron,Politics,UK news,Business,Politics",
"og:description":"Exclusive: Firm he founded, Crosby Textor, advised private healthcare providers how to exploit NHS \u0027failings\u0027",
"og:image":"https://static-secure.guim.co.uk/sys-images/Guardian/Pix/pixies/2013/7/21/1374433351329/Lynton-Crosby-008.jpg",
"og:site_name":"the Guardian",
"og:title":"Tory strategist Lynton Crosby in new lobbying row",
"og:type":"article",
"og:url":"http://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
"resourceName":"tory-strategist-lynton-crosby-lobbying",
"title":"Tory strategist Lynton Crosby in new lobbying row | Politics | The Guardian",
"twitter:app:id:googleplay":"com.guardian",
"twitter:app:id:iphone":409128287,
"twitter:app:name:googleplay":"The Guardian",
"twitter:app:name:iphone":"The Guardian",
"twitter:app:url:googleplay":"guardian://www.guardian.co.uk/politics/2013/jul/21/tory-strategist-lynton-crosby-lobbying",
"twitter:card":"summary_large_image",
"twitter:site":"@guardian"
}
It is possible to set autofocus
on input elements
<input type="text" class="b_calle" id="b_calle" placeholder="Buscar por nombre de calle" autofocus="autofocus">
I used
chooseCRANmirror(81)
it gives you a prompt to select the country. Then you can do a selection by typing the country mirror code specified there.
my problem was with the accents (á É ñ ) and the plus sign (+) when i to try to save javascript "code examples" to mysql:
my solution (not the better way, but it works):
javascript:
function replaceAll( text, busca, reemplaza ){
while (text.toString().indexOf(busca) != -1)
text = text.toString().replace(busca,reemplaza);return text;
}
function cleanCode(cod){
code = replaceAll(cod , "|", "{1}" ); // error | palos de explode en java
code = replaceAll(code, "+", "{0}" ); // error con los signos mas
return code;
}
function to save:
function save(pid,code){
code = cleanCode(code); // fix sign + and |
code = escape(code); // fix accents
var url = 'editor.php';
var variables = 'op=save';
var myData = variables +'&code='+ code +'&pid='+ pid +'&newdate=' +(new Date()).getTime();
var result = null;
$.ajax({
datatype : "html",
data: myData,
url: url,
success : function(result) {
alert(result); // result ok
},
});
} // end function
function in php:
<?php
function save($pid,$code){
$code= preg_replace("[\{1\}]","|",$code);
$code= preg_replace("[\{0\}]","+",$code);
mysql_query("update table set code= '" . mysql_real_escape_string($code) . "' where pid='$pid'");
}
?>
**i have use kotlin-extension so i can access directly by button id:**
btnSignIN.setOnClickListener {
if (AppUtils.isNetworkAvailable(activity as BaseActivity)) {
if (checkValidation()) {
hitApiLogin()
}
}
}
Under Apache, the limit is a configurable value, LimitRequestLine
. Change this value to something larger than its default of 8190 if you want to support a longer request URI. The value is in /etc/apache2/apache2.conf. If not, add a new line (LimitRequestLine 10000
) under AccessFileName .htaccess
.
However, note that if you're actually running into this limit, you are probably abusing GET
to begin with. You should use POST
to transmit this sort of data -- especially since you even concede that you're using it to update values. If you check the link above, you'll notice that Apache even says "Under normal conditions, the value should not be changed from the default."
My one more reason to choose Node.js for a new project is:
Be able to do pure cloud based development
I have used Cloud9 IDE for a while and now I can't imagine without it, it covers all the development lifecycles. All you need is a browser and you can code anytime anywhere on any devices. You don't need to check in code in one Computer(like at home), then checkout in another computer(like at work place).
Of course, there maybe cloud based IDE for other languages or platforms (Cloud 9 IDE is adding supports for other languages as well), but using Cloud 9 to do Node.js developement is really a great experience for me.
The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
Run: brew info mysql
And follow the instructions. From the description in the formula:
Set up databases to run AS YOUR USER ACCOUNT with:
unset TMPDIR
mysql_install_db --verbose --user=`whoami` --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp
To set up base tables in another folder, or use a different user to run
mysqld, view the help for mysql_install_db:
mysql_install_db --help
and view the MySQL documentation:
* http://dev.mysql.com/doc/refman/5.5/en/mysql-install-db.html
* http://dev.mysql.com/doc/refman/5.5/en/default-privileges.html
Hope this helps.
Have you tried escaping the dot? like this:
String[] words = line.split("\\.");
You can use matplotlib.ticker.funcformatter
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
def func(x, pos): # formatter function takes tick label and tick position
s = '%d' % x
groups = []
while s and s[-1].isdigit():
groups.append(s[-3:])
s = s[:-3]
return s + ','.join(reversed(groups))
y_format = tkr.FuncFormatter(func) # make formatter
x = np.linspace(0,10,501)
y = 1000000*np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
ax.yaxis.set_major_formatter(y_format) # set formatter to needed axis
plt.show()
If you're using Git-Gui, it tells you when you should worry:
This repository currently has approximately 1500 loose objects.
The following command will bring a similar number:
$ git count-objects
Except, from its source, git-gui will do the math by itself, actually counting something at .git/objects
folder and probably brings an approximation (I don't know tcl
to properly read that!).
In any case, it seems to give the warning based on an arbitrary number around 300 loose objects.
The same solution as for Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL? should work - send a CREATE USER …
to \gexec
.
SELECT 'CREATE USER my_user'
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec
echo "SELECT 'CREATE USER my_user' WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec" | psql
See accepted answer there for more details.
astype(str)
!Prior to pandas 1.0 (well, 0.25 actually) this was the defacto way of declaring a Series/column as as string:
# pandas <= 0.25
# Note to pedants: specifying the type is unnecessary since pandas will
# automagically infer the type as object
s = pd.Series(['a', 'b', 'c'], dtype=str)
s.dtype
# dtype('O')
From pandas 1.0 onwards, consider using "string"
type instead.
# pandas >= 1.0
s = pd.Series(['a', 'b', 'c'], dtype="string")
s.dtype
# StringDtype
Here's why, as quoted by the docs:
You can accidentally store a mixture of strings and non-strings in an object dtype array. It’s better to have a dedicated dtype.
object
dtype breaks dtype-specific operations likeDataFrame.select_dtypes()
. There isn’t a clear way to select just text while excluding non-text but still object-dtype columns.When reading code, the contents of an
object
dtype array is less clear than'string'
.
See also the section on Behavioral Differences between "string"
and object
.
Extension types (introduced in 0.24 and formalized in 1.0) are closer to pandas than numpy, which is good because numpy types are not powerful enough. For example NumPy does not have any way of representing missing data in integer data (since type(NaN) == float
). But pandas can using Nullable Integer columns.
Accidentally mixing dtypes
The first reason, as outlined in the docs is that you can accidentally store non-text data in object columns.
# pandas <= 0.25
pd.Series(['a', 'b', 1.23]) # whoops, this should have been "1.23"
0 a
1 b
2 1.23
dtype: object
pd.Series(['a', 'b', 1.23]).tolist()
# ['a', 'b', 1.23] # oops, pandas was storing this as float all the time.
# pandas >= 1.0
pd.Series(['a', 'b', 1.23], dtype="string")
0 a
1 b
2 1.23
dtype: string
pd.Series(['a', 'b', 1.23], dtype="string").tolist()
# ['a', 'b', '1.23'] # it's a string and we just averted some potentially nasty bugs.
Challenging to differentiate strings and other python objects
Another obvious example example is that it's harder to distinguish between "strings" and "objects". Objects are essentially the blanket type for any type that does not support vectorizable operations.
Consider,
# Setup
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [{}, [1, 2, 3], 123]})
df
A B
0 a {}
1 b [1, 2, 3]
2 c 123
Upto pandas 0.25, there was virtually no way to distinguish that "A" and "B" do not have the same type of data.
# pandas <= 0.25
df.dtypes
A object
B object
dtype: object
df.select_dtypes(object)
A B
0 a {}
1 b [1, 2, 3]
2 c 123
From pandas 1.0, this becomes a lot simpler:
# pandas >= 1.0
# Convenience function I call to help illustrate my point.
df = df.convert_dtypes()
df.dtypes
A string
B object
dtype: object
df.select_dtypes("string")
A
0 a
1 b
2 c
Readability
This is self-explanatory ;-)
...No. As of writing this answer (version 1.1), there are no performance benefits but the docs expect future enhancements to significantly improve performance and reduce memory usage for "string"
columns as opposed to objects. With that said, however, it's never too early to form good habits!
Try this
test2.removeAll(test1);
Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.
You can easily build a dictionary style collection...
function getQueryStrings() {
var assoc = {};
var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var queryString = location.search.substring(1);
var keyValues = queryString.split('&');
for(var i in keyValues) {
var key = keyValues[i].split('=');
if (key.length > 1) {
assoc[decode(key[0])] = decode(key[1]);
}
}
return assoc;
}
And use it like this...
var qs = getQueryStrings();
var myParam = qs["myParam"];
Try
$entry = current(array_filter($array, function($e) use($v){ return $e->ID==$v; }));
working example here
If you want to make transparent background is gray, pls try:
.transparent{
background:rgba(1,1,1,0.5);
}
It is because Bootstrap's DEFAULT CSS for <hr />
is ::
hr {
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #eeeeee;
}
it creates 40px gap between those two lines
so if you want to change any particular <hr />
margin style in your page you may try something like this ::
<hr style="margin-bottom:5px !important; margin-top:5px !important; " />
if you want to change appearance/other styles of any particular <hr />
in your page like color and border type or thickness the you may try something like :
<hr style="border-top: 1px dotted #000000 !important; " />
for all <hr />
in your page
<style>
hr {
border-top: 1px dotted #000000 !important;
margin-bottom:5px !important;
margin-top:5px !important;
}
</style>
I was trying to publish my own package and then include it in another project. I had that issue because of how I've built the first module. Im using ES2015 export to create the module, e.g lets say the module looks like that:
export default function(who = 'world'){
return `Hello ${who}`;
}
After compiled with Babel and before been published:
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {
var who = arguments.length <= 0 || arguments[0] === undefined ? 'world' : arguments[0];
return 'Hello ' + who;
};
So after npm install module-name
in another project (none ES2015) i had to do
var hello = require('module-name').default;
To actually got the package imported.
Hope that helps!
I know this might sound silly, but I recently came across this myself, Make sure the domain controller is not read-only.
It should not happen. However, when .NET is under a heavy load, it is possible to get duplicate guids. I have two different web servers using two different sql servers. I went to merge the data and found I had 15 million guids and 7 duplicates.
header('Location: http://linkhere.com/' . $your_variable);
To open at a specific line straight from the command line, use:
less +320123 filename
If you want to see the line numbers too:
less +320123 -N filename
You can also choose to display a specific line of the file at a specific line of the terminal, for when you need a few lines of context. For example, this will open the file with line 320123 on the 10th line of the terminal:
less +320123 -j 10 filename
There seem to be something quirky with the 'automatic' entitlements in Xcode 4.6.
There is an Entitlement.plist file for each SDK at:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk/Entitlements.plist
A workaround solution I came up with was to edit this file and add the sneaky aps-environment key manually like so:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>application-identifier</key>
<string>$(AppIdentifierPrefix)$(CFBundleIdentifier)</string>
<key>aps-environment</key>
<string>development</string>
<key>keychain-access-groups</key>
<array>
<string>$(AppIdentifierPrefix)$(CFBundleIdentifier)</string>
</array>
</dict>
</plist>
Then, Xcode is generating correct Xcent file, which contains the aps-environment key at:
/Users/mySelf/Library/Developer/Xcode/DerivedData/myApp-buauvgusocvjyjcwdtpewdzycfmc/Build/Intermediates/myApp.build/Debug-iphoneos/myApp.build/myApp.xcent
You can locate where your Xcent file is created using Xcode's Log Navigator,
look for "ProcessProductPackaging".
Unfortunately, this is the only way I found that fixes the issue.
(and finally able to properly get push token now)
Just wondering if another more elegant solution is available.
Please see my SO question for more details on that:
Xcode 4.6 automatic entitlement not working - "no valid aps-environment"
Yet another possibility not yet mentioned here is to use NumPy tile:
a = numpy.tile(numpy.nan, (3, 3))
Also gives
array([[ NaN, NaN, NaN],
[ NaN, NaN, NaN],
[ NaN, NaN, NaN]])
I don't know about speed comparison.
It's because you're casting to the wrong thing - you're trying to convert to a particular type, and the object that your express refers to is incompatible with that type. For example:
Object x = "this is a string";
InputStream y = (InputStream) x; // This will throw ClassCastException
If you could provide a code sample, that would really help...
public enum EXIT_CODE {
A(104), B(203);
private int numVal;
EXIT_CODE(int numVal) {
this.numVal = numVal;
}
public int getNumVal() {
return numVal;
}
}
UPDATED
I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/
Also, I've changed two ^=
to *=
. See http://api.jquery.com/category/selectors/
And note the :checked
selector. See http://api.jquery.com/checked-selector/
function createcodes() {
//run through each row
$('.authors-list tr').each(function (i, row) {
// reference all the stuff you need first
var $row = $(row),
$family = $row.find('input[name*="family"]'),
$grade = $row.find('input[name*="grade"]'),
$checkedBoxes = $row.find('input:checked');
$checkedBoxes.each(function (i, checkbox) {
// assuming you layout the elements this way,
// we'll take advantage of .next()
var $checkbox = $(checkbox),
$line = $checkbox.next(),
$size = $line.next();
$line.val(
$family.val() + ' ' + $size.val() + ', ' + $grade.val()
);
});
});
}
Try fopen() http://www.php.net/manual/en/function.fopen.php
w as mode will truncate the file.
You can get path by this code
Dim CurDir as string = My.Application.Info.DirectoryPath
Just use substring: "apple".substring(3);
will return le
I ran into the same issue while trying to open the solution on a network share. No unit test would be detected by Test Explorer in this case. The solution turns out to be:
Control Panel -> Internet Options -> "Security" Tab -> Click "Intranet" and add the server IP address or host name holding the network share to the "Sites" list.
After doing this, I recompiled the solution and now tests appeared. This should be quite similar to the answer made by @BigT.
Steps
Create a new Activity, for your player(fullscreen) screen with menu options. Run the mediaplayer and UI in different threads.
For playing media - In general to play audio/video there is mediaplayer api in android. FILE_PATH is the path of file - may be url(youtube) stream or local file path
MediaPlayer mp = new MediaPlayer(); mp.setDataSource(FILE_PATH); mp.prepare(); mp.start();
Also check: Android YouTube app Play Video Intent have already discussed this in detail.
If the object that needs access to the container is a bean in the container, just implement the BeanFactoryAware or ApplicationContextAware interfaces.
If an object outside the container needs access to the container, I've used a standard GoF singleton pattern for the spring container. That way, you only have one singleton in your application, the rest are all singleton beans in the container.
public function updtitle()
{
$data = array(
'table_name' => 'your_table_name_to_update', // pass the real table name
'id' => $this->input->post('id'),
'title' => $this->input->post('title')
);
$this->load->model('Updmodel'); // load the model first
if($this->Updmodel->upddata($data)) // call the method from the model
{
// update successful
}
else
{
// update not successful
}
}
public function upddata($data) {
extract($data);
$this->db->where('emp_no', $id);
$this->db->update($table_name, array('title' => $title));
return true;
}
The active record query is similar to
"update $table_name set title='$title' where emp_no=$id"
For a production system, you can use this configuration :
--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT CONNECT ON DATABASE nova TO user;
--ACCESS SCHEMA
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO user;
--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL ON ALL TABLES IN SCHEMA public TO admin ;
Quick and dirty way:
<View
android:id="@+id/colored_bar"
android:layout_width="48dp"
android:layout_height="3dp"
android:background="@color/bar_red" />
This is not the best way to do it the better answers are above. This is just another way to check it by using Android Logs. Put them all in this helps to catch parsing errors.
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call,
Response<JsonObject> response) {
// Catching Responses From Retrofit
Log.d("TAG", "onResponseisSuccessful: "+response.isSuccessful());
Log.d("TAG", "onResponsebody: "+response.body());
Log.d("TAG", "onResponseerrorBody: "+response.errorBody());
Log.d("TAG", "onResponsemessage: "+response.message());
Log.d("TAG", "onResponsecode: "+response.code());
Log.d("TAG", "onResponseheaders: "+response.headers());
Log.d("TAG", "onResponseraw: "+response.raw());
Log.d("TAG", "onResponsetoString: "+response.toString());
}
@Override
public void onFailure(Call<JsonObject> call,
Throwable t) {
Log.d("TAG", "onFailuregetLocalizedMessage: " +t.getLocalizedMessage());
Log.d("TAG", "onFailuregetMessage: " +t.getMessage());
Log.d("TAG", "onFailuretoString: " +t.toString());
Log.d("TAG", "onFailurefillInStackTrace: " +t.fillInStackTrace());
Log.d("TAG", "onFailuregetCause: " +t.getCause());
Log.d("TAG", "onFailuregetStackTrace: " + Arrays.toString(t.getStackTrace()));
Log.d("TAG", "getSuppressed: " + Arrays.toString(t.getSuppressed()));
}
});
I don't know if this is what you are looking for, but you can achieve this by passing a callback to the child class.
first define a generic callback:
public interface ITypedCallback<T> {
void execute(T type);
}
create a new ITypedCallback instance on ServerConnections instantiation:
public Server(int _address) {
serverConnectionHandler = new ServerConnections(new ITypedCallback<Socket>() {
@Override
public void execute(Socket socket) {
// do something with your socket here
}
});
}
call the execute methode on the callback object.
public class ServerConnections implements Runnable {
private ITypedCallback<Socket> callback;
public ServerConnections(ITypedCallback<Socket> _callback) {
callback = _callback;
}
@Override
public void run() {
try {
mainSocket = new ServerSocket(serverPort);
while (true) {
callback.execute(mainSocket.accept());
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
btw: I didn't check if it's 100% correct, directly coded it here.
You should do:
#include<iostream>
using namespace std;
int main ()
{
int sum = 0;
int number;
int numberitems;
cout << "Enter number of items: \n";
cin >> numberitems;
for(int i=0;i<numberitems;i++)
{
cout << "Enter number <<i<<":" \n";
cin >> number; sum+=number;
}
cout<<"sum is: "<< sum<<endl;
}
And with a while statement
#include <iostream>
using namespace std;
int main ()
{
int sum = 0;
int number;
int numberitems;
cin>>numberitems;
cout << "Enter number: \n";
while (count <=numberitems)
{
cin >> number;
sum+=number;
}
cout << sum << endl;
}
If anyone else stuck on same point, following solved my problem.
In web.xml
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
In Session component
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
In pom.xml
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.1</version>
</dependency>
getting username in MAC terminal is easy...
I generally use whoami
in terminal...
For example, in this case, I needed that to install Tomcat Server...
You have to add your jquery script to your chrome-extension project and to the background
section of your manifest.json like this :
"background":
{
"scripts": ["thirdParty/jquery-2.0.3.js", "background.js"]
}
If you need jquery in a content_scripts, you have to add it in the manifest too:
"content_scripts":
[
{
"matches":["http://website*"],
"js":["thirdParty/jquery.1.10.2.min.js", "script.js"],
"css": ["css/style.css"],
"run_at": "document_end"
}
]
This is what I did.
Also, if I recall correctly, the background scripts are executed in a background window that you can open via chrome://extensions
.
find_elements_by_xpath("//*[@class='class name']")
is a great solution
jQuery.fn.extend({
getStyles: function() {
var rulesUsed = [];
var sheets = document.styleSheets;
for (var c = 0; c < sheets.length; c++) {
var rules = sheets[c].rules || sheets[c].cssRules;
for (var r = 0; r < rules.length; r++) {
var selectorText = rules[r].selectorText.toLowerCase().replace(":hover","");
if (this.is(selectorText) || this.find(selectorText).length > 0) {
rulesUsed.push(rules[r]);
}
}
}
var style = rulesUsed.map(function(cssRule) {
return cssRule.selectorText.toLowerCase() + ' { ' + cssRule.style.cssText.toLowerCase() + ' }';
}).join("\n");
return style;
}
});
usage:
$("#login_wrapper").getStyles()
If you're using PDO:
$offset="+10:00";
$db->exec("SET time_zone='".$offset."';");
If you're using MySQLi:
$db->MySQLi->query("SET time_zone='".$offset."';");
More about formatting the offset here: https://www.sitepoint.com/synchronize-php-mysql-timezone-configuration/
For your interest, to do the same with double
double doubleVal = 1.745;
double doubleVal2 = 0.745;
doubleVal = Math.round(doubleVal * 100 + 0.005) / 100.0;
doubleVal2 = Math.round(doubleVal2 * 100 + 0.005) / 100.0;
System.out.println("bdTest: " + doubleVal); //1.75
System.out.println("bdTest1: " + doubleVal2);//0.75
or just
double doubleVal = 1.745;
double doubleVal2 = 0.745;
System.out.printf("bdTest: %.2f%n", doubleVal);
System.out.printf("bdTest1: %.2f%n", doubleVal2);
both print
bdTest: 1.75
bdTest1: 0.75
I prefer to keep code as simple as possible. ;)
As @mshutov notes, you need to add a little more to ensure that a half value always rounds up. This is because numbers like 265.335
are a little less than they appear.
The code that you have would work, but is executed from the global context, which means that this
refers to the global object.
<script type="text/javascript">
var foo = function(param) {
param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>
You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this
.
<script type="text/javascript">
document.getElementById('bar').onclick = function() {
this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>
dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);
The parameter TRUE preserve the changes.
For more details refer to MSDN.
You have a dash in the middle of the character class, which will mean a character range. Put the dash at the end of the class like so:
[$&+,:;=?@#|'<>.^*()%!-]
I would have done using just single line like
List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(file => new string[] { ".jpg", ".gif", ".png" }
.Contains(Path.GetExtension(file)))
.ToList();
TTFB is something that happens behind the scenes. Your browser knows nothing about what happens behind the scenes.
You need to look into what queries are being run and how the website connects to the server.
This article might help understand TTFB, but otherwise you need to dig deeper into your application.
You have to self join stuff and match name and city. Then group by count.
select
s.id, s.name, s.city
from stuff s join stuff p ON (
s.name = p.city OR s.city = p.name
)
group by s.name having count(s.name) > 1
Try this too
$url = 'http://www.domain.com/';
$html = file_get_contents($url);
//Change encoding to UTF-8 from ISO-8859-1
$html = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $html);
This is an Android 8 update.
In earlier version of Android, to LoadLibrary native shared libraries (for access via JNI for example) I hard-wired my native code to iterate through a range of potential directory paths for the lib folder, based on the various apk installation/upgrade algorithms:
/data/data/<PackageName>/lib
/data/app-lib/<PackageName>-1/lib
/data/app-lib/<PackageName>-2/lib
/data/app/<PackageName>-1/lib
/data/app/<PackageName>-2/lib
This approach is hokey and will not work for Android 8; from https://developer.android.com/about/versions/oreo/android-8.0-changes.html you'll see that as part of their "Security" changes you now need to use sourceDir:
"You can no longer assume that APKs reside in directories whose names end in -1 or -2. Apps should use sourceDir to get the directory, and not rely on the directory format directly."
Correction, sourceDir is not the way to find your native shared libraries; use something like. Tested for Android 4.4.4 --> 8.0
// Return Full path to the directory where native JNI libraries are stored.
private static String getNativeLibraryDir(Context context) {
ApplicationInfo appInfo = context.getApplicationInfo();
return appInfo.nativeLibraryDir;
}
Here is a variant for dynamically adding a class
function setClassStyle(class_name, css) {
var style_sheet = document.createElement('style');
if (style_sheet) {
style_sheet.setAttribute('type', 'text/css');
var cstr = '.' + class_name + ' {' + css + '}';
var rules = document.createTextNode(cstr);
if(style_sheet.styleSheet){// IE
style_sheet.styleSheet.cssText = rules.nodeValue;
} else {
style_sheet.appendChild(rules);
}
var head = document.getElementsByTagName('head')[0];
if (head) {
head.appendChild(style_sheet);
}
}
}
I also needed this and wrote a function for parsing attributes, you can get it from here:
https://gist.github.com/4153580
(Note: It doesn't use regex)
Bernhard's answer needed some tweaking work for me because the %DATE% environment variable is in a different format (as commented elsewhere). Also, there was a tilde (~) missing.
Instead of:
set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:0,2%
I had to use:
set backupFilename=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%
for the date format:
c:\Scripts>echo %DATE%
Thu 05/14/2009
Set the UINavigationControllerDelegate and implement this delegate func (Swift):
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
if viewController is <target class> {
//if the only way to get back - back button was pressed
}
}
I've had some success with HtmlUnit, in Java. It's a simple framework for writing unit tests on web UI's, but equally useful for HTML scraping.
This is using the :hover
pseudoelement in CSS3.
HTML:
<div id="wrapper">
<img src="http://placehold.it/300x200" class="hover" />
<p class="text">text</p>
</div>?
CSS:
#wrapper .text {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}
#wrapper:hover .text {
visibility:visible;
}
?Demo HERE.
This instead is a way of achieving the same result by using jquery:
HTML:
<div id="wrapper">
<img src="http://placehold.it/300x200" class="hover" />
<p class="text">text</p>
</div>?
CSS:
#wrapper p {
position:relative;
bottom:30px;
left:0px;
visibility:hidden;
}
jquery code:
$('.hover').mouseover(function() {
$('.text').css("visibility","visible");
});
$('.hover').mouseout(function() {
$('.text').css("visibility","hidden");
});
You can put the jquery code where you want, in the body of the HTML page, then you need to include the jquery library in the head like this:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
You can see the demo HERE.
When you want to use it on your website, just change the <img src />
value and you can add multiple images and captions, just copy the format i used: insert image with class="hover"
and p with class="text"
Here's a quick and dirty example of how a class could fire different versions of a save method depending on which operating system it's being executed on using getattr()
.
import os
class Log(object):
def __init__(self):
self.os = os.name
def __getattr__(self, name):
""" look for a 'save' attribute, or just
return whatever attribute was specified """
if name == 'save':
try:
# try to dynamically return a save
# method appropriate for the user's system
return getattr(self, self.os)
except:
# bail and try to return
# a default save method
return getattr(self, '_save')
else:
return getattr(self, name)
# each of these methods could have save logic specific to
# the system on which the script is executed
def posix(self): print 'saving on a posix machine'
def nt(self): print 'saving on an nt machine'
def os2(self): print 'saving on an os2 machine'
def ce(self): print 'saving on a ce machine'
def java(self): print 'saving on a java machine'
def riscos(self): print 'saving on a riscos machine'
def _save(self): print 'saving on an unknown operating system'
def which_os(self): print os.name
Now let's use this class in an example:
logger = Log()
# Now you can do one of two things:
save_func = logger.save
# and execute it, or pass it along
# somewhere else as 1st class:
save_func()
# or you can just call it directly:
logger.save()
# other attributes will hit the else
# statement and still work as expected
logger.which_os()
try this
var radio_button=false;_x000D_
$('.radio-button').on("click", function(event){_x000D_
var this_input=$(this);_x000D_
if(this_input.attr('checked1')=='11') {_x000D_
this_input.attr('checked1','11')_x000D_
} else {_x000D_
this_input.attr('checked1','22')_x000D_
}_x000D_
$('.radio-button').prop('checked', false);_x000D_
if(this_input.attr('checked1')=='11') {_x000D_
this_input.prop('checked', false);_x000D_
this_input.attr('checked1','22')_x000D_
} else {_x000D_
this_input.prop('checked', true);_x000D_
this_input.attr('checked1','11')_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
If you are using the Eclipse ADT plugin for your development, open AndroidManifest.xml
in the Android Manifest Editor (should be the default action for opening AndroidManifest.xml
from the project files list).
Afterwards, select the Permissions
tab along the bottom of the editor (Manifest - Application - Permissions - Instrumentation - AndroidManifest.xml
), then click Add...
a Uses Permission
and select the desired permission from the dropdown on the right, or just copy-paste in the necessary one (such as the android.permission.INTERNET
permission you required).
/*------------------------------------------------------------------
Defining Stack Operations using Closures in Javascript, privacy and
state of stack operations are maintained
@author:Arijt Basu
Log: Sun Dec 27, 2015, 3:25PM
-------------------------------------------------------------------
*/
var stackControl = true;
var stack = (function(array) {
array = [];
//--Define the max size of the stack
var MAX_SIZE = 5;
function isEmpty() {
if (array.length < 1) console.log("Stack is empty");
};
isEmpty();
return {
push: function(ele) {
if (array.length < MAX_SIZE) {
array.push(ele)
return array;
} else {
console.log("Stack Overflow")
}
},
pop: function() {
if (array.length > 1) {
array.pop();
return array;
} else {
console.log("Stack Underflow");
}
}
}
})()
// var list = 5;
// console.log(stack(list))
if (stackControl) {
console.log(stack.pop());
console.log(stack.push(3));
console.log(stack.push(2));
console.log(stack.pop());
console.log(stack.push(1));
console.log(stack.pop());
console.log(stack.push(38));
console.log(stack.push(22));
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.push(6));
console.log(stack.pop());
}
//End of STACK Logic
/* Defining Queue operations*/
var queue = (function(array) {
array = [];
var reversearray;
//--Define the max size of the stack
var MAX_SIZE = 5;
function isEmpty() {
if (array.length < 1) console.log("Queue is empty");
};
isEmpty();
return {
insert: function(ele) {
if (array.length < MAX_SIZE) {
array.push(ele)
reversearray = array.reverse();
return reversearray;
} else {
console.log("Queue Overflow")
}
},
delete: function() {
if (array.length > 1) {
//reversearray = array.reverse();
array.pop();
return array;
} else {
console.log("Queue Underflow");
}
}
}
})()
console.log(queue.insert(5))
console.log(queue.insert(3))
console.log(queue.delete(3))
I saw an interesting post from Ikraider here that solved my issue : https://github.com/docker/docker/issues/22599
Website instructions are wrong, here is what works in 16.04:
curl -s https://yum.dockerproject.org/gpg | sudo apt-key add
apt-key fingerprint 58118E89F3A912897C070ADBF76221572C52609D
sudo add-apt-repository "deb https://apt.dockerproject.org/repo ubuntu-$(lsb_release -cs) main"
sudo apt-get update
sudo apt-get install docker-engine=1.13.0-0~ubuntu-xenial
The main differences between github and gists are in terms of number of features and user interface:
One is designed with a great number of features and flexibility in mind, which is a good fit for both small and very big projects, while gists are only a good fit for very small projects.
For example, gists do support multi-files, but the interface is very simple, and they're limited in features, so they don't even have a file browser, nor issues, pull requests or wiki. If you dont need to have that, gists are very nice and more discrete. Like the comments, instead of answers, in SO.
Note: Thanks to @Qwerty for the suggestion of making my comment a real answer.
For Windows, you can find the file in the C:\xampp\php\php.ini
-Folder (Windows) or in the etc
-Folder (within the xampp-Folder).
Under Linux, most distributions put lampp under /opt/lampp
, so the file can be found under /opt/lampp/etc/php.ini
.
It can be edited using a normal Text-Editor.
Clarification:
Xampp
(X (for "some OS"), Apache, MySQL, Perl, PHP)Lampp
(Linux, Apache, MySQL, Perl, PHP)in this context, they can be substituted for one another.
There are a number of tools available which help debugging segmentation faults and I would like to add my favorite tool to the list: Address Sanitizers (often abbreviated ASAN).
Modern¹ compilers come with the handy -fsanitize=address
flag, adding some compile time and run time overhead which does more error checking.
According to the documentation these checks include catching segmentation faults by default. The advantage here is that you get a stack trace similar to gdb's output, but without running the program inside a debugger. An example:
int main() {
volatile int *ptr = (int*)0;
*ptr = 0;
}
$ gcc -g -fsanitize=address main.c
$ ./a.out
AddressSanitizer:DEADLYSIGNAL
=================================================================
==4848==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x5654348db1a0 bp 0x7ffc05e39240 sp 0x7ffc05e39230 T0)
==4848==The signal is caused by a WRITE memory access.
==4848==Hint: address points to the zero page.
#0 0x5654348db19f in main /tmp/tmp.s3gwjqb8zT/main.c:3
#1 0x7f0e5a052b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
#2 0x5654348db099 in _start (/tmp/tmp.s3gwjqb8zT/a.out+0x1099)
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /tmp/tmp.s3gwjqb8zT/main.c:3 in main
==4848==ABORTING
The output is slightly more complicated than what gdb would output but there are upsides:
There is no need to reproduce the problem to receive a stack trace. Simply enabling the flag during development is enough.
ASANs catch a lot more than just segmentation faults. Many out of bounds accesses will be caught even if that memory area was accessible to the process.
¹ That is Clang 3.1+ and GCC 4.8+.
time()
has better precision than clock()
on Linux. clock()
only has precision less than 10 ms. While time()
gives prefect precision.
My test is on CentOS 6.4, python 2.6
using time():
1 requests, response time: 14.1749382019 ms
2 requests, response time: 8.01301002502 ms
3 requests, response time: 8.01491737366 ms
4 requests, response time: 8.41021537781 ms
5 requests, response time: 8.38804244995 ms
using clock():
1 requests, response time: 10.0 ms
2 requests, response time: 0.0 ms
3 requests, response time: 0.0 ms
4 requests, response time: 10.0 ms
5 requests, response time: 0.0 ms
6 requests, response time: 0.0 ms
7 requests, response time: 0.0 ms
8 requests, response time: 0.0 ms
In python 3 you can use os.scandir():
for i in os.scandir(path):
if i.is_file():
print('File: ' + i.path)
elif i.is_dir():
print('Folder: ' + i.path)
Here is an article that explains the problem and solution with alot more detail:
Sorting Locked Cells in Protected Worksheets
The thing to understand is that the purpose of locking cells is to prevent them from being changed, and sorting permanently changes cell values. You can write a macro, but a much better solution is to use the "Allow Users to Edit Ranges" feature. This makes the cells editable so sorting can work, but because the cells are still technically locked you can prevent users from selecting them.
To capitalize on the answer of Alex D, using refinements:
module CoreExtensions
module Integerable
refine String do
def integer?
Integer(self)
rescue ArgumentError
false
else
true
end
end
end
end
Later, in you class:
require 'core_ext/string/integerable'
class MyClass
using CoreExtensions::Integerable
def method
'my_string'.integer?
end
end
I know this is a quite old question, but when you have JavaScript available you could use jQuery and its AJAX methods.
First, create a page with all the navigation bar's HTML content.
Next, use jQuery's $.get
method to fetch the content of the page. For example, let's say you've put all the navigation bar's HTML into a file called navigation.html
and added a placeholder tag (Like <div id="nav-placeholder">
) in your index.html
, then you would use the following code:
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$.get("navigation.html", function(data){
$("#nav-placeholder").replaceWith(data);
});
</script>
You will have to create an auto-increment field with the sequence object (this object generates a number sequence).
Use the following CREATE SEQUENCE syntax:
CREATE SEQUENCE seq_person
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10
The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.
To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):
INSERT INTO Persons (P_Id,FirstName,LastName)
VALUES (seq_person.nextval,'Lars','Monsen')
The SQL statement above would insert a new record into the "Persons" table. The "P_Id" column would be assigned the next number from the seq_person sequence. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".
This may not solve all of your problems, but the variable you are using inside your function (text) is not the same as the parameter you are passing in (x).
Changing:
function textreplace(x) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
To:
function textreplace(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
seems like it would do some good.
If you want to do it in a tidyverse
manner, try add_column
from tibble
, which allows you to specifiy where to place the new column with .before
or .after
parameter:
library(tibble)
df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
add_column(df, a = 0, .before = 1)
# a b c d
# 1 0 1 2 3
# 2 0 1 2 3
# 3 0 1 2 3
I just found a pretty neat solution, I think. The trick is to set the line-height
of image (or any content) height
.
Using CSS:
div{
line-height: 26px; /* height of the image in #submit span:after */
}
span:after{
content: url('images/forward.png');
vertical-align: bottom;
}
That would probably also work without the span.
Server id should match with the repository id of maven settings.xml
Since the question on how to convert from ISO-8859-1 to UTF-8 is closed because of this one I'm going to post my solution here.
The problem is when you try to GET anything by using XMLHttpRequest, if the XMLHttpRequest.responseType is "text" or empty, the XMLHttpRequest.response is transformed to a DOMString and that's were things break up. After, it's almost impossible to reliably work with that string.
Now, if the content from the server is ISO-8859-1 you'll have to force the response to be of type "Blob" and later convert this to DOMSTring. For example:
var ajax = new XMLHttpRequest();
ajax.open('GET', url, true);
ajax.responseType = 'blob';
ajax.onreadystatechange = function(){
...
if(ajax.responseType === 'blob'){
// Convert the blob to a string
var reader = new window.FileReader();
reader.addEventListener('loadend', function() {
// For ISO-8859-1 there's no further conversion required
Promise.resolve(reader.result);
});
reader.readAsBinaryString(ajax.response);
}
}
Seems like the magic is happening on readAsBinaryString so maybe someone can shed some light on why this works.
In addition to the existing answer it is possible to set a default option as follows:
echo off
ECHO A current build of Test Harness exists.
set delBuild=n
set /p delBuild=Delete preexisting build [y/n] (default - %delBuild%)?:
This allows users to simply hit "Enter" if they want to enter the default.
This answer is heavily influenced by a conversation here: http://www.tek-tips.com/viewthread.cfm?qid=1395151&page=3
ALTER SYSTEM ENABLE RESTRICTED SESSION;
begin
for x in (
select Sid, Serial#, machine, program
from v$session
where
machine <> 'MyDatabaseServerName'
) loop
execute immediate 'Alter System Kill Session '''|| x.Sid
|| ',' || x.Serial# || ''' IMMEDIATE';
end loop;
end;
I skip killing sessions originating on the database server to avoid killing off Oracle's connections to itself.
We can use the new fs.promises API
const fs = require('fs').promises;
(async() => {
const stat = await fs.lstat('test.txt');
console.log(stat.isFile());
})().catch(console.error)
Here's how you would detect if a path is a file or a directory asynchronously, which is the recommended approach in node. using fs.lstat
const fs = require("fs");
let path = "/path/to/something";
fs.lstat(path, (err, stats) => {
if(err)
return console.log(err); //Handle error
console.log(`Is file: ${stats.isFile()}`);
console.log(`Is directory: ${stats.isDirectory()}`);
console.log(`Is symbolic link: ${stats.isSymbolicLink()}`);
console.log(`Is FIFO: ${stats.isFIFO()}`);
console.log(`Is socket: ${stats.isSocket()}`);
console.log(`Is character device: ${stats.isCharacterDevice()}`);
console.log(`Is block device: ${stats.isBlockDevice()}`);
});
Note when using the synchronous API:
When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up.
try{
fs.lstatSync("/some/path").isDirectory()
}catch(e){
// Handle error
if(e.code == 'ENOENT'){
//no such file or directory
//do something
}else {
//do something else
}
}
git reset --soft
is just for that: it is like git reset --hard
, but doesn't touch the files.
You can use the following two functions so as to avoid writing a wrapper for each new function:
import itertools
from multiprocessing import Pool
def universal_worker(input_pair):
function, args = input_pair
return function(*args)
def pool_args(function, *args):
return zip(itertools.repeat(function), zip(*args))
Use the function function
with the lists of arguments arg_0
, arg_1
and arg_2
as follows:
pool = Pool(n_core)
list_model = pool.map(universal_worker, pool_args(function, arg_0, arg_1, arg_2)
pool.close()
pool.join()
This answer applies to this question if
path below can be relative
PYTHONPATH=/path/to/dir python script.py
You can do this two options:
I personally use a tooltip to display additional information, so when someone hovers over the event they can view a longer descriptions. This example uses qTip, but any tooltip implementation would work.
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev, next today',
center: 'title',
right: 'month, basicWeek, basicDay'
},
//events: "Calendar.asmx/EventList",
//defaultView: 'dayView',
events: [
{
title: 'All Day Event',
start: new Date(y, m, 1),
description: 'long description',
id: 1
},
{
title: 'Long Event',
start: new Date(y, m, d - 5),
end: new Date(y, m, 1),
description: 'long description3',
id: 2
}],
eventRender: function(event, element) {
element.qtip({
content: event.description + '<br />' + event.start,
style: {
background: 'black',
color: '#FFFFFF'
},
position: {
corner: {
target: 'center',
tooltip: 'bottomMiddle'
}
}
});
}
});
});
You try to access private member of one class from another. The fact that bar-class is declared within foo-class means that bar in visible only inside foo class, but that is still other class.
And what is p->param?
Actually, it isn't clear what do you want to do
Even though this was answered/accepted years ago, the presently accepted answer is only correct for one-byte-per-character encodings like iso-8859-1, or for the single-byte subsets of variable-byte character sets (like Latin characters within UTF-8). Even using multiple-byte splices instead would still only work for fixed-multibyte encodings like UTF-16. Given that now UTF-8 is well on its way to being a universal standard, and when looking at this list of languages by number of native speakers and this list of top 30 languages by native/secondary usage, it is important to point out a simple variable-byte character-friendly (not byte-based) technique, using cut -c
and tr
/sed
with character-classes.
Compare the following which doubly fails due to two common Latin-centric mistakes/presumptions regarding the bytes vs. characters issue (one is head
vs. cut
, the other is [a-z][A-Z]
vs. [:upper:][:lower:]
):
$ printf '??? µp??? ?a µ??? sa?s???t???;\n' | \
$ head -c 1 | \
$ sed -e 's/[A-Z]/[a-z]/g'
[[unreadable binary mess, or nothing if the terminal filtered it]]
to this (note: this worked fine on FreeBSD, but both cut
& tr
on GNU/Linux still mangled Greek in UTF-8 for me though):
$ printf '??? µp??? ?a µ??? sa?s???t???;\n' | \
$ cut -c 1 | \
$ tr '[:upper:]' '[:lower:]'
p
Another more recent answer had already proposed "cut", but only because of the side issue that it can be used to specify arbitrary offsets, not because of the directly relevant character vs. bytes issue.
If your cut
doesn't handle -c
with variable-byte encodings correctly, for "the first X
characters" (replace X
with your number) you could try:
sed -E -e '1 s/^(.{X}).*$/\1/' -e q
- which is limited to the first line thoughhead -n 1 | grep -E -o '^.{X}'
- which is limited to the first line and chains two commands thoughdd
- which has already been suggested in other answers, but is really cumbersomesed
script with sliding window buffer to handle characters spread over multiple lines, but that is probably more cumbersome/fragile than just using something like dd
If your tr
doesn't handle character-classes with variable-byte encodings correctly you could try:
sed -E -e 's/[[:upper:]]/\L&/g
(GNU-specific)First of all, IQueryable<T>
extends the IEnumerable<T>
interface, so anything you can do with a "plain" IEnumerable<T>
, you can also do with an IQueryable<T>
.
IEnumerable<T>
just has a GetEnumerator()
method that returns an Enumerator<T>
for which you can call its MoveNext()
method to iterate through a sequence of T.
What IQueryable<T>
has that IEnumerable<T>
doesn't are two properties in particular—one that points to a query provider (e.g., a LINQ to SQL provider) and another one pointing to a query expression representing the IQueryable<T>
object as a runtime-traversable abstract syntax tree that can be understood by the given query provider (for the most part, you can't give a LINQ to SQL expression to a LINQ to Entities provider without an exception being thrown).
The expression can simply be a constant expression of the object itself or a more complex tree of a composed set of query operators and operands. The query provider's IQueryProvider.Execute()
or IQueryProvider.CreateQuery()
methods are called with an Expression passed to it, and then either a query result or another IQueryable
is returned, respectively.
Here to show equivalent implementation of a flatMap using subscribes.
Without flatMap:
this.searchField.valueChanges.debounceTime(400)
.subscribe(
term => this.searchService.search(term)
.subscribe( results => {
console.log(results);
this.result = results;
}
);
);
With flatMap:
this.searchField.valueChanges.debounceTime(400)
.flatMap(term => this.searchService.search(term))
.subscribe(results => {
console.log(results);
this.result = results;
});
http://plnkr.co/edit/BHGmEcdS5eQGX703eRRE?p=preview
Hope it could help.
Olivier.
This should fix a few edge-cases in kobe's answer:
function getQueryParam(url, key) {
var queryStartPos = url.indexOf('?');
if (queryStartPos === -1) {
return;
}
var params = url.substring(queryStartPos + 1).split('&');
for (var i = 0; i < params.length; i++) {
var pairs = params[i].split('=');
if (decodeURIComponent(pairs.shift()) == key) {
return decodeURIComponent(pairs.join('='));
}
}
}
getQueryParam('http://example.com/form_image_edit.php?img_id=33', 'img_id');
// outputs "33"
If you want to use ArrayList or LinkedList, it seems that the answer is no. Although there are some classes in java that you can set them fixed size, like PriorityQueue, ArrayList and LinkedList can't, because there is no constructor for these two to specify capacity.
If you want to stick to ArrayList/LinkedList, one easy solution is to check the size manually each time.
public void fixedAdd(List<Integer> list, int val, int size) {
list.add(val);
if(list.size() > size) list.remove(0);
}
LinkedList is better than ArrayList in this situation. Suppose there are many values to be added but the list size is quite samll, there will be many remove operations. The reason is that the cost of removing from ArrayList is O(N), but only O(1) for LinkedList.
%d
prints an integer: it will print the ascii representation of your character. What you need is %c
:
printf("%c", ch);
printf("%d", '\0');
prints the ascii representation of '\0'
, which is 0 (by escaping 0 you tell the compiler to use the ascii value 0.
printf("%d", sizeof('\n'));
prints 4 because a character literal is an int
, in C, and not a char
.
Just like that nice warning you got, you are trying to do something that is an Anti-Pattern in React. This is a no-no. React is intended to have an unmount happen from a parent to child relationship. Now if you want a child to unmount itself, you can simulate this with a state change in the parent that is triggered by the child. let me show you in code.
class Child extends React.Component {
constructor(){}
dismiss() {
this.props.unmountMe();
}
render(){
// code
}
}
class Parent ...
constructor(){
super(props)
this.state = {renderChild: true};
this.handleChildUnmount = this.handleChildUnmount.bind(this);
}
handleChildUnmount(){
this.setState({renderChild: false});
}
render(){
// code
{this.state.renderChild ? <Child unmountMe={this.handleChildUnmount} /> : null}
}
}
this is a very simple example. but you can see a rough way to pass through to the parent an action
That being said you should probably be going through the store (dispatch action) to allow your store to contain the correct data when it goes to render
I've done error/status messages for two separate applications, both went through the store. It's the preferred method... If you'd like I can post some code as to how to do that.
Few things to note first. this is in typescript so you would need to remove the type declarations :)
I am using the npm packages lodash for operations, and classnames (cx alias) for inline classname assignment.
The beauty of this setup is I use a unique identifier for each notification when the action creates it. (e.g. notify_id). This unique ID is a Symbol()
. This way if you want to remove any notification at any point in time you can because you know which one to remove. This notification system will let you stack as many as you want and they will go away when the animation is completed. I am hooking into the animation event and when it finishes I trigger some code to remove the notification. I also set up a fallback timeout to remove the notification just in case the animation callback doesn't fire.
import { USER_SYSTEM_NOTIFICATION } from '../constants/action-types';
interface IDispatchType {
type: string;
payload?: any;
remove?: Symbol;
}
export const notifySuccess = (message: any, duration?: number) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: true, message, notify_id: Symbol(), duration } } as IDispatchType);
};
};
export const notifyFailure = (message: any, duration?: number) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: false, message, notify_id: Symbol(), duration } } as IDispatchType);
};
};
export const clearNotification = (notifyId: Symbol) => {
return (dispatch: Function) => {
dispatch({ type: USER_SYSTEM_NOTIFICATION, remove: notifyId } as IDispatchType);
};
};
const defaultState = {
userNotifications: []
};
export default (state: ISystemNotificationReducer = defaultState, action: IDispatchType) => {
switch (action.type) {
case USER_SYSTEM_NOTIFICATION:
const list: ISystemNotification[] = _.clone(state.userNotifications) || [];
if (_.has(action, 'remove')) {
const key = parseInt(_.findKey(list, (n: ISystemNotification) => n.notify_id === action.remove));
if (key) {
// mutate list and remove the specified item
list.splice(key, 1);
}
} else {
list.push(action.payload);
}
return _.assign({}, state, { userNotifications: list });
}
return state;
};
in the base render for your application you would render the notifications
render() {
const { systemNotifications } = this.props;
return (
<div>
<AppHeader />
<div className="user-notify-wrap">
{ _.get(systemNotifications, 'userNotifications') && Boolean(_.get(systemNotifications, 'userNotifications.length'))
? _.reverse(_.map(_.get(systemNotifications, 'userNotifications', []), (n, i) => <UserNotification key={i} data={n} clearNotification={this.props.actions.clearNotification} />))
: null
}
</div>
<div className="content">
{this.props.children}
</div>
</div>
);
}
user notification class
/*
Simple notification class.
Usage:
<SomeComponent notifySuccess={this.props.notifySuccess} notifyFailure={this.props.notifyFailure} />
these two functions are actions and should be props when the component is connect()ed
call it with either a string or components. optional param of how long to display it (defaults to 5 seconds)
this.props.notifySuccess('it Works!!!', 2);
this.props.notifySuccess(<SomeComponentHere />, 15);
this.props.notifyFailure(<div>You dun goofed</div>);
*/
interface IUserNotifyProps {
data: any;
clearNotification(notifyID: symbol): any;
}
export default class UserNotify extends React.Component<IUserNotifyProps, {}> {
public notifyRef = null;
private timeout = null;
componentDidMount() {
const duration: number = _.get(this.props, 'data.duration', '');
this.notifyRef.style.animationDuration = duration ? `${duration}s` : '5s';
// fallback incase the animation event doesn't fire
const timeoutDuration = (duration * 1000) + 500;
this.timeout = setTimeout(() => {
this.notifyRef.classList.add('hidden');
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}, timeoutDuration);
TransitionEvents.addEndEventListener(
this.notifyRef,
this.onAmimationComplete
);
}
componentWillUnmount() {
clearTimeout(this.timeout);
TransitionEvents.removeEndEventListener(
this.notifyRef,
this.onAmimationComplete
);
}
onAmimationComplete = (e) => {
if (_.get(e, 'animationName') === 'fadeInAndOut') {
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}
}
handleCloseClick = (e) => {
e.preventDefault();
this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
}
assignNotifyRef = target => this.notifyRef = target;
render() {
const {data, clearNotification} = this.props;
return (
<div ref={this.assignNotifyRef} className={cx('user-notification fade-in-out', {success: data.isSuccess, failure: !data.isSuccess})}>
{!_.isString(data.message) ? data.message : <h3>{data.message}</h3>}
<div className="close-message" onClick={this.handleCloseClick}>+</div>
</div>
);
}
}
select time, coalesce(count(case when activities = 3 then 1 end), 0) as count
from MyTable
group by time
Output:
| TIME | COUNT |
-----------------
| 13:00 | 2 |
| 13:15 | 2 |
| 13:30 | 0 |
| 13:45 | 1 |
If you want to count all the activities in one query, you can do:
select time,
coalesce(count(case when activities = 1 then 1 end), 0) as count1,
coalesce(count(case when activities = 2 then 1 end), 0) as count2,
coalesce(count(case when activities = 3 then 1 end), 0) as count3,
coalesce(count(case when activities = 4 then 1 end), 0) as count4,
coalesce(count(case when activities = 5 then 1 end), 0) as count5
from MyTable
group by time
The advantage of this over grouping by activities, is that it will return a count of 0 even if there are no activites of that type for that time segment.
Of course, this will not return rows for time segments with no activities of any type. If you need that, you'll need to use a left join with table that lists all the possible time segments.
Here is a var arg XOR method for java...
public static boolean XOR(boolean... args) {
boolean r = false;
for (boolean b : args) {
r = r ^ b;
}
return r;
}
Enjoy
You can also create a soft link to your script in one of the directories (/usr/local/bin
for example) in the super user PATH. It'll then be available to the sudo.
chmod +x foo.sh
sudo ln -s path-to-foo.sh /usr/local/bin/foo
Have a look at this answer to have an idea of which directory to put soft link in.
Here is how to synchronize PHP (>=5.3) and MySQL timezones per session and user settings. Put this where it runs when you need set and synchronized timezones.
date_default_timezone_set($my_timezone);
$n = new \DateTime();
$h = $n->getOffset()/3600;
$i = 60*($h-floor($h));
$offset = sprintf('%+d:%02d', $h, $i);
$this->db->query("SET time_zone='$offset'");
Where $my_timezone is one in the list of PHP timezones: http://www.php.net/manual/en/timezones.php
The PHP timezone has to be converted into the hour and minute offset for MySQL. That's what lines 1-4 do.
Using the patchwork package, you can simply use +
operator:
library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) + geom_boxplot(aes(gear, disp, group = gear))
p1 + p2
Other operators include /
to stack plots to place plots side by side, and ()
to group elements. For example you can configure a top row of 3 plots and a bottom row of one plot with (p1 | p2 | p3) /p
. For more examples, see the package documentation.
Using the -I
(that's a capital i) option on the file
command seems to show the file encoding.
file -I {filename}
If any of you looking for Bootstrap-4. Here it is
<div class="row no-gutters">
<div class="col-10">
<img class="img-fluid" src="/resources/img1.jpg" alt="">
</div>
</div>
Just to update a bit this question with the new Hook methods, you can simply use the useEffect
hook:
import React, { useEffect } from 'react'
export default function App(props) {
useEffect(() => {
// your post layout code (or 'effect') here.
...
},
// array of variables that can trigger an update if they change. Pass an
// an empty array if you just want to run it once after component mounted.
[])
}
Also if you want to run before the layout paint use the useLayoutEffect
hook:
import React, { useLayoutEffect } from 'react'
export default function App(props) {
useLayoutEffect(() => {
// your pre layout code (or 'effect') here.
...
}, [])
}
Also see your php file text encoding. Mine was UTF-8
with BOM
and it prevented the script to work. But now works flawlessly after removing the BOM
...
Your for
loop looks good.
A possible while
loop to accomplish the same thing:
int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i++;
}
System.out.println("The sum is " + sum);
A possible do while
loop to accomplish the same thing:
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= 100);
System.out.println("The sum is " + sum);
The difference between the while
and the do while
is that, with the do while
, at least one iteration is sure to occur.
@jordanstephens said this in a comment, but it kind of gets lost and was a really easy fix for me.
I simply added HEAD method and clicked saved and it started working.
<CORSConfiguration>_x000D_
<CORSRule>_x000D_
<AllowedOrigin>*</AllowedOrigin>_x000D_
<AllowedMethod>GET</AllowedMethod>_x000D_
<AllowedMethod>HEAD</AllowedMethod> <!-- Add this -->_x000D_
<MaxAgeSeconds>3000</MaxAgeSeconds>_x000D_
<AllowedHeader>Authorization</AllowedHeader>_x000D_
</CORSRule>_x000D_
</CORSConfiguration>
_x000D_
There are correct solutions in the comments, but to summarize them into a single answer:
You have to use DECIMAL(6,4).
Then you can have 6 total number of digits, 2 before and 4 after the decimal point (the scale). At least according to this.
The simplest way:
ping hostname
e.g.
ping dynlab938.meng.auth.gr
it will print: Pinging dynlab938.meng.auth.gr [155.207.29.38] with 32 bytes of data
Look at this example, and try to do your own:
import java.io.*;
public class ReadFile {
public static void main(String[] args){
String string = "";
String file = "textFile.txt";
// Reading
try{
InputStream ips = new FileInputStream(file);
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
String line;
while ((line = br.readLine()) != null){
System.out.println(line);
string += line + "\n";
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
// Writing
try {
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter fileOut = new PrintWriter (bw);
fileOut.println (string+"\n test of read and write !!");
fileOut.close();
System.out.println("the file " + file + " is created!");
}
catch (Exception e){
System.out.println(e.toString());
}
}
}
Your onTap
override receives the MapView
from which you can obtain the Context
:
@Override
public boolean onTap(GeoPoint p, MapView mapView)
{
// ...
Intent intent = new Intent();
intent.setClass(mapView.getContext(), FullscreenView.class);
startActivity(intent);
// ...
}
You can declare the variable final, or make it an instance (or global) variable. If you declare it final, you won't be able to change it later.
Any variable defined in a method and accessed by an anonymous inner class must be final. Otherwise, you could use that variable in the inner class, unaware that if the variable changes in the inner class, and then it is used later in the enclosing scope, the changes made in the inner class did not persist in the enclosing scope. Basically, what happens in the inner class stays in the inner class.
I wrote a more in-depth explanation here. It also explains why instance and global variables do not need to be declared final.
Try to use pseudo classes like :first-child & :last-child to remove extra padding from first & last child.
Inspect the generated code of slick slider & try to remove padding on that.
Hope, it'll help!!!
You don't need jQuery to do this. Here's an ES2015 solution:
// Get all input fields
const inputs = document.querySelectorAll('#register input');
// Get only the required ones
const requiredFields = Array.from(inputs).filter(input => input.required);
// Do your stuff with the required fields
requiredFields.forEach(field => /* do what you want */);
Or you could just use the :required
selector:
Array.from(document.querySelectorAll('#register input:required'))
.forEach(field => /* do what you want */);
I wanted a way to do this without using an extra module. First turn list to string, then append to an array:
dataset_list = ''.join(input_list)
dataset_array = []
for item in dataset_list.split(';'): # comma, or other
dataset_array.append(item)
Hi Guys I Did Something like this. For N-th Depth Copy Folder and Files to copy. Which Allows you to copy all the directory structure to copy from Android AssetManager :)
private void manageAssetFolderToSDcard()
{
try
{
String arg_assetDir = getApplicationContext().getPackageName();
String arg_destinationDir = FRConstants.ANDROID_DATA + arg_assetDir;
File FolderInCache = new File(arg_destinationDir);
if (!FolderInCache.exists())
{
copyDirorfileFromAssetManager(arg_assetDir, arg_destinationDir);
}
} catch (IOException e1)
{
e1.printStackTrace();
}
}
public String copyDirorfileFromAssetManager(String arg_assetDir, String arg_destinationDir) throws IOException
{
File sd_path = Environment.getExternalStorageDirectory();
String dest_dir_path = sd_path + addLeadingSlash(arg_destinationDir);
File dest_dir = new File(dest_dir_path);
createDir(dest_dir);
AssetManager asset_manager = getApplicationContext().getAssets();
String[] files = asset_manager.list(arg_assetDir);
for (int i = 0; i < files.length; i++)
{
String abs_asset_file_path = addTrailingSlash(arg_assetDir) + files[i];
String sub_files[] = asset_manager.list(abs_asset_file_path);
if (sub_files.length == 0)
{
// It is a file
String dest_file_path = addTrailingSlash(dest_dir_path) + files[i];
copyAssetFile(abs_asset_file_path, dest_file_path);
} else
{
// It is a sub directory
copyDirorfileFromAssetManager(abs_asset_file_path, addTrailingSlash(arg_destinationDir) + files[i]);
}
}
return dest_dir_path;
}
public void copyAssetFile(String assetFilePath, String destinationFilePath) throws IOException
{
InputStream in = getApplicationContext().getAssets().open(assetFilePath);
OutputStream out = new FileOutputStream(destinationFilePath);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
}
public String addTrailingSlash(String path)
{
if (path.charAt(path.length() - 1) != '/')
{
path += "/";
}
return path;
}
public String addLeadingSlash(String path)
{
if (path.charAt(0) != '/')
{
path = "/" + path;
}
return path;
}
public void createDir(File dir) throws IOException
{
if (dir.exists())
{
if (!dir.isDirectory())
{
throw new IOException("Can't create directory, a file is in the way");
}
} else
{
dir.mkdirs();
if (!dir.isDirectory())
{
throw new IOException("Unable to create directory");
}
}
}
In the end Create a Asynctask:
private class ManageAssetFolders extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... arg0)
{
manageAssetFolderToSDcard();
return null;
}
}
call it From your activity:
new ManageAssetFolders().execute();
Quote:
The "-a" operator also doesn't work:
if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]
For a more elaborate explanation: [
and ]
are not Bash reserved words. The if
keyword introduces a conditional to be evaluated by a job (the conditional is true if the job's return value is 0
or false otherwise).
For trivial tests, there is the test
program (man test
).
As some find lines like if test -f filename; then foo bar; fi
, etc. annoying, on most systems you find a program called [
which is in fact only a symlink to the test
program. When test
is called as [
, you have to add ]
as the last positional argument.
So if test -f filename
is basically the same (in terms of processes spawned) as if [ -f filename ]
. In both cases the test
program will be started, and both processes should behave identically.
Here's your mistake: if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]
will parse to if
+ some job, the job being everything except the if
itself. The job is only a simple command (Bash speak for something which results in a single process), which means the first word ([
) is the command and the rest its positional arguments. There are remaining arguments after the first ]
.
Also not, [[
is indeed a Bash keyword, but in this case it's only parsed as a normal command argument, because it's not at the front of the command.
Any MD5 will produce a good checksum to verify the file. Any of the files listed at the bottom of this page will work fine. http://en.wikipedia.org/wiki/Md5sum
<script type="text/javascript">
$(document).ready(function () {
var gridHeader = $('#<%=grdSiteWiseEmpAttendance.ClientID%>').clone(true); // Here Clone Copy of Gridview with style
$(gridHeader).find("tr:gt(0)").remove(); // Here remove all rows except first row (header row)
$('#<%=grdSiteWiseEmpAttendance.ClientID%> tr th').each(function (i) {
// Here Set Width of each th from gridview to new table(clone table) th
$("th:nth-child(" + (i + 1) + ")", gridHeader).css('width', ($(this).width()).toString() + "px");
});
$("#GHead1").append(gridHeader);
$('#GHead1').css('position', 'top');
$('#GHead1').css('top', $('#<%=grdSiteWiseEmpAttendance.ClientID%>').offset().top);
});
</script>
<div class="row">
<div class="col-lg-12" style="width: auto;">
<div id="GHead1"></div>
<div id="divGridViewScroll1" style="height: 600px; overflow: auto">
<div class="table-responsive">
<asp:GridView ID="grdSiteWiseEmpAttendance" CssClass="table table-small-font table-bordered table-striped" Font-Size="Smaller" EmptyDataRowStyle-ForeColor="#cc0000" HeaderStyle-Font-Size="8" HeaderStyle-Font-Names="Calibri" HeaderStyle-Font-Italic="true" runat="server" AutoGenerateColumns="false"
BackColor="#f0f5f5" OnRowDataBound="grdSiteWiseEmpAttendance_RowDataBound" HeaderStyle-ForeColor="#990000">
<Columns>
</Columns>
<HeaderStyle HorizontalAlign="Justify" VerticalAlign="Top" />
<RowStyle Font-Names="Calibri" ForeColor="#000000" />
</asp:GridView>
</div>
</div>
</div>
</div>
Here's a performance comparison of the two. HTTP is more responsive for request-response of small files, but FTP may be better for large files if tuned properly. FTP used to be generally considered faster. FTP requires a control channel and state be maintained besides the TCP state but HTTP does not. There are 6 packet transfers before data starts transferring in FTP but only 4 in HTTP.
I think a properly tuned TCP layer would have more effect on speed than the difference between application layer protocols. The Sun Blueprint Understanding Tuning TCP has details.
Heres another good comparison of individual characteristics of each protocol.
I may be late but actual code for react-create-app for react > 16 ver. After each change state is saved in sessionStorage (not localStorage) and is crypted via crypto-js. On refresh (when user demands refresh of the page by clicking refresh button) state is loaded from the storage. I also recommend not to use sourceMaps in build to avoid readablility of the key phrases.
my index.js
import React from "react";
import ReactDOM from "react-dom";
import './index.css';
import App from './containers/App';
import * as serviceWorker from './serviceWorker';
import {createStore} from "redux";
import {Provider} from "react-redux"
import {BrowserRouter} from "react-router-dom";
import rootReducer from "./reducers/rootReducer";
import CryptoJS from 'crypto-js';
const key = CryptoJS.enc.Utf8.parse("someRandomText_encryptionPhase");
const iv = CryptoJS.enc.Utf8.parse("someRandomIV");
const persistedState = loadFromSessionStorage();
let store = createStore(rootReducer, persistedState,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
function loadFromSessionStorage() {
try {
const serializedState = sessionStorage.getItem('state');
if (serializedState === null) {
return undefined;
}
const decrypted = CryptoJS.AES.decrypt(serializedState, key, {iv: iv}).toString(CryptoJS.enc.Utf8);
return JSON.parse(decrypted);
} catch {
return undefined;
}
}
function saveToSessionStorage(state) {
try {
const serializedState = JSON.stringify(state);
const encrypted = CryptoJS.AES.encrypt(serializedState, key, {iv: iv});
sessionStorage.setItem('state', encrypted)
} catch (e) {
console.log(e)
}
}
ReactDOM.render(
<BrowserRouter>
<Provider store={store}>
<App/>
</Provider>
</BrowserRouter>,
document.getElementById('root')
);
store.subscribe(() => saveToSessionStorage(store.getState()));
serviceWorker.unregister();
Last-Modified : The last modified date for the requested object
If-Modified-Since : Allows a 304 Not Modified to be returned if last modified date is unchanged.
ETag : An ETag is an opaque identifier assigned by a web server to a specific version of a resource found at a URL. If the resource representation at that URL ever changes, a new and different ETag is assigned.
If-None-Match : Allows a 304 Not Modified to be returned if ETag is unchanged.
the browser store cache with a date(Last-Modified) or id(ETag), when you need to request the URL again, the browser send request message with the header:
the server will return 304 when the if statement is False, and browser will use cache.
At first I was interested in how different programs worked, so I started by looking at the source code. Then when I began to understand how the program worked, I would change certain parameters to see what would happen. So basically I learned how to read before I learned how to write. Which coincidently is how most people learn English.
So if I was trying to teach someone how to program I would give them a small program to try to read and understand how it works, and have them just just play around with the source code.
Only then would I give them "assignments" to try to accomplish.
Now if they had a particular reason for wanting to learn how to program, it would certainly be a good idea to start with something along the lines of what they want to accomplish. For example if they wanted to be proficient in an application like blender, it would definably be a good idea to start with Alice.
I would absolutely recommend sticking with a language that has garbage collection, like D, Perl, or some interpreted language like javascript. It might be a good idea to stay away from Perl until Perl 6 is closer to completion, because it fixes some of the difficulties of reading and understanding Perl.
You can use one of the following:
DateTime.current.midnight
DateTime.current.beginning_of_day
DateTime.current.to_date
You can specify it in your IDE. For example, for Eclipse in Run Configurations ? VM arguments. You can enter -Xmx800m -Xms500m
as
Try to check outline on button's focus:
button:focus {
outline: blue auto 5px;
}
If you have it, just set it to none
.
I don't think this is possible using PostgreSQL alone in the most general case. When you install PostgreSQL, you pick a time zone. I'm pretty sure the default is to use the operating system's timezone. That will usually be reflected in postgresql.conf as the value of the parameter "timezone". But the value ends up as "localtime". You can see this setting with the SQL statement.
show timezone;
But if you change the timezone in postgresql.conf to something like "Europe/Berlin", then show timezone;
will return that value instead of "localtime".
So I think your solution will involve setting "timezone" in postgresql.conf to an explicit value rather than the default "localtime".
You should use ExecuteScalar()
(which returns the first row first column) instead of ExecuteNonQuery()
(which returns the no. of rows affected).
You should refer differences between executescalar and executenonquery for more details.
Hope it helps!
You can use Console.WriteLine()
to write out any native type. To see the output you must write console application (like in Java), then the output will be displayed in the Command Prompt, or if you are developing a windows GUI application, in Visual Studio you must turn on "Output" panel (under View) to see the commands output.
The Difference between $(document).ready()
and $(window).load()
functions is that the code included inside $(window).load()
will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
There are not difference between the above 3 codes.
They are equivalent,but you may face conflict if any other JavaScript Frameworks uses the same dollar symbol $ as a shortcut name.
jQuery.noConflict();
jQuery.ready(function($){
//Code using $ as alias to jQuery
});
I created a simple utility for measuring performance of blocks of code, using the chrono library's high_resolution_clock: https://github.com/nfergu/codetimer.
Timings can be recorded against different keys, and an aggregated view of the timings for each key can be displayed.
Usage is as follows:
#include <chrono>
#include <iostream>
#include "codetimer.h"
int main () {
auto start = std::chrono::high_resolution_clock::now();
// some code here
CodeTimer::record("mykey", start);
CodeTimer::printStats();
return 0;
}
Quite simple:
new File("/Path/To/File/or/Directory").exists();
And if you want to be certain it is a directory:
File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}
You need just removing <TextBlock.Text>
and simply adding your content as following:
<Grid Margin="20">
<TextBlock TextWrapping="Wrap" TextAlignment="Justify" FontSize="17">
<Bold FontFamily="Segoe UI Light" FontSize="70">I.R. Iran</Bold><LineBreak/>
<Span FontSize="35">I</Span>ran or Persia, officially the <Italic>Islamic Republic of Iran</Italic>,
is a country in Western Asia. The country is bordered on the
north by Armenia, Azerbaijan and Turkmenistan, with Kazakhstan and Russia
to the north across the Caspian Sea.<LineBreak/>
<Span FontSize="10">For more information about Iran see <Hyperlink NavigateUri="http://en.WikiPedia.org/wiki/Iran">WikiPedia</Hyperlink></Span>
<LineBreak/>
<LineBreak/>
<Span FontSize="12">
<Span>Is this page helpful?</Span>
<Button Content="No"/>
<Button Content="Yes"/>
</Span>
</TextBlock>
</Grid>
Drop the quotes:
List<Object> bugs = JsonPath.read(githubIssues, "$..labels[?(@.name==bug)]");
See also this Json Path Example page
I had the same problem. I was creating relationships on existing tables but had different column values, which were supposed/assumed to be related. For example, I had a table USERS
that had a column USERID
with rows 1,2,3,4,5
. Then I had another child table ORDERS
with a column USERID
with rows 1,2,3,4,5,6,7
. Then I run MySQl command ALTER TABLE ORDERS ADD CONSTRAINT ORDER_TO_USER_CONS FOREIGN KEY (ORDERUSERID) REFERENCES USERS(USERID) ON DELETE SET NULL ON UPDATE CASCADE;
It was rejected with the message:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (DBNAME1.#sql-4c73_c0, CONSTRAINT ORDER_TO_USER_CONS FOREIGN KEY (ORDERUSERID) REFERENCES USERS (USERID) ON DELETE SET NULL ON UPDATE CASCADE)
I exported data from the ORDERS table, then deleted all data from it, re-run the command again, it worked this time, then re-inserted the data with the corresponding USERID
s from the USERS table.
... and getting back to easy ... for simple scripts you can use:
import sys
needs = (3, 9) # or whatever
pvi = sys.version_info.major, sys.version_info.minor
later in your code
try:
assert pvi >= needs
except:
print("will fail!")
# etc.
If there is any default export in the file, there isn't any need to use the curly braces in the import statement.
if there are more than one export in the file then we need to use curly braces in the import file so that which are necessary we can import.
You can find the complete difference when to use curly braces and default statement in the below YouTube video (very heavy Indian accent, including rolling on the r's...).
21. ES6 Modules. Different ways of using import/export, Default syntax in the code. ES6 | ES2015
Remove the library from your Podfile
Run pod install
on the terminal
Note the require-dev (root-only) !
which means that the require-dev section is only valid when your package is the root of the entire project. I.e. if you run composer update
from your package folder.
If you develop a plugin for some main project, that has it's own composer.json, then your require-dev section will be completely ignored! If you need your developement dependencies, you have to move your require-dev to composer.json in main project.
Forget about a font and use a background image!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
<head>
<title>Select :after pseudo class/element</title>
<style type="text/css">
.close {
background:url(http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/images/ui-icons_222222_256x240.png) NO-REPEAT -96px -128px;
text-indent:-10000px;
width:20px;
height:20px;
}
</style>
</head>
<body>
<input type="button" class="close" value="Close" />
<button class="close">Close</button>
</body>
</html>
This will be more accessible for users visiting the page with a screen reader.
For those guys, who are doing it through UMD, and compile via require.js
, there is a laconic solution.
In the module, which requires tether
as the dependency, which loads Tooltip
as UMD, in front of module definition, just put short snippet on definition of Tether:
// First load the UMD module dependency and attach to global scope
require(['tether'], function(Tether) {
// @todo: make it properly when boostrap will fix loading of UMD, instead of using globals
window.Tether = Tether; // attach to global scope
});
// then goes your regular module definition
define([
'jquery',
'tooltip',
'popover'
], function($, Tooltip, Popover){
"use strict";
//...
/*
by this time, you'll have window.Tether global variable defined,
and UMD module Tooltip will not throw the exception
*/
//...
});
This short snippet at the very beginning, actually may be put on any higher level of your application, the most important thing - to invoke it before actual usage of bootstrap
components with Tether
dependency.
// ===== file: tetherWrapper.js =====
require(['./tether'], function(Tether) {
window.Tether = Tether; // attach to global scope
// it's important to have this, to keep original module definition approach
return Tether;
});
// ===== your MAIN configuration file, and dependencies definition =====
paths: {
jquery: '/vendor/jquery',
// tether: '/vendor/tether'
tether: '/vendor/tetherWrapper' // @todo original Tether is replaced with our wrapper around original
// ...
},
shim: {
'bootstrap': ['tether', 'jquery']
}
UPD: In Boostrap 4.1 Stable they replaced Tether, with Popper.js, see the documentation on usage.
I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.
Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.
Here is an attempt at this with your data:
import matplotlib.pyplot as plt
# ... define 2D array hist as you did
plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case
Use the Javascript string split() function.
var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');
// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc
Haha, Lovely - let me also include my version of stackPusher's code :). We are using this functionality in C#. Works fine for all Excel ranges.:
public static String ConvertToLiteral(int number)
{
int firstLetter = (((number - 27) / (26 * 26))) % 26;
int middleLetter = ((((number - 1) / 26)) % 26);
int lastLetter = (number % 26);
firstLetter = firstLetter == 0 ? 26 : firstLetter;
middleLetter = middleLetter == 0 ? 26 : middleLetter;
lastLetter = lastLetter == 0 ? 26 : lastLetter;
String returnedString = "";
returnedString = number > 27 * 26 ? (Convert.ToChar(firstLetter + 64).ToString()) : returnedString;
returnedString += number > 26 ? (Convert.ToChar(middleLetter + 64).ToString()) : returnedString;
returnedString += lastLetter >= 0 ? (Convert.ToChar(lastLetter + 64).ToString()) : returnedString;
return returnedString;
}
CKEDITOR.instances = new Array();
I am using this before my calls to create an instance (ones per page load). Not sure how this affects memory handling and what not. This would only work if you wanted to replace all of the instances on a page.
With most .net unit testing frameworks you can put an [ExpectedException] attribute on the test method. However this can't tell you that the exception happened at the point you expected it to. That's where xunit.net can help.
With xunit you have Assert.Throws, so you can do things like this:
[Fact]
public void CantDecrementBasketLineQuantityBelowZero()
{
var o = new Basket();
var p = new Product {Id = 1, NetPrice = 23.45m};
o.AddProduct(p, 1);
Assert.Throws<BusinessException>(() => o.SetProductQuantity(p, -3));
}
[Fact] is the xunit equivalent of [TestMethod]
I faced the same issue and It is really strange that the same code works in few case whereas it failed in some random cases.
I got it fixed by just making sure the proper setter/getter (Making sure the case sensitivity)
package com.infy.test;
import java.util.Scanner ;
import java.lang.String ;
public class Test1 {
public static void main (String[]args)
{
String a =null;
Scanner scan = new Scanner(System.in);
System.out.println("*********White Space Remover Program************\n");
System.out.println("Enter your string\n");
a = scan.nextLine();
System.out.println("Input String is :\n"+a);
String b= a.replaceAll("\\s+","");
System.out.println("\nOutput String is :\n"+b);
}
}
This code snippet shows how to insert into table when identity Primary Key column is ON.
SET IDENTITY_INSERT [dbo].[Roles] ON
GO
insert into Roles (Id,Name) values(1,'Admin')
GO
insert into Roles (Id,Name) values(2,'User')
GO
SET IDENTITY_INSERT [dbo].[Roles] OFF
GO
jQuery has the inArray
function:
Store a reference to the meter instance as a member in Production:
public class Production {
//The other members, properties etc...
private Meter m;
Production(Meter m) {
this.m = m;
}
}
And then in the Meter-class:
public class Meter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production(this);
}
}
Also note that you need to implement an accessor method/property so that the Production class can actually access the powerRating member of the Meter class.
I know there already is a previous answer suggesting to use a form but the markup provided is not correct/ideal. Here's the easiest solution, no javascript needed at all and it doesn't break your dropdown. Works with Bootstrap 4.
<form class="dropdown-item">
<!-- Your elements go here -->
</form>
get_loaded_extensions()
output the extensions list.
phpinfo(INFO_MODULES);
output the extensions and their details.
See also: asciichart (implemented in Node.js, Python, Java, Go and Haskell)