I am using mysql 8.0.12 and updating the mysql connector to mysql-connector-java-8.0.12 resolved the issue for me.
Hope it helps somebody.
adding this paramter in header resolved my issue in apiSauce React Native
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
Try to use the latest com.fasterxml.jackson.core/jackson-databind
.
I upgraded it to 2.9.4
and it works now.
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
You shouldn't use ${varName}
when you're outside of strings, you should just use varName
. Inside strings you use it like this; echo "this is a string ${someVariable}";
. Infact you can place an general java expression inside of ${...}
; echo "this is a string ${func(arg1, arg2)}
.
In my case, I'm using j-hipster and I had to do ./mvnw clean
to overcome this warning.
I was experiencing this error on Android 5.1.1
devices sending network requests using okhttp/4.0.0-RC1
. Setting header Content-Length: <sizeof response>
on the server side resolved the issue.
This is what worked for me:
1) add commons-logging.jar to the WEB-INF/lib folder
2) Add this jar as a maven dependency, e.g. add this to the pom.xml:
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
3) Maven install
4) Run the server.
Hope it helps.
https://services.gradle.org/distributions/gradle-2.1-all.zip
open this link in the browser and download the zip file and extract it to folder
Before extraction please delete the old folder whose name ends gradle-2.1-all and then you can start extracting
if you are window user extract it to this folder
C:\Users{Your-Name}.gradle\wrapper\dists
after that just restart your android studio. I hope it works it works for me .
Add the annotation @Repository
to the implementation of UserDaoImpl
@Repository
public class UserDaoImpl implements UserDao {
private static Log log = LogFactory.getLog(UserDaoImpl.class);
@Autowired
@Qualifier("sessionFactory")
private LocalSessionFactoryBean sessionFactory;
//...
}
org.springframework.core.io.Resource
is part of spring-core-<version>.jar
But this lib is already in your lib folder. So I guess it is just a Deployment Problem. -- Try to clean your server and redeploy your application.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController'
Make sure that you have added ojdbc14.jar
into your library.
For oracle 11g, usie ojdbc6.jar
.
Update to Tomcat 7.0.58 (or newer).
See: https://bz.apache.org/bugzilla/show_bug.cgi?id=57173#c16
The performance improvement that triggered this regression has been reverted from from trunk, 8.0.x (for 8.0.16 onwards) and 7.0.x (for 7.0.58 onwards) and will not be reapplied.
Load Project:>Build, execution, Deployment:>(Check on)compiler Independent modules in parllel.
The reason this occur is the JVM/Dalvik haven't not confidence in the CA certificates in the system or in the user certificate stores.
To fix this with Retrofit, If you are used okhttp, with another client it's very similar.
You've to do:
A). Create a cert store contain public Key of CA. To do this you need to launch next script for *nix. You need openssl install in your machine, and download from https://www.bouncycastle.org/ the jar bcprov-jdk16-1.46.jar. Download this version not other, the version 1.5x is not compatible with android 4.0.4.
#!/bin/bash
if [ -z $1 ]; then
echo "Usage: cert2Android<CA cert PEM file>"
exit 1
fi
CACERT=$1
BCJAR=bcprov-jdk16-1.46.jar
TRUSTSTORE=mytruststore.bks
ALIAS=`openssl x509 -inform PEM -subject_hash -noout -in $CACERT`
if [ -f $TRUSTSTORE ]; then
rm $TRUSTSTORE || exit 1
fi
echo "Adding certificate to $TRUSTSTORE..."
keytool -import -v -trustcacerts -alias $ALIAS \
-file $CACERT \
-keystore $TRUSTSTORE -storetype BKS \
-providerclass org.bouncycastle.jce.provider.BouncyCastleProvider \
-providerpath $BCJAR \
-storepass secret
echo ""
echo "Added '$CACERT' with alias '$ALIAS' to $TRUSTSTORE..."
B). Copy the file truststore mytruststore.bks in res/raw of your project
C). Setting SSLContext of the connection:
.............
okHttpClient = new OkHttpClient();
try {
KeyStore ksTrust = KeyStore.getInstance("BKS");
InputStream instream = context.getResources().openRawResource(R.raw.mytruststore);
ksTrust.load(instream, "secret".toCharArray());
// TrustManager decides which certificate authorities to use.
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ksTrust);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | KeyManagementException e) {
e.printStackTrace();
}
.................
This issue arises because of different reasons. It might encountered if you are using Spring boot built war file. As Spring boot web and rest starter projects jars do have embedded Tomcat in it, hence fails with "SEVERE: ContainerBase.addChild: start: org.apache.catalina.LifecycleException".
You can fix this by exclusion of the embedded tomcat at the time of packaging by using exclusions in case of maven.
Maven dependency of "spring-boot-starter-web" will look like
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
I had the same issue in C# using 64-bit Windows and the 64-bit Firefox browser which doesn't seem to work on Selenium. If you are using the 64-bit browser, try the 32-bit one.
Surprisingly, the 32-bit Firefox browser runs on 64-bit Windows just fine.
Edited to clarify the intent of my post.
This error appears because the spring project doesn't read the file properties (bootstrap.yml or application.yml). In order to resolve this, you must add dependency in your pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
</dependency>
In my case, the error "BeanFactory not initialized or already closed - call 'refresh' before" was a consequence of a previous error that I didn't noticed in the server startup. I think that it is not always the real cause of the problem.
Missed to configure tag in manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
In my maven project this error occurs, after i closed my projects and reopens them. The dependencys wasn´t build correctly at that time. So for me the solution was just to update the Maven Dependencies of the projects!
remove this in your manifest file
xmlns:tools="http://schemas.android.com/tools"
Set This in OkHttpClient.Builder() Object
val httpClient = OkHttpClient.Builder()
httpClient.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
.writeTimeout(5, TimeUnit.MINUTES) // write timeout
.readTimeout(5, TimeUnit.MINUTES) // read timeout
You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME
The new way using Jackson 1.9+ is the following:
Object json = OBJECT_MAPPER.readValue(diffResponseJson, Object.class);
String indented = OBJECT_MAPPER.writerWithDefaultPrettyPrinter()
.writeValueAsString(json);
The output will be correctly formatted!
Even I had same problem
Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/]
I have added respective dependency at very begenining it had worked for me.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
i have changed my old path: jdbc:odbc:thin:@localhost:1521:orcl
to new : jdbc:oracle:thin:@//localhost:1521/orcl
and it worked for me.....hurrah!! image
You can use GlassFish server and the error will be resolved. I tried with tomcat7 and tomcat8 but this error was coming continuously but resolved with GlassFish. I think it's a problem with server.
I did not have a servlet-api.jar in the application's WEB-INF/lib directory (or any other jar there). The problem was that in WEB-INF/web.xml I had this...
...
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.bizooka.net.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
...
...according to a tutorial. Removing that still allowed the servlet to function, and did not get the error.
You will have to annotate your service with @Service
since you have said I am using annotations for mapping
Don't panic. You have you copied the servlet code? Ok,
@WebServlet("/HelloWord")
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
You gave the same path @WebServlet("/HelloWord")
for both servlets with different names.
If you create a web.xml
file, then check the classpath
.
I think it comes from this line in your XML file:
<context:component-scan base-package="org.assessme.com.controller." />
Replace it by:
<context:component-scan base-package="org.assessme.com." />
It is because your Autowired service is not scanned by Spring since it is not in the right package.
Pessimistic locking is generally not recommended and it's very costly in terms of performance on database side. The problem that you have mentioned (the code part) a few things are not clear such as:
session
object (not sure if you are using Spring)?Hibernate Session objects are NOT thread-safe. So if there are multiple threads accessing the same session and trying to update the same database entity, your code can potentially end up in an error situation like this.
So what happens here is that more than one thread tries to update the same entity, one thread succeeds and when the next thread goes to commit the data, it sees that its already been modified and ends up throwing StaleObjectStateException
.
EDIT:
There is a way to use Pessimistic Locking in Hibernate. Check out this link. But there seems to be some issue with this mechanism. I came across posting a bug in hibernate (HHH-5275), however. The scenario mentioned in the bug is as follows:
Two threads are reading the same database record; one of those threads should use pessimistic locking thereby blocking the other thread. But both threads can read the database record causing the test to fail.
This is very close to what you are facing. Please try this if this does not work, the only way I can think of is using Native SQL queries where you can achieve pessimistic locking in postgres database with SELECT FOR UPDATE
query.
Using the "Update project configuartion" messed up the build path of the project.
Fix: Open the "configure build path..." menu (right click on the project) and fix the Included/Excluded options for each source folder. That worked for me.
i got the same issue, i updated the hosts file with the server address and it worked
For me, removing and re-adding a reference to Microsoft.CSharp fixed the problem temporarily until the affected file was edited. Closing Visual Studio and reopening the project fixed it more long-term, so that's an option if this situation occurs while Microsoft.CSharp is already referenced.
Maybe restarting the IDE as a first step seems trivial, but here's a reminder for people like me who don't think of that as the first thing to do.
Here is the same subclassed UITextField written in Swift 3. It is quite different from prior versions of Swift, as you'll see:
import UIKit
class MyTextField: UITextField
{
let inset: CGFloat = 10
// placeholder position
override func textRect(forBounds bounds: CGRect) -> CGRect
{
return bounds.insetBy(dx: inset, dy: inset)
}
// text position
override func editingRect(forBounds bounds: CGRect) -> CGRect
{
return bounds.insetBy(dx: inset, dy: inset)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect
{
return bounds.insetBy(dx: inset, dy: inset)
}
}
Incidentally, you can also do something like the following, if you want to control the inset of just one side. This particular example of adjusting only the left inset comes in handy if you place an image on top of the UITextField but you want it to appear to the user to be within the text field:
override func editingRect(forBounds bounds: CGRect) -> CGRect
{
return CGRect.init(x: bounds.origin.x + inset, y: bounds.origin.y, width: bounds.width - inset, height: bounds.height)
}
I had to investigate an endless recursion in smartgwt with IE11, so in order to investigate deeper, I needed a stack trace. The problem was, that I was unable to use the dev console, because the reproduction was more difficult that way.
Use the following in a javascript method:
try{ null.toString(); } catch(e) { alert(e.stack); }
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
you can use a simple list comprehension:
x=[1,2,3,4]
y=[3,4,5]
common = [i for i in x if i in y]
common: [3,4]
Create a method that returns all digits, and another that counts them:
public static int GetNumberOfDigits(this long value)
{
return value.GetDigits().Count();
}
public static IEnumerable<int> GetDigits(this long value)
{
do
{
yield return (int)(value % 10);
value /= 10;
} while (value != 0);
}
This felt like the more intuitive approach to me when tackling this problem. I tried the Log10
method first due to its apparent simplicity, but it has an insane amount of corner cases and precision problems.
I also found the if
-chain proposed in the other answer to a bit ugly to look at.
I know this is not the most efficient method, but it gives you the other extension to return the digits as well for other uses (you can just mark it private
if you don't need to use it outside the class).
Keep in mind that it does not consider the negative sign as a digit.
By using this way its possible to create a different implementation for different types (i.e. Int or custom classes like CurrencyUnit, ...). Its also possible to scan for this method invoke using the genstrings utility. Simply add the routine flag to the command
genstrings MyCoolApp/Views/SomeView.swift -s localize -o .
extension:
import UIKit
extension String {
public static func localize(key: String, comment: String) -> String {
return NSLocalizedString(key, comment: comment)
}
}
usage:
String.localize("foo.bar", comment: "Foo Bar Comment :)")
Well, you need to incorporate exec-maven-plugin
, this plug-in performs the same thing that you do on command prompt when you type in java -cp .;jarpaths TestMain
. You can pass argument and define which phase (test
, package
, integration
, verify
, or deploy
), you want this plug-in to call your main class.
You need to add this plug-in under <build>
tag and specify parameters. For example
<project>
...
...
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1.1</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>my.company.name.packageName.TestMain</mainClass>
<arguments>
<argument>myArg1</argument>
<argument>myArg2</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
...
</project>
Now, if you right-click on on the project folder and do Run As > Maven Test
, or Run As > Maven Package
or Run As > Maven Install
, the test phase
will execute and so your Main class.
Given
d = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]
and your specific question: How can I remove the brackets?
Using list comprehension :
new_d = [i[0] for i in d]
will give you this
[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]
then you can access individual items with the appropriate index, e.g., new_d[0]
will give you 180.0
etc which you can then use for math.
If you are going to have a collection of data, you will have some sort of bracket or parenthesis.
Note, this solution is aimed specifically at your question/problem, it doesn't provide a generalized solution. I.e., it will work for your case.
There are two classes that lives in different assemblies and different namespaces.
WinForms: use following namespace declaration, make sure Main
is marked with [STAThread]
attribute:
using System.Windows.Forms;
WPF: use following namespace declaration
using System.Windows;
console: add reference to System.Windows.Forms
, use following namespace declaration, make sure Main
is marked with [STAThread]
attribute. Step-by-step guide in another answer
using System.Windows.Forms;
To copy an exact string (literal in this case):
Clipboard.SetText("Hello, clipboard");
To copy the contents of a textbox either use TextBox.Copy() or get text first and then set clipboard value:
Clipboard.SetText(txtClipboard.Text);
See here for an example. Or... Official MSDN documentation or Here for WPF.
Remarks:
Clipboard is desktop UI concept, trying to set it in server side code like ASP.Net will only set value on the server and has no impact on what user can see in they browser. While linked answer lets one to run Clipboard access code server side with SetApartmentState
it is unlikely what you want to achieve.
If after following information in this question code still gets an exception see "Current thread must be set to single thread apartment (STA)" error in copy string to clipboard
This question/answer covers regular .NET, for .NET Core see - .Net Core - copy to clipboard?
While it is possible to combine the results, I would advise against doing so.
You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.
The normally used load command will work if you specify the object_pairs_hook parameter:
import json
from collections import OrderedDict
with open('foo.json', 'r') as fp:
metrics_types = json.load(fp, object_pairs_hook=OrderedDict)
This should work...
JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);
public class Person
{
public string Name;
public int Age;
public string Location;
}
public class Record
{
public Person record;
}
Try this instead:
$journalName = preg_replace('/\s+/', '_', $journalName);
Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).
The collections don't maintain order of insertion. Some just default to add a new value at the end. Maintaining order of insertion is only useful if you prioritize the objects by it or use it to sort objects in some way.
As for why some collections maintain it by default and others don't, this is mostly caused by the implementation and only sometimes part of the collections definition.
Lists maintain insertion order as just adding a new entry at the end or the beginning is the fastest implementation of the add(Object ) method.
Sets The HashSet and TreeSet implementations don't maintain insertion order as the objects are sorted for fast lookup and maintaining insertion order would require additional memory. This results in a performance gain since insertion order is almost never interesting for Sets.
ArrayDeque a deque can used for simple que and stack so you want to have ''first in first out'' or ''first in last out'' behaviour, both require that the ArrayDeque maintains insertion order. In this case the insertion order is maintained as a central part of the classes contract.
If you wanted to learn some GUI, may be tic tac toe is good. Even for console, I still find that is a fun problem. Not challenging but a little bit fun. Later you can advance some other games or port that game to GUI, client server or java applet for the web. I think if you want to learn something and get fun as well, game is a good choice:)
After installing the gems, if you want to know where a particular gem is. Try typing:
gem list
You will be able to see the list of gems you have installed. Now use bundle show
and name the gem you want to know the path for, like this:
bundle show <gemName>
Or (as of younger versions of bundler):
bundle info <gemName>
Apple already includes a DEBUG
flag in debug builds, so you don't need to define your own.
You might also want to consider just redefining NSLog
to a null operation when not in DEBUG
mode, that way your code will be more portable and you can just use regular NSLog
statements:
//put this in prefix.pch
#ifndef DEBUG
#undef NSLog
#define NSLog(args, ...)
#endif
You can do something like:
Directory directory = new DirectoryInfo(path);
List<FileInfo> fileInfos = directory.EnumerateFiles("*.*", SearchOption.AllDirectories).ToList();
foreach (FileInfo f in fileInfos)
File.Delete(f.FullName);
Depending on what you want you might be interested in the SPL Object Storage class.
http://php.net/manual/en/class.splobjectstorage.php
It lets you use objects as keys, has an interface to count, get the hash and other goodies.
$s = new SplObjectStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o2->foo = 'bar';
$s[$o1] = 'baz';
$s[$o2] = 'bingo';
echo $s[$o1]; // 'baz'
echo $s[$o2]; // 'bingo'
if you don't have any content with 100% width, you can set the background color of the track to the same color of the body's background
Anyway people ask my comment to post it as answer. i am posting.
URL newurl = new URL(photo_url_str);
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
profile_photo.setImageBitmap(mIcon_val);
To extract STRING
, try:
myString = '123STRINGabc'
startString = '123'
endString = 'abc'
mySubString=myString[myString.find(startString)+len(startString):myString.find(endString)]
If you need to convert some of them to numbers and don't know in advance which ones, some additional code will be needed. Try something like this:
b = []
for x in a:
temp = []
items = x.split(",")
for item in items:
try:
n = int(item)
except ValueError:
temp.append(item)
else:
temp.append(n)
b.append(temp)
This is longer than the other answers, but it's more versatile.
git reset --hard a
git reset --mixed d
git commit
That will act as a revert for all of them at once. Give a good commit message.
You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.
The ISO-8601 format for a DATETIME
when using only the date is: YYYYMMDD
(no dashes or antyhing!)
For a DATETIME
with the time portion, it's YYYY-MM-DDTHH:MM:SS
(with dashes, and a T
in the middle to separate date and time portions).
If you want to convert a string to a DATE
for SQL Server 2008 or newer, you can use YYYY-MM-DD
(with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.
So in your case, you should try:
declare @a datetime
declare @b datetime
set @a = '2012-04-06T12:23:45' -- 6th of April, 2012
set @b = '2012-08-06T21:10:12' -- 6th of August, 2012
exec LogProcedure 'AccountLog', N'test', @a, @b
Furthermore - your stored proc has problem, since you're concatenating together datetime
and string into a string, but you're not converting the datetime
to string first, and also, you're forgetting the close quotes in your statement after both dates.
So change this line here to this:
IF @DateFirst <> '' and @DateLast <> ''
SET @FinalSQL = @FinalSQL + ' OR CONVERT(Date, DateLog) >= ''' +
CONVERT(VARCHAR(50), @DateFirst, 126) + -- convert @DateFirst to string for concatenation!
''' AND CONVERT(Date, DateLog) <=''' + -- you need closing quotes after @DateFirst!
CONVERT(VARCHAR(50), @DateLast, 126) + '''' -- convert @DateLast to string and also: closing tags after that missing!
With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.
You should't write data-toggle="modal" in the element which triggered the modal (like a button), and you manually can show the modal with:
$('#myModal').modal('show');
and hide with:
$('#myModal').modal('hide');
Once you have made your choice of the exit command, press enter to finally quit Vim and close the editor (but not the terminal).
Do note that when you press shift + “:”
the editor will have the next keystrokes displayed at the bottom left of the terminal. Now if you want to simply quit, write exit or wq (save and exit)
You could use formaction attribute (for type=submit/image, overriding form's action) and pass the non-sensitive value through URL (GET-request).
The posted question is not a problem on older browsers (for example on Chrome 49+).
To get it to work I had to switch to Java 8 from Java 10 (In my system PATH variable) then go to
C:\Users\Alex\AppData\Local\Android\Sdk\tools\lib\monitor-x86_64 and run monitor.exe.
Paul A is right about why the discrepancy exists but the solution offered by Ngm is wrong (in the sense of JQuery).
The equivalent of clientHeight and clientWidth in jquery (1.3) is
$(window).width(), $(window).height()
I'm not sure how often you'll find that Java code will run faster than C++, even with Hotspot, but I'll take a swing at explaining how it could happen.
Think of compiled Java code as interpreted machine language for the JVM. When the Hotspot processor notices that certain pieces of the compiled code are going to be used many times, it performs an optimization on the machine code. Since hand-tuning Assembly is almost always faster than C++ compiled code, it's ok to figure that programmatically-tuned machine code isn't going to be too bad.
So, for highly repetitious code, I could see where it'd be possible for Hotspot JVM to run the Java faster than C++... until garbage collection comes into play. :)
If anyone is looking to grab the scope off of a 'controller as' element,.. something like this:
<div id="firstctrl" ng-controller="firstCtrl as vm">
use the following:
var vm = angular.element(document.querySelector('#firstctrl')).scope().vm;
Something like:
File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
I know its too late but if you still wanna try
for /d %%X in (*) do (for /d %%a in (%%X) do ( "C:\Program Files\7-Zip\7z.exe" a -tzip "%%X.zip" ".\%%a\" ))
here * is the current folder. for more options try this link
In March I made a deck presentation in slidify, Rmarkdown with impress.js which is a cool 3D framework. My index.Rmd
header looks like
---
title : French TER (regional train) monthly regularity
subtitle : since January 2013
author : brigasnuncamais
job : Business Intelligence / Data Scientist consultant
framework : impressjs # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js # {highlight.js, prettify, highlight}
hitheme : tomorrow #
widgets : [] # {mathjax, quiz, bootstrap}
mode : selfcontained # {standalone, draft}
knit : slidify::knit2slides
subdirs are:
/assets /css /impress-demo.css
/fig /unnamed-chunk-1-1.png (generated by included R code)
/img /SS850452.png (my image used as background)
/js /impress.js
/layouts/custbg.html # content:--- layout: slide --- {{{ slide.html }}}
/libraries /frameworks /impressjs
/io2012
/highlighters /highlight.js
/impress.js
index.Rmd
A slide with image in background code snippet would be in my .Rmd:
<div id="bg">
<img src="assets/img/SS850452.png" alt="">
</div>
Some issues appeared since I last worked on it (photos are no more in background, text it too large on my R plot) but it works fine on my local. Troubles come when I run it on RPubs.
Yes, you could use a transparent div positioned over the iframe area, with a loader gif as only background.
Then you can attach an onload
event to the iframe:
$(document).ready(function() {
$("iframe#id").load(function() {
$("#loader-id").hide();
});
});
SELECT DISTINCT will always be the same, or faster, than a GROUP BY. On some systems (i.e. Oracle), it might be optimized to be the same as DISTINCT for most queries. On others (such as SQL Server), it can be considerably faster.
Example:
Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.
DROP TABLE IF EXISTS B,C,A;
This can be placed in the beginning of the script instead of individually dropping each table.
var cubes = [["string", "string"], ["string", "string"]];
for(var i = 0; i < cubes.length; i++) {
for(var j = 0; j < cubes[i].length; j++) {
console.log(cubes[i][j]);
}
}
What I always use is:
scp -r username@IP:/path/to/server/source/folder/ .
. (dot) : it means current folder
. so copy from server and paste here only.
IP : can be an IP address like 125.55.41.311
or it can be host like ns1.mysite.com
.
Method1: ADD_MONTHS
ADD_MONTHS(SYSDATE, -6)
Method 2: Interval
SYSDATE - interval '6' month
Note:
if you want to do the operations from start of the current month always, TRUNC(SYSDATE,'MONTH')
would give that. And it expects a Date
datatype as input.
After doing some research found the solution. Run the below command.
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
For Arch Linux add this line to /etc/sysctl.d/99-sysctl.conf:
fs.inotify.max_user_watches=524288
Using this,
String s = "03/24/2013 21:54";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
try
{
Date date = simpleDateFormat.parse(s);
System.out.println("date : "+simpleDateFormat.format(date));
}
catch (ParseException ex)
{
System.out.println("Exception "+ex);
}
Putting the comment of EaterOfCode here as an answer.
grep itself also has the -c flag which just returns the count
So the command and output could look like this.
$ grep -Rl "curl" ./ -c
24
EDIT:
Although this answer might be shorter and thus might seem better than the accepted answer (that is using wc
). I do not agree with this anymore. I feel like remembering that you can count lines by piping to wc -l
is much more useful as you can use it with other programs than grep
as well.
increase the response.getBufferSize() get the buffer size and compare with the bytes you want to transfer !
.selectmenu{_x000D_
_x000D_
-webkit-appearance: none; /*Removes default chrome and safari style*/_x000D_
-moz-appearance: none; /* Removes Default Firefox style*/_x000D_
background: #0088cc ;_x000D_
width: 200px; /*Width of select dropdown to give space for arrow image*/_x000D_
text-indent: 0.01px; /* Removes default arrow from firefox*/_x000D_
text-overflow: ""; /*Removes default arrow from firefox*/ /*My custom style for fonts*/_x000D_
color: #FFF;_x000D_
border-radius: 2px;_x000D_
padding: 5px;_x000D_
border:0 !important;_x000D_
box-shadow: inset 0 0 5px rgba(000,000,000, 0.5);_x000D_
}_x000D_
.hideoption { display:none; visibility:hidden; height:0; font-size:0; }
_x000D_
Try this html_x000D_
_x000D_
<select class="selectmenu">_x000D_
<option selected disabled class="hideoption">Select language</option>_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
<option>Option 3</option>_x000D_
<option>Option 4</option>_x000D_
<option>Option 5</option>_x000D_
</select>
_x000D_
I think you are talking about padding strings with spaces.
One way to do this is with string format codes.
For example, if you want to pad a string to a certain length with spaces, use something like this:
String padded = String.format("%-20s", str);
In a formatter, %
introduces a format sequence. The -
means that the string will be left-justified (spaces will be added on the right of the string). The 20
means the resulting string will be 20 characters long. The s
is the character string format code, and ends the format sequence.
Usually direct queries should not be used in case of linked server because it heavily use temp database of SQL server. At first step data is retrieved into temp DB then filtering occur. There are many threads about this. It is better to use open OPENQUERY because it passes SQL to the source linked server and then it return filtered results e.g.
SELECT *
FROM OPENQUERY(Linked_Server_Name , 'select * from TableName where ID = 500')
Okay I had the same issues first my VS2008 was acting up so i tried to uninstall it and it didn't work...I read online that using an AutoUninstall by MS will do the trick it did just that , but left a lot of nasty files behind..
So i used "Windows Install Clean Up" and cleaned up more stuff that had to do with VS.. then went back into Add and remove in control panel Removed the KB952241... then opened up Ccleaner and scanned the registry found a lot of left behind crap from VB2008 removed all that once that was done.
I went ahead and launch the installed back from the CD again and BAM its working.
I did all this without having to restart my PC..
Hope this helps people who are stuck..like i was
You can find an example below. Basically you attach a function to window
's scroll
event and trace scrollTop
property and if it's higher than desired threshold you apply position: fixed
and some other css properties.
jQuery(function($) {_x000D_
$(window).scroll(function fix_element() {_x000D_
$('#target').css(_x000D_
$(window).scrollTop() > 100_x000D_
? { 'position': 'fixed', 'top': '10px' }_x000D_
: { 'position': 'relative', 'top': 'auto' }_x000D_
);_x000D_
return fix_element;_x000D_
}());_x000D_
});
_x000D_
body {_x000D_
height: 2000px;_x000D_
padding-top: 100px;_x000D_
}_x000D_
code {_x000D_
padding: 5px;_x000D_
background: #efefef;_x000D_
}_x000D_
#target {_x000D_
color: #c00;_x000D_
font: 15px arial;_x000D_
padding: 10px;_x000D_
margin: 10px;_x000D_
border: 1px solid #c00;_x000D_
width: 200px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="target">This <code>div</code> is going to be fixed</div>
_x000D_
To push a single tag:
git push origin <tag_name>
And the following command should push all tags (not recommended):
git push --tags
For big file use the following code (you are less memory hungry)
Parallel.ForEach(File.ReadLines(txtProxyListPath.Text), line => {
//Your stuff
});
Or you can use the ItemDataBound
event in the code behind.
This worked for me:
mysql> FLUSH PRIVILEGES
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'WITH GRANT OPTION;
mysql> FLUSH PRIVILEGES
public class UserCustomAdapter extends ArrayAdapter<User> {
Context context;
int layoutResourceId;
ArrayList<User> data = new ArrayList<User>();
public UserCustomAdapter(Context context, int layoutResourceId,
ArrayList<User> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
holder.textName = (TextView) row.findViewById(R.id.textView1);
holder.textAddress = (TextView) row.findViewById(R.id.textView2);
holder.textLocation = (TextView) row.findViewById(R.id.textView3);
holder.btnEdit = (Button) row.findViewById(R.id.button1);
holder.btnDelete = (Button) row.findViewById(R.id.button2);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
User user = data.get(position);
holder.textName.setText(user.getName());
holder.textAddress.setText(user.getAddress());
holder.textLocation.setText(user.getLocation());
holder.btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Toast.makeText(context, "Edit button Clicked",
Toast.LENGTH_LONG).show();
}
});
holder.btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Delete Button Clicked", "**********");
Toast.makeText(context, "Delete button Clicked",
Toast.LENGTH_LONG).show();
}
});
return row;
}
static class UserHolder {
TextView textName;
TextView textAddress;
TextView textLocation;
Button btnEdit;
Button btnDelete;
}
}
Hey Please have a look here-
I have same answer here on my blog ..
I had the same problem with using webpack-dev-server. I had to add the devServer option to my webpack.
// in webpack
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
There is no such thing as DROP CONSTRAINT
in MySQL. In your case you could use DROP FOREIGN KEY
instead.
.blur-bgimage {
overflow: hidden;
margin: 0;
text-align: left;
}
.blur-bgimage:before {
content: "";
position: absolute;
width : 100%;
height: 100%;
background: inherit;
z-index: -1;
filter : blur(10px);
-moz-filter : blur(10px);
-webkit-filter: blur(10px);
-o-filter : blur(10px);
transition : all 2s linear;
-moz-transition : all 2s linear;
-webkit-transition: all 2s linear;
-o-transition : all 2s linear;
}
You can blur the body background image by using the body's :before pseudo class to inherit the image and then blurring it. Wrap all that into a class and use javascript to add and remove the class to blur and unblur.
If you are using MinGW toolchain for CDT, make.exe is found at C:\MinGW\msys\1.0\bin
(or search the make.exe in MinGW folder.)
Add this path in eclipse window->preferences->environment
You can do this:
satView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
}
}
);
It looks like there is no difference, for
uses each
underneath.
$ irb
>> for x in nil
>> puts x
>> end
NoMethodError: undefined method `each' for nil:NilClass
from (irb):1
>> nil.each {|x| puts x}
NoMethodError: undefined method `each' for nil:NilClass
from (irb):4
Like Bayard says, each is more idiomatic. It hides more from you and doesn't require special language features. Per Telemachus's Comment
for .. in ..
sets the iterator outside the scope of the loop, so
for a in [1,2]
puts a
end
leaves a
defined after the loop is finished. Where as each
doesn't. Which is another reason in favor of using each
, because the temp variable lives a shorter period.
If you're using Bash you could also use one of the following commands:
printf '%(%Y%m%d%H%M%S)T' # prints the current time
printf '%(%Y%m%d%H%M%S)T' -1 # same as above
printf '%(%Y%m%d%H%M%S)T' -2 # prints the time the shell was invoked
You can use the Option -v varname
to store the result in $varname
instead of printing it to stdout:
printf -v varname '%(%Y%m%d%H%M%S)T'
While the date command will always be executed in a subshell (i.e. in a separate process) printf is a builtin command and will therefore be faster.
The statement :: driver.manage().window.maximize();
Works perfectly, but the window maximizes only after loading the page on browser, it does not maximizes at the time of initializing the browser.
here : (driver) is called object of Firefox driver, it may be any thing depending on the initializing of Firefox object by you only.
For me the issue was VPN, I disconnected the VPN and "npm i" command worked with no fail.
I don't like "hacks" but in a quick pinch for a deadline I have done this
<li ng-if="edit === false && filtered.length === 0">
<p ng-if="group.title != 'Dispatcher News'" style="padding: 5px">No links in group.</p>
</li>
Yes, I have another inner nested ng-if, I just didn't like too many conditions on one line.
a core dump is usually only made when the Windows kernel crashes (aka blue screen). A servicecrash will most of the times only leave some logging behind (in the event viewer probably).
If it is the bluescreen crash dump you are looking for, look in C:\Windows\Minidump or C:\windows\MEMORY.DMP
I have made my own implementation to do this on the simplest way as possible.
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import junit.framework.Assert;
/**
* Created by Daniel on 28/08/2016.
*/
public abstract class AbstractSystemServiceTask {
private final Context context;
private final AlarmManager alarmManager;
private final BroadcastReceiver broadcastReceiver;
private final PendingIntent pendingIntent;
public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType, final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("ApplicationContext can't be null", context);
Assert.assertNotNull("ID can't be null", id);
this.context = context;
this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);
this.context.registerReceiver(
this.broadcastReceiver = this.getBroadcastReceiver(backgroundTaskListener),
new IntentFilter(id));
this.configAlarmManager(
this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
time,
alarmType);
}
public void stop() {
this.alarmManager.cancel(this.pendingIntent);
this.context.unregisterReceiver(this.broadcastReceiver);
}
private BroadcastReceiver getBroadcastReceiver(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null.", backgroundTaskListener);
return new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
backgroundTaskListener.perform(context, intent);
}
};
}
private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {
long ensurePositiveTime = Math.max(time, 0L);
switch (alarmType) {
case REPEAT:
this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
break;
case ONE_TIME:
default:
this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
}
}
public interface BackgroundTaskListener {
void perform(Context context, Intent intent);
}
public enum AlarmType {
REPEAT, ONE_TIME;
}
}
The only next step, implement it.
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import ...AbstractSystemServiceTask;
import java.util.concurrent.TimeUnit;
/**
* Created by Daniel on 28/08/2016.
*/
public class UpdateInfoSystemServiceTask extends AbstractSystemServiceTask {
private final static String ID = "UPDATE_INFO_SYSTEM_SERVICE";
private final static long REPEAT_TIME = TimeUnit.SECONDS.toMillis(10);
private final static AlarmType ALARM_TYPE = AlarmType.REPEAT;
public UpdateInfoSystemServiceTask(Context context) {
super(context, ID, REPEAT_TIME, ALARM_TYPE, new BackgroundTaskListener() {
@Override
public void perform(Context context, Intent intent) {
Log.i("MyAppLog", "-----> UpdateInfoSystemServiceTask");
//DO HERE WHATEVER YOU WANT...
}
});
Log.i("MyAppLog", "UpdateInfoSystemServiceTask started.");
}
}
I like to work with this implementation, but another possible good way, it's don't make the AbstractSystemServiceTask
class abstract, and build it through a Builder.
I hope it help you.
UPDATED
Improved to allow several BackgroundTaskListener
on the same BroadCastReceiver
.
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import junit.framework.Assert;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Daniel on 28/08/2016.
*/
public abstract class AbstractSystemServiceTask {
private final Context context;
private final AlarmManager alarmManager;
private final BroadcastReceiver broadcastReceiver;
private final PendingIntent pendingIntent;
private final Set<BackgroundTaskListener> backgroundTaskListenerSet;
public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType) {
Assert.assertNotNull("ApplicationContext can't be null", context);
Assert.assertNotNull("ID can't be null", id);
this.backgroundTaskListenerSet = new HashSet<>();
this.context = context;
this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE);
this.context.registerReceiver(
this.broadcastReceiver = this.getBroadcastReceiver(),
new IntentFilter(id));
this.configAlarmManager(
this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0),
time,
alarmType);
}
public synchronized void registerTask(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);
this.backgroundTaskListenerSet.add(backgroundTaskListener);
}
public synchronized void removeTask(final BackgroundTaskListener backgroundTaskListener) {
Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener);
this.backgroundTaskListenerSet.remove(backgroundTaskListener);
}
public void stop() {
this.backgroundTaskListenerSet.clear();
this.alarmManager.cancel(this.pendingIntent);
this.context.unregisterReceiver(this.broadcastReceiver);
}
private BroadcastReceiver getBroadcastReceiver() {
return new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
for (BackgroundTaskListener backgroundTaskListener : AbstractSystemServiceTask.this.backgroundTaskListenerSet) {
backgroundTaskListener.perform(context, intent);
}
}
};
}
private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) {
long ensurePositiveTime = Math.max(time, 0L);
switch (alarmType) {
case REPEAT:
this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent);
break;
case ONE_TIME:
default:
this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent);
}
}
public interface BackgroundTaskListener {
void perform(Context context, Intent intent);
}
public enum AlarmType {
REPEAT, ONE_TIME;
}
}
like so:
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("cart") > -1)
{
alert("your url contains the name franky");
}
});
</script>
Using UIApplication.openSettingsURLString
Update for Swift 5.1
override func viewDidAppear(_ animated: Bool) {
let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
print("Settings opened: \(success)") // Prints true
})
}
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
Swift 4.2
override func viewDidAppear(_ animated: Bool) {
let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
print("Settings opened: \(success)") // Prints true
})
}
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
You can download 7 free WPF themes from http://www.nukeation.com/free.aspx . I found them very useful. You should surely try it out. They are designed by the people who have desiged the official WPF & Silverlight Themes.
RGB values fall nicely on bit boundaries; decimal digits don't. I don't think there's an easy way to do this using bitwise operators at all. You'd need to use decimal operators like modulo 10 (% 10).
I'm using Chrome and print() literally prints the text on paper. This is what works for me:
document.write("My message");
One can use sympy.
import sympy
sympy.ntheory.primetest.isprime(33393939393929292929292911111111)
True
From sympy docs. The first step is looking for trivial factors, which if found enables a quick return. Next, if the sieve is large enough, use bisection search on the sieve. For small numbers, a set of deterministic Miller-Rabin tests are performed with bases that are known to have no counterexamples in their range. Finally if the number is larger than 2^64, a strong BPSW test is performed. While this is a probable prime test and we believe counterexamples exist, there are no known counterexamples
I am able to download it using apple's download website today. https://developer.apple.com/download/
I do not have a paid apple developer account. Before I was only able to see xcode 8.3.3 but somehow today xcode 9 beta also appeared.
I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.
To undo the two deleted files I had to unstage all of the files:
git reset HEAD .
At that point I was able to do the checkout of the deleted items:
git checkout -- WorkingFolder/FileName.ext
Finally I was able to restage the rest of the files and continue with my commit.
Use delegate
and event.target
. delegate
takes advantage of the event bubbling by letting one element listen for, and handle, events on child elements. target
is the jQ-normalized property of the event
object representing the object from which the event originated.
$(document).delegate('*', 'click', function (event) {
// event.target is the element
// $(event.target).text() gets its text
});
You can add a helper function that clears event listener for example
function clearEventListener(element) {
const clonedElement = element.cloneNode(true);
element.replaceWith(clonedElement);
return clonedElement;
}
just pass in the element to the function and that's it...
// Prepared By Muhammad Mubashir.
// 26, August, 2011.
// Chnage Back Ground Image of Activity.
package com.ChangeBg_01;
import com.ChangeBg_01.R;
import android.R.color;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ChangeBg_01Activity extends Activity
{
TextView tv;
int[] arr = new int[2];
int i=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
arr[0] = R.drawable.icon1;
arr[1] = R.drawable.icon;
// Load a background for the current screen from a drawable resource
//getWindow().setBackgroundDrawableResource(R.drawable.icon1) ;
final Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
//tv.append("Hello World");
if(i== 2){
i=0;
}
getWindow().setBackgroundDrawableResource(arr[i]);
handler.postDelayed(this, 1000);
i++;
}
};
handler.postDelayed(r, 1000);
Thread thread = new Thread()
{
@Override
public void run() {
try {
while(true)
{
if(i== 2){
//finish();
i=0;
}
sleep(1000);
handler.post(r);
//i++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}
}
/*android:background="#FFFFFF"*/
/*
ImageView imageView = (ImageView) findViewById(R.layout.main);
imageView.setImageResource(R.drawable.icon);*/
// Now get a handle to any View contained
// within the main layout you are using
/* View someView = (View)findViewById(R.layout.main);
// Find the root view
View root = someView.getRootView();*/
// Set the color
/*root.setBackgroundColor(color.darker_gray);*/
The simple solution that is working for me:
XmlDocument xmlDoc = new XmlDocument();
StringWriter sw = new StringWriter();
xmlDoc.LoadXml(rawStringXML);
xmlDoc.Save(sw);
String formattedXml = sw.ToString();
Time#localtime
will give you the time in the current time zone of the machine running the code:
> moment = Time.now.utc
=> 2011-03-14 15:15:58 UTC
> moment.localtime
=> 2011-03-14 08:15:58 -0700
Update: If you want to conver to specific time zones rather than your own timezone, you're on the right track. However, instead of worrying about EST vs EDT, just pass in the general Eastern Time zone -- it will know based on the day whether it is EDT or EST:
> Time.now.utc.in_time_zone("Eastern Time (US & Canada)")
=> Mon, 14 Mar 2011 11:21:05 EDT -04:00
> (Time.now.utc + 10.months).in_time_zone("Eastern Time (US & Canada)")
=> Sat, 14 Jan 2012 10:21:18 EST -05:00
Just use dt.Clear()
Also you can set your TableAdapter/DataAdapter to clear before it fills with data.
This one is work for me:-
/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/
If you have access to Excel, look in the "Statistical Functions" section of the Function Reference within Help. For straight-line best-fit, you need SLOPE and INTERCEPT and the equations are right there.
Oh, hang on, they're also defined online here: http://office.microsoft.com/en-us/excel/HP052092641033.aspx for SLOPE, and there's a link to INTERCEPT. OF course, that assumes MS don't move the page, in which case try Googling for something like "SLOPE INTERCEPT EQUATION Excel site:microsoft.com" - the link given turned out third just now.
According SQL Server 2008 Books You can create local and global temporary tables. Local temporary tables are visible only in the current session, and global temporary tables are visible to all sessions.
'#table_temporal
'##table_global
If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database Engine must be able to distinguish the tables created by the different users. The Database Engine does this by internally appending a numeric suffix to each local temporary table name.
Then there occurs no problem.
Found another solution for the same. It will be more helpful.
START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"
finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".
For PHP7 on CentOS or EC2 Linux AMI:
sudo yum install php70-gd
This will only return 1 row, because you're just selecting a COUNT()
. you will use mysql_num_rows()
on the $query
in this case.
If you want to get a count of each of the ID
's, add GROUP BY id
to the end of the string.
Performance-wise, don't ever ever ever use *
in your queries. If there is 100 unique fields in a table and you want to get them all, you write out all 100, not *
. This is because *
has to recalculate how many fields it has to go, every single time it grabs a field, which takes a lot more time to call.
Factory
and Service
is a just wrapper of a provider
.
Factory
Factory
can return anything which can be a class(constructor function)
, instance of class
, string
, number
or boolean
. If you return a constructor
function, you can instantiate in your controller.
myApp.factory('myFactory', function () {
// any logic here..
// Return any thing. Here it is object
return {
name: 'Joe'
}
}
Service
Service does not need to return anything. But you have to assign everything in this
variable. Because service will create instance by default and use that as a base object.
myApp.service('myService', function () {
// any logic here..
this.name = 'Joe';
}
Actual angularjs code behind the service
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
It just a wrapper around the factory
. If you return something from service
, then it will behave like Factory
.
IMPORTANT
: The return result from Factory and Service will be cache and same will be returned for all controllers.
When should i use them?
Factory
is mostly preferable in all cases. It can be used when you have constructor
function which needs to be instantiated in different controllers.
Service
is a kind of Singleton
Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application.
Eg: Authenticated user details.
For further understanding, read
http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html
http://viralpatel.net/blogs/angularjs-service-factory-tutorial/
I'd make both the input
and label
elements display: block
, and then split the name label & input, and the email label & input into div's
and float them next to each other.
input, label {_x000D_
display:block;_x000D_
}
_x000D_
<form name="message" method="post">_x000D_
<section>_x000D_
_x000D_
<div style="float:left;margin-right:20px;">_x000D_
<label for="name">Name</label>_x000D_
<input id="name" type="text" value="" name="name">_x000D_
</div>_x000D_
_x000D_
<div style="float:left;">_x000D_
<label for="email">Email</label>_x000D_
<input id="email" type="text" value="" name="email">_x000D_
</div>_x000D_
_x000D_
<br style="clear:both;" />_x000D_
_x000D_
</section>_x000D_
_x000D_
<section>_x000D_
_x000D_
<label for="subject">Subject</label>_x000D_
<input id="subject" type="text" value="" name="subject">_x000D_
<label for="message">Message</label>_x000D_
<input id="message" type="text" value="" name="message">_x000D_
_x000D_
</section>_x000D_
</form>
_x000D_
The Array.indexOf()
method will replace the first instance. To get every instance use Array.map()
:
a = a.map(function(item) { return item == 3452 ? 1010 : item; });
Of course, that creates a new array. If you want to do it in place, use Array.forEach()
:
a.forEach(function(item, i) { if (item == 3452) a[i] = 1010; });
Use mvn -N versions:update-child-modules
to update child pom`s version
https://www.mojohaus.org/versions-maven-plugin/examples/update-child-modules.html
Utilizing the fact that you can do set operations on arrays by doing &
(intersection), -
(difference), and |
(union).
Obviously I didn't implement the MultiSet to spec, but this should get you started:
class MultiSet
attr_accessor :set
def initialize(set)
@set = set
end
# intersection
def &(other)
@set & other.set
end
# difference
def -(other)
@set - other.set
end
# union
def |(other)
@set | other.set
end
end
x = MultiSet.new([1,1,2,2,3,4,5,6])
y = MultiSet.new([1,3,5,6])
p x - y # [2,2,4]
p x & y # [1,3,5,6]
p x | y # [1,2,3,4,5,6]
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Your Controller", action = "Your Action", id = UrlParameter.Optional }
);
}
}
PHP uses one of two methods to keep track of sessions. If cookies are enabled, like in your case, it uses them.
If cookies are disabled, it uses the URL. Although this can be done securely, it's harder and it often, well, isn't. See, e.g., session fixation.
Search for it, you will get lots of SEO advice. The conventional wisdom is that you should use the cookies, but php will keep track of the session either way.
Workaround with links:
ln path/to/file/outside/context/file_to_copy ./file_to_copy
On Dockerfile, simply:
COPY file_to_copy /path/to/file
For those who reached here searching if they could undo git clean -f -d
, by which a file created in eclipse was deleted,
You can do the same from the UI using "restore from local history" for ref:Restore from local history
I was able to do this on .net c# with PhantomJSDriver with selenium web driver 3.1
[TestMethod]
public void headless()
{
var driverService = PhantomJSDriverService.CreateDefaultService(@"C:\Driver\phantomjs\");
driverService.SuppressInitialDiagnosticInformation = true;
driverService.AddArgument("--web-security=no");
driverService.AddArgument("--ignore-ssl-errors=yes");
driver = new PhantomJSDriver(driverService);
driver.Navigate().GoToUrl("XXXXXX.aspx");
Thread.Sleep(6000);
}
We had a similar situation, but in our case Infosec agreed to allow any to 1, so we didnt had to fix the slave port, rather fixing the master to high level JNLP port 49187 worked ("Configure Global Security" -> "TCP port for JNLP slave agents").
TCP
49187 - Fixed jnlp port
8080 - jenkins http port
Other ports needed to launch slave as a windows service
TCP
135
139
445
UDP
137
138
I would recommend using lastIndexOf() as opposed to indexOf()
var myString = "this.is.my.file.txt"
alert(myString.substring(myString.lastIndexOf(".")+1))
/^(?:(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(?1)$/m
The shortest way (will print "not same" because String comparison is case sensitive):
def compareString = {
it == "india" ? "same" : "not same"
}
compareString("India")
Godaddy hosting it seems fixed on .htaccess
, myself it is working
RewriteRule ^(.*)$ index.php/$1 [L]
to
RewriteRule ^(.*)$ index.php?/$1 [QSA,L]
It's possible to manually trigger events like this:
Apply the slider behavior to the element
var s = $('#slider').slider();
...
Set the slider value
s.slider('value',10);
Trigger the slide event, passing a ui object
s.trigger('slide',{ ui: $('.ui-slider-handle', s), value: 10 });
You can't: It's a security feature in all modern browsers.
For IE8, it's off by default, but can be reactivated using a security setting:
When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.
The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.
In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.
More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.
I usually send the text I want to copy as an sms message through telnet and then copy the text from the sms message. Here's how:
Connect through telnet:
telnet localhost <port>
telnet localhost 5554
(5554 is the default port. The title bar of the emulator shows the port that is being used, so you can see if it's different).
Send message:
sms send <senders phone number> <message>
sms send 1231231234 This is the message you want to send
(You can just make up the senders phone number)
This works really well for links as the message is automatically converted into a hyperlink which you can click without having to copy / paste it into the browser.
Once the emulator receives the message you can copy it and paste it wherever you like.
Also worth mentioning, in C# the OR operator is short-circuiting. In your example, Close seems to be a property, but if it were a method, it's worth noting that:
if (ActionsLogWriter.Close() || ErrorDumpWriter.Close())
is fundamentally different from
if (ErrorDumpWriter.Close() || ActionsLogWriter.Close())
In C#, if the first expression returns true, the second expression will not be evaluated at all. Just be aware of this. It actually works to your advantage most of the time.
You can't extend Enum
as it's a static class. You can only extend instances of a type. With this in mind, you're going to have to create a static method yourself to do this; the following should work when combined with your existing method GetDescription
:
public static class EnumHelper
{
public static T GetEnumFromString<T>(string value)
{
if (Enum.IsDefined(typeof(T), value))
{
return (T)Enum.Parse(typeof(T), value, true);
}
else
{
string[] enumNames = Enum.GetNames(typeof(T));
foreach (string enumName in enumNames)
{
object e = Enum.Parse(typeof(T), enumName);
if (value == GetDescription((Enum)e))
{
return (T)e;
}
}
}
throw new ArgumentException("The value '" + value
+ "' does not match a valid enum name or description.");
}
}
And the usage of it would be something like this:
Animal giantPanda = EnumHelper.GetEnumFromString<Animal>("Giant Panda");
You can use DefiantJS (http://defiantjs.com) which extends the global object JSON with the method "search". With which you can query XPath queries on JSON structures. Example:
var byId = function(s) {return document.getElementById(s);},
data = {
"people": {
"person": [
{
"name": "Peter",
"age": 43,
"sex": "male"
},
{
"name": "Zara",
"age": 65,
"sex": "female"
}
]
}
},
res = JSON.search( data, '//person[name="Peter"]' );
byId('name').innerHTML = res[0].name;
byId('age').innerHTML = res[0].age;
byId('sex').innerHTML = res[0].sex;
Here is a working fiddle;
http://jsfiddle.net/hbi99/NhL7p/
Since November 2017, one can use tomcat8-maven-plugin:
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat8-maven-plugin -->
<dependency>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat8-maven-plugin</artifactId>
<version>2.2</version>
</dependency>
Note that this plugin resides in ICM repo (not in Maven Central), hence you should add the repo to your pluginsRepositories in your pom.xml:
<pluginRepositories>
<pluginRepository>
<id>icm</id>
<name>Spring Framework Milestone Repository</name>
<url>http://maven.icm.edu.pl/artifactory/repo</url>
</pluginRepository>
</pluginRepositories>
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src','http://example.com/site.js');
document.head.appendChild(my_awesome_script);
Here, since onSaveInstanceState
in fragment does not call when you add fragment into backstack. The fragment lifecycle in backstack when restored start onCreateView
and end onDestroyView
while onSaveInstanceState
is called between onDestroyView
and onDestroy
. My solution is create instance variable and init in onCreate
. Sample code:
private boolean isDataLoading = true;
private ArrayList<String> listData;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
isDataLoading = false;
// init list at once when create fragment
listData = new ArrayList();
}
And check it in onActivityCreated
:
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(isDataLoading){
fetchData();
}else{
//get saved instance variable listData()
}
}
private void fetchData(){
// do fetch data into listData
}
Check out Padolsey's article on DOM find and replace, as well as the library to implement the described algorithm.
In this sample usage, I replace all text inside a <div id="content">
that looks like a US telephone number with a tel:
scheme link:
findAndReplaceDOMText(document.getElementById('content'), {
find:/\b(\d\d\d-\d\d\d-\d\d\d\d)\b/g,
replace:function (portion) {
var a = document.createElement('a');
a.className = 'telephone';
a.href = 'tel:' + portion.text.replace(/\D/g, '');
a.textContent = portion.text;
return a;
}
});
(In reply to the "has the situation improved?" part of the question):
Unfortunately, not really. Illustrator's support for SVG has always been a little shaky, and, having mucked around in Illustrator's internals, I doubt we'll see much improvement as far as Illustrator is concerned.
If you're looking for DOM-style access to an Illustrator document, you might want to check out Hanpuku (Disclosure #1: I'm the author. Disclosure #2: It's research code, meaning there are bugs aplenty, and future support is unlikely).
With Hanpuku, you could do something like:
In the script editor, type:
selection.attr('d', 'M 0 0 L 20 134 L 233 24 Z');
Click run
Granted, this approach doesn't expose the original path string. If you follow the instructions toward the end of the plugin's welcome page, it's possible to edit the Illustrator document with Chrome's developer tools, but there will be lots of ugly engineering exposed everywhere (the SVG DOM that mirrors the Illustrator document is buried inside an iframe deep in the extension—changing the DOM with Chrome's tools and clicking "To Illustrator" should still work, but you will likely encounter lots of problems).
TL;DR: Illustrator uses an internal model that's pretty different from SVG in a lot of ways, meaning that when you iterate between the two, currently, your only choice is to use the subset of features that both support in the same way.
Go to the address below on GitHub and download each of the FontAwesome files.
https://github.com/FortAwesome/font-awesome-sass/tree/master/assets/fonts/font-awesome
...but instead of right-clicking and saving the link as, click on each of the files and use the 'Download' button to save them.
I found that saving the link as downloaded an HTML page and not the FontAwesome file binary itself.
Once I had all of the binaries it worked for me.
Usually I will clone the initial repository first, and then move everything in the existing folder to the initial repository. It works every time.
The advantage of this method is that you won't missing anything of the initial repository including README or .gitignore.
You can also use the command below to finish the steps:
$ git clone https://github.com/your_repo.git && mv existing_folder/* your_repo
May be you want this (oop in javascript)
function box(color)
{
this.color=color;
}
var box1=new box('red');
var box2=new box('white');
you need itertools.product
:
>>> import itertools
>>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
>>> list(itertools.product(*a))
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 4, 10), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 5, 10), (1, 6, 7), (1, 6, 8), (1, 6, 9), (1, 6, 10), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 4, 10), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 5, 10), (2, 6, 7), (2, 6, 8), (2, 6, 9), (2, 6, 10), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 4, 10), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 5, 10), (3, 6, 7), (3, 6, 8), (3, 6, 9), (3, 6, 10)]
For completeness, in addition to previous answers (perform calculation of visible people inside controller) you can also perform that calculations in your HTML template as in the example below.
Assuming your list of people is in data
variable and you filter people using query
model, the following code will work for you:
<p>Number of visible people: {{(data|filter:query).length}}</p>
<p>Total number of people: {{data.length}}</p>
{{data.length}}
- prints total number of people{{(data|filter:query).length}}
- prints filtered number of peopleNote that this solution works fine if you want to use filtered data only once in a page. However, if you use filtered data more than once e.g. to present items and to show length of filtered list, I would suggest using alias expression (described below) for AngularJS 1.3+ or the solution proposed by @Wumms for AngularJS version prior to 1.3.
New Feature in Angular 1.3
AngularJS creators also noticed that problem and in version 1.3 (beta 17) they added "alias" expression which will store the intermediate results of the repeater after the filters have been applied e.g.
<div ng-repeat="person in data | filter:query as results">
<!-- template ... -->
</div>
<p>Number of visible people: {{results.length}}</p>
The alias expression will prevent multiple filter execution issue.
I hope that will help.
Not all servers support jsonp. It requires the server to set the callback function in it's results. I use this to get json responses from sites that return pure json but don't support jsonp:
function AjaxFeed(){
return $.ajax({
url: 'http://somesite.com/somejsonfile.php',
data: {something: true},
dataType: 'jsonp',
/* Very important */
contentType: 'application/json',
});
}
function GetData() {
AjaxFeed()
/* Everything worked okay. Hooray */
.done(function(data){
return data;
})
/* Okay jQuery is stupid manually fix things */
.fail(function(jqXHR) {
/* Build HTML and update */
var data = jQuery.parseJSON(jqXHR.responseText);
return data;
});
}
The shortest way to get your local ipv4-address on your linux system:
hostname -I | awk '{print $1}'
Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):
Exception in thread "main" java.lang.ClassCastException:
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
The solution is to get the 'parent' node, and perform a put
, effectively replacing the entire node, regardless of original node type.
If you need to "modify" the node using the existing value of the node:
get
the value/array of the JsonNode
put
on the parent.Code, where the goal is to modify subfield
, which is the child node of NodeA
and Node1
:
JsonNode nodeParent = someNode.get("NodeA")
.get("Node1");
// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");
Credits:
I got this inspiration from here, thanks to wassgreen@
For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:
class DropTables < ActiveRecord::Migration
def up
drop_table :table_you_dont_want
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
Microsoft provides a walkthrough for creating a Windows Explorer style interface in C#.
There are also several examples on Code Project and other sites. Immediate examples are Explorer Tree, My Explorer, File Browser and Advanced File Explorer but there are others. Explorer Tree seems to look the best from the brief glance I took.
I used the search term windows explorer tree view C#
in Google to find these links.
You are applying shapiro.test()
to a data.frame
instead of the column. Try the following:
shapiro.test(heisenberg$HWWIchg)
use:
<input type="image" src=".."/>
or:
<button type="send"><img src=".."/> + any html code</button>
plus some CSS
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
Just add click event by jquery in $(document).ready() like :
$(document).ready(function(){
$('#YourControlID').click(function(){
if(Check your condtion)
{
$.messager.show({
title:'My Title',
msg:'The message content',
showType:'fade',
style:{
right:'',
bottom:''
}
});
}
});
});
If you are a Java programmer you will need JDK in your system and this package will include JRE and JVM as well but if you are normal user who like to play online games then you will only need JRE and this package will not have JDK in it.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent.
JRE
It contains everything you need to run Java applications in compiled form. You don't need any libraries and other stuffs. All things you need are compiled.
JRE is can not used for development, only used for run the applications.
Java SE Development Kit (JDK)
The JDK includes the JRE plus command-line development tools such as compilers and debuggers that are necessary or useful for developing applets and applications.
(Sources: GeeksForGeeks Q&A, Java Platform Overview)
I had to make some long descriptions ellipse(take only one lane) while being responsive, so my solution was to let the text wrap(instead of white-space: nowrap
) and instead of fixed width I added fixed height:
span {_x000D_
display: inline-block;_x000D_
line-height: 1rem;_x000D_
height: 1rem;_x000D_
overflow: hidden;_x000D_
// OPTIONAL LINES_x000D_
width: 75%;_x000D_
background: green;_x000D_
// white-space: normal; default_x000D_
}
_x000D_
<span>_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi quia quod reprehenderit saepe sit. Animi deleniti distinctio dolorum iste molestias reiciendis saepe. Ea eius ex, ipsam iusto laudantium natus obcaecati quas rem repellat temporibus! A alias at, atque deserunt dignissimos dolor earum, eligendi eveniet exercitationem natus non, odit sint sit tempore voluptate. Commodi culpa ex facere id minima nihil nulla omnis praesentium quasi quia quibusdam recusandae repellat sequi ullam, voluptates. Aliquam commodi debitis delectus magnam nulla, omnis sequi sint unde voluptas voluptatum. Adipisci aliquam deserunt dolor enim facilis libero, maxime molestias, nemo neque non nostrum placeat reprehenderit, rerum ullam vel? A atque autem consectetur cum, doloremque doloribus fugiat hic id iste nemo nesciunt officia quaerat quibusdam quidem quisquam similique sit tempora vel. Accusamus aspernatur at au_x000D_
</span>
_x000D_
This works better in my case if you have object or multi-dimensional array. It will shows only first items, other will be just ignored in loop.
.filter('limitItems', function () {
return function (items) {
var result = {}, i = 1;
angular.forEach(items, function(value, key) {
if (i < 5) {
result[key] = value;
}
i = i + 1;
});
return result;
};
});
Change 5 on what you want.
Number("2,299.00".split(',').join('')); // 2299
The split function splits the string into an array using "," as a separator and returns an array.
The join function joins the elements of the array returned from the split function.
The Number() function converts the joined string to a number.
A simple and sustainable solution is to create a layer-list and make it as the background of your TextView:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:left="-5dp"
android:right="-5dp"
android:top="-5dp">
<shape>
<stroke
android:width="1.5dp"
android:color="@color/colorAccent" />
</shape>
</item>
</layer-list>
I am assuming that you are wanting to add items to a ComboBox on an Windows form. Although Klaus is on the right track I believe that the ListItem class is a member of the System.Web.UI.WebControls namespace. So you shouldn't be using it in a Windows forms solution. You can, however, create your own class that you can use in its place. Create a simple class called MyListItem (or whatever name you choose) like this:
Public Class MyListItem
Private mText As String
Private mValue As String
Public Sub New(ByVal pText As String, ByVal pValue As String)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As String
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
Now when you want to add the items to your ComboBox you can do it like this:
myComboBox.Items.Add(New MyListItem("Text to be displayed", "value of the item"))
Now when you want to retrieve the value of the selected item from your ComboBox you can do it like this:
Dim oItem As MyListItem = CType(myComboBox.SelectedItem, MyListItem)
MessageBox.Show("The Value of the Item selected is: " & oItem.Value)
One of the keys here is overriding the ToString method in the class. This is where the ComboBox gets the text that is displayed.
Matt made an excellent point, in his comment below, about using Generics to make this even more flexible. So I wondered what that would look like.
Here's the new and improved GenericListItem
class:
Public Class GenericListItem(Of T)
Private mText As String
Private mValue As T
Public Sub New(ByVal pText As String, ByVal pValue As T)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As T
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
And here is how you would now add Generic items to your ComboBox. In this case an Integer:
Me.myComboBox.Items.Add(New GenericListItem(Of Integer)("Text to be displayed", 1))
And now the retrieval of the item:
Dim oItem As GenericListItem(Of Integer) = CType(Me.myComboBox.SelectedItem, GenericListItem(Of Integer))
MessageBox.Show("The value of the Item selected is: " & oItem.Value.ToString())
Keep in mind that the type Integer
can be any type of object or value type. If you want it to be an object from one of your own custom classes that's fine. Basically anything goes with this approach.
In my EPiServer solution on several controllers there was a ContentOutputCache attribute on the Index action which accepted HttpGet. Each view for those actions contained a form which was posting to a HttpPost action to the same controller or to a different one. As soon as I removed that attribute from all of those Index actions problem was gone.
autoSize for column width set as bellow. It works for me.
$spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
the first thing we need is the permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
so in an asyncTask Kotlin class, we treat the creation of the file
import android.os.AsyncTask
import android.os.Environment
import android.util.Log
import java.io.*
class WriteFile: AsyncTask<String, Int, String>() {
private val mFolder = "/MainFolder"
lateinit var folder: File
internal var writeThis = "string to cacheApp.txt"
internal var cacheApptxt = "cacheApp.txt"
override fun doInBackground(vararg writethis: String): String? {
val received = writethis[0]
if(received.isNotEmpty()){
writeThis = received
}
folder = File(Environment.getExternalStorageDirectory(),"$mFolder/")
if(!folder.exists()){
folder.mkdir()
val readME = File(folder, cacheApptxt)
val file = File(readME.path)
val out: BufferedWriter
try {
out = BufferedWriter(FileWriter(file, true), 1024)
out.write(writeThis)
out.newLine()
out.close()
Log.d("Output_Success", folder.path)
} catch (e: Exception) {
Log.d("Output_Exception", "$e")
}
}
return folder.path
}
override fun onPostExecute(result: String) {
super.onPostExecute(result)
if(result.isNotEmpty()){
//implement an interface or do something
Log.d("onPostExecuteSuccess", result)
}else{
Log.d("onPostExecuteFailure", result)
}
}
}
Of course if you are using Android above Api 23, you must handle the request to allow writing to device memory. Something like this
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class ReadandWrite {
private val mREAD = 9
private val mWRITE = 10
private var readAndWrite: Boolean = false
fun readAndwriteStorage(ctx: Context, atividade: AppCompatActivity): Boolean {
if (Build.VERSION.SDK_INT < 23) {
readAndWrite = true
} else {
val mRead = ContextCompat.checkSelfPermission(ctx, Manifest.permission.READ_EXTERNAL_STORAGE)
val mWrite = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (mRead != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), mREAD)
} else {
readAndWrite = true
}
if (mWrite != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(atividade, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), mWRITE)
} else {
readAndWrite = true
}
}
return readAndWrite
}
}
then in an activity, execute the call.
var pathToFileCreated = ""
val anRW = ReadandWrite().readAndwriteStorage(this,this)
if(anRW){
pathToFileCreated = WriteFile().execute("onTaskComplete").get()
Log.d("pathToFileCreated",pathToFileCreated)
}
To exclude content and subdirectories:
**/bin/*
To just exclude all subdirectories but take the content, add "/":
**/bin/*/
For my mac environment
sudo chown -R $USER /usr/local/lib/node_modules
solve the issue
try it like this
StringBuilder sb = new StringBuilder();
foreach (ListItem item in ddlAge.Items)
{
if (item.Selected)
{
string sqlCommand = "SELECT * from TableA WHERE Age IN (@Age)";
SqlConnection sqlCon = new SqlConnection(connectString);
SqlCommand sqlComm = new SqlCommand();
sqlComm.Connection = sqlCon;
sqlComm.CommandType = System.Data.CommandType.Text;
sqlComm.CommandText = sqlCommand;
sqlComm.CommandTimeout = 300;
sqlComm.Parameters.Add("@Age", SqlDbType.NVarChar);
sb.Append(item.Text + ",");
sqlComm.Parameters["@Age"].Value = sb.ToString().TrimEnd(',');
}
}
just use this.
int fxd=1;
double percent= (double)(fxd*40)/100;
I think it may be worth mentioning that [ConditionalAttribute]
is in the System.Diagnostics;
namespace. I stumbled a bit when I got:
Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)
after using it for the first time (I thought it would have been in System
).
You can use a time_t
struct and clock()
function from time.h.
Store the start time in a time_t
struct by using clock()
and check the elapsed time by comparing the difference between stored time and current time.
If you are using the Eloquent ORM you should consider using scopes. This would keep your logic in the model where it belongs.
So, in the model you would have:
public function scopeIdDescending($query)
{
return $query->orderBy('id','DESC');
}
And outside the model you would have:
$posts = Post::idDescending()->get();
What you have is a parse error. Those are thrown before any code is executed. A PHP file needs to be parsed in its entirety before any code in it can be executed. If there's a parse error in the file where you're setting your error levels, they won't have taken effect by the time the error is thrown.
Either break your files up into smaller parts, like setting the error levels in one file and then include
ing another file which contains the actual code (and errors), or set the error levels outside PHP using php.ini or .htaccess directives.
Blockquote
final int[] count = {0};
showandhide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(count[0] ==0)
{
password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
count[0]++;
}
else {
password.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
showandhide.setText("Hide");
count[0]--;
}
}
});
You may be interested by the pack_forget
and grid_forget
methods of a widget. In the following example, the button disappear when clicked
from Tkinter import *
def hide_me(event):
event.widget.pack_forget()
root = Tk()
btn=Button(root, text="Click")
btn.bind('<Button-1>', hide_me)
btn.pack()
btn2=Button(root, text="Click too")
btn2.bind('<Button-1>', hide_me)
btn2.pack()
root.mainloop()
editText.setInputType(InputType.TYPE_NULL);
You can also use the drop_duplicates() instead of unique()
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].drop_duplicates()
a.sort()
print a
The command for your rescue is git clean
.
If you want to inspect html, css or maybe you need js console in your mobile browser . You can use excelent tool eruda Using it you have the same Developer Tools on your mobile browser like in your desctop device. Dont forget to upvote :) Here is a link https://github.com/liriliri/eruda
@Mark Rajcok gave a great solution for ion projects that include a range type input.
In any other case of non ion projects I will suggest this:
HTML:
<input type="text" name="points" #points maxlength="8" [(ngModel)]="range" (ngModelChange)="range=saverange($event, points)">
Component:
onChangeAchievement(eventStr: string, eRef): string {
//Do something (some manipulations) on input and than return it to be saved:
//In case you need to force of modifing the Element-Reference value on-focus of input:
var eventStrToReplace = eventStr.replace(/[^0-9,eE\.\+]+/g, "");
if (eventStr != eventStrToReplace) {
eRef.value = eventStrToReplace;
}
return this.getNumberOnChange(eventStr);
}
The idea here:
Letting the (ngModelChange)
method to do the Setter job:
(ngModelChange)="range=saverange($event, points)
Enabling direct access to the native Dom element using this call:
eRef.value = eventStrToReplace;
you can use:
$('body').ready(function(){
$(document).on('change', '#elemID', function(){
// do something
});
});
It works with me.
public class MainActivity extends Activity
implements View.OnClickListener {
private Button btnForward, btnBackword, btnPause, btnPlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControl();
}
private void initControl() {
btnForward = (Button) findViewById(R.id.btnForward);
btnBackword = (Button) findViewById(R.id.btnBackword);
btnPause = (Button) findViewById(R.id.btnPause);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnForward.setOnClickListener(this);
btnBackword.setOnClickListener(this);
btnPause.setOnClickListener(this);
btnPlay.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnForward:
break;
case R.id.btnBackword:
break;
case R.id.btnPause:
break;
case R.id.btnPlay:
break;
}
}
}
HTML:
<a href="#" class="yourlink">Click Here</a>
JS:
$('a.yourlink').click(function(e) {
e.preventDefault();
window.open('http://yoururl1.com');
window.open('http://yoururl2.com');
});
window.open
also can take additional parameters. See them here: http://www.javascript-coder.com/window-popup/javascript-window-open.phtml
You should also know that window.open is sometimes blocked by popup blockers and/or ad-filters.
Addition from Paul below: This approach also places a dependency on JavaScript being enabled. Not typically a good idea, but sometimes necessary.
I think it's meant to mean nothing. The wiki says:
"Foo is commonly used with the metasyntactic variables bar and foobar."
const year = 2014;_x000D_
const month = 09;_x000D_
_x000D_
// months start at index 0 in momentjs, so we subtract 1_x000D_
const startDate = moment([year, month - 1, 01]).format("YYYY-MM-DD");_x000D_
_x000D_
// get the number of days for this month_x000D_
const daysInMonth = moment(startDate).daysInMonth();_x000D_
_x000D_
// we are adding the days in this month to the start date (minus the first day)_x000D_
const endDate = moment(startDate).add(daysInMonth - 1, 'days').format("YYYY-MM-DD");_x000D_
_x000D_
console.log(`start date: ${startDate}`);_x000D_
console.log(`end date: ${endDate}`);
_x000D_
<script_x000D_
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js">_x000D_
</script>
_x000D_
use -Wno-reorder
(man gcc is your friend :) )
You can use a while loop like this:
String text = "Hello";
while (text.length() < 10) { text += "*"; }
System.out.println(text);
Will give you:
Hello*****
Or get the same result with a custom method:
public static String extendString(String text, String symbol, Integer len) {
while (text.length() < len) { text += symbol; }
return text;
}
Then just call:
extendString("Hello", "*", 10)
It may also be a good idea to set a length check to prevent infinite loop.
Two things: Change the variables x
, y
, z
as int
and call the method as Math.max(Math.max(x,y),z)
as it accepts two parameters only.
In Summary, change below:
String x = keyboard.nextLine();
String y = keyboard.nextLine();
String z = keyboard.nextLine();
int max = Math.max(x,y,z);
to
int x = keyboard.nextInt();
int y = keyboard.nextInt();
int z = keyboard.nextInt();
int max = Math.max(Math.max(x,y),z);
In Swift 3.0
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
In older swift: Do something like this:
let screenSize: CGRect = UIScreen.mainScreen().bounds
then you can access the width and height like this:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if you want 75% of your screen's width you can go:
let screenWidth = screenSize.width * 0.75
Swift 4.0
// Screen width.
public var screenWidth: CGFloat {
return UIScreen.main.bounds.width
}
// Screen height.
public var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
In Swift 5.0
let screenSize: CGRect = UIScreen.main.bounds
I added the .ico file to my project, setting the Build Action to Embedded Resource. I specified the path to that file as the project's icon in the project settings, and then I used the code below in the form's constructor to share it. This way, I don't need to maintain a resources file anywhere with copies of the icon. All I need to do to update it is to replace the file.
var exe = System.Reflection.Assembly.GetExecutingAssembly();
var iconStream = exe.GetManifestResourceStream("Namespace.IconName.ico");
if (iconStream != null) Icon = new Icon(iconStream);
Validate the INPUT.
$time = strtotime($_POST['dateFrom']);
if ($time) {
$new_date = date('Y-m-d', $time);
echo $new_date;
} else {
echo 'Invalid Date: ' . $_POST['dateFrom'];
// fix it.
}
If your environment doesn't allow overwriting with >
, use pipe |
and tee
instead as follows:
echo "text" | tee 'Users/Name/Desktop/TheAccount.txt'
Note this will also print to the stdout. In case this is unwanted, you can redirect the output to /dev/null
as follows:
echo "text" | tee 'Users/Name/Desktop/TheAccount.txt' > /dev/null
Try this:
$('#ddlCodes').change(function() {
var option = this.options[this.selectedIndex];
$('#txtEntry2').text($(option).text());
});
if your table is like this
rowId col1 col2 col3 col4
1 a e 12 2
2 b f 42 5
3 a e 32 2
4 b f 44 5
var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});
I am not sure if this fits your oracle version. On my 10g I can use pipelined table functions:
set serveroutput on
create type number_list as table of number;
-- since you want this solution
create or replace function split_csv (i_csv varchar2) return number_list pipelined
is
mystring varchar2(2000):= i_csv;
begin
for r in
( select regexp_substr(mystring,'[^,]+',1,level) element
from dual
connect by level <= length(regexp_replace(mystring,'[^,]+')) + 1
)
loop
--dbms_output.put_line(r.element);
pipe row(to_number(r.element, '999999.99'));
end loop;
end;
/
insert into foo
select column_a,column_b from
(select column_value column_a, rownum rn from table(split_csv('0.75, 0.64, 0.56, 0.45'))) a
,(select column_value column_b, rownum rn from table(split_csv('0.25, 0.5, 0.65, 0.8'))) b
where a.rn = b.rn
;
I would recommend the read_csv
function from the pandas
library:
import pandas as pd
df=pd.read_csv('myfile.csv', sep=',',header=None)
df.values
array([[ 1. , 2. , 3. ],
[ 4. , 5.5, 6. ]])
This gives a pandas DataFrame - allowing many useful data manipulation functions which are not directly available with numpy record arrays.
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table...
I would also recommend genfromtxt
. However, since the question asks for a record array, as opposed to a normal array, the dtype=None
parameter needs to be added to the genfromtxt
call:
Given an input file, myfile.csv
:
1.0, 2, 3
4, 5.5, 6
import numpy as np
np.genfromtxt('myfile.csv',delimiter=',')
gives an array:
array([[ 1. , 2. , 3. ],
[ 4. , 5.5, 6. ]])
and
np.genfromtxt('myfile.csv',delimiter=',',dtype=None)
gives a record array:
array([(1.0, 2.0, 3), (4.0, 5.5, 6)],
dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<i4')])
This has the advantage that file with multiple data types (including strings) can be easily imported.
If you want to stick to command line FTP, you should try NcFTP. Then you can use get -R to recursively get a folder. You will also get completion.
I had this issue in Windows 10 when I needed IIS instead of IIS Express. New Web Project failed with OP's error. Fix was
Control Panel > Turn Windows Features on or off > Internet Information Services > World Wide Web Services > Application Development Features
tick ASP.NET 4.7
(in my case)
For people who find this when attempting to run tests because via npm test
or ng test
using Karma or whatever else. Your .spec module needs a special router testing import to be able to build.
import { RouterTestingModule } from '@angular/router/testing';
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [AppComponent],
});
http://www.kirjai.com/ng2-component-testing-routerlink-routeroutlet/
You can try the following code to request camera permission in marshmallow. First check if the user grant the permission. If user has not granted the permission, then request the camera permission:
private static final int MY_CAMERA_REQUEST_CODE = 100;
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
}
After requesting the permission, dialog will display to ask permission containing allow
and deny
options. After clicking action we can get result of the request with the following method:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
}
Just for completeness, you can also use ORA_DATABASE_NAME.
It might be worth noting that not all of the methods give you the same output:
SQL> select sys_context('userenv','db_name') from dual;
SYS_CONTEXT('USERENV','DB_NAME')
--------------------------------------------------------------------------------
orcl
SQL> select ora_database_name from dual;
ORA_DATABASE_NAME
--------------------------------------------------------------------------------
ORCL.XYZ.COM
SQL> select * from global_name;
GLOBAL_NAME
--------------------------------------------------------------------------------
ORCL.XYZ.COM
There is a package called yum-utils
that builds on YUM and contains a tool called repoquery
that can do this.
$ repoquery --help | grep -E "list\ files"
-l, --list list files in this package/group
Combined into one example:
$ repoquery -l time
/usr/bin/time
/usr/share/doc/time-1.7
/usr/share/doc/time-1.7/COPYING
/usr/share/doc/time-1.7/NEWS
/usr/share/doc/time-1.7/README
/usr/share/info/time.info.gz
On at least one RH system, with rpm v4.8.0, yum v3.2.29, and repoquery v0.0.11, repoquery -l rpm
prints nothing.
If you are having this issue, try adding the --installed
flag: repoquery --installed -l rpm
.
DNF
Update:To use dnf
instead of yum-utils
, use the following command:
$ dnf repoquery -l time
/usr/bin/time
/usr/share/doc/time-1.7
/usr/share/doc/time-1.7/COPYING
/usr/share/doc/time-1.7/NEWS
/usr/share/doc/time-1.7/README
/usr/share/info/time.info.gz
there are many ways. as awk
solutions shows, it's the clean solution
sed solution is to delete anything till the last space. So if there is no space at the end, it should work
sed 's/.* //g' <file>
you can avoid sed
also and go for a while
loop.
while read line
do [ -z "$line" ] && continue ;
echo $line|rev|cut -f1 -d' '|rev
done < file
it reads a line, reveres it, cuts the first (i.e. last in the original) and restores back
the same can be done in a pure bash way
while read line
do [ -z "$line" ] && continue ;
echo ${line##* }
done < file
it is called parameter expansion
If you use XHTML, for some reason, note that XHTML 1.0 C 4 says: “Use external scripts if your script uses < or & or ]]> or --.” That is, don’t embed script code inside a script
element but put it into a separate JavaScript file and refer to it with <script src="foo.js"></script>
.
Percent encoding. Replace the hash with %23
.
If you are using VB.NET (or imported the dependency into your C# project), there actually exists a convenience method that allows to filter for multiple extensions:
Microsoft.VisualBasic.FileIO.FileSystem.GetFiles("C:\\path", Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, new string[] {"*.mp3", "*.jpg"});
In VB.NET this can be accessed through the My-namespace:
My.Computer.FileSystem.GetFiles("C:\path", FileIO.SearchOption.SearchAllSubDirectories, {"*.mp3", "*.jpg"})
Unfortunately, these convenience methods don't support a lazily evaluated variant like Directory.EnumerateFiles()
does.
If you want to do a redirect, you can either:
ViewBag.Error = "error message";
or
TempData["Error"] = "error message";
To start the process with parameters, you can use following code:
string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);
To kill/exit the program again, you can use following code:
proc.CloseMainWindow();
proc.Close();
I wanted to use Font Awesome 5+ and most answers focus on older versions
For the new Font Awesome 5+ the angular project hasn't been released yet, so if you want to make use of the examples mentioned on the font awesome website atm you need to use a work around. (especially the fas, far classes instead of the fa class)
I've just imported the cdn to Font Awesome 5 in my styles.css. Just added this in case it helps someone find the answer quicker than I did :-)
Code in Style.css
@import "https://use.fontawesome.com/releases/v5.0.7/css/all.css";
I found that in my code when I used a ration or percentage for line-height line-height;1.5;
My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px;
so that I could predict exactly how many pixels each page would take with a given number of lines.
Edit you xml file in Notepad++ and build it again. It's work for me
In this context, the word "stub" is used in place of "mock", but for the sake of clarity and precision, the author should have used "mock", because "mock" is a sort of stub, but for testing. To avoid further confusion, we need to define what a stub is.
In the general context, a stub is a piece of program (typically a function or an object) that encapsulates the complexity of invoking another program (usually located on another machine, VM, or process - but not always, it can also be a local object). Because the actual program to invoke is usually not located on the same memory space, invoking it requires many operations such as addressing, performing the actual remote invocation, marshalling/serializing the data/arguments to be passed (and same with the potential result), maybe even dealing with authentication/security, and so on. Note that in some contexts, stubs are also called proxies (such as dynamic proxies in Java).
A mock is a very specific and restrictive kind of stub, because a mock is a replacement of another function or object for testing. In practice we often use mocks as local programs (functions or objects) to replace a remote program in the test environment. In any case, the mock may simulate the actual behaviour of the replaced program in a restricted context.
Most famous kinds of stubs are obviously for distributed programming, when needing to invoke remote procedures (RPC) or remote objects (RMI, CORBA). Most distributed programming frameworks/libraries automate the generation of stubs so that you don't have to write them manually. Stubs can be generated from an interface definition, written with IDL for instance (but you can also use any language to define interfaces).
Typically, in RPC, RMI, CORBA, and so on, one distinguishes client-side stubs, which mostly take care of marshaling/serializing the arguments and performing the remote invocation, and server-side stubs, which mostly take care of unmarshaling/deserializing the arguments and actually execute the remote function/method. Obviously, client stubs are located on the client side, while sever stubs (often called skeletons) are located on the server side.
Writing good efficient and generic stubs becomes quite challenging when dealing with object references. Most distributed object frameworks such as RMI and CORBA deal with distributed objects references, but that's something most programmers avoid in REST environments for instance. Typically, in REST environments, JavaScript programmers make simple stub functions to encapsulate the AJAX invocations (object serialization being supported by JSON.parse
and JSON.stringify
). The Swagger Codegen project provides an extensive support for automatically generating REST stubs in various languages.
There is another solution, if component for React:
var Node = require('react-if-comp');
...
render: function() {
return (
<div id="page">
<Node if={this.state.banner}
then={<div id="banner">{this.state.banner}</div>} />
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
You can open the preferences (multiple options):
Tools
-> Preferences
And depending on the Spyder version you can change the interpreter in the Python interpreter
section (Spyder 3.x):
or in the advanced Console
section (Spyder 2.x):
IMO, the justification for a long param list is that the data or context is dynamic in nature, think of printf(); a good example of using varargs. A better way to handle such cases is by passing a stream or xml structure, this again minimises the number of parameters.
A machine surely wouldn't mind a large number of arguments, but developers do, also think of the maintenance overhead, the number of unit test cases and validation checks. Designers also hate lengthy args list, more arguments mean more changes to interface definitions, whenever a change is to be done. The questions about the coupling/cohesion spring from above aspects.
You can use slice notation with steps:
>>> x = "abcdefghijklm"
>>> x[0::2] #0. 2. 4...
'acegikm'
>>> x[1::2] #1. 3. 5 ..
'bdfhjl'
>>> [i+j for i,j in zip(x[::2], x[1::2])] # zip makes (0,1),(2,3) ...
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']
Same logic applies for lists too. String lenght doesn't matter, because you're simply adding two strings together.
in my case I have used -
(Hyphen) in my script name in case of Jenkinsfile Library.
Got resolved after replacing Hyphen(-) with Underscore(_)
Say P7 is a Cell then you can use the following Syntex to check the value of the cell and assign appropriate value to another cell based on this following nested if:
=IF(P7=0,200,IF(P7=1,100,IF(P7=2,25,IF(P7=3,10,IF((P7=4),5,0)))))
Well that's not possible, but in intellij 13, how about adding a mouse gesture, something like single left mouse click to reformat the code? Or if you don't use the mouse much then add a very simple keyboard hotkey that you use all the time (possibly the "enter"? not sure if intellij would be happy with that to be honest)
Now there's the s (single line) modifier, that lets the dot matches new lines as well :) \s will also match new lines :D
Just add the s behind the slash
/<pre.*?<\/pre>/gms
A map will not keep insertion order. Use *(myMap.begin())
to get the value of the first pair (the one with the smallest key when ordered).
You could also do myMap.begin()->first
to get the key and myMap.begin()->second
to get the value.
From the config shown in the question there is but one appender configured and it is named "EventLogAppender". But in the config for root, the author references an appender named "ConsoleAppender", hence the error message.
<android.support.v7.widget.AppCompatCheckBox
android:id="@+id/checkBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layoutDirection="rtl"
android:text="text" />`
the correct syntax is -
with t1
as
(select * from tab1
where conditions...
),
t2
as
(select * from tab2
where conditions...
(you can access columns of t1 here as well)
)
select * from t1, t2
where t1.col1=t2.col2;
If you have access to the Java 8 Comparable API, Comparable.comparingToInt()
may be of use. (See Java 8 Comparable Documentation).
For example, a Comparator<Dog>
to sort Dog
instances descending by age could be created with the following:
Comparable.comparingToInt(Dog::getDogAge).reversed();
The function take a lambda mapping T
to Integer
, and creates an ascending comparator. The chained function .reversed()
turns the ascending comparator into a descending comparator.
Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.
__main__.py
file for?When creating a Python module, it is common to make the module execute some functionality (usually contained in a main
function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:
if __name__ == '__main__':
# execute only if run as the entry point into the program
main()
You can get the same semantics for a Python package with __main__.py
, which might have the following structure:
.
+-- demo
+-- __init__.py
+-- __main__.py
To see this, paste the below into a Python 3 shell:
from pathlib import Path
demo = Path.cwd() / 'demo'
demo.mkdir()
(demo / '__init__.py').write_text("""
print('demo/__init__.py executed')
def main():
print('main() executed')
""")
(demo / '__main__.py').write_text("""
print('demo/__main__.py executed')
from demo import main
main()
""")
We can treat demo as a package and actually import it, which executes the top-level code in the __init__.py
(but not the main
function):
>>> import demo
demo/__init__.py executed
When we use the package as the entry point to the program, we perform the code in the __main__.py
, which imports the __init__.py
first:
$ python -m demo
demo/__init__.py executed
demo/__main__.py executed
main() executed
You can derive this from the documentation. The documentation says:
__main__
— Top-level script environment
'__main__'
is the name of the scope in which top-level code executes. A module’s__name__
is set equal to'__main__'
when read from standard input, a script, or from an interactive prompt.A module can discover whether or not it is running in the main scope by checking its own
__name__
, which allows a common idiom for conditionally executing code in a module when it is run as a script or withpython -m
but not when it is imported:if __name__ == '__main__': # execute only if run as a script main()
For a package, the same effect can be achieved by including a
__main__.py
module, the contents of which will be executed when the module is run with-m
.
You can also zip up this directory, including the __main__.py
, into a single file and run it from the command line like this - but note that zipped packages can't execute sub-packages or submodules as the entry point:
from pathlib import Path
demo = Path.cwd() / 'demo2'
demo.mkdir()
(demo / '__init__.py').write_text("""
print('demo2/__init__.py executed')
def main():
print('main() executed')
""")
(demo / '__main__.py').write_text("""
print('demo2/__main__.py executed')
from __init__ import main
main()
""")
Note the subtle change - we are importing main
from __init__
instead of demo2
- this zipped directory is not being treated as a package, but as a directory of scripts. So it must be used without the -m
flag.
Particularly relevant to the question - zipapp
causes the zipped directory to execute the __main__.py
by default - and it is executed first, before __init__.py
:
$ python -m zipapp demo2 -o demo2zip
$ python demo2zip
demo2/__main__.py executed
demo2/__init__.py executed
main() executed
Note again, this zipped directory is not a package - you cannot import it either.