I will use CXF also you can think of AXIS 2 .
The best way to do it may be using JAX RS Refer this example
Example:
wsimport -p stockquote http://stockquote.xyz/quote?wsdl
This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.
I
Use this filter mask on email input:
emailMask: /[\w.\-@'"!#$%&'*+/=?^_
{|}~]/i`
You can use random.uniform
import random
random.uniform(0, 1)
I found this hard way after trying all of the solutions above. If you're using sub-directories in the zip file, ensure you include the __init__.py
file in each of the sub-directories and that worked for me.
Welcome to hell.
You can just pass a datetime64 object to pandas.Timestamp
:
In [16]: Timestamp(numpy.datetime64('2012-05-01T01:00:00.000000'))
Out[16]: <Timestamp: 2012-05-01 01:00:00>
I noticed that this doesn't work right though in NumPy 1.6.1:
numpy.datetime64('2012-05-01T01:00:00.000000+0100')
Also, pandas.to_datetime
can be used (this is off of the dev version, haven't checked v0.9.1):
In [24]: pandas.to_datetime('2012-05-01T01:00:00.000000+0100')
Out[24]: datetime.datetime(2012, 5, 1, 1, 0, tzinfo=tzoffset(None, 3600))
You can call view.setVisibility(View.GONE)
if you want to remove it from the layout.
Or view.setVisibility(View.INVISIBLE)
if you just want to hide it.
From Android Docs:
INVISIBLE
This view is invisible, but it still takes up space for layout purposes. Use with
setVisibility(int)
andandroid:visibility
.GONE
This view is invisible, and it doesn't take any space for layout purposes. Use with
setVisibility(int)
andandroid:visibility
.
Here you are ;-)
<script type="text/javascript">
alert("Hello there.\nI am on a second line ;-)")
</script>
Instead of changing the user, I've found this advise:
This might help someone else out - after trying every solution to trying and fix this error on SQL 64..
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
..I found an article here...
http://sqlserverpedia.com/blog/sql-server-bloggers/too-many-bits/
..which suggested I give Everyone full permission on this folder..
C:\Users\SQL Service account name\AppData\Local\Temp
And hey presto! My query suddenly burst into life. I punched the air in delight.
Edwaldo
This code is contained within a jUnit test class I use to test if a connection is available. I always receive a connection, but if you check the content length it should be -1 if not known :
try {
URL url = new URL("http://www.google.com");
URLConnection connection = url.openConnection();
if(connection.getContentLength() == -1){
fail("Failed to verify connection");
}
}
catch (IOException e) {
fail("Failed to open a connection");
e.printStackTrace();
}
No, nothing faster than the current O(n) can be done. You need to alter every node, so time will be proportional to the number of elements anyway and that's O(n) you already have.
<FORM Action="mailto:xyz?Subject=Test_Post" METHOD="POST">
mailto: protocol test:
<Br>Subject:
<INPUT name="Subject" value="Test Subject">
<Br>Body: 
<TEXTAREA name="Body">
kfdskfdksfkds
</TEXTAREA>
<BR>
<INPUT type="submit" value="Submit">
</FORM>
Have appended the html in componentDidMount using jQuery append. This should solve the problem.
var MyComponent = React.createClass({
render: function() {
return (
<div>
</div>
);
},
componentDidMount() {
$(ReactDOM.findDOMNode(this)).append(this.props.text);
}
});
falsetru's solution is nice, but has a little bug:
Suppose original 'id' length was larger than 5 characters. When we then dump with the new 'id' (134 with only 3 characters) the length of the string being written from position 0 in file is shorter than the original length. Extra chars (such as '}') left in file from the original content.
I solved that by replacing the original file.
import json
import os
filename = 'data.json'
with open(filename, 'r') as f:
data = json.load(f)
data['id'] = 134 # <--- add `id` value.
os.remove(filename)
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
In a similar case, I wanted to avoid always calling addClass or removeClass due to performance issues. I've split the scroll handler function into two individual functions, used according to the current state. I also added a debounce functionality according to this article: https://developers.google.com/web/fundamentals/performance/rendering/debounce-your-input-handlers
var $header = jQuery( ".clearHeader" );
var appScroll = appScrollForward;
var appScrollPosition = 0;
var scheduledAnimationFrame = false;
function appScrollReverse() {
scheduledAnimationFrame = false;
if ( appScrollPosition > 500 )
return;
$header.removeClass( "darkHeader" );
appScroll = appScrollForward;
}
function appScrollForward() {
scheduledAnimationFrame = false;
if ( appScrollPosition < 500 )
return;
$header.addClass( "darkHeader" );
appScroll = appScrollReverse;
}
function appScrollHandler() {
appScrollPosition = window.pageYOffset;
if ( scheduledAnimationFrame )
return;
scheduledAnimationFrame = true;
requestAnimationFrame( appScroll );
}
jQuery( window ).scroll( appScrollHandler );
Maybe someone finds this helpful.
NOTE: The recommended way to do string formatting in Python is to use format()
, as outlined in the accepted answer. I'm preserving this answer as an example of the C-style syntax that's also supported.
# NOTE: format() is a better choice!
string1 = "go"
string2 = "now"
string3 = "great"
s = """
I will %s there
I will go %s
%s
""" % (string1, string2, string3)
print(s)
Some reading:
If you have ReSharper, try emptying the ReSharper cache:
In menu, ReSharper > Options > Environment > General > Clear Caches
and disabling and re-enabling ReSharper:
In menu, Tools > Options > ReSharper > General > Suspend / Restore
You can select dropdown options by value:
$('#locregion').$('[value="1"]').click();
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
If you are using zsh you can run:
setopt histignorespace
After this is set, each command starting with a space will be excluded from history.
You can use aliases in .zshrc
to turn this on/off:
# Toggle ignore-space. Useful when entering passwords.
alias history-ignore-space-on='\
setopt hist_ignore_space;\
echo "Commands starting with space are now EXCLUDED from history."'
alias history-ignore-space-off='\
unsetopt hist_ignore_space;\
echo "Commands starting with space are now ADDED to history."'
You can start your container with the flag -P
. This "assigns" a random port to the exposed port of your image.
With docker port <container id>
you can see the randomly choosen port. Access is then possible via localhost:port
.
In Angular 7, the (ngModelChange)="eventHandler()"
will fire before the value bound to [(ngModel)]="value"
is changed while the (change)="eventHandler()"
will fire after the value bound to [(ngModel)]="value"
is changed.
It works with Spring Boot 2.1.0 and Hibernate 5
@PersistenceContext
private EntityManager entityManager;
Then you can create new Session by using entityManager.unwrap(Session.class)
Session session = null;
if (entityManager == null
|| (session = entityManager.unwrap(Session.class)) == null) {
throw new NullPointerException();
}
example create query:
session.createQuery("FROM Student");
application.properties:
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:db11g
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
A php/ajax progress bar can be done. (Checkout the Html_Ajax library in pear). However this requires installing a custom module into php.
Other methods require using an iframe, through which php looks to see how much of the file has been uploaded. However this hidden iframe, may be blocked by some browsers addons because hidden iframes are often used to send malicious data to a users computer.
Your best bet is to use some form of flash progress bar if you do not have control over your server.
If you are copy-pasting code into R, it sometimes won't accept some special characters such as "~" and will appear instead as a "?". So if a certain character is giving an error, make sure to use your keyboard to enter the character, or find another website to copy-paste from if that doesn't work.
Is the name of your service class really IService (on the Service namespace)? What you probably had originally was a mismatch in the name of the service class in the name
attribute of the <service>
element.
In fact, except the Html object, you also could use the Spannable type classes, e.g. TextAppearanceSpan or TypefaceSpan and SpannableString togather. Html class also uses these mechanisms. But with the Spannable type classes, you've more freedom.
The declaration and initialization
char *array = "One good thing about music";
declares a pointer array
and make it point to a constant array of 31 characters.
The declaration and initialization
char array[] = "One, good, thing, about, music";
declares an array of characters, containing 31 characters.
And yes, the size of the arrays is 31, as it includes the terminating '\0'
character.
Laid out in memory, it will be something like this for the first:
+-------+ +------------------------------+ | array | --> | "One good thing about music" | +-------+ +------------------------------+
And like this for the second:
+------------------------------+ | "One good thing about music" | +------------------------------+
Arrays decays to pointers to the first element of an array. If you have an array like
char array[] = "One, good, thing, about, music";
then using plain array
when a pointer is expected, it's the same as &array[0]
.
That mean that when you, for example, pass an array as an argument to a function it will be passed as a pointer.
Pointers and arrays are almost interchangeable. You can not, for example, use sizeof(pointer)
because that returns the size of the actual pointer and not what it points to. Also when you do e.g. &pointer
you get the address of the pointer, but &array
returns a pointer to the array. It should be noted that &array
is very different from array
(or its equivalent &array[0]
). While both &array
and &array[0]
point to the same location, the types are different. Using the arrat above, &array
is of type char (*)[31]
, while &array[0]
is of type char *
.
For more fun: As many knows, it's possible to use array indexing when accessing a pointer. But because arrays decays to pointers it's possible to use some pointer arithmetic with arrays.
For example:
char array[] = "Foobar"; /* Declare an array of 7 characters */
With the above, you can access the fourth element (the 'b
' character) using either
array[3]
or
*(array + 3)
And because addition is commutative, the last can also be expressed as
*(3 + array)
which leads to the fun syntax
3[array]
the path you are using is not correct you could just open the node_module and find the path of font-awesome. use could use js or svg font but i prefer the css style.
at first use this command to install font-awesome-free
npm install --save-dev @fortawesome/fontawesome-free
after that you can do this
@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/brands";
and I copy the font path like below this is optional
.copy('node_modules/@fortawesome/fontawesome-free/webfonts', 'public/fonts');
and finally just run the script
npm run dev
or npm run watch
in laravel
volatile variable value access will be direct from main memory. It should be used only in multi-threading environment. static variable will be loaded one time. If its used in single thread environment, even if the copy of the variable will be updated and there will be no harm accessing it as there is only one thread.
Now if static variable is used in multi-threading environment then there will be issues if one expects desired result from it. As each thread has their own copy then any increment or decrement on static variable from one thread may not reflect in another thread.
if one expects desired results from static variable then use volatile with static in multi-threading then everything will be resolved.
git commit --amend
then edit and change the message in the current window. After that do
git push --force-with-lease
How about
SELECT *
FROM Employees
WHERE PhoneNumber IN (
SELECT PhoneNumber
FROM Employees
GROUP BY PhoneNumber
HAVING COUNT(Employee_ID) > 1
)
((SelectionListViewController *)myEditController).list
More examples:
int i = (int)19.5f; // (precision is lost)
id someObject = [NSMutableArray new]; // you don't need to cast id explicitly
Swift 3:
Try this:
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil) else { return nil }
return html
}
}
And for using:
let str = "<h1>Hello bro</h1><h2>Come On</h2><h3>Go sis</h3><ul><li>ME 1</li><li>ME 2</li></ul> <p>It is me bro , remember please</p>"
self.contentLabel.attributedText = str.htmlAttributedString()
Four easy steps
./adb kill-server
./adb start-server
replug the device, unlock it and accept the new key
Run it on a single command line like so:
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile
-WindowStyle Hidden -Command "Get-AppLockerFileInformation -Directory <folderpath>
-Recurse -FileType <type>"
Another good way to serialize json into c# is below:
RootObject ro = new RootObject();
try
{
StreamReader sr = new StreamReader(FileLoc);
string jsonString = sr.ReadToEnd();
JavaScriptSerializer ser = new JavaScriptSerializer();
ro = ser.Deserialize<RootObject>(jsonString);
}
you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client
The tags include 'sendmail' so here's a solution using that:
(
echo "From: [email protected] "
echo "To: [email protected] "
echo "MIME-Version: 1.0"
echo "Content-Type: multipart/alternative; "
echo ' boundary="some.unique.value.ABC123/server.xyz.com"'
echo "Subject: Test HTML e-mail."
echo ""
echo "This is a MIME-encapsulated message"
echo ""
echo "--some.unique.value.ABC123/server.xyz.com"
echo "Content-Type: text/html"
echo ""
echo "<html>
<head>
<title>HTML E-mail</title>
</head>
<body>
<a href='http://www.google.com'>Click Here</a>
</body>
</html>"
echo "------some.unique.value.ABC123/server.xyz.com--"
) | sendmail -t
A wrapper for sendmail can make this job easier, for example, mutt:
mutt -e 'set content_type="text/html"' [email protected] -s "subject" < message.html
removeChild
should be invoked on the parent, i.e.:
parent.removeChild(child);
In your example, you should be doing something like:
if (frameid) {
frameid.parentNode.removeChild(frameid);
}
border radius is good option, if struggling with old IE versions then try HTML codes
•
and use css to change color. Output:
•
You can use
<?php the_category(', '); ?>
which would output them in a comma separated list.
You can also do the same for tags as well:
<?php the_tags('<em>:</em>', ', ', ''); ?>
Assuming a list like below - and assuming some of the options were selected ... (this is a multi select, but this will also work on a single select.
<select multiple='multiple' id='selectListName'>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
In some function called based on some event, the following code would clear all selected options.
$("#selectListName").prop('selectedIndex', -1);
should write like this -->
import Map from './map';
Map
should have first later is capital .(important note)Use Math.round()
, possibly in conjunction with MidpointRounding.AwayFromZero
eg:
Math.Round(1.2) ==> 1
Math.Round(1.5) ==> 2
Math.Round(2.5) ==> 2
Math.Round(2.5, MidpointRounding.AwayFromZero) ==> 3
The existing answers are correct, but sometimes you aren't actually returning something explicitly with a Write-Output
or a return
, yet there is some mystery value in the function results. This could be the output of a builtin function like New-Item
PS C:\temp> function ContrivedFolderMakerFunction {
>> $folderName = [DateTime]::Now.ToFileTime()
>> $folderPath = Join-Path -Path . -ChildPath $folderName
>> New-Item -Path $folderPath -ItemType Directory
>> return $true
>> }
PS C:\temp> $result = ContrivedFolderMakerFunction
PS C:\temp> $result
Directory: C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2/9/2020 4:32 PM 132257575335253136
True
All that extra noise of the directory creation is being collected and emitted in the output. The easy way to mitigate this is to add | Out-Null
to the end of the New-Item
statement, or you can assign the result to a variable and just not use that variable. It would look like this...
PS C:\temp> function ContrivedFolderMakerFunction {
>> $folderName = [DateTime]::Now.ToFileTime()
>> $folderPath = Join-Path -Path . -ChildPath $folderName
>> New-Item -Path $folderPath -ItemType Directory | Out-Null
>> # -or-
>> $throwaway = New-Item -Path $folderPath -ItemType Directory
>> return $true
>> }
PS C:\temp> $result = ContrivedFolderMakerFunction
PS C:\temp> $result
True
New-Item
is probably the more famous of these, but others include all of the StringBuilder.Append*()
methods, as well as the SqlDataAdapter.Fill()
method.
$('#myDiv').click
is better, because it separates JavaScript code from HTML. One must try to keep the page behaviour and structure different. This helps a lot.
You can try to use as well this functions to capture StdErr StdOut and return code.
def runShell(String command){
def responseCode = sh returnStatus: true, script: "${command} &> tmp.txt"
def output = readFile(file: "tmp.txt")
if (responseCode != 0){
println "[ERROR] ${output}"
throw new Exception("${output}")
}else{
return "${output}"
}
}
Notice:
&>name means 1>name 2>name -- redirect stdout and stderr to the file name
Go via POSIXct
and you want to set a TZ
there -- here you see my (Chicago) default:
R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05"
R>
Edit: A few years later, we can now use the anytime package:
R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R>
Note how all this works without any format or origin arguments.
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
Using new Function() is better than eval, but still should only be used with safe input.
const parseJSON = obj => Function('"use strict";return (' + obj + ')')();
console.log(parseJSON("{a:(4-1), b:function(){}, c:new Date()}"))
// outputs: Object { a: 3, b: b(), c: Date 2019-06-05T09:55:11.777Z }
Response you are getting is in object form i.e.
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Replace below line of code :
List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))
with
Post post = gson.fromJson(reader, Post.class);
For IntelliJ IDEA Ultimate latest version as of 18th Dec 2017, if the above suggestions don't work, then please try the following: Right Click on the project and navigate to "Open Module Settings". Open it, then change the "Language Level" from the dropdown.
Your question contains the string literal "\b[A-Z]{2,}\b"
,
but that \b
will mean backspace, because there is no r-modifier.
Try: r"\b[A-Z]{2,}\b"
.
The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.
Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.
An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.
If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.
To actually deodex, use small and baksmali:
Use this:
<link onclick='doWithThisElement(this.attributes["id"].value)' />
In the context of the onclick JavaScript, this refers to the current element (which in this case is the whole HTML element link).
You can use a function comparator without wrapping it like so:
bool comparator(const MyType &lhs, const MyType &rhs)
{
return [...];
}
std::set<MyType, bool(*)(const MyType&, const MyType&)> mySet(&comparator);
which is irritating to type out every time you need a set of that type, and can cause issues if you don't create all sets with the same comparator.
Use the correct call: strptime
is a classmethod of the datetime.datetime
class, it's not a function in the datetime
module.
self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")
As mentioned by Jon Clements in the comments, some people do from datetime import datetime
, which would bind the datetime
name to the datetime
class, and make your initial code work.
To identify which case you're facing (in the future), look at your import statements
import datetime
: that's the module (that's what you have right now).from datetime import datetime
: that's the class.I've created a bit of an adaptation of script @devnull69 submitted. I felt for my application it would be more useful as a function that returned the value that I could, then use as a variable.
HTML
<input type="text" id="time_field" />
<button>Submit</submit>
jQuery
$(document).ready(function() {
function convertTime(time) {
var hours = Number(time.match(/^(\d\d?)/)[1]);
var minutes = Number(time.match(/:(\d\d?)/)[1]);
var AMPM = time.match(/\s(AM|PM)$/i)[1];
if((AMPM == 'PM' || AMPM == 'pm') && hours < 12) {
hours = hours + 12;
}
else if((AMPM == 'AM' || AMPM == "am") && hours == 12) {
hours = hours - 12;
}
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours < 10) {
sHours = "0" + sHours;
}
else if(minutes < 10) {
sMinutes = "0" + sMinutes;
}
return sHours + ":" + sMinutes;
}
$('button').click(function() {
alert(convertTime($('#time_field').val()));
});
});
You'll probably have to put another element around the table and style that with a rounded border.
The working draft specifies that border-radius
does not apply to table elements when the value of border-collapse
is collapse
.
You can assign one color to every functionality to make it more useful.
#define Color_Red "\33[0:31m\\]" // Color Start
#define Color_end "\33[0m\\]" // To flush out prev settings
#define LOG_RED(X) printf("%s %s %s",Color_Red,X,Color_end)
foo()
{
LOG_RED("This is in Red Color");
}
Like wise you can select different color codes and make this more generic.
Goto Setting->Plugin->Search for "Lombok Plugin" -> It will show results. Install Lombok Plugin from the list and Restart Intellij
Below is Neil's answer updated.
I'm no expert but I'd say that if you really want to be semantic, you should use vocabularies (RDFa).
This should result in something like that:
<em property="italic" href="http://url/to/a/definition_of_italic"> Your text </em>
em
is used for the presentation (humans will see it in italic) and the property
and href
attributes are linking to a definition of what italic is (for machines).
You should check if there's a vocabulary for that kind of thing, maybe properties already exist.
More info about RDFa here: http://www.alistapart.com/articles/introduction-to-rdfa/
use this:
pil_image = PIL.Image.open('Image.jpg').convert('RGB')
open_cv_image = numpy.array(pil_image)
# Convert RGB to BGR
open_cv_image = open_cv_image[:, :, ::-1].copy()
Powershell Commandlets.
Parsing done by powershell based on attributes specified on the commandlets, support for validations, parameter sets, pipelining, error reporting, help, and best of all returning .NET objects for use in other commandlets.
A couple links i found helpful getting started:
There is no direct string compare function in SQL Server
CASE
WHEN str1 = str2 THEN 0
WHEN str1 < str2 THEN -1
WHEN str1 > str2 THEN 1
ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END
Notes
I have used both R and MATLAB to solve problems and construct models related to Environmental Engineering and there is a lot of overlap between the two systems. In my opinion, the advantages of MATLAB lie in specialized domain-specific applications. Some examples are:
Functions such as streamline that aid in fluid dynamics investigations.
Toolboxes such as the image processing toolset. I have not found a R package that provides an equivalent implementation of tools like the watershed algorithm.
In my opinion MATLAB provides far better interactive graphics capabilities. However, I think R produces better static print-quality graphics, depending on the application. MATLAB's symbolic math toolbox is also better integrated and more capable than R equivalents such as Ryacas or rSymPy. The existence of the MATLAB compiler also allows systems based on MATLAB code to be deployed independently of the MATLAB environment-- although it's availability will depend on how much money you have to throw around.
Another thing I should note is that the MATLAB debugger is one of the best I have worked with.
The principle advantage I see with R is the openness of the system and the ease with which it can be extended. This has resulted in an incredible diversity of packages on CRAN. I know Mathworks also maintains a repository of user-contributed toolboxes and I can't make a fair comparison as I have not used it that much.
The openness of R also extends to linking in compiled code. A while back I had a model written in Fortran and I was trying to decide between using R or MATLAB as a front-end to help prepare input and process results. I spent an hour reading about the MEX interface to compiled code. When I found that I would have to write and maintain a separate Fortran routine that did some intricate pointer juggling in order to manage the interface, I shelved MATLAB.
The R interface consists of calling .Fortran( [subroutine name], [argument list]) and is simply quicker and cleaner.
I just want to add, if you get this error because you are using Cygwin make and auto-generated files, you can fix it with the following sed,
sed -e 's@\\\([^ ]\)@/\1@g' -e 's@[cC]:@/cygdrive/c@' -i filename.d
You may need to add more characters than just space to the escape list in the first substitution but you get the idea. The concept here is that /cygdrive/c is an alias for c: that cygwin's make will recognize.
And may as well throw in
-e 's@^ \+@\t@'
just in case you did start with spaces on accident (although I /think/ this will usually be a "missing separator" error).
you can do:
A = randi(10, [3 4]); %# a random matrix
any( A(:)==5 ) %# does A contain 5?
To do the above in a vectorized way, use:
any( bsxfun(@eq, A(:), [5 7 11] )
or as @woodchips suggests:
ismember([5 7 11], A)
Should you ever crave deeper understanding, I heartily recommend Patterson and Hennessy as an intro and Hennessy and Patterson as an intermediate to advanced text. They're pricey, but truly non-pareil; I just wish either or both were available when I got my Masters' degree and entered the workforce designing chips, systems, and parts of system software for them (but, alas!, that was WAY too long ago;-). Stack pointers are so crucial (and the distinction between a microprocessor and any other kind of CPU so utterly meaningful in this context... or, for that matter, in ANY other context, in the last few decades...!-) that I doubt anything but a couple of thorough from-the-ground-up refreshers can help!-)
On Virtualenv try editing the pip file, like so:
vi <your_virtualenv_folder>/bin/pip
look at the first line and check if it corresponds to the project folder, if not just change it.
#!/<your_path>/<project_folder>/<your_virtualenv_folder>/bin/python
When the branch is no remote branch you can push your local branch direct to the remote.
git checkout master
git push origin master
or when you have a dev branch
git checkout dev
git push origin dev
or when the remote branch exists
git branch dev -t origin/dev
There are some other posibilites to push a remote branch.
Use Application.ActiveWorkbook.Path
for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName
for the path with the workbook name.
I'd guess that Remove
and Substring
would tie for first place, since they both slurp up a fixed-size portion of the string, whereas TrimStart
does a scan from the left with a test on each character and then has to perform exactly the same work as the other two methods. Seriously, though, this is splitting hairs.
You can also use google-collections (guava) Joiner class if you want to customize the print format
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
per @Kevin-Reid's answer, here's an alternative to the "I ended up doing the following" example that avoids needing to name and then lookup the form object again by constructing the form specifically (using jQuery)..
var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="api_url" value="' + Return_URL + '" />' +
'</form>');
$('body').append(form);
form.submit();
http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.goto
If you have been told that there is no goto statement in Java you have been fooled. Indeed, Java consists two layers of 'source' code.
This is what worked for me on iOS 6 (very slight adaptation of rmarscher's answer):
<script>
(function(document,navigator,standalone) {
if (standalone in navigator && navigator[standalone]) {
var curnode,location=document.location,stop=/^(a|html)$/i;
document.addEventListener("click", function(e) {
curnode=e.target;
while (!stop.test(curnode.nodeName)) {
curnode=curnode.parentNode;
}
if ("href" in curnode && (curnode.href.indexOf("http") || ~curnode.href.indexOf(location.host)) && curnode.target == false) {
e.preventDefault();
location.href=curnode.href
}
},false);
}
})(document,window.navigator,"standalone")
</script>
While using the date formats, you may want to keep in mind to always use MM
for months and mm
for minutes. That should resolve your problem.
The syntax is changed for Angular 2 and above:
[ngStyle]="{'background-image': 'url(path)'}"
HTML:
<select class="shortenedSelect">
<option value="0" disabled>Please select an item</option>
<option value="1">Item text goes in here but it is way too long to fit inside a select option that has a fixed width adding more</option>
</select>
CSS:
.shortenedSelect {
max-width: 350px;
}
Javascript:
// Shorten select option text if it stretches beyond max-width of select element
$.each($('.shortenedSelect option'), function(key, optionElement) {
var curText = $(optionElement).text();
$(this).attr('title', curText);
// Tip: parseInt('350px', 10) removes the 'px' by forcing parseInt to use a base ten numbering system.
var lengthToShortenTo = Math.round(parseInt($(this).parent('select').css('max-width'), 10) / 7.3);
if (curText.length > lengthToShortenTo) {
$(this).text('... ' + curText.substring((curText.length - lengthToShortenTo), curText.length));
}
});
// Show full name in tooltip after choosing an option
$('.shortenedSelect').change(function() {
$(this).attr('title', ($(this).find('option:eq('+$(this).get(0).selectedIndex +')').attr('title')));
});
Works perfectly. I had the same issue myself. Check out this JSFiddle http://jsfiddle.net/jNWS6/426/
Didn't work for me:
ng serve --watch
Try :
sudo ng serve
this worked for me!
Solved it. Turns out the column had a limited set of characters it would accept, changed it, and now the query works fine.
1-> Using File Default Config- Angular-cli comes from the ember-cli project. To run the application on specific port, create an .ember-cli file in the project root. Add your JSON config in there:
{ "port": 1337 }
2->Using Command Line Tool Run this command in Angular-Cli
ng serve --port 1234
To change the port number permanently:
Goto
node_modules/angular-cli/commands/server.js
Search for var defaultPort = process.env.PORT || 4200;
(change 4200 to anything else you want).
You could use box-shadow
, possibly:
#something {
background: transparent url(https://i.stack.imgur.com/RL5UH.png) 50% 50% no-repeat;
min-width: 300px;
min-height: 300px;
box-shadow: inset 0 0 10px #0f0;
}
#something {
background: transparent url(https://i.stack.imgur.com/RL5UH.png) 50% 50% no-repeat;
min-width: 300px;
min-height: 300px;
box-shadow: inset 0 0 10px #0f0;
}
_x000D_
<div id="something"></div>
_x000D_
This has the advantage that it will overlay the background-image of the div
, but it is, of course, blurred (as you'd expect from the box-shadow
property). To build up the density
of the shadow you can add additional shadows of course:
#something {
background: transparent url(https://i.stack.imgur.com/RL5UH.png) 50% 50% no-repeat;
min-width: 300px;
min-height: 300px;
box-shadow: inset 0 0 20px #0f0, inset 0 0 20px #0f0, inset 0 0 20px #0f0;
}
#something {
background: transparent url(https://i.stack.imgur.com/RL5UH.png) 50% 50% no-repeat;
min-width: 300px;
min-height: 300px;
box-shadow: inset 0 0 20px #0f0, inset 0 0 20px #0f0, inset 0 0 20px #0f0;
}
_x000D_
<div id="something"></div>
_x000D_
Edited because I realised that I'm an idiot, and forgot to offer the simplest solution first, which is using an otherwise-empty child element to apply the borders over the background:
#something {
background: transparent url(https://i.stack.imgur.com/RL5UH.png) 50% 50% no-repeat;
min-width: 300px;
min-height: 300px;
padding: 0;
position: relative;
}
#something div {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border: 10px solid rgba(0, 255, 0, 0.6);
}
_x000D_
<div id="something">
<div></div>
</div>
_x000D_
Edited after @CoryDanielson's comment, below:
jsfiddle.net/dPcDu/2 you can add a 4th px parameter for the
box-shadow
that does the spread and will more easily reflect his images.
#something {
background: transparent url(https://i.stack.imgur.com/RL5UH.png) 50% 50% no-repeat;
min-width: 300px;
min-height: 300px;
box-shadow: inset 0 0 0 10px rgba(0, 255, 0, 0.5);
}
_x000D_
<div id="something"></div>
_x000D_
Provide a portable and generic getdelim
function, test passed via msvc, clang, gcc.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
ssize_t
portabl_getdelim(char ** restrict linep,
size_t * restrict linecapp,
int delimiter,
FILE * restrict stream) {
if (0 == *linep) {
*linecapp = 8;
*linep = malloc(*linecapp);
if (0 == *linep) {
return EOF;
}
}
ssize_t linelen = 0;
int c = 0;
char *p = *linep;
while (EOF != (c = fgetc(stream))) {
if (linelen == (ssize_t) *linecapp - 1) {
*linecapp <<= 1;
char *p1 = realloc(*linep, *linecapp);
if (0 == *p1) {
return EOF;
}
p = p1 + linelen;
}
*p++ = c;
linelen++;
if (delimiter == c) {
*p = 0;
return linelen;
}
}
return EOF == c ? EOF : linelen;
}
int
main(int argc, char **argv) {
const char *filename = "/a/b/c.c";
FILE *file = fopen(filename, "r");
if (!file) {
perror(filename);
return 1;
}
char *line = 0;
size_t linecap = 0;
ssize_t linelen;
while (0 < (linelen = portabl_getdelim(&line, &linecap, '\n', file))) {
fwrite(line, linelen, 1, stdout);
}
if (line) {
free(line);
}
fclose(file);
return 0;
}
Here's the map solution:
#include <iostream>
#include <map>
typedef std::map<char, char> BasePairMap;
int main()
{
BasePairMap m;
m['A'] = 'T';
m['T'] = 'A';
m['C'] = 'G';
m['G'] = 'C';
std::cout << "A:" << m['A'] << std::endl;
std::cout << "T:" << m['T'] << std::endl;
std::cout << "C:" << m['C'] << std::endl;
std::cout << "G:" << m['G'] << std::endl;
return 0;
}
The problem is the charset that is being used by apache to serve the pages. I work with Linux, so I don't know anything about XAMPP. I had the same problem too, what I did to solve the problem was to add the charset to the charset
config file (It is commented by default).
In my case I have it in /etc/apache2/conf.d/charset
but, since you're using Windows the location is different. So I'm giving you this like an idea of how to solve it.
At the end, my charset config file is like this:
# Read the documentation before enabling AddDefaultCharset.
# In general, it is only a good idea if you know that all your files
# have this encoding. It will override any encoding given in the files
# in meta http-equiv or xml encoding tags.
AddDefaultCharset UTF-8
I hope it helps.
Here's my version
import requests
try:
if requests.get('https://google.com').ok:
print("You're Online")
except:
print("You're Offline")
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
After writing to external storage, some file managers don't see the file right away. This can be confusing if a user thinks they copied something to the SD card, but then can't find it there. So after you copy the file, run the following code to notify file managers of its presence.
MediaScannerConnection.scanFile(
context,
new String[]{myFile.getAbsolutePath()},
null,
null);
See the documentation and this answer for more.
Probably an issue with strings having whitespace. Here's a cleaned up version that works for me:
Function Test-RegistryValue($regkey, $name) {
$exists = Get-ItemProperty -Path "$regkey" -Name "$name" -ErrorAction SilentlyContinue
If (($exists -ne $null) -and ($exists.Length -ne 0)) {
Return $true
}
Return $false
}
Python's eager in its evaluation, so eval(input(...))
(Python 3) will evaluate the user's input as soon as it hits the eval
, regardless of what you do with the data afterwards. Therefore, this is not safe, especially when you eval
user input.
Use ast.literal_eval
.
As an example, entering this at the prompt could be very bad for you:
__import__('os').system('rm -rf /a-path-you-really-care-about')
The answer has already been here. If you don't want to use any library, you can follow these steps:
Explanation:
In onCreateViewHolder
method we can check viewType
and depending on the value (our "special" kind) inflate a special layout.
For example:
public static final int TITLE = 0;
public static final int ITEM = 1;
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (context == null) {
context = parent.getContext();
}
if (viewType == TITLE) {
view = LayoutInflater.from(context).inflate(R.layout.recycler_adapter_title, parent,false);
return new TitleElement(view);
} else if (viewType == ITEM) {
view = LayoutInflater.from(context).inflate(R.layout.recycler_adapter_item, parent,false);
return new ItemElement(view);
}
return null;
}
where class ItemElement
and class TitleElement
can look like ordinary ViewHolder
:
public class ItemElement extends RecyclerView.ViewHolder {
//TextView text;
public ItemElement(View view) {
super(view);
//text = (TextView) view.findViewById(R.id.text);
}
So the idea of all of that is interesting. But i am interested if it's effectively, cause we need to sort the data list. And i think this will take the speed down. If any thoughts about it, please write me :)
And also the opened question : is how to hold the "special" layout on the top, while the items are recycling. Maybe combine all of that with CoordinatorLayout
.
The items with code "200 (cache)" were fulfilled directly from your browser cache, meaning that the original requests for the items were returned with headers indicating that the browser could cache them (e.g. future-dated Expires
or Cache-Control: max-age
headers), and that at the time you triggered the new request, those cached objects were still stored in local cache and had not yet expired.
304s, on the other hand, are the response of the server after the browser has checked if a file was modified since the last version it had cached (the answer being "no").
For most optimal web performance, you're best off setting a far-future Expires:
or Cache-Control: max-age
header for all assets, and then when an asset needs to be changed, changing the actual filename of the asset or appending a version string to requests for that asset. This eliminates the need for any request to be made unless the asset has definitely changed from the version in cache (no need for that 304 response). Google has more details on correct use of long-term caching.
Like this ? (Visual Studio Code version 0.10.11)
Fold All (Ctrl+K Ctrl+0)
Unfold All (Ctrl+K Ctrl+J)
Fold Level n (Ctrl+K Ctrl+N)
I was interested in this question, so I did a test just now. Using .NET Framework 4.5.2 on an Intel(R) Core(TM) i3-2328M CPU @ 2.20GHz, 2200 Mhz, 2 Core(s) with 8GB ram running Microsoft Windows 7 Ultimate.
It looks like LINQ might be faster than for each loop. Here are the results I got:
Exists = True
Time = 174
Exists = True
Time = 149
It would be interesting if some of you could copy & paste this code in a console app and test as well. Before testing with an object (Employee) I tried the same test with integers. LINQ was faster there as well.
public class Program
{
public class Employee
{
public int id;
public string name;
public string lastname;
public DateTime dateOfBirth;
public Employee(int id,string name,string lastname,DateTime dateOfBirth)
{
this.id = id;
this.name = name;
this.lastname = lastname;
this.dateOfBirth = dateOfBirth;
}
}
public static void Main() => StartObjTest();
#region object test
public static void StartObjTest()
{
List<Employee> items = new List<Employee>();
for (int i = 0; i < 10000000; i++)
{
items.Add(new Employee(i,"name" + i,"lastname" + i,DateTime.Today));
}
Test3(items, items.Count-100);
Test4(items, items.Count - 100);
Console.Read();
}
public static void Test3(List<Employee> items, int idToCheck)
{
Stopwatch s = new Stopwatch();
s.Start();
bool exists = false;
foreach (var item in items)
{
if (item.id == idToCheck)
{
exists = true;
break;
}
}
Console.WriteLine("Exists=" + exists);
Console.WriteLine("Time=" + s.ElapsedMilliseconds);
}
public static void Test4(List<Employee> items, int idToCheck)
{
Stopwatch s = new Stopwatch();
s.Start();
bool exists = items.Exists(e => e.id == idToCheck);
Console.WriteLine("Exists=" + exists);
Console.WriteLine("Time=" + s.ElapsedMilliseconds);
}
#endregion
#region int test
public static void StartIntTest()
{
List<int> items = new List<int>();
for (int i = 0; i < 10000000; i++)
{
items.Add(i);
}
Test1(items, -100);
Test2(items, -100);
Console.Read();
}
public static void Test1(List<int> items,int itemToCheck)
{
Stopwatch s = new Stopwatch();
s.Start();
bool exists = false;
foreach (var item in items)
{
if (item == itemToCheck)
{
exists = true;
break;
}
}
Console.WriteLine("Exists=" + exists);
Console.WriteLine("Time=" + s.ElapsedMilliseconds);
}
public static void Test2(List<int> items, int itemToCheck)
{
Stopwatch s = new Stopwatch();
s.Start();
bool exists = items.Contains(itemToCheck);
Console.WriteLine("Exists=" + exists);
Console.WriteLine("Time=" + s.ElapsedMilliseconds);
}
#endregion
}
When your view loads, so does its associated controller. Instead of using ng-init
, simply call your init()
method in your controller:
$scope.init = function () {
if ($routeParams.Id) {
//get an existing object
} else {
//create a new object
}
$scope.isSaving = false;
}
...
$scope.init();
Since your controller runs before ng-init
, this also solves your second issue.
As John David Five
mentioned, you might not want to attach this to $scope
in order to make this method private.
var init = function () {
// do something
}
...
init();
If you want to wait for certain data to be preset, either move that data request to a resolve or add a watcher to that collection or object and call your init method when your data meets your init criteria. I usually remove the watcher once my data requirements are met so the init function doesnt randomly re-run if the data your watching changes and meets your criteria to run your init method.
var init = function () {
// do something
}
...
var unwatch = scope.$watch('myCollecitonOrObject', function(newVal, oldVal){
if( newVal && newVal.length > 0) {
unwatch();
init();
}
});
Also, it has to be noted that if you're using your_tensor.assign()
, then the tf.global_variables_initializer
need not be called explicitly since the assign operation does it for you in the background.
Example:
In [212]: w = tf.Variable(12)
In [213]: w_new = w.assign(34)
In [214]: with tf.Session() as sess:
...: sess.run(w_new)
...: print(w_new.eval())
# output
34
However, this will not initialize all variables, but it will only initialize the variable on which assign
was executed on.
Try this : Using this you can select date by last 30 days,
SELECT DATEADD(DAY,-30,GETDATE())
private static boolean isValidFolderPath(String path) {
File file = new File(path);
if (!file.exists()) {
return file.mkdirs();
}
return true;
}
I had the same problem and after hours of looking found the answer.
The error I was getting was a little different: <path> already exists and is not a valid git repo
(and added here for SEO value)
The solution is to NOT create the directory that will house the submodule. The directory will be created as part of the git submodule add
command.
Also, the argument is expected to be relative to the parent-repo root, not your working directory, so watch out for that.
Solution for the example above:
common_code
directory does not exist.cd Repo
git submodule add git://url_to_repo projectfolder/common_code/
(Note the required trailing slash.)I hope this helps someone, as there is very little information to be found elsewhere about this.
There is no difference, in browsers that you can find in the wild these days (that is, excluding things like Netscape 1 that you might find in a museum). There is no reason to suspect that any of them would be deprecated ever, especially since they are all valid in XML, in HTML 4.01, and in HTML5 CR.
There is no reason to use any of them, as opposite to using the Ascii quotation mark (") directly, except in the very special case where you have an attribute value enclosed in such marks and you would like to use the mark inside the value (e.g., title="Hello "world""
), and even then, there are almost always better options (like title='Hello "word"'
or title="Hello “word”"
.
If you want to use “smart” quotation marks instead, then it’s a different question, and none of the constructs has anything to do with them. Some people expect notations like "
to produce “smart” quotes, but it is easy to see that they don’t; the notations unambiguously denote the Ascii quote ("), as used in computer languages.
SOLUTION:
Run the emulator from the command line:
sdk/tools> ./emulator-x86 -avd <DeviceName> -partition-size 1024 -gpu on
Then I launched the app from the command line as well (using built-in Cordova/PhoneGap tools):
myapp/cordova> ./run
BACKGROUND
I believe this is some sort of hardware compatibility issue. I came across this problem when following the PhoneGap 2.4.0 Getting Started Instructions. I followed their advice to install the Intel Hardware Accelerated Execution Manager, and I think this is the source of my trouble. Eclipse uses the emulator64-x86
program (in the sdk/tools
folder) to launch the emulator. I could not find any way inside of Eclipse to change this but I found by following the "Tips & Tricks" section of the Intel HAXM web page that I could get the emulator to run successfully from the command line by using the emulator-x86
program instead. I'm not sure why the emulator64-x86
program doesn't work on my system. I confirmed at the Apple website that I do have a 64-bit processor.
My system:
My AVD:
For Ubuntu 15.10 and Python 3, comming to this question as they don't have Python.h
but having administrative rights, the following might solve it:
sudo apt-get install python-dev
sudo apt-get install python3-dev
sudo apt-get install libpython3-dev
sudo apt-get install libpython3.4-dev
sudo apt-get install libpython3.5-dev
var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"};
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;
If you want code is running on multiple servers with different environments,then we have need to use dirname(FILE) in an include or include_once statement. reason is follows. 1. Do not give absolute path to include files on your server. 2. Dynamically calculate the full path like absolute path.
Use a combination of dirname(FILE) and subsequent calls to itself until you reach to the home of your '/myfile.php'. Then attach this variable that contains the path to your included files.
interface supports Python 2.7 and Python 3.4+.
To install interface you have to
pip install python-interface
Example Code:
from interface import implements, Interface
class MyInterface(Interface):
def method1(self, x):
pass
def method2(self, x, y):
pass
class MyClass(implements(MyInterface)):
def method1(self, x):
return x * 2
def method2(self, x, y):
return x + y
Try this:
With xlApp.ActiveSheet.Pictures.Insert(PicPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 75
.Height = 100
End With
.Left = xlApp.ActiveSheet.Cells(i, 20).Left
.Top = xlApp.ActiveSheet.Cells(i, 20).Top
.Placement = 1
.PrintObject = True
End With
It's better not to .select anything in Excel, it is usually never necessary and slows down your code.
You can move Application.java
to a folder under the java.
I've written a library that is up-to-date, since all the other answers are outdated:
If you want a pure iterator solution for large strings with constant memory usage:
from typing import Iterable
import itertools
def ngrams_iter(input: str, ngram_size: int, token_regex=r"[^\s]+") -> Iterable[str]:
input_iters = [
map(lambda m: m.group(0), re.finditer(token_regex, input))
for n in range(ngram_size)
]
# Skip first words
for n in range(1, ngram_size): list(map(next, input_iters[n:]))
output_iter = itertools.starmap(
lambda *args: " ".join(args),
zip(*input_iters)
)
return output_iter
Test:
input = "If you want a pure iterator solution for large strings with constant memory usage"
list(ngrams_iter(input, 5))
Output:
['If you want a pure',
'you want a pure iterator',
'want a pure iterator solution',
'a pure iterator solution for',
'pure iterator solution for large',
'iterator solution for large strings',
'solution for large strings with',
'for large strings with constant',
'large strings with constant memory',
'strings with constant memory usage']
Try this using HTML like here:
var myDate = window.document.getElementById("startdate").value;
Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'
Stop recording and you can start inspecting your code.
I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"
Option Explicit
Sub SaveFile()
Dim fdate As Date
Dim fname As String
Dim path As String
fdate = Range("A1").Value
path = Application.ActiveWorkbook.path
If fdate > 0 Then
fname = "Event " & fdate
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
MsgBox "Chose a date for the event", vbOKOnly
End If
End Sub
Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!
I ran into this issue when using IntelliJ 14's bundled Maven 3 instance.
I switched to using my own local Maven instance, via:
Settings -> Build, Execution, Deployment -> Build Tools -> Maven -> Maven Home Directory
Then added the path to my locally installed instance.
This got the dependencies to magically appear.
#1 I use the last one frequently when having buttons on the layout which are not generated (but static obviously).
If you use it in practice and in a business application, pay extra attention here, because when you use source obfuscater like ProGuard, you'll need to mark these methods in your activity as to not be obfuscated.
For archiving some kind of compile-time-security with this approach, have a look at Android Lint (example).
#2 Pros and cons for all methods are almost the same and the lesson should be:
Use what ever is most appropriate or feels most intuitive to you.
If you have to assign the same OnClickListener
to multiple button instances, save it in the class-scope (#1). If you need a simple listener for a Button, make an anonymous implementation:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Take action.
}
});
I tend to not implement the OnClickListener
in the activity, this gets a little confusing from time to time (especially when you implement multiple other event-handlers and nobody knows what this
is all doing).
[object Object]
This means somewhere the object is being converted to a string.
Converted to a string:
//Copy and paste in the browser console to see result
var product = {'name':'test'};
JSON.stringify(product + '');
Not converted to a string:
//Copy and paste in the browser console to see result
var product = {'name':'test'};
JSON.stringify(product);
In java8, I would use the Instant
class which is already in UTC and is convenient to work with.
import java.time.Instant;
Instant ins = Instant.now();
long ts = ins.toEpochMilli();
Instant ins2 = Instant.ofEpochMilli(ts)
Alternatively, you can use the following:
import java.time.*;
Instant ins = Instant.now();
OffsetDateTime odt = ins.atOffset(ZoneOffset.UTC);
ZonedDateTime zdt = ins.atZone(ZoneId.of("UTC"));
Back to Instant
Instant ins4 = Instant.from(odt);
Just for fun:
var mystring = "this,is,a,test"
var newchar = '|'
mystring = mystring.split(',').join(newchar);
How about this ...
string ThisdllDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Then just hack off what you do not need
The first thing you must know is that indexes are a way to avoid scanning the full table to obtain the result that you're looking for.
There are different kinds of indexes and they're implemented in the storage layer, so there's no standard between them and they also depend on the storage engine that you're using.
For InnoDB, the most common index type is the B+Tree based index, that stores the elements in a sorted order. Also, you don't have to access the real table to get the indexed values, which makes your query return way faster.
The "problem" about this index type is that you have to query for the leftmost value to use the index. So, if your index has two columns, say last_name and first_name, the order that you query these fields matters a lot.
So, given the following table:
CREATE TABLE person (
last_name VARCHAR(50) NOT NULL,
first_name VARCHAR(50) NOT NULL,
INDEX (last_name, first_name)
);
This query would take advantage of the index:
SELECT last_name, first_name FROM person
WHERE last_name = "John" AND first_name LIKE "J%"
But the following one would not
SELECT last_name, first_name FROM person WHERE first_name = "Constantine"
Because you're querying the first_name
column first and it's not the leftmost column in the index.
This last example is even worse:
SELECT last_name, first_name FROM person WHERE first_name LIKE "%Constantine"
Because now, you're comparing the rightmost part of the rightmost field in the index.
This is a different index type that unfortunately, only the memory backend supports. It's lightning fast but only useful for full lookups, which means that you can't use it for operations like >
, <
or LIKE
.
Since it only works for the memory backend, you probably won't use it very often. The main case I can think of right now is the one that you create a temporary table in the memory with a set of results from another select and perform a lot of other selects in this temporary table using hash indexes.
If you have a big VARCHAR
field, you can "emulate" the use of a hash index when using a B-Tree, by creating another column and saving a hash of the big value on it. Let's say you're storing a url in a field and the values are quite big. You could also create an integer field called url_hash
and use a hash function like CRC32
or any other hash function to hash the url when inserting it. And then, when you need to query for this value, you can do something like this:
SELECT url FROM url_table WHERE url_hash=CRC32("http://gnu.org");
The problem with the above example is that since the CRC32
function generates a quite small hash, you'll end up with a lot of collisions in the hashed values. If you need exact values, you can fix this problem by doing the following:
SELECT url FROM url_table
WHERE url_hash=CRC32("http://gnu.org") AND url="http://gnu.org";
It's still worth to hash things even if the collision number is high cause you'll only perform the second comparison (the string one) against the repeated hashes.
Unfortunately, using this technique, you still need to hit the table to compare the url
field.
Some facts that you may consider every time you want to talk about optimization:
Integer comparison is way faster than string comparison. It can be illustrated with the example about the emulation of the hash index in InnoDB
.
Maybe, adding additional steps in a process makes it faster, not slower. It can be illustrated by the fact that you can optimize a SELECT
by splitting it into two steps, making the first one store values in a newly created in-memory table, and then execute the heavier queries on this second table.
MySQL has other indexes too, but I think the B+Tree one is the most used ever and the hash one is a good thing to know, but you can find the other ones in the MySQL documentation.
I highly recommend you to read the "High Performance MySQL" book, the answer above was definitely based on its chapter about indexes.
I want to extend this topic/answers with the following. As someone mentioned, this auto-generated AssemblyInfo can be an obstacle for the external tools. In my case, using FinalBuilder, I had an issue that AssemblyInfo wasn't getting updated by build action. Apparently, FinalBuilder relies on ~proj
file to find location of the AssemblyInfo. I thought, it was looking anywhere under project folder. No. So, changing this
<PropertyGroup>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
did only half the job, it allowed custom assembly info if built by VS IDE/MS Build. But I needed FinalBuilder do it too without manual manipulations to assembly info file. I needed to satisfy all programs, MSBuild/VS and FinalBuilder.
I solved this by adding an entry to the existing ItemGroup
<ItemGroup>
<Compile Remove="Common\**" />
<Content Remove="Common\**" />
<EmbeddedResource Remove="Common\**" />
<None Remove="Common\**" />
<!-- new added item -->
<None Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
Now, having this item, FinalBuilder finds location of AssemblyInfo and modifies the file. While action None
allows MSBuild/DevEnv ignore this entry and no longer report an error based on Compile
action that usually comes with Assembly Info entry in proj
files.
C:\Program Files\dotnet\sdk\2.0.2\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.DefaultItems.targets(263,5): error : Duplicate 'Compile' items were included. The .NET SDK includes 'Compile' items from your project directory by default. You can either remove these items from your project file, or set the 'EnableDefaultCompileItems' property to 'false' if you want to explicitly include them in your project file. For more information, see https://aka.ms/sdkimplicititems. The duplicate items were: 'AssemblyInfo.cs'
Mozilla has full implementation details on how to do it in a browser where it isn't supported, if that helps:
if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
var result = [];
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) result.push(prop);
}
if (hasDontEnumBug) {
for (var i=0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
}
}
return result;
};
})();
}
You could include it however you'd like, but possibly in some kind of extensions.js
file at the top of your script stack.
Update from 10 years later In 2008 the hard drives you would run a database on would have much different characteristics and much higher cost than the disks you would store files on. These days there are much better solutions for storing files that didn't exist 10 years ago and I would revoke this advice and advise readers to look at some of the other answers in this thread.
Original
Don't store in images in the database unless you absolutely have to. I understand that this is not a web application, but if there isn't a shared file location that you can point to save the location of the file in the database.
//linuxserver/images/imagexxx.jpg
then perhaps you can quickly set up a webserver and store the web urls in the database (as well as the local path). While databases can handle LOB's and 3000 images (4-6 Megapixels, assuming 500K an image) 1.5 Gigs isn't a lot of space file systems are much better designed for storing large files than a database is.
This code work in my mysql db:
ALTER TABLE `goods`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (`id`);
You can do this using with jQuery UI dialog, you can download JQuery ui from here Download JQueryUI
Include these scripts first inside <head>
tag
<link href="css/smoothness/jquery-ui-1.9.0.custom.css" rel="stylesheet">
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script src="js/jquery-ui-1.9.0.custom.js"></script>
JQuery code
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#trigger').click(function(){
$("#dialog").dialog();
});
});
</script>
HTML code within <body>
tag. Use an iframe to load the pdf file inside
<a href="#" id="trigger">this link</a>
<div id="dialog" style="display:none">
<div>
<iframe src="yourpdffile.pdf"></iframe>
</div>
</div>
I was getting this same error and spent a day and a half trying to find a solution. Naomi's answer lead me to the solution I needed.
My input (type=button) had an attribute name
that was identical to a function name that was being called by the onClick event. Once I changed the attribute name
everything worked.
<input type="button" name="clearEmployer" onClick="clearEmployer();">
changed to:
<input type="button" name="clearEmployerBtn" onClick="clearEmployer();">
By Using like
use css and font same location
@font-face {
font-family: 'Material-Design-Icons';
src: url('Material-Design-Icons.eot');
src: url('Material-Design-Icons.eot?#iefix') format('embedded-opentype'),
url('Material-Design-Icons.woff2') format('woff2'),
url('Material-Design-Icons.woff') format('woff'),
url('Material-Design-Icons.ttf') format('truetype'),
url('Material-Design-Icons.svg#ge_dinar_oneregular') format('svg');
font-weight: normal;
font-style: normal;
}
Thank you for posting the realWidth function above, it really helped me. Based on "realWidth" function above, I wrote, a CSS reset, (reason described below).
function getUnvisibleDimensions(obj) {
if ($(obj).length == 0) {
return false;
}
var clone = obj.clone();
clone.css({
visibility:'hidden',
width : '',
height: '',
maxWidth : '',
maxHeight: ''
});
$('body').append(clone);
var width = clone.outerWidth(),
height = clone.outerHeight();
clone.remove();
return {w:width, h:height};
}
"realWidth" gets the width of an existing tag. I tested this with some image tags. The problem was, when the image has given CSS dimension per width (or max-width), you will never get the real dimension of that image. Perhaps, the img has "max-width: 100%", the "realWidth" function clone it and append it to the body. If the original size of the image is bigger than the body, then you get the size of the body and not the real size of that image.
Make sure you are following the Same Origin Policy. This means same domain, same subdomain, same protocol (http vs https) and same port.
How does pushState protect against potential content forgeries?
EDIT: As @robertc aptly pointed out in his comment, some browsers actually implement slightly different security policies when the origin is file:///
. Not to mention you can encounter problems when testing locally with file:///
when the page expects it is running from a different origin (and so your pushState
assumes production origin scenarios, not localhost scenarios)
const idivmod = (a, b) => [a/b |0, a%b];
there is also a proposal working on it Modulus and Additional Integer Math
How about this? /(7|8|9)\d{9}/
It starts by either looking for 7 or 8 or 9, and then followed by 9 digits.
The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:
File > Preferences > Settings > Encoding > Choose your option
This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.
You can use a pseudo-element to insert that character before each list item:
ul {_x000D_
list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
content: '?';_x000D_
}
_x000D_
<ul>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
<li>this is my text</li>_x000D_
</ul>
_x000D_
Try FileUtils
from Apache commons-io (listFiles
and iterateFiles
methods):
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("sample*.java");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
To solve your issue with the TestX
folders, I would first iterate through the list of folders:
File[] dirs = new File(".").listFiles(new WildcardFileFilter("Test*.java");
for (int i=0; i<dirs.length; i++) {
File dir = dirs[i];
if (dir.isDirectory()) {
File[] files = dir.listFiles(new WildcardFileFilter("sample*.java"));
}
}
Quite a 'brute force' solution but should work fine. If this doesn't fit your needs, you can always use the RegexFileFilter.
As you use Joda Time, you should use DateTimeFormatter
:
final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);
If using Java 8 or later, then refer to hertzi's answer
I dislike having Docker environment variables when I do not expect user of a Docker image to change them.
Just put it somewhere in one RUN
. If you do not have UTF-8 locales generated, then you can do the following set of commands:
export DEBIAN_FRONTEND=noninteractive
apt-get update -q -q
apt-get install --yes locales
locale-gen --no-purge en_US.UTF-8
update-locale LANG=en_US.UTF-8
echo locales locales/locales_to_be_generated multiselect en_US.UTF-8 UTF-8 | debconf-set-selections
echo locales locales/default_environment_locale select en_US.UTF-8 | debconf-set-selections
dpkg-reconfigure locales
both answers are is incorrect. it should read:
x-=r;
y-=r;
drawOval(x,y,r*2,r*2);
i know this is old, i actually just had the same issue. i was able to solve it by running npm install -g node-gyp
and fixed! npm
Can you split up the query? Insert the stored proc results into a table variable or a temp table. Then, select the 2 columns from the table variable.
Declare @tablevar table(col1 col1Type,..
insert into @tablevar(col1,..) exec MyStoredProc 'param1', 'param2'
SELECT col1, col2 FROM @tablevar
do like this :
child{
position:absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
When you call document.write
after a page has loaded it will eliminate all content and replace it with the parameter you provide. Instead use DOM methods to add content, for example:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
var text = document.createTextNode('hi');
OpenWindow.document.body.appendChild(text);
If you want to use jQuery you get some better APIs to deal with. For example:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).append('<p>hi</p>');
If you need the code to run after the new window's DOM is ready try:
var OpenWindow = window.open('mypage.html','_blank','width=335,height=330,resizable=1');
$(OpenWindow.document.body).ready(function() {
$(OpenWindow.document.body).append('<p>hi</p>');
});
A simple method of creating the service, adding headers and reading the JSON response,
private static void WebRequest()
{
const string WEBSERVICE_URL = "<<Web Service URL>>";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "GET";
webRequest.Timeout = 20000;
webRequest.ContentType = "application/json";
webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
Console.WriteLine(String.Format("Response: {0}", jsonResponse));
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
with()
is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
Example:
User > hasMany > Post
$users = User::with('posts')->get();
foreach($users as $user){
$users->posts; // posts is already loaded and no additional DB query is run
}
has()
is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation')
that means you only want to get the models that have at least one related model in this relation.
Example:
User > hasMany > Post
$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection
whereHas()
works basically the same as has()
but allows you to specify additional filters for the related model to check.
Example:
User > hasMany > Post
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned
Try this :
$('#resetBtn').on('click', function(e){
e.preventDefault();
$("#myform")[0].reset.click();
}
I used these code Hope it could help
dataGridView2.Rows[n].Cells[3].Value = item[2].ToString();
dataGridView2.Rows[n].Cells[3].Value = Convert.ToDateTime(item[2].ToString()).ToString("d");
Issue in my case: Some updates were made to some rows within a transaction and before the transaction was committed, in another place, the same rows were being updated outside this transaction. Ensuring that all the updates to the rows are made within the same transaction resolved my issue
.
Use WebElement.send_keys
method to simulate key typing.
name
in the code (Username
, Password
) does not match actual name
of the elements (username
, password
).
username = browser.find_element_by_name('username')
username.send_keys('user1')
password = browser.find_element_by_name('password')
password.send_keys('secret')
form = browser.find_element_by_id('loginForm')
form.submit()
# OR browser.find_element_by_id('submit').click()
Best and working solution with Pure-Javascript sample Live demo : https://jsfiddle.net/manoj2010/ygkpa89o/
<script>_x000D_
function removeCommas(nStr) {_x000D_
if (nStr == null || nStr == "")_x000D_
return ""; _x000D_
return nStr.toString().replace(/,/g, "");_x000D_
}_x000D_
_x000D_
function NumbersOnly(myfield, e, dec,neg)_x000D_
{ _x000D_
if (isNaN(removeCommas(myfield.value)) && myfield.value != "-") {_x000D_
return false;_x000D_
}_x000D_
var allowNegativeNumber = neg || false;_x000D_
var key;_x000D_
var keychar;_x000D_
_x000D_
if (window.event)_x000D_
key = window.event.keyCode;_x000D_
else if (e)_x000D_
key = e.which;_x000D_
else_x000D_
return true;_x000D_
keychar = String.fromCharCode(key);_x000D_
var srcEl = e.srcElement ? e.srcElement : e.target; _x000D_
// control keys_x000D_
if ((key == null) || (key == 0) || (key == 8) ||_x000D_
(key == 9) || (key == 13) || (key == 27))_x000D_
return true;_x000D_
_x000D_
// numbers_x000D_
else if ((("0123456789").indexOf(keychar) > -1))_x000D_
return true;_x000D_
_x000D_
// decimal point jump_x000D_
else if (dec && (keychar == ".")) {_x000D_
//myfield.form.elements[dec].focus();_x000D_
return srcEl.value.indexOf(".") == -1; _x000D_
}_x000D_
_x000D_
//allow negative numbers_x000D_
else if (allowNegativeNumber && (keychar == "-")) { _x000D_
return (srcEl.value.length == 0 || srcEl.value == "0.00")_x000D_
}_x000D_
else_x000D_
return false;_x000D_
}_x000D_
</script>_x000D_
<input name="txtDiscountSum" type="text" onKeyPress="return NumbersOnly(this, event,true)" />
_x000D_
Your Event.hbm.xml says:
<set name="attendees" cascade="all">
<key column="attendeeId" />
<one-to-many class="Attendee" />
</set>
In plain english, this means that the column Attendee.attendeeId
is the foreign key for the association attendees
and points to the primary key of Event
.
When you add those Attendees to the event, hibernate updates the foreign key to express the changed association. Since that same column is also the primary key of Attendee, this violates the primary key constraint.
Since an Attendee's identity and event participation are independent, you should use separate columns for the primary and foreign key.
Edit: The selects might be because you don't appear to have a version property configured, making it impossible for hibernate to know whether the attendees already exists in the database (they might have been loaded in a previous session), so hibernate emits selects to check. As for the update statements, it was probably easier to implement that way. If you want to get rid of these separate updates, I recommend mapping the association from both ends, and declare the Event
-end as inverse
.
const arr = [1, 2, 3];
console.log(`${arr}`)
It should be:
...
WHERE LastName LIKE '%' + @LastName + '%';
Instead of:
...
WHERE LastName LIKE '%@LastName%'
You can shuffle the rows of a dataframe by indexing with a shuffled index. For this, you can eg use np.random.permutation
(but np.random.choice
is also a possibility):
In [12]: df = pd.read_csv(StringIO(s), sep="\s+")
In [13]: df
Out[13]:
Col1 Col2 Col3 Type
0 1 2 3 1
1 4 5 6 1
20 7 8 9 2
21 10 11 12 2
45 13 14 15 3
46 16 17 18 3
In [14]: df.iloc[np.random.permutation(len(df))]
Out[14]:
Col1 Col2 Col3 Type
46 16 17 18 3
45 13 14 15 3
20 7 8 9 2
0 1 2 3 1
1 4 5 6 1
21 10 11 12 2
If you want to keep the index numbered from 1, 2, .., n as in your example, you can simply reset the index: df_shuffled.reset_index(drop=True)
I quote Andrew Dunstan on the pgsql-hackers list:
At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.
Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.
Offers an arsenal of new functions and operators to add "json-processing".
The answer to the original question in Postgres 9.3:
SELECT *
FROM json_array_elements(
'[{"name": "Toby", "occupation": "Software Engineer"},
{"name": "Zaphod", "occupation": "Galactic President"} ]'
) AS elem
WHERE elem->>'name' = 'Toby';
Advanced example:
For bigger tables you may want to add an expression index to increase performance:
Adds jsonb
(b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb
also supports GIN, btree and hash indexes, GIN being the most potent of these.
json
and jsonb
data types and functions.The manual goes as far as suggesting:
In general, most applications should prefer to store JSON data as
jsonb
, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.
Bold emphasis mine.
Performance benefits from general improvements to GIN indexes.
Complete jsonb
functions and operators. Add more functions to manipulate jsonb
in place and for display.
Here's something to gather all the GET
variables in a global object, a routine optimized over several years. Since the rise of jQuery, it now seems appropriate to store them in jQuery itself, am checking with John on a potential core implementation.
jQuery.extend({
'Q' : window.location.search.length <= 1 ? {}
: function(a){
var i = a.length,
r = /%25/g, // Ensure '%' is properly represented
h = {}; // (Safari auto-encodes '%', Firefox 1.5 does not)
while(i--) {
var p = a[i].split('=');
h[ p[0] ] = r.test( p[1] ) ? decodeURIComponent( p[1] ) : p[1];
}
return h;
}(window.location.search.substr(1).split('&'))
});
Example usage:
switch ($.Q.event) {
case 'new' :
// http://www.site.com/?event=new
$('#NewItemButton').trigger('click');
break;
default :
}
Hope this helps. ;)
All you have to do is to remove the table row (<tr>
) tag from your table. For example here is the code to remove the last row from the table:
$('#myTable tr:last').remove();
*Code above was taken from this jQuery Howto post.
Using cuzillion you can test the affect on page load of different placement of script tags using different methods: inline, external, "HTML tags", "document.write", "JS DOM element", "iframe", and "XHR eval". See the help for an explanation of the differences. It can also test stylesheets, images and iframes.
Why would the first way not work. Canvas object is created and the size is set and the grahpics are set. I always find this strange. Also if a class extends JComponent you can override the
paintComponent(){
super...
}
and then shouldn't you be able to create and instance of the class inside of another class and then just call NewlycreateinstanceOfAnyClass.repaint();
I have tried this approach for some game programming I have been working and it doesn't seem to work the way I think that it should be.
Doug Hauf
A simple map builder is trivial to write:
public class Maps {
public static <Q,W> MapWrapper<Q,W> map(Q q, W w) {
return new MapWrapper<Q, W>(q, w);
}
public static final class MapWrapper<Q,W> {
private final HashMap<Q,W> map;
public MapWrapper(Q q, W w) {
map = new HashMap<Q, W>();
map.put(q, w);
}
public MapWrapper<Q,W> map(Q q, W w) {
map.put(q, w);
return this;
}
public Map<Q,W> getMap() {
return map;
}
}
public static void main(String[] args) {
Map<String, Integer> map = Maps.map("one", 1).map("two", 2).map("three", 3).getMap();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
}
If you have Python installed, you can do
python -c "import datetime;print(datetime.date.today().strftime('%Y-%m-%d'))"
You can easily adapt the format string to your needs.
There is a very easy to use package available in PyPI that handles exactly that: django-related-admin. You can also see the code in GitHub.
Using this, what you want to achieve is as simple as:
class PersonAdmin(RelatedFieldAdmin):
list_display = ['book__author',]
Both links contain full details of installation and usage so I won't paste them here in case they change.
Just as a side note, if you're already using something other than model.Admin
(e.g. I was using SimpleHistoryAdmin
instead), you can do this: class MyAdmin(SimpleHistoryAdmin, RelatedFieldAdmin)
.
You can use string.indexOf('a')
.
If the char a
is present in string
:
it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
I can't see why you would care. Other than the "don't use ports below 1024" privilege rule, you should be able to use any port because your clients should be configurable to talk to any IP address and port!
If they're not, then they haven't been done very well. Go back and do them properly :-)
In other words, run the server at IP address X
and port Y
then configure clients with that information. Then, if you find you must run a different server on X
that conflicts with your Y
, just re-configure your server and clients to use a new port. This is true whether your clients are code, or people typing URLs into a browser.
I, like you, wouldn't try to get numbers assigned by IANA since that's supposed to be for services so common that many, many environments will use them (think SSH or FTP or TELNET).
Your network is your network and, if you want your servers on port 1234 (or even the TELNET or FTP ports for that matter), that's your business. Case in point, in our mainframe development area, port 23 is used for the 3270 terminal server which is a vastly different beast to telnet. If you want to telnet to the UNIX side of the mainframe, you use port 1023. That's sometimes annoying if you use telnet clients without specifying port 1023 since it hooks you up to a server that knows nothing of the telnet protocol - we have to break out of the telnet client and do it properly:
telnet big_honking_mainframe_box.com 1023
If you really can't make the client side configurable, pick one in the second range, like 48042, and just use it, declaring that any other software on those boxes (including any added in the future) has to keep out of your way.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main (){
int pid;
int status;
printf("Parent: %d\n", getpid());
pid = fork();
if (pid == 0){
printf("Child %d\n", getpid());
sleep(2);
exit(EXIT_SUCCESS);
}
//Comment from here to...
//Parent waits process pid (child)
waitpid(pid, &status, 0);
//Option is 0 since I check it later
if (WIFSIGNALED(status)){
printf("Error\n");
}
else if (WEXITSTATUS(status)){
printf("Exited Normally\n");
}
//To Here and see the difference
printf("Parent: %d\n", getpid());
return 0;
}
Since the frameborder
attribute is only necessary for IE, there is another way to get around the validator. This is a lightweight way that doesn't require Javascript or any DOM manipulation.
<!--[if IE]>
<iframe src="source" frameborder="0">?</iframe>
<![endif]-->
<!--[if !IE]>-->
<iframe src="source" style="border:none">?</iframe>
<!-- <![endif]-->
open C:\myfile.txt for append as #1
write #1, text1.text, text2.text
close()
This is the code I use in Visual Basic 6.0. It helps me to create a txt file on my drive, write two pieces of data into it, and then close the file... Give it a try...
I used this solution.
If you have a nested state like this:
this.state = {
formInputs:{
friendName:{
value:'',
isValid:false,
errorMsg:''
},
friendEmail:{
value:'',
isValid:false,
errorMsg:''
}
}
}
you can declare the handleChange function that copy current status and re-assigns it with changed values
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let statusCopy = Object.assign({}, this.state);
statusCopy.formInputs[inputName].value = inputValue;
this.setState(statusCopy);
}
here the html with the event listener. Make sure to use the same name used into state object (in this case 'friendName')
<input type="text" onChange={this.handleChange} " name="friendName" />
@Joe Philllips
SQlDataReader.IsDBNull(int index) requires the ordinal number of the column. Is there a way to check for nulls using Column Name, and not it's Ordinal Number?
I was really looking for a way to fetch the connection status of a device, not listen to connection events. Here's what worked for me:
BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bm.getConnectedDevices(BluetoothGatt.GATT);
int status = -1;
for (BluetoothDevice device : devices) {
status = bm.getConnectionState(device, BLuetoothGatt.GATT);
// compare status to:
// BluetoothProfile.STATE_CONNECTED
// BluetoothProfile.STATE_CONNECTING
// BluetoothProfile.STATE_DISCONNECTED
// BluetoothProfile.STATE_DISCONNECTING
}
I used DateTime.Now.TimeOfDay.TotalMilliseconds (for current day), hope it helps you out as well.
Probably you haven't injected $http
service to your controller. There are several ways of doing that.
Please read this reference about DI. Then it gets very simple:
function MyController($scope, $http) {
// ... your code
}
I Don't know what do you mean exactly, but technially speaking, this is not possible without a loop.
May be you mean using a LINQ, like for example:
list.Where(x=>x.Title == title)
It's worth mentioning that the iteration over is not skipped, but simply wrapped into the LINQ query.
Hope this helps.
EDIT
In other words if you really concerned about performance, keep coding the way you already doing. Otherwise choose LINQ for more concise and clear syntax.
No, you don't want a generic method. This is much easier:
MyEnum myEnum = (MyEnum)myInt;
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), myString);
I think it will also be faster.
Content and before are both highly unreliable across browsers. I would suggest sticking with jQuery to accomplish this. I'm not sure what you're doing to figure out if this carrot needs to be added or not, but you should get the overall idea:
$(".Modal").before("<img src='blackCarrot.png' class='ModalCarrot' />");
The easiest solution is to use
For mysql 8.0.7, Go to your mysql directory, and then use:
sudo bin/mysql_secure_installation
to configure the password option.
Another silly mistake you can do is copy recursive function from non class environment to class and don`t change inner self calls to $this->method_name()
i`m writing this because couldn`t understand why i got this error and this thread is first in google when you search for this error.
As you are worried about user upload other file by mistake, I would suggest you to use accept=".csv"
in <input>
tag. It will show only csv files in browser when the user uploads the file. If you have found some better solution then please let me know as I am also trying to do same and in the same condition - 'trusted users but trying to avoid mistake'
Private Sub DataGridView1_CellClick(ByVal sender As System.Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles DataGridView1.CellClick
MsgBox(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
End Sub
There is are multiple ways to execute the commands or script in the multiple remote Linux machines.
One simple & easiest way is via pssh (parallel ssh program)
pssh: is a program for executing ssh in parallel on a number of hosts. It provides features such as sending input to all of the processes, passing a password to ssh, saving the output to files, and timing out.
Example & Usage:
Connect to host1 and host2, and print "hello, world" from each:
pssh -i -H "host1 host2" echo "hello, world"
Run commands via a script on multiple servers:
pssh -h hosts.txt -P -I<./commands.sh
Usage & run a command without checking or saving host keys:
pssh -h hostname_ip.txt -x '-q -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey -o PubkeyAuthentication=yes' -i 'uptime; hostname -f'
If the file hosts.txt has a large number of entries, say 100, then the parallelism option may also be set to 100 to ensure that the commands are run concurrently:
pssh -i -h hosts.txt -p 100 -t 0 sleep 10000
Options:
-I: Read input and sends to each ssh process.
-P: Tells pssh to display output as it arrives.
-h: Reads the host's file.
-H : [user@]host[:port] for single-host.
-i: Display standard output and standard error as each host completes
-x args: Passes extra SSH command-line arguments
-o option: Can be used to give options in the format used in the configuration file.(/etc/ssh/ssh_config) (~/.ssh/config)
-p parallelism: Use the given number as the maximum number of concurrent connections
-q Quiet mode: Causes most warning and diagnostic messages to be suppressed.
-t: Make connections time out after the given number of seconds. 0 means pssh will not timeout any connections
When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.
Disable the StrictHostKeyChecking to handle the RSA authentication prompt.
-o StrictHostKeyChecking=no
Source: man pssh
I regularly work on the same file in 2 different positions. I solved this in Sublime Text 3 using origami and chain with some additional config.
My workflow is Ctrl + k + 2 splits the view of the file in two (horizontal) panes with the lower one active. Use Ctrl + k + o to toggle between the panes. When done ensure the lower pane is the active and press Ctrl + F4 to close the duplicated view and the pane.
In sublime global settings (not origami settings!) add
"origami_auto_close_empty_panes": true,
Add the following shortcuts
{ "keys": ["ctrl+k", "2"],
"command": "chain",
"args": {
"commands": [
["create_pane", {"direction": "down"}],
["clone_file_to_pane", {"direction": "down"}],
],
}
},
{ "keys": ["ctrl+k", "o"], "command": "focus_neighboring_group" },
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
This is working for me.
Define a factor:
hospitals.factor<- factor( c("H0","H1","H2") )
and use, in ggplot()
:
facet_grid( hospitals.factor[hospital] ~ . )
forceUpdate(), but every time I've ever heard someone talk about it, it's been followed up with you should never use this.
Referer is not a compulsory header. It may or may not be there or could be modified/fictitious. Rely on it at your own risk. Anyways, you should wrap your call so you do not get an undefined index error:
$server = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";
The numeric type overview for MySQL states: BOOL, BOOLEAN: These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true.
See here: https://dev.mysql.com/doc/refman/5.7/en/numeric-type-overview.html
$("select[name='CCards'] option:selected")
should do the trick
See jQuery documentation for more detail: http://api.jquery.com/selected-selector/
UPDATE:
if you need the index of the selected option, you need to use the .index()
jquery method:
$("select[name='CCards'] option:selected").index()
use Json & jQuery. It's way easier than oldschool javascript
function savedata1() {
var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
td_1: $row.find(':nth-child(1)').text(),
td_2: $row.find(':nth-child(2)').text(),
td_3: $row.find(':nth-child(3)').text()
};
}).get();
if you are using Django 2.0 Then
python manage.py flush
will work
This solved it for me: I supplied a third argument being an object.
in app.js
(working with laravel and webpack):
Vue.component('news-item', require('./components/NewsItem.vue'), {
name: 'news-item'
});
The initiale code must have borderBottomLeftRadius: 0px
$('#user_button').toggle().css('borderBottomLeftRadius','+5px');
With the introduction of private
, static
, default
modifiers for interface methods in Java 8/9, things get more complicated and I tend to think that full declarations are more readable (needs Java 9 to compile):
public interface MyInterface {
//minimal
int CONST00 = 0;
void method00();
static void method01() {}
default void method02() {}
private static void method03() {}
private void method04() {}
//full
public static final int CONST10 = 0;
public abstract void method10();
public static void method11() {}
public default void method12() {}
private static void method13() {}
private void method14() {}
}
Just want to add that apparently adding a space at the end of the string will use UTC for creation.
new Date("2016-07-06")
> Tue Jul 05 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
new Date("2016-07-06 ")
> Wed Jul 06 2016 00:00:00 GMT-0700 (Pacific Daylight Time)
Edit: This is not a recommended solution, just an alternative answer. Please do not use this approach since it is very unclear what is happening. There are a number of ways someone could refactor this accidentally causing a bug.
Try typing all of this on the command line:
sqlplus / as sysdba
As what you are doing is starting sqlplus and then using sys as sysdba
as the user-name which is incorrect as that is not a valid user. By using the above command Oracle is using your system login credentials to access the db.
Also, I would confirm that the sqlplus executable you are running is the correct one by checking your path - ensure it is in the bin of the server installation directories.
The Date
documentation states that :
The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC
Click on start button then on end button. It will show you the number of seconds between the 2 clicks.
The milliseconds diff is in variable timeDiff
. Play with it to find seconds/minutes/hours/ or what you need
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = new Date();_x000D_
var timeDiff = endTime - startTime; //in ms_x000D_
// strip the ms_x000D_
timeDiff /= 1000;_x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
OR another way of doing it for modern browser
Using performance.now()
which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.
The time origin is a standard time which is considered to be the beginning of the current document's lifetime.
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = performance.now();_x000D_
var timeDiff = endTime - startTime; //in ms _x000D_
// strip the ms _x000D_
timeDiff /= 1000; _x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
Following is a list of solutions to centering things in CSS horizontally. The snippet includes all of them.
html {_x000D_
font: 1.25em/1.5 Georgia, Times, serif;_x000D_
}_x000D_
_x000D_
pre {_x000D_
color: #fff;_x000D_
background-color: #333;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
blockquote {_x000D_
max-width: 400px;_x000D_
background-color: #e0f0d1;_x000D_
}_x000D_
_x000D_
blockquote > p {_x000D_
font-style: italic;_x000D_
}_x000D_
_x000D_
blockquote > p:first-of-type::before {_x000D_
content: open-quote;_x000D_
}_x000D_
_x000D_
blockquote > p:last-of-type::after {_x000D_
content: close-quote;_x000D_
}_x000D_
_x000D_
blockquote > footer::before {_x000D_
content: "\2014";_x000D_
}_x000D_
_x000D_
.container,_x000D_
blockquote {_x000D_
position: relative;_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
.container {_x000D_
background-color: tomato;_x000D_
}_x000D_
_x000D_
.container::after,_x000D_
blockquote::after {_x000D_
position: absolute;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
padding: 2px 10px;_x000D_
border: 1px dotted #000;_x000D_
background-color: #fff;_x000D_
}_x000D_
_x000D_
.container::after {_x000D_
content: ".container-" attr(data-num);_x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
blockquote::after {_x000D_
content: ".quote-" attr(data-num);_x000D_
z-index: 2;_x000D_
}_x000D_
_x000D_
.container-4 {_x000D_
margin-bottom: 200px;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Solution 1_x000D_
*/_x000D_
.quote-1 {_x000D_
max-width: 400px;_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Solution 2_x000D_
*/_x000D_
.container-2 {_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.quote-2 {_x000D_
display: inline-block;_x000D_
text-align: left;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Solution 3_x000D_
*/_x000D_
.quote-3 {_x000D_
display: table;_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Solution 4_x000D_
*/_x000D_
.container-4 {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.quote-4 {_x000D_
position: absolute;_x000D_
left: 50%;_x000D_
transform: translateX(-50%);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Solution 5_x000D_
*/_x000D_
.container-5 {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}
_x000D_
<main>_x000D_
<h1>CSS: Horizontal Centering</h1>_x000D_
_x000D_
<h2>Uncentered Example</h2>_x000D_
<p>This is the scenario: We have a container with an element inside of it that we want to center. I just added a little padding and background colors so both elements are distinquishable.</p>_x000D_
_x000D_
<div class="container container-0" data-num="0">_x000D_
<blockquote class="quote-0" data-num="0">_x000D_
<p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
<footer>Tasha Yar about Data</footer>_x000D_
</blockquote>_x000D_
</div>_x000D_
_x000D_
<h2>Solution 1: Using <code>max-width</code> & <code>margin</code> (IE7)</h2>_x000D_
_x000D_
<p>This method is widely used. The upside here is that only the element which one wants to center needs rules.</p>_x000D_
_x000D_
<pre><code>.quote-1 {_x000D_
max-width: 400px;_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
}</code></pre>_x000D_
_x000D_
<div class="container container-1" data-num="1">_x000D_
<blockquote class="quote quote-1" data-num="1">_x000D_
<p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
<footer>Tasha Yar about Data</footer>_x000D_
</blockquote>_x000D_
</div>_x000D_
_x000D_
<h2>Solution 2: Using <code>display: inline-block</code> and <code>text-align</code> (IE8)</h2>_x000D_
_x000D_
<p>This method utilizes that <code>inline-block</code> elements are treated as text and as such they are affected by the <code>text-align</code> property. This does not rely on a fixed width which is an upside. This is helpful for when you don’t know the number of elements in a container for example.</p>_x000D_
_x000D_
<pre><code>.container-2 {_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.quote-2 {_x000D_
display: inline-block;_x000D_
text-align: left;_x000D_
}</code></pre>_x000D_
_x000D_
<div class="container container-2" data-num="2">_x000D_
<blockquote class="quote quote-2" data-num="2">_x000D_
<p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
<footer>Tasha Yar about Data</footer>_x000D_
</blockquote>_x000D_
</div>_x000D_
_x000D_
<h2>Solution 3: Using <code>display: table</code> and <code>margin</code> (IE8)</h2>_x000D_
_x000D_
<p>Very similar to the second solution but only requires to apply rules on the element that is to be centered.</p>_x000D_
_x000D_
<pre><code>.quote-3 {_x000D_
display: table;_x000D_
margin-right: auto;_x000D_
margin-left: auto;_x000D_
}</code></pre>_x000D_
_x000D_
<div class="container container-3" data-num="3">_x000D_
<blockquote class="quote quote-3" data-num="3">_x000D_
<p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
<footer>Tasha Yar about Data</footer>_x000D_
</blockquote>_x000D_
</div>_x000D_
_x000D_
<h2>Solution 4: Using <code>translate()</code> and <code>position</code> (IE9)</h2>_x000D_
_x000D_
<p>Don’t use as a general approach for horizontal centering elements. The downside here is that the centered element will be removed from the document flow. Notice the container shrinking to zero height with only the padding keeping it visible. This is what <i>removing an element from the document flow</i> means.</p>_x000D_
_x000D_
<p>There are however applications for this technique. For example, it works for <b>vertically</b> centering by using <code>top</code> or <code>bottom</code> together with <code>translateY()</code>.</p>_x000D_
_x000D_
<pre><code>.container-4 {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.quote-4 {_x000D_
position: absolute;_x000D_
left: 50%;_x000D_
transform: translateX(-50%);_x000D_
}</code></pre>_x000D_
_x000D_
<div class="container container-4" data-num="4">_x000D_
<blockquote class="quote quote-4" data-num="4">_x000D_
<p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
<footer>Tasha Yar about Data</footer>_x000D_
</blockquote>_x000D_
</div>_x000D_
_x000D_
<h2>Solution 5: Using Flexible Box Layout Module (IE10+ with vendor prefix)</h2>_x000D_
_x000D_
<p></p>_x000D_
_x000D_
<pre><code>.container-5 {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}</code></pre>_x000D_
_x000D_
<div class="container container-5" data-num="5">_x000D_
<blockquote class="quote quote-5" data-num="5">_x000D_
<p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
<footer>Tasha Yar about Data</footer>_x000D_
</blockquote>_x000D_
</div>_x000D_
</main>
_x000D_
display: flex
.container {
display: flex;
justify-content: center;
}
Notes:
max-width
& margin
You can horizontally center a block-level element by assigning a fixed width and setting margin-right
and margin-left
to auto
.
.container ul {
/* for IE below version 7 use `width` instead of `max-width` */
max-width: 800px;
margin-right: auto;
margin-left: auto;
}
Notes:
transform: translatex(-50%)
& left: 50%
This is similar to the quirky centering method which uses absolute positioning and negative margins.
.container {
position: relative;
}
.container ul {
position: absolute;
left: 50%;
transform: translatex(-50%);
}
Notes:
top
instead of left
and translateY()
instead of translateX()
. The two can even be combined. transform2d
display: table
& margin
Just like the first solution, you use auto values for right and left margins, but don’t assign a width. If you don’t need to support IE7 and below, this is better suited, although it feels kind of hacky to use the table
property value for display
.
.container ul {
display: table;
margin-right: auto;
margin-left: auto;
}
display: inline-block
& text-align
Centering an element just like you would do with regular text is possible as well. Downside: You need to assign values to both a container and the element itself.
.container {
text-align: center;
}
.container ul {
display: inline-block;
/* One most likely needs to realign flow content */
text-align: initial;
}
Notes:
Try changing your CSS to this
button #rock {
background: url('img/rock.png') no-repeat;
}
...provided that the image is in that place
Solution can be done be this way:
Example:
public static final int cameraRequestCode = 999;
Hope this will help you.
In order to check if the value is a valid type of the standard JS-date object, you can make use of this predicate:
function isValidDate(date) {
return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
}
date
checks whether the parameter was not a falsy value (undefined
, null
, 0
, ""
, etc..)Object.prototype.toString.call(date)
returns a native string representation of the given object type - In our case "[object Date]"
. Because date.toString()
overrides its parent method, we need to .call
or .apply
the method from Object.prototype
directly which ..
instanceof
or Date.prototype.isPrototypeOf
.!isNaN(date)
finally checks whether the value was not an Invalid Date
.