You can use the getText() method anywhere in your code it is instancely called by your object, So you can use the method anywhere within a calass
You don't need to go level up and use ..
since all buttons are on the same level:
//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']
The most efficient is to create a buffer of the correct size and then read the file into the buffer.
#include <fstream>
#include <vector>
int main()
{
std::ifstream file("Plop");
if (file)
{
/*
* Get the size of the file
*/
file.seekg(0,std::ios::end);
std::streampos length = file.tellg();
file.seekg(0,std::ios::beg);
/*
* Use a vector as the buffer.
* It is exception safe and will be tidied up correctly.
* This constructor creates a buffer of the correct length.
* Because char is a POD data type it is not initialized.
*
* Then read the whole file into the buffer.
*/
std::vector<char> buffer(length);
file.read(&buffer[0],length);
}
}
add this line in your actiity when you adding tabs in tablayout
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
GROUP BY DATE(date_time_column)
Well, take care of what you mean by "between" too...
days_apart = (to - from).to_i # from + days_apart = to
total_days = (to - from).to_i + 1 # number of "selected" days
in_between_days = (to - from).to_i - 1 # how many days are in between from and to, i.e. excluding those two days
It's a very old post, but if it benefits anyone, we can do something like this:
Long max=((BigInteger) Collections.max(dynamics)).longValue();
Dictionary
<<<>>> Hashtable
differences:
Synchronized()
methodKeyValuePair
<<<>>> Enumerated item: DictionaryEntry
Dictionary
/ Hashtable
similarities:
GetHashCode()
methodSimilar .NET collections (candidates to use instead of Dictionary and Hashtable):
ConcurrentDictionary
- thread safe (can be safely accessed from several threads concurrently)HybridDictionary
- optimized performance (for few items and also for many items)OrderedDictionary
- values can be accessed via int index (by order in which items were added)SortedDictionary
- items automatically sortedStringDictionary
- strongly typed and optimized for stringsThe Java Packager tool compiles, packages, and prepares Java and JavaFX applications for distribution. The javapackager command is the command-line version.
– Oracle's documentation
The javapackager
utility ships with the JDK. It can generate .exe files with the -native exe
flag, among many other things.
WinRun4j is a java launcher for windows. It is an alternative to javaw.exe and provides the following benefits:
- Uses an INI file for specifying classpath, main class, vm args, program args.
- Custom executable name that appears in task manager.
- Additional JVM args for more flexible memory use.
- Built-in icon replacer for custom icon.
- [more bullet points follow]
– WinRun4J's webpage
WinRun4J is an open source utility. It has many features.
Packages your JAR, assets and a JVM for distribution on Windows, Linux and Mac OS X, adding a native executable file to make it appear like a native app. Packr is most suitable for GUI applications.
– packr README
packr is another open source tool.
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself.
– JSmooth's website
JSmooth is open source and has features, but it is very old. The last release was in 2007.
JexePack is a command line tool (great for automated scripting) that allows you to package your Java application (class files), optionally along with its resources (like GIF/JPG/TXT/etc), into a single compressed 32-bit Windows EXE, which runs using Sun's Java Runtime Environment. Both console and windowed applications are supported.
– JexePack's website
JexePack is trialware. Payment is required for production use, and exe files created with this tool will display "reminders" without payment. Also, the last release was in 2013.
InstallAnywhere makes it easy for developers to create professional installation software for any platform. With InstallAnywhere, you’ll adapt to industry changes quickly, get to market faster and deliver an engaging customer experience. And know the vulnerability of your project’s OSS components before you ship.
– InstallAnywhere's website
InstallAnywhere is a commercial/enterprise package that generates installers for Java-based programs. It's probably capable of creating .exe files.
As an alternative to .exe files, you can create a JAR file that automatically runs when double-clicked, by adding an entry point to the JAR manifest.
An excellent source of information on this topic is Excelsior's article "Convert Java to EXE – Why, When, When Not and How".
See also the companion article "Best JAR to EXE Conversion Tools, Free and Commercial".
This code give an animation like pushing viewController in uinavigation controller...
CATransition *animation = [CATransition animation];
animation.type = kCATransitionPush;
animation.subtype = kCATransitionFromRight;
animation.duration = 0.3;
[_viewAccountName.layer addAnimation:animation forKey:nil];
_viewAccountName.hidden = true;
Used this for pop animation...
CATransition *animation = [CATransition animation];
animation.type = kCATransitionPush;
animation.subtype = kCATransitionFromLeft;
animation.duration = 0.3;
[_viewAccountName.layer addAnimation:animation forKey:nil];
_viewAccountName.hidden = false;
I think a better question is "When would you use @classmethod
vs @staticmethod
?"
@classmethod
allows you easy access to private members that are associated to the class definition. this is a great way to do singletons, or factory classes that control the number of instances of the created objects exist.
@staticmethod
provides marginal performance gains, but I have yet to see a productive use of a static method within a class that couldn't be achieved as a standalone function outside the class.
According to this it does have a Text property
http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox_members.aspx
You can also try the "Lines" property if you want the text broken up as lines.
In my case, my dataframe has the following characteristics
<class 'pandas.core.frame.DataFrame'>
Index: 3040 entries, 15/12/2008 to
Data columns (total 1 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Close 3038 non-null float64
dtypes: float64(1)
memory usage: 47.5+ KB
The first option data.index = pd.to_datetime(data.index)
returned
ParserError: String does not contain a date: ParserError: String does not contain a date:
The second option: data.index.to_datetime()
returned
AttributeError: 'Index' object has no attribute 'to_datetime'
It returned
Another option I have tested is. data.index = pd.to_datetime(data.index)
It returned: ParserError: String does not contain a date:
What could be my problem? Thanks
in jquery ajax functions, the success callback signature is:
function (data, textStatus) {
// data could be xmlDoc, jsonObj, html, text, etc...
this; // the options for this ajax request
}
depending on the data type you've asked, using the 'dataType' parameter, you'll get the 'data' argument.
from the docs:
dataType (String) Default: Intelligent Guess (xml or html). The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently pass either responseXML or responseText to your success callback, based on the MIME type of the response.
The available types (and the result passed as the first argument to your success callback) are:
"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching unless option "cache" is used. Note: This will turn POSTs into GETs for remote-domain requests.
"json": Evaluates the response as JSON and returns a JavaScript Object.
"jsonp": Loads in a JSON block using JSONP. Will add an extra "?callback=?" to the end of your URL to specify the callback. (Added in jQuery 1.2)
"text": A plain text string.
IE 7 and previous versions sent the full path of the uploaded file to the server related to the input type="file"
field. Firefox and other modern browsers consider this to be a security flaw and do not. However, this appears to be have been fixed in IE 8.
Perhaps you should instead evaluate why you need the full path to the file as it was located on the client's system. I think it is really superfluous information that should never be posted at all. All you should be concerned with the is the file name so that you can save the file without making changes to the name.
You can use JavaScript as well, in case the textfield is dithered.
WebDriver driver=new FirefoxDriver();
driver.get("http://localhost/login.do");
driver.manage().window().maximize();
RemoteWebDriver r=(RemoteWebDriver) driver;
String s1="document.getElementById('username').value='admin'";
r.executeScript(s1);
The answers so far tell you how to find existing branches:
git branch -r
Or repositories for the same project [see note below]:
git remote -v
There is another case. You might want to know about other project repositories hosted on the same server.
To discover that information, I use SSH or PuTTY to log into to host and ls
to find the directories containing the other repositories. For example, if I cloned a repository by typing:
git clone ssh://git.mycompany.com/git/ABCProject
and want to know what else is available, I log into git.mycompany.com via SSH or PuTTY and type:
ls /git
assuming ls
says:
ABCProject DEFProject
I can use the command
git clone ssh://git.mycompany.com/git/DEFProject
to gain access to the other project.
NOTE: Usually
git remote
simply tells me aboutorigin
-- the repository from which I cloned the project.git remote
would be handy if you were collaborating with two or more people working on the same project and accessing each other's repositories directly rather than passing everything through origin.
I found the answer to may previous post. Here it is.
CREATE TABLE #TempTable (id int)
INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 1,2
INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 3,4
SELECT * FROM #TempTable --this select will chage @@ROWCOUNT value
This is quite handy to use:
var myRedirect = function(redirectUrl, arg, value) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="'+ arg +'" value="' + value + '"></input>' + '</form>');
$('body').append(form);
$(form).submit();
};
then use it like:
myRedirect("/yourRedirectingUrl", "arg", "argValue");
I had the same issue and atom-goto-definition (package name goto-definition) worked like charm for me. Please try once. You can download directly from Atom.
This package is DEPRECATED. Please check it in Github.
Something that works for me. Enjoy.
Excel.Application excelApplication = new Excel.Application() // start excel and turn off msg boxes
{
DisplayAlerts = false,
Visible = false
};
Excel.Workbook workBook = excelApplication.Workbooks.Open(targetFile);
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Worksheets[1];
var rDT = workSheet.Range(workSheet.Cells[monthYearNameRow, monthYearNameCol], workSheet.Cells[monthYearNameRow, maxTableColumnIndex]);
rDT.Merge();
rDT.Value = monthName + " " + year;
var reportDateRowStyle = workBook.Styles.Add("ReportDateRowStyle");
reportDateRowStyle.HorizontalAlignment = XlHAlign.xlHAlignCenter;
reportDateRowStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
reportDateRowStyle.Font.Bold = true;
reportDateRowStyle.Font.Size = 14;
rDT.Style = reportDateRowStyle;
Does it re-import every time the function is run?
No; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn't actually force them to go through the whole import process again. 1
Does it import once at the beginning whether or not the function is run?
No, it is only imported if and when the function is executed. 2, 3
As for the benefits: it depends, I guess. If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function. (Of course, there's always from my_module import my_function as f
for those cases.)
In general practice, it's probably not that beneficial. In fact, most Python style guides encourage programmers to place all imports at the beginning of the module file.
If you know that the collection is a queue then you can cast the collection to a queue and get it easily.
There are several structures you can use to get the order, but you will need to cast to it.
SQLite doesn't define any particular extension for this, it's your own choice. Personally, I name them with the .sqlite
extension, just so there isn't any ambiguity when I'm looking at my files later.
Implementing exceptions in c by Eric Roberts
Chapter 4 of C Interfaces and Implementations by Hanson.
A Discipline of Error Handling by Doug Moen
Implementing Exceptions in C (details the article of E Roberts)
parseInt always rounds down soo.....
console.log(parseInt(5.8)+1);
_x000D_
do parseInt()+1
As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.
After 9.2.x. IOS remove this tag check on its' browser.
You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html
since I had already compiled opencv when I discovered this problem, all I had to do was (from my opencv build directory):
make opencv_nonfree
sudo make install
In case this helps anyone :
static bool myFunction(Node& p1, Node& p2) {}
priority_queue <Node, vector<Node>, function<bool(Node&, Node&)>> pq1(myFunction);
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
Another way is to use tidy evaluation
approach. It is pretty straightforward to pass columns of a data frame either as strings or bare column names. See more about tidyeval
here.
library(rlang)
library(tidyverse)
set.seed(123)
df <- data.frame(B = rnorm(10), D = rnorm(10))
Use column names as strings
fun3 <- function(x, ...) {
# capture strings and create variables
dots <- ensyms(...)
# unquote to evaluate inside dplyr verbs
summarise_at(x, vars(!!!dots), list(~ max(., na.rm = TRUE)))
}
fun3(df, "B")
#> B
#> 1 1.715065
fun3(df, "B", "D")
#> B D
#> 1 1.715065 1.786913
Use bare column names
fun4 <- function(x, ...) {
# capture expressions and create quosures
dots <- enquos(...)
# unquote to evaluate inside dplyr verbs
summarise_at(x, vars(!!!dots), list(~ max(., na.rm = TRUE)))
}
fun4(df, B)
#> B
#> 1 1.715065
fun4(df, B, D)
#> B D
#> 1 1.715065 1.786913
#>
Created on 2019-03-01 by the reprex package (v0.2.1.9000)
I got this error when I was trying to create a virtualenv
with command virtualenv myVirtualEnv
. I just added a sudo
before the command; it solved everything.
I am also new to MVC and I received the same error and found that it is not passing proper routeValues
in the Index
view or whatever view is present to view the all data.
It was as below
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
I changed it to the as show below and started to work properly.
<td>
@Html.ActionLink("Edit", "Edit", new { EmployeeID=item.EmployeeID }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
Basically this error can also come because of improper navigation also.
I think because C would be seen the C drive on the client pc, it wont let you. And if it could do this, it would be a big security hole.
To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm.dll
, please install or use the JRE or JDK that contains these missing components.
Follow these steps:
Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)
After that, go to C:/Program files/java/jre7/bin
Here, create an folder called Server
Now go into the C:/Program files/java/jre7/bin/client
folder
Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server
folder
A good way of going about this is not to use nargin
, but to check whether the variables have been set using exist('opt', 'var')
.
Example:
function [a] = train(x, y, opt)
if (~exist('opt', 'var'))
opt = true;
end
end
See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?
Note:
to remove, delete, or uninstall nvm - just remove the $NVM_DIR
folder (usually ~/.nvm
)
you can try :
rm -rf ~/.nvm
I'd probably go with this (I know its not pure linq), keep a reference to the original list if you want to retain all items, and you should find the updated values are in there:
foreach (var mc in list.Where(x => x.Name == "height"))
mc.Value = 30;
Maybe is late now but following Spacedman, did you try duplicate="strip" or any other option?
x=runif(1000)
y=runif(1000)
z=rnorm(1000)
s=interp(x,y,z,duplicate="strip")
surface3d(s$x,s$y,s$z,color="blue")
points3d(s)
dat <- dat[-1, ]
worked but it killed my dataframe, changing it into another type. Had to instead use
dat <- data.frame(dat[-1, ])
but this is possibly a special case as this dataframe initially had only one column.
Alternative syntax:
INSERT tbl (Col1, Col2, ..., ColN)
SELECT Col1, Col2, ..., ColN
FROM Tbl2
WHERE ...
The select query can (of course) include expressions, case statements, constants/literals, etc.
You can.
Extending @marcg 's UtilException
and adding generic <E extends Exception>
where necessary: this way, the compiler will force you again to add throw clauses and everything's as if you could throw checked exceptions natively on java 8's streams.
public final class LambdaExceptionUtil {
@FunctionalInterface
public interface Function_WithExceptions<T, R, E extends Exception> {
R apply(T t) throws E;
}
/**
* .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName))
*/
public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E {
return t -> {
try {
return function.apply(t);
} catch (Exception exception) {
throwActualException(exception);
return null;
}
};
}
@SuppressWarnings("unchecked")
private static <E extends Exception> void throwActualException(Exception exception) throws E {
throw (E) exception;
}
}
public class LambdaExceptionUtilTest {
@Test
public void testFunction() throws MyTestException {
List<Integer> sizes = Stream.of("ciao", "hello").<Integer>map(rethrowFunction(s -> transform(s))).collect(toList());
assertEquals(2, sizes.size());
assertEquals(4, sizes.get(0).intValue());
assertEquals(5, sizes.get(1).intValue());
}
private Integer transform(String value) throws MyTestException {
if(value==null) {
throw new MyTestException();
}
return value.length();
}
private static class MyTestException extends Exception { }
}
In dynamic languages, when the interpreter import
s, it simply reads a file and evaluates it.
In C, external libraries are located by the linker at compile time to build the final object if the library is statically compiled, while for dynamic libraries a smaller version of the linker is called at runtime which remaps addresses and so makes code in the library available to the executable.
In Java, import
is simply used by the compiler to let you name your classes by their unqualified name, let's say String
instead of java.lang.String
. You don't really need to import java.lang.*
because the compiler does it by default. However this mechanism is just to save you some typing. Types in Java are fully qualified class names, so a String
is really a java.lang.String
object when the code is run. Packages are intended to prevent name clashes and allow two classes to have the same simple name, instead of relying on the old C convention of prefixing types like this. java_lang_String
. This is called namespacing.
BTW, in Java there's the static import construct, which allows to further save typing if you use lots of constants from a certain class. In a compilation unit (a .java file) which declares
import static java.lang.Math.*;
you can use the constant PI
in your code, instead of referencing it through Math.PI
, and the method cos()
instead of Math.cos()
. So for example you can write
double r = cos(PI * theta);
Once you understand that classes are always referenced by their fully qualified name in the final bytecode, you must understand how the class code is actually loaded. This happens the first time an object of that class is created, or the first time a static member of the class is accessed. At this time, the ClassLoader
tries to locate the class and instantiate it. If it can't find the class a NoClassDefFoundError
is thrown (or a a ClassNotFoundException
if the class is searched programmatically). To locate the class, the ClassLoader
usually checks the paths listed in the $CLASSPATH
environment variable.
To solve your problem, it seems you need an applet
element like this
<applet
codebase = "http://san.redenetimoveis.com"
archive="test.jar, core.jar"
code="com.colorfulwolf.webcamapplet.WebcamApplet"
width="550" height="550" >
BTW, you don't need to import the archives in the standard JRE.
It’s very simple, it just advertises a string which contains a few characters conforming to Apple’s iBeacon standard. you can refer the Link http://glimwormbeacons.com/learn/what-makes-an-ibeacon-an-ibeacon/
Obviously this issue has different causes. :)
For my case, my account log in expired... I solved it by simply:
XCode -> Preferences -> Account -> Apple IDs -> Select the related ID and renew the log in...
Hope this helps!
In general, you're looking for the "Except" extension.
var rejectStatus = GenerateRejectStatuses();
var fullList = GenerateFullList();
var rejectList = fullList.Where(i => rejectStatus.Contains(i.Status));
var filteredList = fullList.Except(rejectList);
In this example, GenerateRegectStatuses() should be the list of statuses you wish to reject (or in more concrete terms based on your example, a List<int>
of IDs)
Here is the solution to convert the string to valid plain or decimal numbers using Regex:
//something123.777.321something to 123.777321
const str = 'something123.777.321something';
let initialValue = str.replace(/[^0-9.]+/, '');
//initialValue = '123.777.321';
//characterCount just count the characters in a given string
if (characterCount(intitialValue, '.') > 1) {
const splitedValue = intitialValue.split('.');
//splittedValue = ['123','777','321'];
intitialValue = splitedValue.shift() + '.' + splitedValue.join('');
//result i.e. initialValue = '123.777321'
}
Even though this is an old question, I've just come across the problem and solved it differently from the given answers. Maybe it could be helpful to others.
I noticed that even though my XML files looked like:
<tag>
<subTag>content with newline.\r\nto display</subTag>
</tag>
When it was read into my C# code the string had double backslashes.
\\r\\n
To fix this I wrote a ValueConverter to strip the extra backslash.
public class XmlStringConverter : IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
string valueAsString = value as string;
if (string.IsNullOrEmpty(valueAsString))
{
return value;
}
valueAsString = valueAsString.Replace("\\r\\n", "\r\n");
return valueAsString;
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}
}
With ECMA script 2017 (supported by Node 7.6 and above), it becomes a one-liner:
function sleep(millis) {
return new Promise(resolve => setTimeout(resolve, millis));
}
// Usage in async function
async function test() {
await sleep(1000)
console.log("one second has elapsed")
}
// Usage in normal function
function test2() {
sleep(1000).then(() => {
console.log("one second has elapsed")
});
}
I might be missing something in your question here... but from what I can gather, by using the subtract method this should be what you're looking to do:
var timeStr = "00:03:15";
timeStr = timeStr.split(':');
var h = timeStr[1],
m = timeStr[2];
var newTime = moment("01:20:00 06-26-2014")
.subtract({'hours': h, 'minutes': m})
.format('hh:mm');
var str = h + " hours and " + m + " minutes earlier: " + newTime;
console.log(str); // 3 hours and 15 minutes earlier: 10:05
$(document).ready(function(){ _x000D_
var timeStr = "00:03:15";_x000D_
timeStr = timeStr.split(':');_x000D_
_x000D_
var h = timeStr[1],_x000D_
m = timeStr[2];_x000D_
_x000D_
var newTime = moment("01:20:00 06-26-2014")_x000D_
.subtract({'hours': h, 'minutes': m})_x000D_
.format('hh:mm');_x000D_
_x000D_
var str = h + " hours and " + m + " minutes earlier: " + newTime;_x000D_
_x000D_
$('#new-time').html(str);_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="new-time"></p>
_x000D_
I used placeholders so just follow along, as you might want to still keep the inheritance from the original style.
Before
<android.support.v7.widget.Toolbar
android:id="@+id/toolBar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/{{originalBaseStyle}}"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
After:
styles.xml
<style name="{{yourToolbarStyle}}" parent="{{originalBaseStyle}}">
<item name="android:textColorPrimary">@android:color/white</item>
<item name="android:textColorSecondary">@android:color/white</item>
<item name="actionMenuTextColor">@android:color/white</item>
<item name="actionOverflowButtonStyle">@style/ActionButtonOverflowStyle</item>
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>
Therefore
<android.support.v7.widget.Toolbar
android:id="@+id/toolBar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/{{yourToolbarStyle}}"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
DO NOT USE self::
, use static::
There is another aspect of self:: that is worth mentioning. Annoyingly self::
refers to the scope at the point of definition not at the point of execution. Consider this simple class with two methods:
class Person
{
public static function status()
{
self::getStatus();
}
protected static function getStatus()
{
echo "Person is alive";
}
}
If we call Person::status()
we will see "Person is alive" . Now consider what happens when we make a class that inherits from this:
class Deceased extends Person
{
protected static function getStatus()
{
echo "Person is deceased";
}
}
Calling Deceased::status()
we would expect to see "Person is deceased" however what we see is "Person is alive" as the scope contains the original method definition when call to self::getStatus()
was defined.
PHP 5.3 has a solution. the static::
resolution operator implements "late static binding" which is a fancy way of saying that it's bound to the scope of the class called. Change the line in status()
to static::getStatus()
and the results are what you would expect. In older versions of PHP you will have to find a kludge to do this.
So to answer the question not as asked ...
$this->
refers to the current object (an instance of a class), whereas static::
refers to a class
String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();
mediaPlayer.start()
and this play from raw folder.
int resID = myContext.getResources().getIdentifier(playSoundName,"raw",myContext.getPackageName());
MediaPlayer mediaPlayer = MediaPlayer.create(myContext,resID);
mediaPlayer.prepare();
mediaPlayer.start();
mycontext=application.this. use.
An ed
answer
ed file << END
8i
Project_Name=sowstest
.
w
q
END
.
on its own line ends input mode; w
writes; q
quits. GNU ed has a wq
command to save and quit, but old ed's don't.
Further reading: https://gnu.org/software/ed/manual/ed_manual.html
Press the start button in visual studio. Then go to the location where your solution is stored and open the folder of your main project then the bin folder. If your application was running in debug mode then go to the debug folder. If running in release mode then go to the release folder. You should find your exe there.
SELECT name FROM sqlite_master where name = '<TABLE_NAME_HERE>'
If the table name does not exist then there would not be any records returned!
You can as well use
SELECT count(name) FROM sqlite_master where name = '<TABLE_NAME_HERE>'
if the count is 1, means table exists, otherwise, it would return 0
Hardware -> Erase all content and settings did the job for me (other things didn't).
PDT eclipse from ZEND has a mac version (PDT all-in-one).
I've been using it for about 3 months and it's pretty solid and has debugging capabilities with xdebug (debug howto) and zend debugger.
I was facing "java.lang.OutOfMemoryError: Java heap space" error while building my project using maven install command.
I was able to get rid of it by changing maven runner settings.
Settings
| Build, Execution, Deployment
| Build Tools
| Maven
| Runner
| VM options
to -Xmx512m
$('head').append('<meta http-equiv="X-UA-Compatible" content="IE=Edge" />');
or
var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);
Though I'm not certain it will have an affect as it will be generated after the page is loaded
If you want to add meta data tags for page description, use the SETTINGS of your DNN page to add Description and Keywords. Beyond that, the best way to go when modifying the HEAD is to dynamically inject your code into the HEAD via a third party module.
Found at http://www.dotnetnuke.com/Resources/Forums/forumid/7/threadid/298385/scope/posts.aspx
This may allow other meta tags, if you're lucky
Additional HEAD tags can be placed into Page Settings > Advanced Settings > Page Header Tags.
Found at http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/223250/scope/posts.aspx
In head:
(function() {
var jsapi = document.createElement('script'); jsapi.type = 'text/javascript'; jsapi.async = true;
jsapi.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'www.google.com/jsapi?key=YOUR KEY';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('head')[0]).appendChild(jsapi);
})();
End of Body:
<script type="text/javascript">
google.load("jquery", "version");
</script>
Create Table:
Create Table EmployeeProfile (
EmpId int,
EmpName varchar(50) not null,
EmpPhoto varbinary(max) not null )
Go
Insert statement:
Insert EmployeeProfile
(EmpId, EmpName, EmpPhoto)
Select 1001, 'Vadivel', BulkColumn
from Openrowset( Bulk 'C:\Image1.jpg', Single_Blob) as EmployeePicture
This Sql Query Working Fine.
You could also do
function insertAfter(node1, node2) {
node1.outerHTML += node2.outerHTML;
}
or
function insertAfter2(node1, node2) {
var wrap = document.createElement("div");
wrap.appendChild(node2.cloneNode(true));
var node2Html = wrap.innerHTML;
node1.insertAdjacentHTML('afterend', node2Html);
}
On a fresh Linux machine you also need to install git
. Bundle uses it behind the scenes.
echo "Subject: test" | /usr/sbin/sendmail [email protected]
This enables you to do it within one command line without having to echo a text file. This answer builds on top of @mti2935's answer. So credit goes there.
In my case the "Fix Issue" button triggers a spinner for about 20 seconds and fixes nothing.
This works for me (iOS 7 iPhone 5, Xcode 5):
Xcode > Window > Organizer > Devices
Find the connected device(with a green dot) on the left pane. Select "Provisioning Profiles" On the right pane, there is a line with warning. Delete this line.
Now go back to click the "Fix Issue" button and everything is fine - the app runs in the device as expected.
I know it's been a while, but I'll this here in case it helps someone out.
The right answer by far is (and the selected one) the one from CommonsWare. I was having the same problem as posted, the following
MyFragmentClass fragmentList =
(MyFragmentClass) getSupportFragmentManager().findFragmentById(R.id.fragementID);
kept on returning null. My mistake was really silly, in my xml file:
<fragment
android:tag="@+id/fragementID"
android:name="com.sf.lidgit_android.content.MyFragmentClass"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
The mistake was that I had android:tag INSTEAD OF android:id.
Depending on your table type, locking will perform differently, but so will a SELECT count. For MyISAM tables a simple SELECT count(*) FROM table should not lock the table since it accesses meta data to pull the record count. Innodb will take longer since it has to grab the table in a snapshot to count the records, but it shouldn't cause locking.
You should at least have concurrent_insert set to 1 (default). Then, if there are no "gaps" in the data file for the table to fill, inserts will be appended to the file and SELECT and INSERTs can happen simultaneously with MyISAM tables. Note that deleting a record puts a "gap" in the data file which will attempt to be filled with future inserts and updates.
If you rarely delete records, then you can set concurrent_insert equal to 2, and inserts will always be added to the end of the data file. Then selects and inserts can happen simultaneously, but your data file will never get smaller, no matter how many records you delete (except all records).
The bottom line, if you have a lot of updates, inserts and selects on a table, you should make it InnoDB. You can freely mix table types in a system though.
A lot of answers above have fields compared in single comparator method which is not actually working. There are some answers though with different comparators implemented for each field, I am posting this because this example would be much more clearer and simple to understand I am believing.
class Student{
Integer bornYear;
Integer bornMonth;
Integer bornDay;
public Student(int bornYear, int bornMonth, int bornDay) {
this.bornYear = bornYear;
this.bornMonth = bornMonth;
this.bornDay = bornDay;
}
public Student(int bornYear, int bornMonth) {
this.bornYear = bornYear;
this.bornMonth = bornMonth;
}
public Student(int bornYear) {
this.bornYear = bornYear;
}
public Integer getBornYear() {
return bornYear;
}
public void setBornYear(int bornYear) {
this.bornYear = bornYear;
}
public Integer getBornMonth() {
return bornMonth;
}
public void setBornMonth(int bornMonth) {
this.bornMonth = bornMonth;
}
public Integer getBornDay() {
return bornDay;
}
public void setBornDay(int bornDay) {
this.bornDay = bornDay;
}
@Override
public String toString() {
return "Student [bornYear=" + bornYear + ", bornMonth=" + bornMonth + ", bornDay=" + bornDay + "]";
}
}
class TestClass
{
// Comparator problem in JAVA for sorting objects based on multiple fields
public static void main(String[] args)
{
int N,c;// Number of threads
Student s1=new Student(2018,12);
Student s2=new Student(2018,12);
Student s3=new Student(2018,11);
Student s4=new Student(2017,6);
Student s5=new Student(2017,4);
Student s6=new Student(2016,8);
Student s7=new Student(2018);
Student s8=new Student(2017,8);
Student s9=new Student(2017,2);
Student s10=new Student(2017,9);
List<Student> studentList=new ArrayList<>();
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
studentList.add(s4);
studentList.add(s5);
studentList.add(s6);
studentList.add(s7);
studentList.add(s8);
studentList.add(s9);
studentList.add(s10);
Comparator<Student> byMonth=new Comparator<Student>() {
@Override
public int compare(Student st1,Student st2) {
if(st1.getBornMonth()!=null && st2.getBornMonth()!=null) {
return st2.getBornMonth()-st1.getBornMonth();
}
else if(st1.getBornMonth()!=null) {
return 1;
}
else {
return -1;
}
}};
Collections.sort(studentList, new Comparator<Student>() {
@Override
public int compare(Student st1,Student st2) {
return st2.getBornYear()-st1.getBornYear();
}}.thenComparing(byMonth));
System.out.println("The sorted students list in descending is"+Arrays.deepToString(studentList.toArray()));
}
}
OUTPUT
The sorted students list in descending is[Student [bornYear=2018, bornMonth=null, bornDay=null], Student [bornYear=2018, bornMonth=12, bornDay=null], Student [bornYear=2018, bornMonth=12, bornDay=null], Student [bornYear=2018, bornMonth=11, bornDay=null], Student [bornYear=2017, bornMonth=9, bornDay=null], Student [bornYear=2017, bornMonth=8, bornDay=null], Student [bornYear=2017, bornMonth=6, bornDay=null], Student [bornYear=2017, bornMonth=4, bornDay=null], Student [bornYear=2017, bornMonth=2, bornDay=null], Student [bornYear=2016, bornMonth=8, bornDay=null]]
Here a simple example for a function to load JS files. Relevant points:
$.ajax
or $.getScript
you can use nonces, solving thus issues with CSP unsafe-inline
. Just use the property script.nonce
var getScriptOnce = function() {
var scriptArray = []; //array of urls (closure)
//function to defer loading of script
return function (url, callback){
//the array doesn't have such url
if (scriptArray.indexOf(url) === -1){
var script=document.createElement('script');
script.src=url;
var head=document.getElementsByTagName('head')[0],
done=false;
script.onload=script.onreadystatechange = function(){
if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
done=true;
if (typeof callback === 'function') {
callback();
}
script.onload = script.onreadystatechange = null;
head.removeChild(script);
scriptArray.push(url);
}
};
head.appendChild(script);
}
};
}();
Now you use it simply by
getScriptOnce("url_of_your_JS_file.js");
Based on @Raghuram answer, I find a tutorial on Copying project dependencies, Just:
Open your project pom.xml
file and find this:
<project>
[...]
<build>
<plugins>
...
</plugins>
</build>
[...]
</project>
Than replace the <plugins> ... </plugins>
with:
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/alternateLocation</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
And call maven within the command line mvn dependency:copy-dependencies
After it finishes, it will create the folder target/dependency
within all the jar
's dependencies on the current directory where the pom.xml
lives.
Don't know why @Janos deleted his answer, but it's correct: your data frame Train
doesn't have a column named pre
. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train
has columns called residual.sugar
, total.sulfur
, alcohol
and quality
. You need to change either your formula or your data frame so they're consistent with each other.
And just to clarify: Pre
is an object containing a formula. That formula contains a reference to the variable pre
. It's the latter that has to be consistent with the data frame.
If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator
.
This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator")
can be overriden via command line options and isn't as type safe as java.io.File.separator
.
The last one, java.nio.file.FileSystems.getDefault().getSeparator();
was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.
So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.
I will add a StackBlitz example and a comment to the answer from @tahiche.
The return value is a function to remove the event listener after you have added it. It is considered good practice to remove event listeners when you don't need them anymore. So you can store this return value and call it inside your ngOnDestroy
method.
I admit that it might seem confusing at first, but it is actually a very useful feature. How else can you clean up after yourself?
export class MyComponent implements OnInit, OnDestroy {
public removeEventListener: () => void;
constructor(
private renderer: Renderer2,
private elementRef: ElementRef
) {
}
public ngOnInit() {
this.removeEventListener = this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
if (event.target instanceof HTMLAnchorElement) {
// Prevent opening anchors the default way
event.preventDefault();
// Your custom anchor click event handler
this.handleAnchorClick(event);
}
});
}
public ngOnDestroy() {
this.removeEventListener();
}
}
You can find a StackBlitz here to show how this could work for catching clicking on anchor elements.
I added a body with an image as follows:
<img src="x" onerror="alert(1)"></div>
to show that the sanitizer is doing its job.
Here in this fiddle you find the same body attached to an innerHTML
without sanitizing it and it will demonstrate the issue.
To put it in another way, can we replicate the appearance of these text views without using the android:textAppearance attribute?
Like biegleux already said:
If you want to use the small, medium or large value on any text in your Android app, you can just create a dimens.xml
file in your values
folder and define the text size there with the following 3 lines:
<dimen name="text_size_small">14sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="text_size_large">22sp</dimen>
Here is an example for a TextView with large text from the dimens.xml
file:
<TextView
android:id="@+id/hello_world"
android:text="hello world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/text_size_large"/>
On Ubuntu, you'll need to install unixodbc-dev:
sudo apt-get install unixodbc-dev
Install pip by using this command:
sudo apt-get install python-pip
once that is installed, you should be able to install pyodbc successfully:
pip install pyodbc
Firstly create app.js
file in the directory you want to publish.
var http = require('http');
var fs = require('fs');
var mime = require('mime');
http.createServer(function(req,res){
if (req.url != '/app.js') {
var url = __dirname + req.url;
fs.stat(url,function(err,stat){
if (err) {
res.writeHead(404,{'Content-Type':'text/html'});
res.end('Your requested URI('+req.url+') wasn\'t found on our server');
} else {
var type = mime.getType(url);
var fileSize = stat.size;
var range = req.headers.range;
if (range) {
var parts = range.replace(/bytes=/, "").split("-");
var start = parseInt(parts[0], 10);
var end = parts[1] ? parseInt(parts[1], 10) : fileSize-1;
var chunksize = (end-start)+1;
var file = fs.createReadStream(url, {start, end});
var head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': type
}
res.writeHead(206, head);
file.pipe(res);
} else {
var head = {
'Content-Length': fileSize,
'Content-Type': type
}
res.writeHead(200, head);
fs.createReadStream(url).pipe(res);
}
}
});
} else {
res.writeHead(403,{'Content-Type':'text/html'});
res.end('Sorry, access to that file is Forbidden');
}
}).listen(8080);
Simply run node app.js
and your server shall be running on port 8080. Besides video it can stream all kinds of files.
With Dojo Toolkit, you would use dojo.indexOf()
. See dojo.indexOf for the documentation, and Arrays Made Easy by Bryan Forbes for some examples.
Nov 2020
With Material-UI and React Hooks
import * as React from "react";
import {
Button,
IconButton,
Tooltip,
makeStyles,
Theme,
} from "@material-ui/core";
import { PhotoCamera } from "@material-ui/icons";
const useStyles = makeStyles((theme: Theme) => ({
root: {
"& > *": {
margin: theme.spacing(1),
},
},
input: {
display: "none",
},
faceImage: {
color: theme.palette.primary.light,
},
}));
interface FormProps {
saveFace: any; //(fileName:Blob) => Promise<void>, // callback taking a string and then dispatching a store actions
}
export const FaceForm: React.FunctionComponent<FormProps> = ({ saveFace }) => {
const classes = useStyles();
const [selectedFile, setSelectedFile] = React.useState(null);
const handleCapture = ({ target }: any) => {
setSelectedFile(target.files[0]);
};
const handleSubmit = () => {
saveFace(selectedFile);
};
return (
<>
<input
accept="image/jpeg"
className={classes.input}
id="faceImage"
type="file"
onChange={handleCapture}
/>
<Tooltip title="Select Image">
<label htmlFor="faceImage">
<IconButton
className={classes.faceImage}
color="primary"
aria-label="upload picture"
component="span"
>
<PhotoCamera fontSize="large" />
</IconButton>
</label>
</Tooltip>
<label>{selectedFile ? selectedFile.name : "Select Image"}</label>. . .
<Button onClick={() => handleSubmit()} color="primary">
Save
</Button>
</>
);
};
You don't need to call json.getJSONArray()
at all, because the JSON you're working with already is an array. So, don't construct an instance of JSONObject
; use a JSONArray
. This should suffice:
// ...
JSONArray json = new JSONArray(result);
// ...
for(int i=0;i<json.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = json.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("eqid"));
map.put("magnitude", "Magnitude: " + e.getString("magnitude"));
mylist.add(map);
}
You can't use exactly the same methods as in the tutorial, because the JSON you're dealing with needs to be parsed into a JSONArray
at the root, not a JSONObject
.
The issue has been resolved while installation of the maven settings is provided as External in Eclipse. The navigation settings are Window --> Preferences --> Installations. Select the External as installation Type, provide the Installation home and name and click on Finish. Finally select this as default installations.
Giving width to Label is not a proper way. you should take one div or table structure to manage this. but still if you don't want to change your whole code then you can use following code.
label {
width:200px;
float: left;
}
Saudate, I ran across this looking for a different problem. You most definitely can use the Sql Server Import wizard to import data into a new table. Of course, you do not wish to leave that table in the database, so my suggesting is that you import into a new table, then script the data in query manager to insert into the existing table. You can add a line to drop the temp table created by the import wizard as the last step upon successful completion of the script.
I believe your original issue is in fact related to Sql Server 64 bit and is due to your having a 32 bit Excel and these drivers don't play well together. I did run into a very similar issue when first using 64 bit excel.
Direct MSDN link to Management Studio 2012 ONLY: SQL Server 2012 Express Management Studio with Service Pack 1 (x64) - (English)
Multicast sender that broadcasts to a multicast group:
#!/usr/bin/env python
import socket
import struct
def main():
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
sock.sendto('Hello World!', (MCAST_GRP, MCAST_PORT))
if __name__ == '__main__':
main()
Multicast receiver that reads from a multicast group and prints hex data to the console:
#!/usr/bin/env python
import socket
import binascii
def main():
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except AttributeError:
pass
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
sock.bind((MCAST_GRP, MCAST_PORT))
host = socket.gethostbyname(socket.gethostname())
sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host))
sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(MCAST_GRP) + socket.inet_aton(host))
while 1:
try:
data, addr = sock.recvfrom(1024)
except socket.error, e:
print 'Expection'
hexdata = binascii.hexlify(data)
print 'Data = %s' % hexdata
if __name__ == '__main__':
main()
In order to comply with boneheaded precedent, getYear()
returns the number of years since 1900.
Instead, you should call getFullYear()
, which returns the actual year.
Check out the BusyIndicator in the extended WPF Toolkit.
I'am using VisualStdio 2008.
In this case I often set Preprocessor Definitions
Menu \ Project \ [ProjectName] Properties... Alt+F7
If click this menu or press Alt + F7 in project window, you can see "Property Pages" window.
Then see menu on left of window.
Configuration Properties \ C/C++ \ Preprocessor
Then add _CRT_SECURE_NO_WARNINGS
to \ Preprocessor Definitions.
Since header files from some C libraries use the keyword, the C++ language will have to do something about it.. at the minimum, ignoring the keyword, so we don't have to #define the keyword to a blank macro to suppress the keyword.
using (SqlConnection connection = new SqlConnection("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True"))
{
SqlCommand command =
new SqlCommand("select * from Pending_Tasks WHERE CustomerId=...", connection);
connection.Open();
SqlDataReader read= command.ExecuteReader();
while (read.Read())
{
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();
}
Make sure you have data in the query : select * from Pending_Tasks and you are using "using System.Data.SqlClient;"
class Program
{
static void Main(string[] args)
{
Type type = typeof(MyReflectionClass);
MethodInfo method = type.GetMethod("MyMethod");
MyReflectionClass c = new MyReflectionClass();
string result = (string)method.Invoke(c, null);
Console.WriteLine(result);
}
}
public class MyReflectionClass
{
public string MyMethod()
{
return DateTime.Now.ToString();
}
}
The present solution produces the same flow as your OP. It does not use Labels, but this was not a requirement of the OP. You only asked for "a simple conditional loop that will go to the next iteration if a condition is true", and since this is cleaner to read, it is likely a better option than that using a Label.
What you want inside your for
loop follows the pattern
If (your condition) Then
'Do something
End If
In this case, your condition is Not(Return = 0 And Level = 0)
, so you would use
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If (Not(Return = 0 And Level = 0)) Then
'Do something
End If
Next i
PS: the condition is equivalent to (Return <> 0 Or Level <> 0)
**JAVA SCRIPT**
<html>
<body>
<script>
function @ToCaps(obj)
{
obj.value=obj.value.toUpperCase();
}
</script>
<input type="text" onkeyup=@ToCaps(this)"/>
</body>
</html>
**ASP.NET**
Use a css style on the text box, write css like this:
.ToCaps { text-transform: uppercase; }
<asp:TextBox ID="TextBox1" runat="server" CssClass="ToCaps"></asp:Te writxtBox>
**OR**
simply write this code in textbox
<asp:TextBox ID="TextBox1" runat="server" style="text-transform:uppercase"></asp:TextBox>
**1.Note you don't get intelligence until you type up to style="**
Your expression is never going to evaluate.
You are comparing a
with a property of a
.
a
is of type Answer. a.Correct
, I'm guessing is a boolean.
Long form:-
Answer = answer.SingleOrDefault(a => a.Correct == true);
Short form:-
Answer = answer.SingleOrDefault(a => a.Correct);
According to Martin Fowler a POJO is an object which encapsulates Business Logic while a Bean (except for the definition already stated in other answers) is little more than a container for holding data and the operations available on the object merely set and get data.
The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely.
If you using Ubuntu, So firstly you have unhide all files from your home directory or where located your android studio folder :
Sometimes it is not eligible to set height to pixel values.
However, it is possible to show vertical scrollbar through setting height of div to 100%
and overflow
to auto
.
Let me show an example:
<div id="content" style="height: 100%; overflow: auto">
<p>some text</p>
<ul>
<li>text</li>
.....
<li>text</li>
</div>
Another point to take in consideration is that the new UI for Service Interface will give you much more flexibility on how you want to create your proxy class. For example, it will allow you to map data contracts to existing dlls, if they match (actually this is the default behaviour).
I am working on DOM Keyboard Event Level 3 polyfill . In latest browsers or with this polyfill you can do something like this:
element.addEventListener("keydown", function(e){ console.log(e.key, e.char, e.keyCode) })
var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", char : "Q", shiftKey : true});
element.dispatchEvent(e);
//If you need legacy property "keyCode"
// Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari)
delete e.keyCode;
Object.defineProperty(e, "keyCode", {"value" : 666})
UPDATE:
Now my polyfill supports legacy properties "keyCode", "charCode" and "which"
var e = new KeyboardEvent("keydown", {
bubbles : true,
cancelable : true,
char : "Q",
key : "q",
shiftKey : true,
keyCode : 81
});
Examples here
Additionally here is cross-browser initKeyboardEvent separately from my polyfill: (gist)
Polyfill demo
bool EndsWith(const std::string& data, const std::string& suffix)
{
return data.find(suffix, data.size() - suffix.size()) != string::npos;
}
Tests
#include <iostream>
int main()
{
cout << EndsWith(u8"o!hello!1", u8"o!") << endl;
cout << EndsWith(u8"o!hello!", u8"o!") << endl;
cout << EndsWith(u8"hello!", u8"o!") << endl;
cout << EndsWith(u8"o!hello!o!", u8"o!") << endl;
return 0;
}
Output
0
1
1
1
In Advance Tab -> scroll down and un-checked all options in advance security setting and try by checking one-by-one and finally app start running with one option TLS 1.1
that was the solution I got it.
You can use PdfBox from Apache which is simple to use and has good performance.
Here is an example of extracting text from a PDF file (you can read more here) :
import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.util.*;
public class PDFTest {
public static void main(String[] args){
PDDocument pd;
BufferedWriter wr;
try {
File input = new File("C:\\Invoice.pdf"); // The PDF file from where you would like to extract
File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data
pd = PDDocument.load(input);
System.out.println(pd.getNumberOfPages());
System.out.println(pd.isEncrypted());
pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
PDFTextStripper stripper = new PDFTextStripper();
wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
stripper.writeText(pd, wr);
if (pd != null) {
pd.close();
}
// I use close() to flush the stream.
wr.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
UPDATE:
You can get the text using PDFTextStripper:
PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created
You can use this comment in jsp page
<%--your comment --%>
Second way of comment declaration in jsp page you can use the comment of two typ in jsp code
single line comment
<% your code //your comment%>
multiple line comment
<% your code
/**
your another comment
**/
%>
And you can also comment on jsp page from html code for example:
<!-- your commment -->
I have created my own git alias to do exactly this. I'm calling it git freebase
! It will take your existing messy, unrebasable feature branch and recreate it so that it becomes a new branch with the same name with its commits squashed into one commit and rebased onto the branch you specify (master by default). At the very end, it will allow you to use whatever commit message you like for your newly "freebased" branch.
Install it by placing the following alias in your .gitconfig:
[alias]
freebase = "!f() { \
TOPIC="$(git branch | grep '\\*' | cut -d ' ' -f2)"; \
NEWBASE="${1:-master}"; \
PREVSHA1="$(git rev-parse HEAD)"; \
echo "Freebaseing $TOPIC onto $NEWBASE, previous sha1 was $PREVSHA1"; \
echo "---"; \
git reset --hard "$NEWBASE"; \
git merge --squash "$PREVSHA1"; \
git commit; \
}; f"
Use it from your feature branch by running:
git freebase <new-base>
I've only tested this a few times, so read it first and make sure you want to run it. As a little safety measure it does print the starting sha1 so you should be able to restore your old branch if anything goes wrong.
I'll be maintaining it in my dotfiles repo on github: https://github.com/stevecrozz/dotfiles/blob/master/.gitconfig
So, I checked Windows Features to make sure I didn't have this thing called WebDAV installed, and it said I didn't. Anyways, I went ahead and placed the following in my web.config (both front end and WebAPI, just to be sure), and it works now. I placed this inside <system.webServer>
.
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- add this -->
</modules>
Additionally, it is often required to add the following to web.config
in the handlers. Thanks to Babak
<handlers>
<remove name="WebDAV" />
...
</handlers>
document.write(`<td width='74'><button id='button' type='button' onclick='myfunction(\``+ name + `\`)'>click</button></td>`)
Better to use `` than "". This is a more dynamic answer.
I would do it with cssSelector:
// for all checked checkboxes
driver.findElements(By.cssSelector("input:checked[type='checkbox']"));
// for all notchecked checkboxes
driver.findElements(By.cssSelector("input:not(:checked)[type='checkbox']"));
Maybe that also helps ;-)
Well it has a simple and easy solution. You can make your video easily to fit for any device and screen size. Here is the HTML and CSS code:
.yt-container {_x000D_
position:relative;_x000D_
padding-bottom:56.25%;_x000D_
padding-top:30px;_x000D_
height:0;_x000D_
overflow:hidden;_x000D_
}_x000D_
_x000D_
.yt-container iframe, .yt-container object, .yt-container embed {_x000D_
position:absolute;_x000D_
top:0;_x000D_
left:0;_x000D_
width:100%;_x000D_
height:100%;_x000D_
}
_x000D_
<div class="yt-container">_x000D_
<iframe src="https://www.youtube.com/embed/hfQdkBOxXTc" frameborder="0" allowfullscreen></iframe>_x000D_
</div>
_x000D_
Source: https://www.codespeedy.com/make-youtube-embed-video-responsive-using-css/
Check the daemon option in nginx.conf file. It has to be ON. Or you can simply rip out this line from config file. This option is fully described here http://nginx.org/en/docs/ngx_core_module.html#daemon
Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below
import 'package:jiffy/jiffy.dart';
var now = Jiffy().format("yyyy-MM-dd HH:mm:ss");
You can also do the following
var a = Jiffy().yMMMMd; // October 18, 2019
And you can also pass in your DateTime object, A string and an array
var a = Jiffy(DateTime(2019, 10, 18)).yMMMMd; // October 18, 2019
var a = Jiffy("2019-10-18").yMMMMd; // October 18, 2019
var a = Jiffy([2019, 10, 18]).yMMMMd; // October 18, 2019
Once you have selected the highest value, which is "12" in my example, you can then declare it as integer and increment your value:
$FileList = "1", "2", "11"
$foldername = [int]$FileList[2] + 1
$foldername
Run this command in terminal to remove simulators that can't be accessed from the current version of Xcode (8+?) in use on your machine.
xcrun simctl delete unavailable
Also if you're looking to reclaim simulator related space Michael Tsai found that deleting sim logs saved him 30 GB.
~/Library/Logs/CoreSimulator
Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.
public class SubSubClass extends SubClass {
@Override
public void print() {
super.superPrint();
}
public static void main(String[] args) {
new SubSubClass().print();
}
}
class SuperClass {
public void print() {
System.out.println("Printed in the GrandDad");
}
}
class SubClass extends SuperClass {
public void superPrint() {
super.print();
}
}
Output: Printed in the GrandDad
As a follow-up to Adam Matan's answer, the /proc/<pid>
directory's time stamp as such is not necessarily directly useful, but you can use
awk -v RS=')' 'END{print $20}' /proc/12345/stat
to get the start time in clock ticks since system boot.1
This is a slightly tricky unit to use; see also convert jiffies to seconds for details.
awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/12345/stat
This should give you seconds, which you can pass to strftime()
to get a (human-readable, or otherwise) timestamp.
awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next }
END { print strftime("%c", systime() - (now-($20/ticks))) }' /proc/uptime RS=')' /proc/12345/stat
Updated with some fixes from Stephane Chazelas in the comments; thanks as always!
If you only have Mawk, maybe try
awk -v ticks="$(getconf CLK_TCK)" -v epoch="$(date +%s)" '
NR==1 { now=$1; next }
END { printf "%9.0f\n", epoch - (now-($20/ticks)) }' /proc/uptime RS=')' /proc/12345/stat |
xargs -i date -d @{}
1 man proc; search for starttime.
Test e = static_cast<Test>(1);
If getting this error while performing a backup, max_allowed_packet
can be set in the my.cnf
particularly for mysqldump
.
[mysqldump]
max_allowed_packet=512M
I kept getting this error while performing a mysqldump
and I did not understand because I had this set in my.cnf
under the [mysqld]
section. Once I figured out I could set it for [mysqldump]
and I set the value, my backups completed without issue.
Does xxxxxxxxxxxx specify a file name or directory name on the target
(F = file, D = directory)? D
if a File : (echo F)
if a Directory (echo D)
For Jackson versions < 2.0 use this annotation on the class being serialized:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
How about using the C++ language itself?
bool t = true;
bool f = false;
std::cout << std::noboolalpha << t << " == " << std::boolalpha << t << std::endl;
std::cout << std::noboolalpha << f << " == " << std::boolalpha << f << std::endl;
UPDATE:
If you want more than 4 lines of code without any console output, please go to cppreference.com's page talking about std::boolalpha
and std::noboolalpha
which shows you the console output and explains more about the API.
Additionally using std::boolalpha
will modify the global state of std::cout
, you may want to restore the original behavior go here for more info on restoring the state of std::cout
.
Add the following code before you instantiate your web service client:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Or for backward compatibility with TLS 1.1 and prior:
System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
SHOULD be unique does not mean MUST be unique. However, as stated, some parsers would fail and others would just use the last value parsed. However, if the spec was cleaned up a little to allow for duplicates then I could see a use where you may have an event handler which is transforming the JSON to HTML or some other format... In such cases it would be perfectly valid to parse the JSON and create another document format...
[
"div":
{
"p": "hello",
"p": "universe"
},
"div":
{
"h1": "Heading 1",
"p": "another paragraph"
}
]
could then easily parse to html for example:
<body>
<div>
<p>hello</p>
<p>universe</p>
</div>
<div>
<h1>Heading 1</h1>
<p>another paragraph</p>
</div>
</body>
I can see the reasoning behind the question but as it stands... I wouldn't trust it.
I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.
Bootstrap requires a specific file structure to work. I see from your code you have this:
<link href="bootstrap.css" rel="stylesheet" media="screen">
Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.
But first, let me recommend you setup your folder structure like so:
/css <-- Bootstrap.css here
/fonts <-- Bootstrap fonts here
/img
/js <-- Bootstrap JavaScript here
index.html
If you notice, this is also how Bootstrap structures its files in its download ZIP.
You then include your Bootstrap file like so:
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">
Depending on your server structure or what you're going for.
The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).
The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.
So, why do this?
Bootstrap.css has this specific line for Glyphfonts:
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
What you can see is that that Glyphfonts are loaded by going up one directory ../
and then looking for a folder called /fonts
and THEN loading the font file.
The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:
/fonts
Bootstrap.css
index.html
The CSS file is going one level deeper than looking for a /fonts
folder.
So, let's say the actual location of these files are:
C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html
The CSS file would technically be looking for a folder at:
C:\fonts
but your folder is actually in:
C:\www\fonts
So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.
When you get that fixed, your HTML should simply be:
<span class="glyphicon glyphicon-comment"></span>
Note, you need both classes. The first class glyphicon
sets up the basic styles while glyphicon-comment
sets the specific image.
It looks like people answered the first part of your question (use application/json).
For the second part: It is perfectly legal to send query parameters in a HTTP POST Request.
Example:
POST /members?id=1234 HTTP/1.1
Host: www.example.com
Content-Type: application/json
{"email":"[email protected]"}
Query parameters are commonly used in a POST request to refer to an existing resource. The above example would update the email address of an existing member with the id of 1234.
It is BAD habit and terribly ANNOYING practice to quote Joshua Bloch without understanding the basic ground-zero fundamentalism.
I have not read anything Joshua Bloch, so either
As in Bible fundamentalism all the biblical laws can be summed up by
and so similarly software engineering fundamentalism can be summed up by
Also, among biblical fundamentalist circles a strong and reasonable corollary is drawn
Similarly, if you do not respect yourself as a programmer and just accept the pronouncements and prophecies of some programming guru-nath WITHOUT questioning the fundamentals, your quotations and reliance on Joshua Bloch (and the like) is meaningless. And therefore, you would actually have no respect for your fellow-programmers.
The fundamental laws of software programming
Under what laws of fundamentally effective and responsible programming does this religious edict fall into ?
Just read the wikipedia article on interface-pattern constants (https://en.wikipedia.org/wiki/Constant_interface), and the silly excuses it states against interface-pattern constants.
Whatif-No IDE? Who on earth as a software programmer would not use an IDE? Most of us are programmers who prefer not to have to prove having macho aescetic survivalisticism thro avoiding the use of an IDE.
Pollutes the namespace with variables not used within the current scope? It could be proponents of this opinion
Using interfaces for enforcing constants is an abuse of interfaces. Proponents of such have a bad habit of
It is difficult if not impossible to convert interfaces into implemented classes in the future. Hah .... hmmm ... ???
Whatever the excuses, there is NO VALID EXCUSE when it comes to FUNDAMENTALLY EFFECTIVE software engineering to delegitimize or generally discourage the use of interface constants.
It doesn't matter what the original intents and mental states of the founding fathers who crafted the United States Constitution were. We could debate the original intents of the founding fathers but all I care is the written statements of the US Constitution. And it is the responsibility of every US citizen to exploit the written literary-fundamentalism, not the unwritten founding-intents, of the US Constitution.
Similarly, I do not care what the "original" intents of the founders of the Java platform and programming language had for the interface. What I care are the effective features the Java specification provides, and I intend to exploit those features to the fullest to help me fulfill the fundamental laws of responsible software programming. I don't care if I am perceived to "violate the intention for interfaces". I don't care what Gosling or someone Bloch says about the "proper way to use Java", unless what they say does not violate my need to EFFECTIVE fulfilling fundamentals.
It doesn't matter how your data-model is hosted or transmitted. Whether you use interfaces or enums or whatevernots, relational or no-SQL, if you don't understand the need and process of data-model normalization.
We must first define and normalize the data-model of a set of processes. And when we have a coherent data-model, ONLY then can we use the process flow of its components to define the functional behaviour and process blocks a field or realm of applications. And only then can we define the API of each functional process.
Even the facets of data normalization as proposed by EF Codd is now severely challenged and severely-challenged. e.g. his statement on 1NF has been criticized as ambiguous, misaligned and over-simplified, as is the rest of his statements especially in the advent of modern data services, repo-technology and transmission. IMO, the EF Codd statements should be completely ditched and new set of more mathematically plausible statements be designed.
A glaring flaw of EF Codd's and the cause of its misalignment to effective human comprehension is his belief that humanly perceivable multi-dimensional, mutable-dimension data can be efficiently perceived thro a set of piecemeal 2-dimensional mappings.
What EF Codd failed to express.
Within each coherent data-model, these are the sequential graduated order of data-model coherence to achieve.
In a field or grid of inter-servicing component-applications, there must be one and only one coherent data-model or exists a means for a data-model/version to identify itself.
There are data-normalization issues at stake more consequential than this mundane question. IF you don't solve those issues, the confusion that you think interface constants cause is comparatively nothing. Zilch.
From the data-model normalization then you determine the components as variables, as properties, as contract interface constants.
Then you determine which goes into value injection, property configuration placeholding, interfaces, final strings, etc.
If you have to use the excuse of needing to locate a component easier to dictate against interface constants, it means you are in the bad habit of not practicing data-model normalization.
Perhaps you wish to compile the data-model into a vcs release. That you can pull out a distinctly identifiable version of a data-model.
Values defined in interfaces are completely assured to be non-mutable. And shareable. Why load a set of final strings into your class from another class when all you need is that set of constants ??
So why not this to publish a data-model contract? I mean if you can manage and normalize it coherently, why not? ...
public interface CustomerService {
public interface Label{
char AssignmentCharacter = ':';
public interface Address{
String Street = "Street";
String Unit= "Unit/Suite";
String Municipal = "City";
String County = "County";
String Provincial = "State";
String PostalCode = "Zip"
}
public interface Person {
public interface NameParts{
String Given = "First/Given name"
String Auxiliary = "Middle initial"
String Family = "Last name"
}
}
}
}
Now I can reference my apps' contracted labels in a way such as
CustomerService.Label.Address.Street
CustomerService.Label.Person.NameParts.Family
This confuses the contents of the jar file? As a Java programmer I don't care about the structure of the jar.
This presents complexity to osgi-motivated runtime swapping ? Osgi is an extremely efficient means to allow programmers to continue in their bad habits. There are better alternatives than osgi.
Or why not this? There is no leakage of of the private Constants into published contract. All private constants should be grouped into a private interface named "Constants", because I don't want to have to search for constants and I am too lazy to repeatedly type "private final String".
public class PurchaseRequest {
private interface Constants{
String INTERESTINGName = "Interesting Name";
String OFFICIALLanguage = "Official Language"
int MAXNames = 9;
}
}
Perhaps even this:
public interface PurchaseOrderConstants {
public interface Properties{
default String InterestingName(){
return something();
}
String OFFICIALLanguage = "Official Language"
int MAXNames = 9;
}
}
The only issue with interface constants worth considering is when the interface is implemented.
This is not the "original intention" of interfaces? Like I would care about the "original intention" of the founding fathers in crafting the US Constitution, rather than how the Supreme Court would interpret the written letters of the US Constitution ???
After all, I live in the land of the free, the wild and home of the brave. Be brave, be free, be wild - use the interface. If my fellow-programmers refuse to use efficient and lazy means of programming, am I obliged by the golden rule to lessen my programming efficiency to align with theirs? Perhaps I should, but that is not an ideal situation.
For those using sdkman
, this helped me.
Use Case:
I was using identifier 8.0.202-amzn
I decided to install Azul Zulu as follows: sdk install java 13.0.2-zulu
Error:
And then i got this unbound error.
Solution:
1. Right-click on your project in Eclipse
/STS
2. Choose Build Path
> Configure Build Path...
3. Under Libraries, remove the JRE Library, for my case 8.0.202-amzn
4. Under Libraries, click on Modulepath
> Add Library...
5. Choose JRE System Library
, click Next
6. Choose Alternate JRE
, click on Installed JREs...
7. Your previous configured value should be there
8. If it is there, edit it, if it is not there, add one
9. Make sure the name
is: 13.0.2-zulu
10. And the location
(JRE home) is: /Users/jumping_monkey/.sdkman/candidates/java/current
11. Click Apply and close
12. Click Finish
13. Voila!
You will see JRE System Library [13.0.2-zulu] in your Project Explorer and all errors gone
Bravo!
class FileReadWriteService {
private var context:Context? = ContextHolder.instance.appContext
fun writeFileOnInternalStorage(fileKey: String, sBody: String) {
val file = File(context?.filesDir, "files")
try {
if (!file.exists()) {
file.mkdir()
}
val fileToWrite = File(file, fileKey)
val writer = FileWriter(fileToWrite)
writer.append(sBody)
writer.flush()
writer.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
}
fun readFileOnInternalStorage(fileKey: String): String {
val file = File(context?.filesDir, "files")
var ret = ""
try {
if (!file.exists()) {
return ret
}
val fileToRead = File(file, fileKey)
val reader = FileReader(fileToRead)
ret = reader.readText()
reader.close()
} catch (e: Exception) {
Logger.e(classTag, e)
}
return ret
}
}
Imagine you've thread A and thread B. They are both synchronised
on the same object and inside this block there's a global variable they are both updating;
static boolean commonVar = false;
Object lock = new Object;
...
void threadAMethod(){
...
while(commonVar == false){
synchornized(lock){
...
commonVar = true
}
}
}
void threadBMethod(){
...
while(commonVar == true){
synchornized(lock){
...
commonVar = false
}
}
}
So, when thread A enters in the while
loop and holds the lock, it does what it has to do and set the commonVar
to true
. Then thread B comes in, enters in the while
loop and since commonVar
is true
now, it is be able to hold the lock. It does so, executes the synchronised
block, and sets commonVar
back to false
. Now, thread A again gets it's new CPU window, it was about to quit the while
loop but thread B has just set it back to false
, so the cycle repeats over again. Threads do something (so they're not blocked in the traditional sense) but for pretty much nothing.
It maybe also nice to mention that livelock does not necessarily have to appear here. I'm assuming that the scheduler favours the other thread once the synchronised
block finish executing. Most of the time, I think it's a hard-to-hit expectation and depends on many things happening under the hood.
// Put the image file path into this method
public static String getFileToByte(String filePath){
Bitmap bmp = null;
ByteArrayOutputStream bos = null;
byte[] bt = null;
String encodeString = null;
try{
bmp = BitmapFactory.decodeFile(filePath);
bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bt = bos.toByteArray();
encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
}
catch (Exception e){
e.printStackTrace();
}
return encodeString;
}
It couldn't be simpler than this:
public SomeClass Clone () {
var clonedJson = JsonConvert.SerializeObject (this);
return JsonConvert.DeserializeObject<SomeClass> (clonedJson);
}
Just serialize any object to a JSON string and then deserialize it. This will do a deep copy...
On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.
BTW: The correct way to do this is to use TryGetValue
obj item;
if(!dict.TryGetValue(name, out item))
return null;
return item;
This accesses the dictionary only once instead of twice.
If you really want to just return null
if the key doesn't exist, the above code can be simplified further:
obj item;
dict.TryGetValue(name, out item);
return item;
This works, because TryGetValue
sets item
to null
if no key with name
exists.
struct Rect
{
Rect(int x1, int x2, int y1, int y2)
: x1(x1), x2(x2), y1(y1), y2(y2)
{
assert(x1 < x2);
assert(y1 < y2);
}
int x1, x2, y1, y2;
};
//some area of the r1 overlaps r2
bool overlap(const Rect &r1, const Rect &r2)
{
return r1.x1 < r2.x2 && r2.x1 < r1.x2 &&
r1.y1 < r2.y2 && r2.x1 < r1.y2;
}
//either the rectangles overlap or the edges touch
bool touch(const Rect &r1, const Rect &r2)
{
return r1.x1 <= r2.x2 && r2.x1 <= r1.x2 &&
r1.y1 <= r2.y2 && r2.x1 <= r1.y2;
}
A very useful lib for custom progress bar in android.
In your layout file
<com.lylc.widget.circularprogressbar.example.CircularProgressBar
android:id="@+id/mycustom_progressbar"
.
.
.
/>
and Java file
CircularProgressBar progressBar = (CircularProgressBar) findViewById(R.id.mycustom_progressbar);
progressBar.setTitle("Circular Progress Bar");
I just came up with the same problem since we still use bootstrap 2.3.2.
My solution for this: http://jsfiddle.net/KnuU6/281/
css:
.myCollapse {
display: none;
}
.myCollapse.in {
display: block;
}
javascript:
$("[data-toggle=myCollapse]").click(function( ev ) {
ev.preventDefault();
var target;
if (this.hasAttribute('data-target')) {
target = $(this.getAttribute('data-target'));
} else {
target = $(this.getAttribute('href'));
};
target.toggleClass("in");
});
html:
<table>
<tr><td><a href="#demo" data-toggle="myCollapse">Click me to toggle next row</a></td></tr>
<tr class="collapse" id="#demo"><td>You can collapse and expand me.</td></tr>
</table>
If by "hex data" you mean a string of the form
s = "6a48f82d8e828ce82b82"
you can use
i = int(s, 16)
to convert it to an integer and
str(i)
to convert it to a decimal string.
with UnionTable as
(
SELECT a.id, a.time FROM dbo.a
UNION
SELECT b.id, b.time FROM dbo.b
) SELECT id FROM UnionTable GROUP BY id
If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto
Vertical centering is a bit tricker, but possible.
This is my solution
var error=0;
var test = [" ", " "];
if(test[0].match(/^\s*$/g)) {
$("#output").html("MATCH!");
error+=1;
} else {
$("#output").html("no_match");
}
I'd just like to add something to this post for asp:button
. I've tried clientId and it doesn't seem to work for me:
__doPostBack('<%= btn.ClientID%>', '');
However, getting the UniqueId seems to post back to the server, like below:
__doPostBack('<%= btn.UniqueID%>', '');
This might help someone else in future, hence posting this.
I would not make the primary key of the "info" table a composite of the two values from other tables.
Others can articulate the reasons better, but it feels wrong to have a column that is really made up of two pieces of information. What if you want to sort on the ID from the second table for some reason? What if you want to count the number of times a value from either table is present?
I would always keep these as two distinct columns. You could use a two-column primay key in mysql ...PRIMARY KEY(id_a, id_b)... but I prefer using a two-column unique index, and having an auto-increment primary key field.
Use crosstab()
from the tablefunc module.
SELECT * FROM crosstab(
$$SELECT user_id, user_name, rn, email_address
FROM (
SELECT u.user_id, u.user_name, e.email_address
, row_number() OVER (PARTITION BY u.user_id
ORDER BY e.creation_date DESC NULLS LAST) AS rn
FROM usr u
LEFT JOIN email_tbl e USING (user_id)
) sub
WHERE rn < 4
ORDER BY user_id
$$
, 'VALUES (1),(2),(3)'
) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);
I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:
Detailed explanation and instructions here:
And in particular, for "extra columns":
The special difficulties here are:
The lack of key names.
-> We substitute with row_number()
in a subquery.
The varying number of emails.
-> We limit to a max. of three in the outer SELECT
and use crosstab()
with two parameters, providing a list of possible keys.
Pay attention to NULLS LAST
in the ORDER BY
.
I think we can modify the UsedRange
code from @Readify's answer above to get the last used column even if the starting columns are blank or not.
So this lColumn = ws.UsedRange.Columns.Count
modified to
this lColumn = ws.UsedRange.Column + ws.UsedRange.Columns.Count - 1
will give reliable results always
?Sheet1.UsedRange.Column + Sheet1.UsedRange.Columns.Count - 1
Above line Yields 9
in the immediate window.
First you need to find a row with id == 2 then change the name so:
foreach(DataRow dr in table.Rows) // search whole table
{
if(dr["Product_id"] == 2) // if id==2
{
dr["Product_name"] = "cde"; //change the name
//break; break or not depending on you
}
}
You could also try these solutions:
table.Rows[1]["Product_name"] = "cde" // not recommended as it selects 2nd row as I know that it has id 2
Or:
DataRow dr = table.Select("Product_id=2").FirstOrDefault(); // finds all rows with id==2 and selects first or null if haven't found any
if(dr != null)
{
dr["Product_name"] = "cde"; //changes the Product_name
}
I just found Scandinavian Keyboard as a fine solution to this problem. It do also have English and German keyboard, but neither Dutch nor Spanish - but I guess they could be added. And I guess there is other alternatives out there.
Through the Computer management console, navigate through Event Viewer > Windows Logs > System. Every services that change state will be logged here.
You'll see info like: The XXXX service entered the running state or The XXXX service entered the stopped state, etc.
try this...
public class Student
{
public int Grade { get; set; }
public string Name { get; set; }
public override string ToString()
{
return string.Format("Name{0} : Grade{1}", Name, Grade);
}
}
class Program
{
static void Main(string[] args)
{
List<Student> listStudents = new List<Student>();
listStudents.Add(new Student() { Grade = 10, Name = "Pedro" });
listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
listStudents.Add(new Student() { Grade = 10, Name = "Maria" });
listStudents.Add(new Student() { Grade = 11, Name = "Mario" });
listStudents.Add(new Student() { Grade = 15, Name = "Mario" });
listStudents.Add(new Student() { Grade = 10, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
listStudents.Add(new Student() { Grade = 11, Name = "Luana" });
listStudents.Add(new Student() { Grade = 22, Name = "Maria" });
listStudents.Add(new Student() { Grade = 55, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 77, Name = "Maria" });
listStudents.Add(new Student() { Grade = 66, Name = "Maria" });
listStudents.Add(new Student() { Grade = 88, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 42, Name = "Pedro" });
listStudents.Add(new Student() { Grade = 33, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 33, Name = "Luciana" });
listStudents.Add(new Student() { Grade = 17, Name = "Maria" });
listStudents.Add(new Student() { Grade = 25, Name = "Luana" });
listStudents.Add(new Student() { Grade = 25, Name = "Pedro" });
listStudents.GroupBy(g => g.Name).OrderBy(g => g.Key).SelectMany(g => g.OrderByDescending(x => x.Grade)).ToList().ForEach(x => Console.WriteLine(x.ToString()));
}
}
Create a .env file that will hold your credentials at the root of your project and leave it out of versioning:
$ echo ".env" >> .gitignore
In the .env file, add the variables (adapt them according to your installation):
$ echo "DJANGO_SETTINGS_MODULE=myproject.settings.production"> .env
#50 caracter random key
$ echo "SECRET_KEY='####'">> .env
To use them, put this on top of your production.py settings file:
import os
env = os.environ.copy()
SECRET_KEY = env['SECRET_KEY']
Publish it to Heroku using this gem: http://github.com/ddollar/heroku-config.git
$ heroku plugins:install git://github.com/ddollar/heroku-config.git
$ heroku config:push
This way you avoid to change virtualenv files.
*Based on this tutorial
Just index using you ind_pos
ind_pos = [1,5,7]
print (a[ind_pos])
[88 85 16]
In [55]: a = [0,88,26,3,48,85,65,16,97,83,91]
In [56]: import numpy as np
In [57]: arr = np.array(a)
In [58]: ind_pos = [1,5,7]
In [59]: arr[ind_pos]
Out[59]: array([88, 85, 16])
private List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
return files;
}
and if you don't want to load the entire list in memory and avoid blocking you may take a look at the following answer
.
It basically tells the program when you encounter an error just continue at the next line.
If you need to be able to remove the BOM from UTF-8 encoded files, you first need to get hold of an editor that is aware of them.
I personally use E Text Editor.
In the bottom right, there are options for character encoding, including the BOM tag. Load your file, deselect Byte Order Marker if it is selected, resave, and it should be done.
Alt text http://oth4.com/encoding.png
E is not free, but there is a free trial, and it is an excellent editor (limited TextMate compatibility).
Based on @Patrick Boos solution but fixing potential problem with intermediate scrollbars.
export function getRelativeCoordinates(event: MouseEvent, referenceElement: HTMLElement) {
const position = {
x: event.pageX,
y: event.pageY,
};
const offset = {
left: referenceElement.offsetLeft,
top: referenceElement.offsetTop,
};
let reference = referenceElement.offsetParent as HTMLElement;
while (reference) {
offset.left += reference.offsetLeft;
offset.top += reference.offsetTop;
reference = reference.offsetParent as HTMLElement;
}
const scrolls = {
left: 0,
top: 0,
};
reference = event.target as HTMLElement;
while (reference) {
scrolls.left += reference.scrollLeft;
scrolls.top += reference.scrollTop;
reference = reference.parentElement as HTMLElement;
}
return {
x: position.x + scrolls.left - offset.left,
y: position.y + scrolls.top - offset.top,
};
}
EDIT 2020-09-21: Since 3.4.0, Mockito supports mocking static methods, API is still incubating and is likely to change, in particular around stubbing and verification. It requires the mockito-inline
artifact. And you don't need to prepare the test or use any specific runner. All you need to do is :
@Test
public void name() {
try (MockedStatic<LoggerFactory> integerMock = mockStatic(LoggerFactory.class)) {
final Logger logger = mock(Logger.class);
integerMock.when(() -> LoggerFactory.getLogger(any(Class.class))).thenReturn(logger);
new Controller().log();
verify(logger).warn(any());
}
}
The two inportant aspect in this code, is that you need to scope when the static mock applies, i.e. within this try block. And you need to call the stubbing and verification api from the MockedStatic
object.
@Mick, try to prepare the owner of the static field too, eg :
@PrepareForTest({GoodbyeController.class, LoggerFactory.class})
EDIT1 : I just crafted a small example. First the controller :
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Controller {
Logger logger = LoggerFactory.getLogger(Controller.class);
public void log() { logger.warn("yup"); }
}
Then the test :
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Controller.class, LoggerFactory.class})
public class ControllerTest {
@Test
public void name() throws Exception {
mockStatic(LoggerFactory.class);
Logger logger = mock(Logger.class);
when(LoggerFactory.getLogger(any(Class.class))).thenReturn(logger);
new Controller().log();
verify(logger).warn(anyString());
}
}
Note the imports ! Noteworthy libs in the classpath : Mockito, PowerMock, JUnit, logback-core, logback-clasic, slf4j
EDIT2 : As it seems to be a popular question, I'd like to point out that if these log messages are that important and require to be tested, i.e. they are feature / business part of the system then introducing a real dependency that make clear theses logs are features would be a so much better in the whole system design, instead of relying on static code of a standard and technical classes of a logger.
For this matter I would recommend to craft something like= a Reporter
class with methods such as reportIncorrectUseOfYAndZForActionX
or reportProgressStartedForActionX
. This would have the benefit of making the feature visible for anyone reading the code. But it will also help to achieve tests, change the implementations details of this particular feature.
Hence you wouldn't need static mocking tools like PowerMock. In my opinion static code can be fine, but as soon as the test demands to verify or to mock static behavior it is necessary to refactor and introduce clear dependencies.
Your syntax is for table valued function which return a resultset and can be queried like a table. For scalar function do
select dbo.fun_functional_score('01091400003') as [er]
By default in Eclipse you only have to press Ctrl-space for autocomplete. Then select the desired method and wait 500ms for the javadoc info to pop up. If this doesn't work go to the Eclipse Windows menu -> Preferences -> Java -> Editor -> Content assist and check your settings here
PHP and MySQL have their own default timezone configurations. You should synchronize time between your data base and web application, otherwise you could run some issues.
Read this tutorial: How To Synchronize Your PHP and MySQL Timezones
This how I managed to get the screen width in React JS Project:
If width is equal to 1680 then return 570 else return 200
var screenWidth = window.screen.availWidth;
<Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a </Label>
So you need to use what we call promise. Read how angular handles it here, https://docs.angularjs.org/api/ng/service/$q. Turns our $http support promises inherently so in your case we'll do something like this,
(function() {
"use strict";
var serviceCallJson = function($http) {
this.getCustomers = function() {
// http method anyways returns promise so you can catch it in calling function
return $http({
method : 'get',
url : '../viewersData/userPwdPair.json'
});
}
}
var validateIn = function (serviceCallJson, $q) {
this.called = function(username, password) {
var deferred = $q.defer();
serviceCallJson.getCustomers().then(
function( returnedData ) {
console.log(returnedData); // you should get output here this is a success handler
var i = 0;
angular.forEach(returnedData, function(value, key){
while (i < 10) {
if(value[i].username == username) {
if(value[i].password == password) {
alert("Logged In");
}
}
i = i + 1;
}
});
},
function() {
// this is error handler
}
);
return deferred.promise;
}
}
angular.module('assignment1App')
.service ('serviceCallJson', serviceCallJson)
angular.module('assignment1App')
.service ('validateIn', ['serviceCallJson', validateIn])
}())
tabs = {}
def new_tab():
global browser
hpos = browser.window_handles.index(browser.current_window_handle)
browser.execute_script("window.open('');")
browser.switch_to.window(browser.window_handles[hpos + 1])
return(browser.current_window_handle)
def switch_tab(name):
global tabs
global browser
if not name in tabs.keys():
tabs[name] = {'window_handle': new_tab(), 'url': url+name}
browser.get(tabs[name]['url'])
else:
browser.switch_to.window(tabs[name]['window_handle'])
Up through C++03, your first example was valid, but used a deprecated implicit conversion--a string literal should be treated as being of type char const *
, since you can't modify its contents (without causing undefined behavior).
As of C++11, the implicit conversion that had been deprecated was officially removed, so code that depends on it (like your first example) should no longer compile.
You've noted one way to allow the code to compile: although the implicit conversion has been removed, an explicit conversion still works, so you can add a cast. I would not, however, consider this "fixing" the code.
Truly fixing the code requires changing the type of the pointer to the correct type:
char const *p = "abc"; // valid and safe in either C or C++.
As to why it was allowed in C++ (and still is in C): simply because there's a lot of existing code that depends on that implicit conversion, and breaking that code (at least without some official warning) apparently seemed to the standard committees like a bad idea.
Use combine
from moreutils
package, a sets utility that supports not
, and
, or
, xor
operations
combine file1 not file2
i.e give me lines that are in file1 but not in file2
OR give me lines in file1 minus lines in file2
Note: combine
sorts and finds unique lines in both files before performing any operation but diff
does not. So you might find differences between output of diff
and combine
.
So in effect you are saying
Find distinct lines in file1 and file2 and then give me lines in file1 minus lines in file2
In my experience, it's much faster than other options
Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie
var fs = require("fs");
var filename = "./index.html";
function start(resp) {
resp.writeHead(200, {
"Content-Type": "text/html"
});
fs.readFile(filename, "utf8", function(err, data) {
if (err) throw err;
resp.write(data);
resp.end();
});
}
To insert a VARCHAR2
into a BLOB
column you can rely on the function utl_raw.cast_to_raw
as next:
insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));
It will cast your input VARCHAR2
into RAW
datatype without modifying its content, then it will insert the result into your BLOB
column.
More details about the function utl_raw.cast_to_raw
Also, for other readers, if you are trying to do this in Django AND your server allows local_infile (you can check by typing SHOW VARIABLES via a mysql client) then you can add this to your settings.py file (since python MySQLdb doesn't by default read the .my.cnf file):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb',
'USER': 'myname',
'PASSWORD': 'mypass',
'HOST': 'myserver',
'PORT': '3306',
'OPTIONS' : {
'local_infile':1,
},
}
}
save()
can take a file-like object as well as a path, so you can use an in-memory buffer like a StringIO
:
buf = StringIO.StringIO()
im.save(buf, format='JPEG')
jpeg = buf.getvalue()
There are several ways to accomplish that in Vim. I don't know which are most similar to Sublime Text's though.
The first one would be via multiline insert mode. Put your cursor to the
second "a" in the first line, press Ctrl-V
, select all lines, then press I
, and
put in a doublequote. Pressing <esc>
will repeat the operation on every line.
The second one is via macros. Put the cursor on the first character, and start
recording a macro with qa
.
Go the your right with llll
, enter insert mode with
a
, put down a doublequote, exit insert mode, and go back to the beginning of
your row with <home>
(or equivalent). Press j
to move down one row.
Stop recording with q
.
And then replay the macro with @a
. Several times.
Does any of the above approaches work for you?
Another easy way to filter out null values from multiple columns in spark dataframe. Please pay attention there is AND between columns.
df.filter(" COALESCE(col1, col2, col3, col4, col5, col6) IS NOT NULL")
If you need to filter out rows that contain any null (OR connected) please use
df.na.drop()
It is possible to center a video inside an element just like a cover
sized background-image
without JS using the object-fit
attribute or CSS Transforms
.
As pointed in the comments, it is possible to achieve the same result without CSS transform
, but using object-fit
, which I think it's an even better option for the same result:
.video-container {
height: 300px;
width: 300px;
position: relative;
}
.video-container video {
width: 100%;
height: 100%;
position: absolute;
object-fit: cover;
z-index: 0;
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
_x000D_
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>
_x000D_
You can set a video as a background to any HTML element easily thanks to transform
CSS property.
Note that you can use the transform
technique to center vertically and horizontally any HTML element.
.video-container {
height: 300px;
width: 300px;
overflow: hidden;
position: relative;
}
.video-container video {
min-width: 100%;
min-height: 100%;
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
/* Just styling the content of the div, the *magic* in the previous rules */
.video-container .caption {
z-index: 1;
position: relative;
text-align: center;
color: #dc0000;
padding: 10px;
}
_x000D_
<div class="video-container">
<video autoplay muted loop>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4" />
</video>
<div class="caption">
<h2>Your caption here</h2>
</div>
</div>
_x000D_
No need for Javascript, you just have to add a target="_blank"
attribute in your form tag.
<form target="_blank" action="http://example.com"
method="post" id="mc-embedded-subscribe-form"
name="mc-embedded-subscribe-form" class="validate"
>
Use a function like this:
public static string FlattenException(Exception exception)
{
var stringBuilder = new StringBuilder();
while (exception != null)
{
stringBuilder.AppendLine(exception.Message);
stringBuilder.AppendLine(exception.StackTrace);
exception = exception.InnerException;
}
return stringBuilder.ToString();
}
Then you can call it like this:
try
{
// invoke code above
}
catch(MyCustomException we)
{
Debug.Writeline(FlattenException(we));
}
No there isn't. Instead use a while
loop such as:
while 1:
...statements...
if cond:
break
Here's a simple function that I use.
var pad=function(num,field){
var n = '' + num;
var w = n.length;
var l = field.length;
var pad = w < l ? l-w : 0;
return field.substr(0,pad) + n;
};
For example:
pad (20,' '); // 20
pad (321,' '); // 321
pad (12345,' '); //12345
pad ( 15,'00000'); //00015
pad ( 999,'*****'); //**999
pad ('cat','_____'); //__cat
8-bit characters with leading 0
'sometext'
.split('')
.map((char) => '00'.concat(char.charCodeAt(0).toString(2)).slice(-8))
.join(' ');
If you need 6 or 7 bit, just change .slice(-8)
if (User.Identity.IsAuthenticated)
{
Page.Title = "Home page for " + User.Identity.Name;
}
else
{
Page.Title = "Home page for guest user.";
}
I'd say export your server config in IIS manager:
Move these files to your new server
administration.config
applicationHost.config
configEncKey.key
On the new server, go back to the “Shared Configuration” section and check “Enable shared configuration.” Enter the location in physical path to these files and apply them.
BAM! Go have a beer!
Use PtrSafe and see how that works on Excel 2010.
Corrected typo from the book "Microsoft Excel 2010 Power Programming with VBA".
#If vba7 and win64 then
declare ptrsafe function ....
#Else
declare function ....
#End If
val(application.version)>12.0 won't work because Office 2010 has both 32 and 64 bit versions
That's a bit of informal terminology.
As far as Git is concerned, every other repository is just a remote.
Generally speaking, upstream is where you cloned from (the origin). Downstream is any project that integrates your work with other works.
The terms are not restricted to Git repositories.
For instance, Ubuntu is a Debian derivative, so Debian is upstream for Ubuntu.
This works fine too:
HttpContext.Current.Server.MapPath(relativePath)
Where relative path is something like "~/foo/file.jpg"
About access
<ol class="viewer-nav">
<li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value"
(click)="get_data($event)">
{{ section.text }}
</li>
</ol>
And
get_data(event) {
console.log(event.target.dataset.sectionvalue)
}
After some experimentation (see below), I can confirm that as of September 2017, nothing has changed with regards to the functionality described in the accepted answer:-
NULL
s for both VARCHAR
and VARCHAR2
.The historical reason for these two keywords is explained well in an answer to a different question.
There are different ways to do so. You can use DateTime.Now.ToLongTimeString()
which
returns only the time in string format.
Declare @number float = 35.44987665;
Select round(@number,2)
This is simple and sort. Use hsla css function like below
.transparent {
background-color: hsla(0,0%,4%,.4);
}
call listView.scheduleLayoutAnimation(); before changing the list
This also works for me:-
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "CREATE_DATE_TIME", nullable = false, updatable = false, insertable = false, columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
public Date getCreateDateTime() {
return createDateTime;
}
public void setCreateDateTime(Date createDateTime) {
this.createDateTime = createDateTime;
}
You can look up an object's keys and values by either invoking JavaScript's native for in
loop:
var obj = {
foo: 'bar',
base: 'ball'
};
for(var key in obj) {
alert('key: ' + key + '\n' + 'value: ' + obj[key]);
}
or using jQuery's .each()
method:
$.each(obj, function(key, element) {
alert('key: ' + key + '\n' + 'value: ' + element);
});
With the exception of six primitive types, everything in ECMA-/JavaScript is an object. Arrays; functions; everything is an object. Even most of those primitives are actually also objects with a limited selection of methods. They are cast into objects under the hood, when required. To know the base class name, you may invoke the Object.prototype.toString
method on an object, like this:
alert(Object.prototype.toString.call([]));
The above will output [object Array]
.
There are several other class names, like [object Object]
, [object Function]
, [object Date]
, [object String]
, [object Number]
, [object Array]
, and [object Regex]
.
Please try this:
DELETE FROM `table` WHERE id >=163 and id<= 265
It is returning a Buffer object.
If you want it in a string, you can convert it with data.toString()
:
var fs = require("fs");
fs.readFile("test.txt", function (err, data) {
if (err) throw err;
console.log(data.toString());
});
you can use enum constructor for enum to have primitive data type..
public enum DaysOfWeek {
MONDAY(1),
TUESDAY(2),
WEDNESDAY(3),
THURSDAY(4),
FRIDAY(5),
SATURDAY(6),
SUNDAY(7);
private int value;
private DaysOfWeek(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
private static final SparseArray<DaysOfWeek> map = new SparseArray<DaysOfWeek>();
static
{
for (DaysOfWeek daysOfWeek : DaysOfWeek.values())
map.put(daysOfWeek.value, daysOfWeek);
}
public static DaysOfWeek from(int value) {
return map.get(value);
}
}
you can use to pass int as extras then pull it from enum using its value.
dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/
Double quotes should work too... it should create a string, then it should APPEND/INSERT the casted STRING value of $myVar in between 2 empty strings.
If you just want a delay
from time import *
sleep(20)
On my Arch Linux install, gems were installed to the ~/.gem/ruby/2.6.0/bin
directory if installed as user, or /root/.gem/ruby/2.6.0/bin
if installed via sudo
. Just append the appropriate one to your $PATH
environment variable:
export PATH=$PATH:/home/your_username/.gem/ruby/2.6.0/bin
The error is completely correct.
As it's trying to tell you, .sort()
takes a function that returns number, not boolean.
You need to return negative if the first item is smaller; positive if it it's larger, or zero if they're equal.
Change
$info=$_POST['id[]'];
to
$info=$_POST['id'];
by adding []
to the end of your form field names, PHP will automatically convert these variables into arrays.
In Flutter
Container()
widget use for styling your widget.UsingContainer()
widget you can set border or rounded corner of any widget
If you want to set any type of styling & set decoration put that widget into the Container()
widget, that provide many property to decoration.
Container(
width: 100,
padding: EdgeInsets.all(10),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.blueAccent,
borderRadius: BorderRadius.circular(30)), // make rounded corner
child: Text("Click"),
)
clearing the cache works for me.
for React developers try to restart the project otherwise it will show the same error again and again.
Try preventing default on mousedown event:
<div onmousedown="event.preventDefault ? event.preventDefault() : event.returnValue = false">asd</div>
or
<div onmousedown="return false">asd</div>