The error usually gets introduced while creation of CSV. Try using Linux for saving the CSV as a TextCSV. Libre Office in Ubuntu can enforce the encoding to be UTF-8, worked for me. I wasted a lot of time trying this on Mac OS. Linux is the key. I've tested on Ubuntu.
Good Luck
What you could do is have the selected
attribute on the <select>
tag be an attribute of this.state
that you set in the constructor. That way, the initial value you set (the default) and when the dropdown changes you need to change your state.
constructor(){
this.state = {
selectedId: selectedOptionId
}
}
dropdownChanged(e){
this.setState({selectedId: e.target.value});
}
render(){
return(
<select value={this.selectedId} onChange={this.dropdownChanged.bind(this)}>
{option_id.map(id =>
<option key={id} value={id}>{options[id].name}</option>
)}
</select>
);
}
http://jsfiddle.net/isherwood/gfgux
html, body {
height: 100%;
}
#table-row, #table-col, #table-wrapper {
height: 80%;
}
<div id="content" class="container">
<div id="table-row" class="row">
<div id="table-col" class="col-md-7 col-xs-10 pull-left">
<p>Hello</p>
<div id="table-wrapper" class="table-responsive">
<table class="table table-bordered ">
You're not looping over the items. Try this instead:
$.getJSON(url, function(data){
$.each(data.response.venue.tips.groups.items, function (index, value) {
console.log(this.text);
});
});
For ad hoc queries, the ODBC Test utility is pretty handy. Its design and interface is more oriented toward testing various parts of the ODBC API. But it works quite nicely for running queries and showing the output. It is part of the Microsoft Data Access Components.
To run a query, you can click the connect button (or use ctrl-F
), choose a data source, type a query, then ctrl-E
to execute it and ctrl-R
to display the results (e.g., if it is a SELECT or something that returns a cursor).
Go to Tools|options|keymap. Search for 'zoom in text' and set your preferred key. I've set alt+plus and alt+minus.
A very simple way is to keep the problem columns out of the filtered data, but add a column into the filtered section with cell references to them (simply "='cell'").
That way the problem formulas will remain untouched but the filtered data will reference them correctly so you can use those cells to sort accordingly
With gnuplot using gplot.py
from gplot import *
l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),
(2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),
(4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
gplot.log('y')
gplot(*zip(*l))
Async/Await with axios
useEffect(() => {
const getData = async () => {
await axios.get('your_url')
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
});
}
getData()
}, [])
The best source for rationale for a Python addition would be its PEP: PEP 389: argparse - New Command Line Parsing Module, in particular, the section entitled, Why aren't getopt and optparse enough?
To GET requests with headers, use this format.
fetch('http://example.com', {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json',
'someheader': 'headervalue'
})
})
.then(res => res.json())
.then(console.log)
Related issue:
I was having trouble converting struct to JSON, sending it as response from Golang, then, later catch the same in JavaScript via Ajax.
Wasted a lot of time, so posting solution here.
In Go:
// web server
type Foo struct {
Number int `json:"number"`
Title string `json:"title"`
}
foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"})
fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w)
In JavaScript:
// web call & receive in "data", thru Ajax/ other
var Foo = JSON.parse(data);
console.log("number: " + Foo.number);
console.log("title: " + Foo.title);
Use the valgrind option --track-origins=yes
to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.
Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:
It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.
From the Valgrind FAQ:
As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.
LocalDateTime.parse(
"2016-01-23 12:34".replace( " " , "T" )
)
.atZone( ZoneId.of( "Asia/Karachi" ) )
.plusMinutes( 10 )
Use the excellent java.time classes for date-time work. These classes supplant the troublesome old date-time classes such as java.util.Date
and java.util.Calendar
.
The java.time classes use standard ISO 8601 formats by default for parsing/generating strings of date-time values. To make your input string comply, replace the SPACE in the middle with a T
.
String input = "2016-01-23 12:34" ;
String inputModified = input.replace( " " , "T" );
LocalDateTime
Parse your input string as a LocalDateTime
as it lacks any info about time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( inputModified );
Add ten minutes.
LocalDateTime ldtLater = ldt.plusMinutes( 10 );
ldt.toString(): 2016-01-23T12:34
ldtLater.toString(): 2016-01-23T12:44
That LocalDateTime
has no time zone, so it does not represent a point on the timeline. Apply a time zone to translate to an actual moment. Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
, or Asia/Karachi
. Never use the 3-4 letter abbreviation such as EST
or IST
or PKT
as they are not true time zones, not standardized, and not even unique(!).
ZonedDateTime
If you know the intended time zone for this value, apply a ZoneId
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "Asia/Karachi" );
ZonedDateTime zdt = ldt.atZone( z );
zdt.toString(): 2016-01-23T12:44+05:00[Asia/Karachi]
Think about whether to add those ten minutes before or after adding a time zone. You may get a very different result because of anomalies such as Daylight Saving Time (DST) that shift the wall-clock time.
Whether you should add the 10 minutes before or after adding the zone depends on the meaning of your business scenario and rules.
Tip: When you intend a specific moment on the timeline, always keep the time zone information. Do not lose that info, as done with your input data. Is the value 12:34
meant to be noon in Pakistan or noon in France or noon in Québec? If you meant noon in Pakistan, say so by including at least the offset-from-UTC (+05:00
), and better still, the name of the time zone (Asia/Karachi
).
Instant
If you want the same moment as seen through the lens of UTC, extract an Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = zdt.toInstant();
Avoid the troublesome old date-time classes whenever possible. But if you must, you can convert. Call new methods added to the old classes.
java.util.Date utilDate = java.util.Date.from( instant );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
For those who like it short, here's an other one using Array.reduce
which will not cause stack overflow:
var base64 = btoa(
new Uint8Array(arrayBuffer)
.reduce((data, byte) => data + String.fromCharCode(byte), '')
);
The simpliest way I've found to get the current UTC time in milliseconds is:
# timeutil.py
import datetime
def get_epochtime_ms():
return round(datetime.datetime.utcnow().timestamp() * 1000)
# sample.py
import timeutil
timeutil.get_epochtime_ms()
I know this post is really old but, to get the contents of an element in reference to its ID, this is what I would do:
window.onclick = e => {
console.log(e.target);
console.log(e.target.id, ' -->', e.target.innerHTML);
}
Simplified way of doing this based on the accepted answer.
In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.
var currentDate = new Date().toJSON().slice(0,10);
var from = new Date('2020/01/01');
var to = new Date('2020/01/31');
var check = new Date(currentDate);
console.log(check > from && check < to);
[ |\t]+$
with an empty replace works. \s+($)
with a $1
replace also works.
At least in Visual Studio Code...
From this thread:
import os
os.system("import -window root temp.png")
I followed the answers from above when i ran into this. And If you are having this issue than make sure to force push both jar and properties files. After these two, i stopped getting this issue.
git add -f gradle/wrapper/gradle-wrapper.jar
git add -f gradle/wrapper/gradle-wrapper.properties
From my experience I've found that some commands which run in IPython do not run in base Python. For example, pwd
and ls
don't work alone in base Python. However they will work if prefaced with a %
such as: %pwd
and %ls
.
Also, in IPython, you can run the cd command like: cd C:\Users\
... This doesn't seem to work in base python, even when prefaced with a %
however.
Initialize tSize to
tSize = ""
before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.
My 5 cents:
async/await
if and only if you do an IO operation, like DB or external service webservice.P.S. There are exceptional cases for point 1, but you need to have a good understanding of async internals for this.
As an additional advantage, you can do few IO calls in parallel if needed:
Task task1 = FooAsync(); // launch it, but don't wait for result
Task task2 = BarAsync(); // launch bar; now both foo and bar are running
await Task.WhenAll(task1, task2); // this is better in regard to exception handling
// use task1.Result, task2.Result
Thread class defines several methods that can be overriden
by the the extending class. But to create a thread we must override the run()
method. Same applies to Runnable
as well.
However Runnable
is a preferred method of creating a thread. The primary reasons are:
Since Runnable is an interface, you can extend other classes. But if you extend Thread then that option is gone.
If you are not modifying or enhancing a whole lot of Thread
functionalities and extending the Thread
class is not a preferred way.
As others have pointed out, the cd
command needs to start with a percentage sign:
%cd SwitchFrequencyAnalysis
%
and !
Google Colab seems to inherit these syntaxes from Jupyter (which inherits them from IPython). Jake VanderPlas explains this IPython behaviour here. You can see the excerpt below.
If you play with IPython's shell commands for a while, you might notice that you cannot use
!cd
to navigate the filesystem:In [11]: !pwd /home/jake/projects/myproject In [12]: !cd .. In [13]: !pwd /home/jake/projects/myproject
The reason is that shell commands in the notebook are executed in a temporary subshell. If you'd like to change the working directory in a more enduring way, you can use the
%cd
magic command:In [14]: %cd .. /home/jake/projects
Another way to look at this: you need %
because changing directory is relevant to the environment of the current notebook but not to the entire server runtime.
In general, use !
if the command is one that's okay to run in a separate shell. Use %
if the command needs to be run on the specific notebook.
finish()
gives you method to close current Activity not whole application. And you better don't try to look for methods to kill application. Little advice.
Have you tried conjunction of Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY
? Remember to use this flags in Intent
starting activity!
Restarting the SQL Server will clear up the log space used by your database. If this however is not an option, you can try the following:
* Issue a CHECKPOINT command to free up log space in the log file.
* Check the available log space with DBCC SQLPERF('logspace'). If only a small
percentage of your log file is actually been used, you can try a DBCC SHRINKFILE
command. This can however possibly introduce corruption in your database.
* If you have another drive with space available you can try to add a file there in
order to get enough space to attempt to resolve the issue.
Hope this will help you in finding your solution.
Something like that
foreach (FileInfo file in new DirectoryInfo("SomeFolder").GetFiles().Where(p => p.CreationTime < DateTime.Now.AddDays(-90)).ToArray())
File.Delete(file.FullName);
Java libs makes it almost a one liner to read the public cert, as generated by openssl:
val certificate: X509Certificate = ByteArrayInputStream(
publicKeyCert.toByteArray(Charsets.US_ASCII))
.use {
CertificateFactory.getInstance("X.509")
.generateCertificate(it) as X509Certificate
}
But, o hell, reading the private key was problematic:
RSAPrivateKey
.see this: Final solution in kotlin
str = str.Remove(0,10);
Removes the first 10 characters
or
str = str.Substring(10);
Creates a substring starting at the 11th character to the end of the string.
For your purposes they should work identically.
You'd need to create a class with CSS -
.greenclass {color:green;}
Then you could add that to elements with
$('selector').addClass("greenclass");
and remove it with -
$('selector').removeClass("greenclass");
From java.util.Date to XMLGregorianCalendar you can simply do:
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.datatype.DatatypeFactory;
import java.util.GregorianCalendar;
......
GregorianCalendar gcalendar = new GregorianCalendar();
gcalendar.setTime(yourDate);
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcalendar);
Code edited after the first comment of @f-puras, by cause i do a mistake.
I think that you are looking for something like this:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
Here is filter
with Underscore library might help you, we remove item with name "ted"
$scope.items = _.filter($scope.items, function(item) {
return !(item.name == 'ted');
});
var app = angular.module('myApp', [])
app.controller('MainCtrl', ['$scope', function($scope){
$scope.num1 = 1;
$scope.num2 = 1;
$scope.total = parseInt($scope.num1 + $scope.num2);
}]);
Demo: parseInt with AngularJS
you can use that code for Kotlin which you will use calendar class from java into Kotlin
val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
fun dayOfWeek() {
println("What day is it today?")
val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
println( when (day) {
1 -> "Sunday"
2 -> "Monday"
3 -> "Tuesday"
4 -> "Wednesday"
5 -> "Thursday"
6 -> "Friday"
7 -> "Saturday"
else -> "Time has stopped"
})
}
Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.
This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).
It is usually much faster to script out all the objects in the database, and create an empty one, that to delete from or truncate tables.
<script>
$(document).ready(function(){
$('#connectBtn').click(function(e){
e.preventDefault();
})
});
</script>
This will prevent the default action.
Standard C++ doesn't have a constant for PI.
Many C++ compilers define M_PI
in cmath
(or in math.h
for C) as a non-standard extension. You may have to #define _USE_MATH_DEFINES
before you can see it.
Simply obj instanceof Object[]
(tested on JShell).
Here's an alternate
req.hostname
Read about it in the Express Docs.
Adding to bobble bubble's answer, there are other regex flavors where recursive constructs are supported.
Lua
Use %b()
(%b{}
/ %b[]
for curly braces / square brackets):
for s in string.gmatch("Extract (a(b)c) and ((d)f(g))", "%b()") do print(s) end
(see demo)Raku (former Perl6):
Non-overlapping multiple balanced parentheses matches:
my regex paren_any { '(' ~ ')' [ <-[()]>+ || <&paren_any> ]* }
say "Extract (a(b)c) and ((d)f(g))" ~~ m:g/<&paren_any>/;
# => (?(a(b)c)? ?((d)f(g))?)
Overlapping multiple balanced parentheses matches:
say "Extract (a(b)c) and ((d)f(g))" ~~ m:ov:g/<&paren_any>/;
# => (?(a(b)c)? ?(b)? ?((d)f(g))? ?(d)? ?(g)?)
See demo.
Python re
non-regex solution
See poke's answer for How to get an expression between balanced parentheses.
Java customizable non-regex solution
Here is a customizable solution allowing single character literal delimiters in Java:
public static List<String> getBalancedSubstrings(String s, Character markStart,
Character markEnd, Boolean includeMarkers)
{
List<String> subTreeList = new ArrayList<String>();
int level = 0;
int lastOpenDelimiter = -1;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == markStart) {
level++;
if (level == 1) {
lastOpenDelimiter = (includeMarkers ? i : i + 1);
}
}
else if (c == markEnd) {
if (level == 1) {
subTreeList.add(s.substring(lastOpenDelimiter, (includeMarkers ? i + 1 : i)));
}
if (level > 0) level--;
}
}
return subTreeList;
}
}
Sample usage:
String s = "some text(text here(possible text)text(possible text(more text)))end text";
List<String> balanced = getBalancedSubstrings(s, '(', ')', true);
System.out.println("Balanced substrings:\n" + balanced);
// => [(text here(possible text)text(possible text(more text)))]
The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {
public SimplePlayer(){
try{
FileInputStream fis = new FileInputStream("File location.");
Player playMP3 = new Player(fis);
playMP3.play();
} catch(Exception e){
System.out.println(e);
}
}
}
and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;
Besides de color, my problem was that I was setting the text using textlabel
bt.titleLabel?.text = title
and I solved changing to:
bt.setTitle(title, for: .normal)
When you use a const
string, the compiler embeds the string's value at compile-time.
Therefore, if you use a const
value in a different assembly, then update the original assembly and change the value, the other assembly won't see the change until you re-compile it.
A static readonly
string is a normal field that gets looked up at runtime. Therefore, if the field's value is changed in a different assembly, the changes will be seen as soon as the assembly is loaded, without recompiling.
This also means that a static readonly
string can use non-constant members, such as Environment.UserName
or DateTime.Now.ToString()
. A const
string can only be initialized using other constants or literals.
Also, a static readonly
string can be set in a static constructor; a const
string can only be initialized inline.
Note that a static string
can be modified; you should use static readonly
instead.
I managed to render the following SELECT with SQLAlchemy on both layers.
SELECT count(*) AS count_1
FROM "table"
from sqlalchemy import select, func, Integer, Table, Column, MetaData
metadata = MetaData()
table = Table("table", metadata,
Column('primary_key', Integer),
Column('other_column', Integer) # just to illustrate
)
print select([func.count()]).select_from(table)
You just subclass Query
(you have probably anyway) and provide a specialized count()
method, like this one.
from sqlalchemy.sql.expression import func
class BaseQuery(Query):
def count_star(self):
count_query = (self.statement.with_only_columns([func.count()])
.order_by(None))
return self.session.execute(count_query).scalar()
Please note that order_by(None)
resets the ordering of the query, which is irrelevant to the counting.
Using this method you can have a count(*)
on any ORM Query, that will honor all the filter
andjoin
conditions already specified.
I had to add parseInt()
to tell v-for it was looking at a number.
<li v-for="n in parseInt(count)" :key="n">{{n}}</li>
Solved by installing the latest mySQL release, following the instructions here http://coolestguidesontheplanet.com/get-apache-mysql-php-phpmyadmin-working-osx-10-10-yosemite/
EDIT
As Yosemite gets more popular, more people are stumbling on this question. The answer above has to do with upgrading MySQL, so that it runs. The answer linked by @doc in the comments has to do with getting MySQL to start automatically. These are 2 separate issues.
The problem is that flex: 1
sets flex-basis: 0
. Instead, you need
.container .box {
min-width: 200px;
max-width: 400px;
flex-basis: auto; /* default value */
flex-grow: 1;
}
.container {_x000D_
display: -webkit-flex;_x000D_
display: flex;_x000D_
-webkit-flex-wrap: wrap;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
-webkit-flex-grow: 1;_x000D_
flex-grow: 1;_x000D_
min-width: 100px;_x000D_
max-width: 400px;_x000D_
height: 200px;_x000D_
background-color: #fafa00;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
<div class="box">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Content</td>_x000D_
<td>Content</td>_x000D_
</tr>_x000D_
</table> _x000D_
</div>_x000D_
</div>
_x000D_
You can do it using javascript
Plain javascript
var iframe = document.getElementsByTagName('iframe')[0];
iframe.style.background = 'white';
iframe.contentWindow.document.body.style.backgroundColor = 'white';
jQuery
$('iframe').css('background', 'white');
$('iframe').contents().find('body').css('backgroundColor', 'white');
I hate to add yet another answer to a long thread, but I found a solution that enables recursive reloading of submodules on %run()
that others might find useful (I have anyway)
del
the submodule you wish to reload on run from sys.modules
in iPython:
In[1]: from sys import modules
In[2]: del modules["mymodule.mysubmodule"] # tab completion can be used like mymodule.<tab>!
Now your script will recursively reload this submodule:
In[3]: %run myscript.py
numpy.binary_repr(num, width=None)
has a magic width argumentRelevant examples from the documentation linked above:
>>> np.binary_repr(3, width=4) '0011'
The two’s complement is returned when the input number is negative and width is specified:
>>> np.binary_repr(-3, width=5) '11101'
==
tests for reference equality (whether they are the same object).
.equals()
tests for value equality (whether they are logically "equal").
Objects.equals() checks for null
before calling .equals()
so you don't have to (available as of JDK7, also available in Guava).
Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals()
.
// These two have the same value
new String("test").equals("test") // --> true
// ... but they are not the same object
new String("test") == "test" // --> false
// ... neither are these
new String("test") == new String("test") // --> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" // --> true
// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true
// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
Objects.equals(null, null) // --> true
You almost always want to use Objects.equals()
. In the rare situation where you know you're dealing with interned strings, you can use ==
.
From JLS 3.10.5. String Literals:
Moreover, a string literal always refers to the same instance of class
String
. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the methodString.intern
.
Similar examples can also be found in JLS 3.10.5-1.
String.equalsIgnoreCase() value equality that ignores case. Beware, however, that this method can have unexpected results in various locale-related cases, see this question.
String.contentEquals() compares the content of the String
with the content of any CharSequence
(available since Java 1.5). Saves you from having to turn your StringBuffer, etc into a String before doing the equality comparison, but leaves the null checking to you.
Thats how it works stored procedures run in order, you don't need begin just something like
exec dbo.sp1
exec dbo.sp2
After a long struggle, I've switched my node architecture to x86 and it worked like a charm.
By default overflow
does not apply to table group elements unless you give a display:block
to <tbody>
also you have to give a position:relative
and display: block
to <thead>
. Check the DEMO.
.fixed {
width:350px;
table-layout: fixed;
border-collapse: collapse;
}
.fixed th {
text-decoration: underline;
}
.fixed th,
.fixed td {
padding: 5px;
text-align: left;
min-width: 200px;
}
.fixed thead {
background-color: red;
color: #fdfdfd;
}
.fixed thead tr {
display: block;
position: relative;
}
.fixed tbody {
display: block;
overflow: auto;
width: 100%;
height: 100px;
overflow-y: scroll;
overflow-x: hidden;
}
It's got a number of names. Most likely you've heard it as either Card Security Code (CSC) or Card Verification Value (CVV).
function doThen(conditional,then,timer) {
var timer = timer || 1;
var interval = setInterval(function(){
if(conditional()) {
clearInterval(interval);
then();
}
}, timer);
}
Example usage:
var counter = 1;
doThen(
function() {
counter++;
return counter == 1000;
},
function() {
console.log("Counter hit 1000"); // 1000 repeats later
}
)
You should use Validator to check whether you class is valid.
Person person = ....;
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Set<ConstraintViolation<Person>> violations = validator.validate(person);
Then, iterating violations set, you can find violations.
var query = from a in d.tbl_Usuarios
from b in d.tblComidaPreferidas
from c in d.tblLugarNacimientoes
select new
{
_nombre = a.Nombre,
_comida = b.ComidaPreferida,
_lNacimiento = c.Ciudad
};
foreach (var i in query)
{
Console.WriteLine($"{i._nombre } le gusta {i._comida} y nació en {i._lNacimiento}");
}
I found a much simpler alternative way to generating soap message. Given a Person Object:
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {
private String name;
private int age;
private String address; //setter and getters below
}
Below is a simple Soap Message Generator:
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@Slf4j
public class SoapGenerator {
protected static final ObjectMapper XML_MAPPER = new XmlMapper()
.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.registerModule(new JavaTimeModule());
private static final String SOAP_BODY_OPEN = "<soap:Body>";
private static final String SOAP_BODY_CLOSE = "</soap:Body>";
private static final String SOAP_ENVELOPE_OPEN = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
private static final String SOAP_ENVELOPE_CLOSE = "</soap:Envelope>";
public static String soapWrap(String xml) {
return SOAP_ENVELOPE_OPEN + SOAP_BODY_OPEN + xml + SOAP_BODY_CLOSE + SOAP_ENVELOPE_CLOSE;
}
public static String soapUnwrap(String xml) {
return StringUtils.substringBetween(xml, SOAP_BODY_OPEN, SOAP_BODY_CLOSE);
}
}
You can use by:
public static void main(String[] args) throws Exception{
Person p = new Person();
p.setName("Test");
p.setAge(12);
String xml = SoapGenerator.soapWrap(XML_MAPPER.writeValueAsString(p));
log.info("Generated String");
log.info(xml);
}
I had the exact same symptom, and this was my problem, very tricky to track down, so I hope it helps someone.
I was using JQuery parseJSON()
and the content I was attempting to parse was actually not JSON, but an error page that was being returned.
On Windows XP -
rundll32.exe syssetup,SetupOobeBnk
This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.
->DECLARE co_id INT ;
->DECLARE sname VARCHAR(10) ;
->SELECT course_id INTO co_id FROM course_details ;
->SELECT student_name INTO sname FROM course_details;
->DECLARE val1 int;
->DECLARE val2 int;
->SELECT student__id,student_name INTO val1,val2 FROM student_details;
--HAPPY CODING--
I hope I am not overstating the obvious, but why not do it directly in the ASP side? Unless you are dynamically altering the SQL based on certain conditions in your program, you should avoid codebehind as much as possible.
You could do the above all in ASP directly without code using the SqlDataSource control and a property in your dropdownlist.
<asp:GridView ID="gvSubjects" runat="server" DataKeyNames="SubjectID" OnRowDataBound="GridView_RowDataBound" OnDataBound="GridView_DataBound">
<Columns>
<asp:TemplateField HeaderText="Subjects">
<ItemTemplate>
<asp:DropDownList ID="ddlSubjects" runat="server" DataSourceID="sdsSubjects" DataTextField="SubjectName" DataValueField="SubjectID">
</asp:DropDownList>
<asp:SqlDataSource ID="sdsSubjects" runat="server"
SelectCommand="SELECT SubjectID,SubjectName FROM Students.dbo.Subjects"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I found this somewhere else. I like this answer!
SELECT [Hourly], COUNT(*) as [Count]
FROM
(SELECT dateadd(hh, datediff(hh, '20010101', [date_created]), '20010101') as [Hourly]
FROM table) idat
GROUP BY [Hourly]
There are a couple of ways to solve this. The least hackiest and almost what you want:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
)
);
$params = new \SoapVar("<Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer>", XSD_ANYXML);
$result = $client->Echo($params);
This gets you the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://example.com/wsdl">
<SOAP-ENV:Body>
<ns1:Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</ns1:Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
That is almost exactly what you want, except for the namespace on the method name. I don't know if this is a problem. If so, you can hack it even further. You could put the <Echo>
tag in the XML string by hand and have the SoapClient not set the method by adding 'style' => SOAP_DOCUMENT,
to the options array like this:
$client = new SoapClient(
null,
array(
'location' => 'https://example.com/ExampleWebServiceDL/services/ExampleHandler',
'uri' => 'http://example.com/wsdl',
'trace' => 1,
'use' => SOAP_LITERAL,
'style' => SOAP_DOCUMENT,
)
);
$params = new \SoapVar("<Echo><Acquirer><Id>MyId</Id><UserId>MyUserId</UserId><Password>MyPassword</Password></Acquirer></Echo>", XSD_ANYXML);
$result = $client->MethodNameIsIgnored($params);
This results in the following request XML:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<Echo>
<Acquirer>
<Id>MyId</Id>
<UserId>MyUserId</UserId>
<Password>MyPassword</Password>
</Acquirer>
</Echo>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Finally, if you want to play around with SoapVar and SoapParam objects, you can find a good reference in this comment in the PHP manual: http://www.php.net/manual/en/soapvar.soapvar.php#104065. If you get that to work, please let me know, I failed miserably.
As of June 2019 this setting can be found through searching 'Panel' - if you want to change the default there is an option for it as shown in the screenshot:
Here is a simple way
<div (click)="$event.preventDefault()">
<a href="#"></a>
</div>
capture the bubbling event and shoot it down
The following worked for me.
These are Unicode property shortcuts (\p{L}
for Unicode letters, \p{N}
for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)
At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:
[\p{L}\p{N}_.-]*
I found that in my case, calling to the service without secure protocol (meaning: http), after adding the key=API_KEY, cause this issue. Changing to https solved it.
If a subquery returns more than one value, you might need to execute the outer query- if the values within the column specified in the condition match any value in the result set of the subquery. To perform this task, you need to use the in
keyword.
You can use a subquery to check if a set of records exists. For this, you need to use the exists
clause with a subquery. The exists
keyword always return true or false value.
We can also use .pop:
>>> lst = [23,34,54,45]
>>> remove_element = 23
>>> if remove_element in lst:
... lst.pop(lst.index(remove_element))
...
23
>>> lst
[34, 54, 45]
>>>
To pass a NULL to MySQL, you do just that.
INSERT INTO table (field,field2) VALUES (NULL,3)
So, in your code, check if $intLat, $intLng
are empty
, if they are, use NULL
instead of '$intLat'
or '$intLng'
.
$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
$intLat, $intLng)";
the emptyList method has this signature:
public static final <T> List<T> emptyList()
That <T>
before the word List means that it infers the value of the generic parameter T from the type of variable the result is assigned to. So in this case:
List<String> stringList = Collections.emptyList();
The return value is then referenced explicitly by a variable of type List<String>
, so the compiler can figure it out. In this case:
setList(Collections.emptyList());
There's no explicit return variable for the compiler to use to figure out the generic type, so it defaults to Object
.
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
int version = Build.VERSION.SDK_INT;
String versionRelease = Build.VERSION.RELEASE;
Log.e("MyActivity", "manufacturer " + manufacturer
+ " \n model " + model
+ " \n version " + version
+ " \n versionRelease " + versionRelease
);
E/MyActivity: manufacturer ManufacturerX
model SM-T310
version 19
versionRelease 4.4.2
protected static $_instance;
public static function getInstance()
{
if(is_null(self::$_instance))
{
self::$_instance = new self();
}
return self::$_instance;
}
This code can apply for any class without caring about its class name.
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
There are two problems with this question:
Assuming you have a gray scale bitmap, you have two factors to consider:
Answer those questions, and then you might be able to find your original answer.
You can make a bookmark with this as the url:
javascript:
var cached_anchors = $$('a');
for (var i in cached_anchors) {
var ca = cached_anchors[i];
if(ca.href.search('sprite') < 0 && ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {
var a = document.createElement('a');
a.href = ca.innerHTML;
a.target = '_blank';
var img = document.createElement('img');
img.src = ca.innerHTML;
img.style.maxHeight = '100px';
a.appendChild(img);
document.getElementsByTagName('body')[0].appendChild(a);
}
}
document.getElementsByTagName('body')[0].removeChild(document.getElementsByTagName('table')[0]);
void(0);
Then just go to chrome://cache and then click your bookmark and it'll show you all the images.
The for
-in
loops for each property in an object or array. You can use this property to get to the value as well as change it.
Note: Private properties are not available for inspection, unless you use a "spy"; basically, you override the object and write some code which does a for-in loop inside the object's context.
For in looks like:
for (var property in object) loop();
Some sample code:
function xinspect(o,i){
if(typeof i=='undefined')i='';
if(i.length>50)return '[MAX ITERATIONS]';
var r=[];
for(var p in o){
var t=typeof o[p];
r.push(i+'"'+p+'" ('+t+') => '+(t=='object' ? 'object:'+xinspect(o[p],i+' ') : o[p]+''));
}
return r.join(i+'\n');
}
// example of use:
alert(xinspect(document));
Edit: Some time ago, I wrote my own inspector, if you're interested, I'm happy to share.
Edit 2: Well, I wrote one up anyway.
It's just a matter of scaling
>>> a=[10,11,12,13,14,15,16,17,18,19,20]
>>> for b in a:
... int(round(b/5.0)*5.0)
...
10
10
10
15
15
15
15
15
20
20
20
var object = {
key1 : {
name : 'xxxxxx',
value : '100.0'
},
key2 : {
name : 'yyyyyyy',
value : '200.0'
},
key3 : {
name : 'zzzzzz',
value : '500.0'
},
}
If thats how your object looks and you want to loop each name and value then I would try and do something like.
$.each(object,function(key,innerjson){
/*
key would be key1,key2,key3
innerjson would be the name and value **
*/
//Alerts and logging of the variable.
console.log(innerjson); //should show you the value
alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});
You don't have to reset IIS, you can just recycle the app pool.
Here is a forum thread that provides a C# image resizing code sample. You could use one of the GD library binders to do resampling in C#.
you can use:
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Another tricky way that just occurred to me (tested and it worked!).
Conditional Formatting
, Highlight Cells
, Duplicate Values
Data
and then Filter
Filter based on color:
Admittedly, this is more for one-off checks of data than a spreadsheet you'll use often, since it requires some formatting changes.
The Mobile data setting requires to be turned on. Did a cold boot it didn't work but after I turned on Mobile Data it worked
I know it's not pretty but it is simple. Try this:
declare @AlpaNumber nvarchar(50) = 'ABC'
declare @MyNumber int = 0
begin Try
select @MyNumber = case when ISNUMERIC(@AlpaNumber) = 1 then cast(@AlpaNumber as int) else 0 end
End Try
Begin Catch
-- Do nothing
End Catch
if exists(select * from mytable where mynumber = @MyNumber)
Begin
print 'Found'
End
Else
Begin
print 'Not Found'
End
Check if the cross product of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned.
But, as you want to know if c is between a and b, you also have to check that the dot product of (b-a) and (c-a) is positive and is less than the square of the distance between a and b.
In non-optimized pseudocode:
def isBetween(a, b, c):
crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)
# compare versus epsilon for floating point values, or != 0 if using integers
if abs(crossproduct) > epsilon:
return False
dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
if dotproduct < 0:
return False
squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
if dotproduct > squaredlengthba:
return False
return True
SELECT sum(num) WHERE num = 1;
Another option is to use Symbols in your module. This way you can protect your class, also if the final user of your API is using normal Javascript:
let _instance = Symbol();
export default class Singleton {
constructor(singletonToken) {
if (singletonToken !== _instance) {
throw new Error("Cannot instantiate directly.");
}
//Init your class
}
static get instance() {
return this[_instance] || (this[_instance] = new Singleton(_singleton))
}
public myMethod():string {
return "foo";
}
}
Usage:
var str:string = Singleton.instance.myFoo();
If the user is using your compiled API js file, also will get an error if he try to instantiate manually your class:
// PLAIN JAVASCRIPT:
var instance = new Singleton(); //Error the argument singletonToken !== _instance symbol
Let's look in the source of wisdom for such questions: Joshua Bloch's Effective Java:
Technically, there is no such thing as a static inner class. According to Effective Java, the correct terminology is a static nested class. A non-static nested class is indeed an inner class, along with anonymous classes and local classes.
And now to quote:
Each instance of a non-static nested class is implicitly associated with an enclosing instance of its containing class... It is possible to invoke methods on the enclosing instance.
A static nested class does not have access to the enclosing instance. It uses less space too.
By specifying the @JoinColumn
on both models you don't have a two way relationship. You have two one way relationships, and a very confusing mapping of it at that. You're telling both models that they "own" the IDAIRLINE column. Really only one of them actually should! The 'normal' thing is to take the @JoinColumn
off of the @OneToMany
side entirely, and instead add mappedBy to the @OneToMany
.
@OneToMany(cascade = CascadeType.ALL, mappedBy="airline")
public Set<AirlineFlight> getAirlineFlights() {
return airlineFlights;
}
That tells Hibernate "Go look over on the bean property named 'airline' on the thing I have a collection of to find the configuration."
The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.
It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.
An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:
com.awesomeapps.thebestapp
In this case the suffix is thebestapp
.
Senguttuvan: your solution was the only thing that worked for me.
function btnClose() {
$(".ui-dialog-titlebar-close").trigger('click');
}
For the position for the context menu, y found the problem that I needed a it to be relative to the DataGridView, and the event I needed to use gives the poistion relative to the cell clicked. I haven't found a better solution so I implemented this function in the commons class, so I call it from wherever I need.
It's quite tested and works well. I Hope you find it useful.
/// <summary>
/// When DataGridView_CellMouseClick ocurs, it gives the position relative to the cell clicked, but for context menus you need the position relative to the DataGridView
/// </summary>
/// <param name="dgv">DataGridView that produces the event</param>
/// <param name="e">Event arguments produced</param>
/// <returns>The Location of the click, relative to the DataGridView</returns>
public static Point PositionRelativeToDataGridViewFromDataGridViewCellMouseEventArgs(DataGridView dgv, DataGridViewCellMouseEventArgs e)
{
int x = e.X;
int y = e.Y;
if (dgv.RowHeadersVisible)
x += dgv.RowHeadersWidth;
if (dgv.ColumnHeadersVisible)
y += dgv.ColumnHeadersHeight;
for (int j = 0; j < e.ColumnIndex; j++)
if (dgv.Columns[j].Visible)
x += dgv.Columns[j].Width;
for (int i = 0; i < e.RowIndex; i++)
if (dgv.Rows[i].Visible)
y += dgv.Rows[i].Height;
return new Point(x, y);
}
If you change baudrate for example back and forth it clears the Serial Monitor window in version 1.5.3 of Arduino IDE for Intel Galileo development
Volatile tells the compiler not to optimize anything that has to do with the volatile variable.
There are at least three common reasons to use it, all involving situations where the value of the variable can change without action from the visible code: When you interface with hardware that changes the value itself; when there's another thread running that also uses the variable; or when there's a signal handler that might change the value of the variable.
Let's say you have a little piece of hardware that is mapped into RAM somewhere and that has two addresses: a command port and a data port:
typedef struct
{
int command;
int data;
int isbusy;
} MyHardwareGadget;
Now you want to send some command:
void SendCommand (MyHardwareGadget * gadget, int command, int data)
{
// wait while the gadget is busy:
while (gadget->isbusy)
{
// do nothing here.
}
// set data first:
gadget->data = data;
// writing the command starts the action:
gadget->command = command;
}
Looks easy, but it can fail because the compiler is free to change the order in which data and commands are written. This would cause our little gadget to issue commands with the previous data-value. Also take a look at the wait while busy loop. That one will be optimized out. The compiler will try to be clever, read the value of isbusy just once and then go into an infinite loop. That's not what you want.
The way to get around this is to declare the pointer gadget as volatile. This way the compiler is forced to do what you wrote. It can't remove the memory assignments, it can't cache variables in registers and it can't change the order of assignments either:
This is the correct version:
void SendCommand (volatile MyHardwareGadget * gadget, int command, int data)
{
// wait while the gadget is busy:
while (gadget->isbusy)
{
// do nothing here.
}
// set data first:
gadget->data = data;
// writing the command starts the action:
gadget->command = command;
}
Most database servers have a COALESCE function, which will return the first argument that is non-null, so the following should do what you want:
SELECT COALESCE(SUM(Price),0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
Since there seems to be a lot of discussion about
COALESCE/ISNULL will still return NULL if no rows match, try this query you can copy-and-paste into SQL Server directly as-is:
SELECT coalesce(SUM(column_id),0) AS TotalPrice
FROM sys.columns
WHERE (object_id BETWEEN -1 AND -2)
Note that the where clause excludes all the rows from sys.columns from consideration, but the 'sum' operator still results in a single row being returned that is null, which coalesce fixes to be a single row with a 0.
The option(s) to resolve this Oracle error are:
Option #1 This error occurs when you try to use a special character in a SQL statement. If a special character other than $, _, and # is used in the name of a column or table, the name must be enclosed in double quotations.
Option #2 This error may occur if you've pasted your SQL into your editor from another program. Sometimes there are non-printable characters that may be present. In this case, you should try retyping your SQL statement and then re-execute it.
Option #3 This error occurs when a special character is used in a SQL WHERE clause and the value is not enclosed in single quotations.
For example, if you had the following SQL statement:
SELECT * FROM suppliers WHERE supplier_name = ?;
You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream ifs( "c:/demo.txt" ); // note no mode needed
if ( ! ifs.is_open() ) {
cout <<" Failed to open" << endl;
}
else {
cout <<"Opened OK" << endl;
}
}
What does this code produce on your system?
For Intellij 2018 it's quite confusing as there's an Editor ? Font section but it's usually overriden by Editor ? Color Scheme ? Color Scheme Font:
The accepted answer worked for me until deployed on JDK 1.8u91.
Then I realized it failed at field.set(null, newValue);
line when I had read the value via reflection before calling of setFinalStatic
method.
Probably the read caused somehow different setup of Java reflection internals (namely sun.reflect.UnsafeQualifiedStaticObjectFieldAccessorImpl
in failing case instead of sun.reflect.UnsafeStaticObjectFieldAccessorImpl
in success case) but I didn't elaborate it further.
Since I needed to temporarily set new value based on old value and later set old value back, I changed signature little bit to provide computation function externally and also return old value:
public static <T> T assignFinalField(Object object, Class<?> clazz, String fieldName, UnaryOperator<T> newValueFunction) {
Field f = null, ff = null;
try {
f = clazz.getDeclaredField(fieldName);
final int oldM = f.getModifiers();
final int newM = oldM & ~Modifier.FINAL;
ff = Field.class.getDeclaredField("modifiers");
ff.setAccessible(true);
ff.setInt(f,newM);
f.setAccessible(true);
T result = (T)f.get(object);
T newValue = newValueFunction.apply(result);
f.set(object,newValue);
ff.setInt(f,oldM);
return result;
} ...
However for general case this would not be sufficient.
From what I know, the correct syntax is:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
document.getElementById(tabName).style.backgroundImage = "url('buttons/" + imagePrefix + ".png')";
}
So basically, getElementById(tabName).backgroundImage
and split the string like:
"cssInHere('and" + javascriptOutHere + "/cssAgain')";
in my own case in django 1.10.1 running on python2.7.11, I was trying to start the server using django-admin runserver
instead of manage.py runserver
in my project directory.
In addition to the answer from @StephanBijzitter I would use the following PATH
variables instead:
%appdata%\npm
%ProgramFiles%\nodejs
So your new PATH
would look like:
[existing stuff];%appdata%\npm;%ProgramFiles%\nodejs
This has the advantage of neiter being user dependent nor 32/64bit dependent.
Tomcat is a web server and a Servlet/JavaServer Pages container. It is often used as an application server for strictly web-based applications but does not include the entire suite of capabilities that a Java EE application server would supply.
Links:
I research a lot on this issue but no solution fix my problem until I try this:
My repo folder is shared with a Windows xp virtual machine, so I execute the clean up from the VM and then execute SVN UPDATE from the host.
It worked for me.
Greetings from Costa Rica.
Working successfuly :
sudo apt install libjpeg8-dev zlib1g-dev
Another common use is for std containers to do equality comparison on key values inside custom objects
class Foo
{
public: int val;
};
class Comparer { public:
bool operator () (Foo& a, Foo&b) const {
return a.val == b.val;
};
class Blah
{
std::set< Foo, Comparer > _mySet;
};
Try this
// Create a DecimalFormat that fits your requirements
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);
// parse the string
BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse("10,692,467,440,017.120");
System.out.println(bigDecimal);
If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)
Also keep in mind that decimalFormat.parse
can throw a ParseException
so you need to handle it (with try/catch) or throw it and let another part of your program handle it
If you are Windows guy and using "Tortoise SVN' user.
Select the File. Right Click. Option 'Tortoise SVN' --> get Lock. Use option 'Steal The Lock'.
@echo off
net use z: /delete
cmdkey /add:servername /user:userserver /pass:userstrongpass
net use z: \\servername\userserver /savecred /persistent:yes
set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"
echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo sLinkFile = "%USERPROFILE%\Desktop\userserver_in_server.lnk" >> %SCRIPT%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT%
echo oLink.TargetPath = "Z:\" >> %SCRIPT%
echo oLink.Save >> %SCRIPT%
cscript /nologo %SCRIPT%
del %SCRIPT%
You can use pandas.Series.tolist
e.g.:
import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
Run:
>>> df['a'].tolist()
You will get
>>> [1, 2, 3]
All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.
If you have accidentally removed DLL file from php/ext
folder, just add it back (get the copy from XAMPP zip archive - its downloadable).
If you have deleted the accompanying INI configuration line from php.ini
file, add it back as well:
extension=php_mbstring.dll
Also, ensure to restart your webserver (Apache) using XAMPP control panel.
Additional Info on Enabling PHP Extensions
/XAMPP/php/ext
directory)extension_dir = "ext"
)Turn off NUMLOCK
and press NUMPAD 9 to rotate the emulator.
To centered the pagination in BS4, should add justify-content-center
in ul
:
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center">
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1">Previous</a>
</li>
<li class="page-item"><a class="page-link" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
<li class="page-item">
<a class="page-link" href="#">Next</a>
</li>
</ul>
</nav>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
_x000D_
See Pagination Bootstrap 4 for further information.
Use a for loop that ranges through all keys in prices
:
for key, value in prices.items():
print key
print "price: %s" %value
Make sure that you change prices.items()
to prices.iteritems()
if you're using Python 2.x
Background color of views (navigator, console, tasks etc) is set according to the desktop (system) settings. On Linux/GNome I changed System/Preferences/Appeareance to change this color.
Editor colors are set chaotically by different editors, search for background in eclipse preferences to find different options. One easy way to get beautiful dark (and not only dark) themes is to install Afae plugin, and then pick theme within its preferences (twilight theme is beautiful, for example) - again, eclipse prefs, Afae group. Of course this applies only when you edit with Afae.
pdf2htmlEX by coolwanglu is probably the best solution out there to convert a pdf file into html. You could do a simple convert and then embed the html page as an iframe or something similar.
click()
to the QMainWindow custom slot you have created).Code example:
MainWindow.h
// ...
include "newwindow.h"
// ...
public slots:
void openNewWindow();
// ...
private:
NewWindow *mMyNewWindow;
// ...
}
MainWindow.cpp
// ...
MainWindow::MainWindow()
{
// ...
connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
// ...
}
// ...
void MainWindow::openNewWindow()
{
mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
mMyNewWindow->show();
// ...
}
This is an example on how display a custom new window. There are a lot of ways to do this.
Parenthesis ()
are used to enable grouping of regex phrases.
The group(1)
contains the string that is between parenthesis (.*)
so .*
in this case
And group(0)
contains whole matched string.
If you would have more groups (read (...)
) it would be put into groups with next indexes (2, 3 and so on).
According to http://docs.python.org/dev/py3k/library/stdtypes.html#dictionary-view-objects , the keys(), values() and items() methods of a dict will return corresponding iterators whose orders correspond. However, I am unable to find a reference to the official documentation for python 2.x for the same thing.
So as far as I can tell, the answer is yes, but only in python 3.0+
The error is here:
hasLetter("a",words[]);
You are passing the first item of words
, instead of the array.
Instead, pass the array to the function:
hasLetter("a",words);
Problem solved!
Here's a breakdown of what the problem was:
I'm guessing in your browser (chrome throws a different error), words[] == words[0]
, so when you call hasLetter("a",words[]);
, you are actually calling hasLetter("a",words[0]);
. So, in essence, you are passing the first item of words to your function, not the array as a whole.
Of course, because words
is just an empty array, words[0]
is undefined
. Therefore, your function call is actually:
hasLetter("a", undefined);
which means that, when you try to access d[ascii]
, you are actually trying to access undefined[0]
, hence the error.
I think you are trying to configure your service in a similar way to the following config. There is more information here: Specify a Service with Two Endpoints Using Different Binding Values. Also, other than for development, it's probably not a good idea to have both HTTP & HTTPS endpoints to the same service. It kinda defeats the purpose of HTTPS. Hope this helps!
<service type="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null">
<endpoint
address="http://computer:8080/Hello"
contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
binding="basicHttpBinding"
bindingConfiguration="shortTimeout"
</endpoint>
<endpoint
address="http://computer:8080/Hello"
contract="HelloWorld, IndigoConfig, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
binding="basicHttpBinding"
bindingConfiguration="Secure"
</endpoint>
</service>
<bindings>
<basicHttpBinding
name="shortTimeout"
timeout="00:00:00:01"
/>
<basicHttpBinding
name="Secure">
<Security mode="Transport" />
</basicHttpBinding>
</bindings>
Use x=as.name("string")
. You can use then use x
to refer to the variable with name string.
I don't know, if it answers your question correctly.
A few options:
(1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance.
(2) The documentation mentions "the underlying writer
instance" ... so just use it (example at the end).
dw.writer.writerow(dw.fieldnames)
(3) Avoid the csv.Dictwriter overhead and do it yourself with csv.writer
Writing data:
w.writerow([d[k] for k in fieldnames])
or
w.writerow([d.get(k, restval) for k in fieldnames])
Instead of the extrasaction
"functionality", I'd prefer to code it myself; that way you can report ALL "extras" with the keys and values, not just the first extra key. What is a real nuisance with DictWriter is that if you've verified the keys yourself as each dict was being built, you need to remember to use extrasaction='ignore' otherwise it's going to SLOWLY (fieldnames is a list) repeat the check:
wrong_fields = [k for k in rowdict if k not in self.fieldnames]
============
>>> f = open('csvtest.csv', 'wb')
>>> import csv
>>> fns = 'foo bar zot'.split()
>>> dw = csv.DictWriter(f, fns, restval='Huh?')
# dw.writefieldnames(fns) -- no such animal
>>> dw.writerow(fns) # no such luck, it can't imagine what to do with a list
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\python26\lib\csv.py", line 144, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "C:\python26\lib\csv.py", line 141, in _dict_to_list
return [rowdict.get(key, self.restval) for key in self.fieldnames]
AttributeError: 'list' object has no attribute 'get'
>>> dir(dw)
['__doc__', '__init__', '__module__', '_dict_to_list', 'extrasaction', 'fieldnam
es', 'restval', 'writer', 'writerow', 'writerows']
# eureka
>>> dw.writer.writerow(dw.fieldnames)
>>> dw.writerow({'foo':'oof'})
>>> f.close()
>>> open('csvtest.csv', 'rb').read()
'foo,bar,zot\r\noof,Huh?,Huh?\r\n'
>>>
As looking on your error #1062 - Duplicate entry '2-S. Name' for key 'PRIMARY'
it is saying that you use primary key in your number field that's why it is showing duplicate Error on Number Field.
So Remove this primary Key then it inset duplicate also.
in web application in .cs page
txtbox.Style.Add("background-color","black");
in css specify it by using backcolor property
Note that IETF RFC4627 has been superseded by IETF RFC7158. In section [8.1] it retracts the text cited by @Drew earlier by saying:
Implementations MUST NOT add a byte order mark to the beginning of a JSON text.
Assume that you have MyPayments class like
public class Mypayment
{
public int year { get; set; }
public string month { get; set; }
public string price { get; set; }
public bool ispaid { get; set; }
}
and you have a list of MyPayments
public List<Mypayment> mypayments { get; set; }
and you want group the list by year. You can use linq like this:
List<List<Mypayment>> mypayments = (from IGrouping<int, Mypayment> item in yearGroup
let mypayments1 = (from _payment in UserProjects.mypayments
where _payment.year == item.Key
select _payment).ToList()
select mypayments1).ToList();
The following script can be run in the Package Manger Console window, and will remove all packages from each project in your solution before reinstalling them.
foreach ($project in Get-Project -All) {
$packages = Get-Package -ProjectName $project.ProjectName
foreach ($package in $packages) {
Uninstall-Package $package.Id -Force -ProjectName $project.ProjectName
}
foreach ($package in $packages) {
Install-Package $package.Id -ProjectName $project.ProjectName -Version $package.Version
}
}
This will run every package's install script again, which should restore the missing assembly references. Unfortunately, all the other stuff that install scripts can do -- like creating files and modifying configs -- will also happen again. You'll probably want to start with a clean working copy, and use your SCM tool to pick and choose what changes in your project to keep and which to ignore.
I just had this problem myself because I was in the wrong folder. I was nested 1 level in, so there were no git files to be found.
When I execute cd ..
to the correct directory, I was able to commit, as expected.
You can implement a Comparator
which compares two Person
objects, and you can examine as many of the fields as you like. You can put in a variable in your comparator that tells it which field to compare to, although it would probably be simpler to just write multiple comparators.
I am using Jupiter Notebook 5.6.0. Here, to get autosuggestion I am just hitting Tab key after entering at least one character.
**Example:** Enter character `p` and hit Tab.
To get the methods and properties inside the imported library use same Tab key with Alice
import numpy as np
np. --> Hit Tab key
<section></section>
The HTML
<section>
element represents a generic section of a document, i.e., a thematic grouping of content, typically with a heading. Each<section>
should be identified, typically by including a heading (<h1>
-<h6>
element) as a child of the<section>
element. For Details Please following link.
References :
<div></div>
The HTML
<div>
element (or HTML Document Division Element) is the generic container for flow content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element (such as<article>
or<nav>
) is appropriate.
References: - http://www.w3schools.com/tags/tag_div.asp - https://developer.mozilla.org/en/docs/Web/HTML/Element/div
Here are some links that discuss more about the differences between them:
Looking at your requirement, there is alternate solution as well. It seems you know the dimensions in dp at compile time, so you can add a dimen entry in the resources. Then you can query the dimen entry and it will be automatically converted to pixels in this call:
final float inPixels= mActivity.getResources().getDimension(R.dimen.dimen_entry_in_dp);
And your dimens.xml will have:
<dimen name="dimen_entry_in_dp">72dp</dimen>
Extending this idea, you can simply store the value of 1dp or 1sp as a dimen entry and query the value and use it as a multiplier. Using this approach you will insulate the code from the math stuff and rely on the library to perform the calculations.
I have been seeing the exact same error today, but it was not a config or direct JavaScript issue.
An external .net project had been updated but the changes not picked up properly in the compilation of the web site. My presumption is that ASP.NET ajax was not able to construct the client representations of the .NET objects properly and so was failing to load correctly.
To resolve, I rebuilt the external project(s), and rebuilt my solution that was experiencing issues. The problem went away.
docker-compose up --force-recreate
is one option, but if you're using it for CI, I would start the build with docker-compose rm -f
to stop and remove the containers and volumes (then follow it with pull and up).
This is what I use:
docker-compose rm -f
docker-compose pull
docker-compose up --build -d
# Run some tests
./tests
docker-compose stop -t 1
The reason containers are recreated is to preserve any data volumes that might be used (and it also happens to make up
a lot faster).
If you're doing CI you don't want that, so just removing everything should get you want you want.
Update: use up --build
which was added in docker-compose
1.7
Also, in .NET 4 this is even easier if you use the dynamic keyword:
dynamic document = this.browser.Document;
dynamic head = document.GetElementsByTagName("head")[0];
dynamic scriptEl = document.CreateElement("script");
scriptEl.text = ...;
head.AppendChild(scriptEl);
abs()
:
Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float.
Also it works on complex variable also i.e. abs(a+bj)
also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)
math.fabs()
:
It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).
You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding
class.
or try this
System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
System.Text.ASCIIEncoding.ASCII.GetByteCount(string);
If you have several dialogs that could be opened on a page, this will allow any of them to be closed by clicking on the background:
$('body').on('click','.ui-widget-overlay', function() {
$('.ui-dialog').filter(function () {
return $(this).css("display") === "block";
}).find('.ui-dialog-content').dialog('close');
});
(Only works for modal dialogs, as it relies on '.ui-widget-overlay'. And it does close all open dialogs any time the background of one of them is clicked.)
PHP way of getting text from span tag:
$spanText = $this->webDriver->findElement(WebDriverBy::xpath("//*[@id='specInformation']/tbody/tr[2]/td[1]/span[1]"))->getText();
<form id="form1" runat="server">
<input type="search" name="Search" placeholder="Search for a Product..." list="datalist1"
required="">
<datalist id="datalist1" runat="server">
</datalist>
</form>
protected void Page_Load(object sender, EventArgs e)
{
autocomplete();
}
protected void autocomplete()
{
Database p = new Database();
DataSet ds = new DataSet();
ds = p.sqlcall("select [name] from [stu_reg]");
int row = ds.Tables[0].Rows.Count;
string abc="";
for (int i = 0; i < row;i++ )
abc = abc + "<option>"+ds.Tables[0].Rows[i][0].ToString()+"</option>";
datalist1.InnerHtml = abc;
}
Here Database is a File (Database.cs) In Which i have created on method named sqlcall for retriving data from database.
You can create your own filter function using query
in pandas
. Here you have filtering of df
results by all the kwargs
parameters. Dont' forgot to add some validators(kwargs
filtering) to get filter function for your own df
.
def filter(df, **kwargs):
query_list = []
for key in kwargs.keys():
query_list.append(f'{key}=="{kwargs[key]}"')
query = ' & '.join(query_list)
return df.query(query)
Put in addresses this code:
objMessage.To.Add(***addresses:=***"[email protected] , [email protected] , [email protected]")
You can include a .js file which has the script to set the
window.location.href = url;
Where url would be the url you wish to load.
After lots of tweaking, here's a configuration that works generating files on Linux, reading on Windows+Excel, though the embedded newline format is not according to the standard:
In Perl, I used Text::CSV to do this as follows:
use Text::CSV;
open my $FO, ">:encoding(utf8)", $filename or die "Cannot create $filename: $!";
my $csv = Text::CSV->new({ binary => 1, eol => "\r\n" });
#for each row...:
$csv -> print ($FO, \@row);
I think what BrandonS wants is not the position of the mouse relative to the root element, but rather the position of some descendant element.
For that, there is the TransformToAncestor method:
Point relativePoint = myVisual.TransformToAncestor(rootVisual)
.Transform(new Point(0, 0));
Where myVisual
is the element that was just double-clicked, and rootVisual
is Application.Current.MainWindow or whatever you want the position relative to.
I use GroovyShell in java to parse template with Groovy GString:
Binding binding = new Binding();
GroovyShell gs = new GroovyShell(binding);
// this JSONObject can also be replaced by any Java Object
JSONObject obj = new JSONObject();
obj.put("key", "value");
binding.setProperty("obj", obj)
String str = "${obj.key}";
String exp = String.format("\"%s\".toString()", str);
String res = (String) gs.evaluate(exp);
// value
System.out.println(str);
Still, this can be done with the following steps:
send an https ajax request to your web-site (the same domain)
jQuery.ajax({
'url' : '//same_domain.com/ajax_receiver.php',
'type' : 'get',
'data' : {'foo' : 'bar'},
'success' : function(response) {
console.log('Successful request');
}
}).fail(function(xhr, err) {
console.error('Request error');
});
get ajax request, for example, by php, and make a CURL get request to any desired website via http.
use linslin\yii2\curl;
$curl = new curl\Curl();
$curl->get('http://example.com');
it appears that this also works
def normalizeRows(M):
row_sums = M.sum(axis=1)
return M / row_sums
Use List.AddRange(collection As IEnumerable(Of T)) method.
It allows you to append at the end of your list another collection/list.
Example:
List<string> initialList = new List<string>();
// Put whatever you want in the initial list
List<string> listToAdd = new List<string>();
// Put whatever you want in the second list
initialList.AddRange(listToAdd);
It might be obvious, but make sure that you are sending to the parser URL object not a String containing www adress. This will not work:
ObjectMapper mapper = new ObjectMapper();
String www = "www.sample.pl";
Weather weather = mapper.readValue(www, Weather.class);
But this will:
ObjectMapper mapper = new ObjectMapper();
URL www = new URL("http://www.oracle.com/");
Weather weather = mapper.readValue(www, Weather.class);
Consider Below Html
<html>
<body>
<input type ="text" id="username">
</body>
</html>
so Absoulte path= html/body/input and Relative path = //*[@id="username"]
Disadvantage with Absolute xpath is maintenance is high if there is nay change made in html it may disturb the entire path and also sometime we need to write long absolute xpaths so relative xpaths are preferred
As we know filter and order by are removed from ANGULAR 2 and we need to write our own, here is a good example on plunker and detailed article
It used both filter as well as orderby, here is the code for order pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'orderBy' })
export class OrderrByPipe implements PipeTransform {
transform(records: Array<any>, args?: any): any {
return records.sort(function(a, b){
if(a[args.property] < b[args.property]){
return -1 * args.direction;
}
else if( a[args.property] > b[args.property]){
return 1 * args.direction;
}
else{
return 0;
}
});
};
}
You can any time switch between type of applications, to console or windows. So, you will not write special logic to see the stdout. Also, when running application in debugger, you will see all the stdout in output window. You might also just add a breakpoint, and in breakpoint properties change "When Hit...", you can output any messages, and variables. Also you can check/uncheck "Continue execution", and your breakpoint will become square shaped. So, the breakpoint messages without changhing anything in the application in the debug output window.
another way to do is get the UriInfo instead of all the QueryParam
Then you will be able to get the queryParam as per needed in your code
@GET
@Path("/query")
public Response getUsers(@Context UriInfo info) {
String param_1 = info.getQueryParameters().getFirst("param_1");
String param_2 = info.getQueryParameters().getFirst("param_2");
return Response ;
}
I just want to add - most of the other answers worked fine for me; however, it took a long time to get them working!
This is because setting height: 100%
only picks up parent div's height!
So if your entire html (inside of the body) looks like the following:
<div id="holder">
<header>.....</header>
<div id="body">....</div>
<footer>....</footer>
</div>
Then the following will be fine:
html,body{
height: 100%
}
#holder{
min-height: 100%;
position:relative;
}
#body{
padding-bottom: 100px; /* height of footer */
}
footer{
height: 100px;
width:100%;
position: absolute;
left: 0;
bottom: 0;
}
...as "holder" will pick up it's height directly from "body".
Kudos to My Head Hurts, whose answer was the one I ended up getting to work!
However. If your html is more nested (because it's only an element of the full page, or it's within a certain column, etc) then you need to make sure every containing element also has height: 100%
set on the div. Otherwise, the information on height will be lost between "body" and "holder".
E.g. the following, where I've added the "full height" class to every div to make sure the height gets all the way down to our header/body/footer elements:
<div class="full-height">
<div class="container full-height">
<div id="holder">
<header>.....</header>
<div id="body">....</div>
<footer>....</footer>
</div>
</div>
</div>
And remember to set height on full-height class in the css:
#full-height{
height: 100%;
}
That fixed my issues!
There are plenty of good answers but I created a template header I use that is quite concise and easy to use.
To add an iterator to your class it is only necessary to write a small class to represent the state of the iterator with 7 small functions, of which 2 are optional:
#include <iostream>
#include <vector>
#include "iterator_tpl.h"
struct myClass {
std::vector<float> vec;
// Add some sane typedefs for STL compliance:
STL_TYPEDEFS(float);
struct it_state {
int pos;
inline void begin(const myClass* ref) { pos = 0; }
inline void next(const myClass* ref) { ++pos; }
inline void end(const myClass* ref) { pos = ref->vec.size(); }
inline float& get(myClass* ref) { return ref->vec[pos]; }
inline bool cmp(const it_state& s) const { return pos != s.pos; }
// Optional to allow operator--() and reverse iterators:
inline void prev(const myClass* ref) { --pos; }
// Optional to allow `const_iterator`:
inline const float& get(const myClass* ref) const { return ref->vec[pos]; }
};
// Declare typedef ... iterator;, begin() and end() functions:
SETUP_ITERATORS(myClass, float&, it_state);
// Declare typedef ... reverse_iterator;, rbegin() and rend() functions:
SETUP_REVERSE_ITERATORS(myClass, float&, it_state);
};
Then you can use it as you would expect from an STL iterator:
int main() {
myClass c1;
c1.vec.push_back(1.0);
c1.vec.push_back(2.0);
c1.vec.push_back(3.0);
std::cout << "iterator:" << std::endl;
for (float& val : c1) {
std::cout << val << " "; // 1.0 2.0 3.0
}
std::cout << "reverse iterator:" << std::endl;
for (auto it = c1.rbegin(); it != c1.rend(); ++it) {
std::cout << *it << " "; // 3.0 2.0 1.0
}
}
I hope it helps.
To prevent full size category images slowing page down, you can use smaller images with wp_get_attachment_image_src()
:
<?php
$thumbnail_id = get_woocommerce_term_meta( $term->term_id, 'thumbnail_id', true );
// get the medium-sized image url
$image = wp_get_attachment_image_src( $thumbnail_id, 'medium' );
// Output in img tag
echo '<img src="' . $image[0] . '" alt="" />';
// Or as a background for a div
echo '<div class="image" style="background-image: url("' . $image[0] .'")"></div>';
?>
EDIT: Fixed variable name and missing quote
Move points into test:
def test():
points = 0
addpoint = raw_input ("type ""add"" to add a point")
...
or use global statement, but it is bad practice. But better way it move points to parameters:
def test(points=0):
addpoint = raw_input ("type ""add"" to add a point")
...
In a project i´m working on we have another solution doing this.
First I don´t like the ExpectedExceptionAttribute becuase it does take in consideration which method call that caused the Exception.
I do this with a helpermethod instead.
Test
[TestMethod]
public void AccountRepository_ThrowsExceptionIfFileisCorrupt()
{
var file = File.Create("Accounts.bin");
file.WriteByte(1);
file.Close();
IAccountRepository repo = new FileAccountRepository();
TestHelpers.AssertThrows<SerializationException>(()=>repo.GetAll());
}
HelperMethod
public static TException AssertThrows<TException>(Action action) where TException : Exception
{
try
{
action();
}
catch (TException ex)
{
return ex;
}
Assert.Fail("Expected exception was not thrown");
return null;
}
Neat, isn´t it;)
I came across this question when trying to check if a file existed on an FTP site or not. If the file doesn't exist there will be an error when trying to check its timestamp. But I want to make sure the error is not something else, by checking its type.
The Response
property on WebException
will be of type FtpWebResponse
on which you can check its StatusCode
property to see which FTP error you have.
Here's the code I ended up with:
public static bool FileExists(string host, string username, string password, string filename)
{
// create FTP request
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + host + "/" + filename);
request.Credentials = new NetworkCredential(username, password);
// we want to get date stamp - to see if the file exists
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
var lastModified = response.LastModified;
// if we get the last modified date then the file exists
return true;
}
catch (WebException ex)
{
var ftpResponse = (FtpWebResponse)ex.Response;
// if the status code is 'file unavailable' then the file doesn't exist
// may be different depending upon FTP server software
if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
// some other error - like maybe internet is down
throw;
}
}
cout << fixed << setprecision(2) << total;
setprecision
specifies the minimum precision. So
cout << setprecision (2) << 1.2;
will print 1.2
fixed
says that there will be a fixed number of decimal digits after the decimal point
cout << setprecision (2) << fixed << 1.2;
will print 1.20
You can use each
for this:
$('#productList li').each(function(i, li) {
var $product = $(li);
// your code goes here
});
That being said - are you sure you want to be updating the values to be +1 each time? Couldn't you just find the count and then set the values based on that?
Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).
Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});
In general, I break lines before operators, and indent the subsequent lines:
Map<long parameterization> longMap
= new HashMap<ditto>();
String longString = "some long text"
+ " some more long text";
To me, the leading operator clearly conveys that "this line was continued from something else, it doesn't stand on its own." Other people, of course, have different preferences.
if you're using NSNotificationCenter for updating your view, don't forget to send it from the main thread by calling dispatch_async
:
dispatch_async(dispatch_get_main_queue(),^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"my_notification" object:nil];
});
I am partial to ES2015 arrow function for finding values in an array
const result = data.find(x=> x.TEST1 === '46');
Checkout Array.prototype.find() HERE
You're probably looking for -A:
git add -A
this is similar to git add -u, but also adds new files. This is roughly the equivalent of hg's addremove
command (although the move detection is automatic).
You are looking for "|." See http://cran.r-project.org/doc/manuals/R-intro.html#Logical-vectors
my.data.frame <- data[(data$V1 > 2) | (data$V2 < 4), ]
Just this 1 line of code changed the background programmatically
tv.setBackgroundColor(Color.parseColor("#808080"));
add layout_gravity and gravity with center value on TextView
<TextView
android:text="welcome text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
/>
With [ChildActionOnly] attribute annotated, an action method can be called only as a child method from within a view. Here is an example for [ChildActionOnly]..
there are two action methods: Index() and MyDateTime() and corresponding Views: Index.cshtml and MyDateTime.cshtml.
this is HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "This is from Index()";
var model = DateTime.Now;
return View(model);
}
[ChildActionOnly]
public PartialViewResult MyDateTime()
{
ViewBag.Message = "This is from MyDateTime()";
var model = DateTime.Now;
return PartialView(model);
}
}
Here is the view for Index.cshtml.
@model DateTime
@{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<div>
This is the index view for Home : @Model.ToLongTimeString()
</div>
<div>
@Html.Action("MyDateTime") // Calling the partial view: MyDateTime().
</div>
<div>
@ViewBag.Message
</div>
Here is MyDateTime.cshtml partial view.
@model DateTime
<p>
This is the child action result: @Model.ToLongTimeString()
<br />
@ViewBag.Message
</p>
if you run the application and do this request http://localhost:57803/home/mydatetime The result will be Server Error like so:
This means you can not directly call the partial view. but it can be called via Index() view as in the Index.cshtml
@Html.Action("MyDateTime") // Calling the partial view: MyDateTime().
If you remove [ChildActionOnly] and do the same request http://localhost:57803/home/mydatetime it allows you to get the mydatetime partial view result:
This is the child action result. 12:53:31 PM
This is from MyDateTime()
Dim text As String = "123.45"
Dim value As Double
If Double.TryParse(text, value) Then
' text is convertible to Double, and value contains the Double value now
Else
' Cannot convert text to Double
End If
You can use my loadScript ES module for loading of the JavaScript files.
In your head tag, include the following code:
<script src="https://raw.githack.com/anhr/loadScriptNodeJS/master/build/loadScript.js"></script>
or
<script src="https://raw.githack.com/anhr/loadScriptNodeJS/master/build/loadScript.min.js"></script>
Now you can use window.loadScript for loading of your JavaScript files.
Asynchronous load JavaScript file.
src
: URL of an external script file or array of the script file names.
options
: the following options are available
onload: function () The onload event occurs when a script has been loaded. Default is undefined.
onerror: function ( str, e ) The onerror event occurs when an error has been occurred. The default is undefined.
str: error details
e: event
appendTo: The node to which the new script will be append. The default is the head node.
For example
loadScript.async( "JavaScript.js",
{
onload: function () {
var str = 'file has been loaded successfully';
console.log( str );
},
onerror: function ( str, e ) {
console.error( str );
},
} );
You probably want something like this overload of String.Join:
String.Join<T> Method (String, IEnumerable<T>)
Docs:
http://msdn.microsoft.com/en-us/library/dd992421.aspx
In your example, you'd use
String.Join("", Client);
You can try this:
You must follow the following format
$('element,id,class').on('click', function(){....});
*JQuery code*
$('body').addClass('.anything').on('click', function(){
//do some code here i.e
alert("ok");
});
You can use JSONPath
Doing something like this:
results = JSONPath(null, TestObj, "$..[?(@.id=='A')]")
Note that JSONPath returns an array of results
(I have not tested the expression "$..[?(@.id=='A')]" btw. Maybe it needs to be fine-tuned with the help of a browser console)
When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.
json_decode( html_entity_decode( stripslashes ($jsonString ) ) );
Thanks to @Thisguyhastwothumbs
If you dig into NSInteger's implementation:
#if __LP64__
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
Simply, the NSInteger typedef does a step for you: if the architecture is 32-bit, it uses int
, if it is 64-bit, it uses long
. Using NSInteger, you don't need to worry about the architecture that the program is running on.
I think this solution is short and seem looks nice:
long long fib(int n){
return n<=2?1:fib(n-1)+fib(n-2);
}
Edit : as jweyrich mentioned, true recursive function should be:
long long fib(int n){
return n<2?n:fib(n-1)+fib(n-2);
}
(because fib(0) = 0. but base on above recursive formula, fib(0) will be 1)
To understand recursion algorithm, you should draw to your paper, and the most important thing is : "Think normal as often".
You can do this:
sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)
records_array
would then be the result of your sql query in an array which you can iterate through.
Today I found, that the old ways are not working very well.
So I used: "Customize YouTube Start and End Time - Acetrot.com" from http://www.youtubestartend.com/
They provide a link into https://xxxx.app.goo.gl/yyyyyyyyyy e.g. https://v637g.app.goo.gl/Cs2SV9NEeoweNGGy9 Link contain forward to format like this https://www.youtube.com/embed/xyzabc123?start=17&end=21&version=3&autoplay=1
Suggestions:
for example,
type
functionname( arguments )
{
if (something)
{
do stuff
}
else
{
do other stuff
}
switch (value)
{
case 'a':
astuff
break;
case 'b':
bstuff
//fallthrough //always comment fallthrough as intentional
case 'c':
break;
default: //always consider default, and handle it explicitly
break;
}
while ( the lights are on )
{
if ( something happened )
{
run around in circles
if ( you are scared ) //yeah, much more than 3-4 levels of indent are too many!
{
scream and shout
}
}
}
return typevalue; //always return something, you'll thank me later
}
A node is the base class for both elements and attributes (and basically all other XML representations too).
I read all the posts here and realized that we may need a real life example. Why, actually, we have @property?
So, consider a Flask app where you use authentication system.
You declare a model User in models.py
:
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
...
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
In this code we've "hidden" attribute password
by using @property
which triggers AttributeError
assertion when you try to access it directly, while we used @property.setter to set the actual instance variable password_hash
.
Now in auth/views.py
we can instantiate a User with:
...
@auth.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
user = User(email=form.email.data,
username=form.username.data,
password=form.password.data)
db.session.add(user)
db.session.commit()
...
Notice attribute password
that comes from a registration form when a user fills the form. Password confirmation happens on the front end with EqualTo('password', message='Passwords must match')
(in case if you are wondering, but it's a different topic related Flask forms).
I hope this example will be useful
My approach is very close to Garret Wilson's (thanks, I voted you up ;)
In addition it provides downward compatibility with Android < 3.
I just recognized that my solution is even closer to the one by Kevin Remo. It's just a wee bit cleaner (as it does not rely on the "expection" antipattern).
public class MyPreferenceActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
onCreatePreferenceActivity();
} else {
onCreatePreferenceFragment();
}
}
/**
* Wraps legacy {@link #onCreate(Bundle)} code for Android < 3 (i.e. API lvl
* < 11).
*/
@SuppressWarnings("deprecation")
private void onCreatePreferenceActivity() {
addPreferencesFromResource(R.xml.preferences);
}
/**
* Wraps {@link #onCreate(Bundle)} code for Android >= 3 (i.e. API lvl >=
* 11).
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void onCreatePreferenceFragment() {
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new MyPreferenceFragment ())
.commit();
}
}
For a "real" (but more complex) example see NusicPreferencesActivity and NusicPreferencesFragment.
viewNoteDateMonth.text = [[displayDate objectAtIndex:2] uppercaseString];
You can also use lowercaseString and capitalizedString