Two things. First, you must base64 decode the mykey.pem
file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey
ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec
, which is based on the SubjectPublicKeyInfo
ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
// ...
String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);
It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:
unspecified
emailAddress
– e.g. [email protected]
X509SubjectName
– e.g. CN=john,O=Company Ltd.,C=US
WindowsDomainQualifiedName
– e.g. CompanyDomain\John
kerberos
– e.g. john@realm
entity
– this one in used to identify entities that provide SAML-based services and looks like a URIpersistent
– this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.transient
– opaque identifier which should be treated as temporary.Try this:
mynewlist = [s for s in mylist if s.isdigit()]
From the docs:
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
As noted in the comments, isdigit()
returning True
does not necessarily indicate that the string can be parsed as an int via the int()
function, and it returning False
does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.
Probably the most definitive is Figure B.1(d) of the ggplot2 book, the appendices of which are available at http://ggplot2.org/book/appendices.pdf.
However, it is not quite that simple. hjust
and vjust
as described there are how it works in geom_text
and theme_text
(sometimes). One way to think of it is to think of a box around the text, and where the reference point is in relation to that box, in units relative to the size of the box (and thus different for texts of different size). An hjust
of 0.5 and a vjust
of 0.5 center the box on the reference point. Reducing hjust
moves the box right by an amount of the box width times 0.5-hjust
. Thus when hjust=0
, the left edge of the box is at the reference point. Increasing hjust
moves the box left by an amount of the box width times hjust-0.5
. When hjust=1
, the box is moved half a box width left from centered, which puts the right edge on the reference point. If hjust=2
, the right edge of the box is a box width left of the reference point (center is 2-0.5=1.5
box widths left of the reference point. For vertical, less is up and more is down. This is effectively what that Figure B.1(d) says, but it extrapolates beyond [0,1].
But, sometimes this doesn't work. For example
DF <- data.frame(x=c("a","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()
p + opts(axis.text.x=theme_text(vjust=0))
p + opts(axis.text.x=theme_text(vjust=1))
p + opts(axis.text.x=theme_text(vjust=2))
The three latter plots are identical. I don't know why that is. Also, if text is rotated, then it is more complicated. Consider
p + opts(axis.text.x=theme_text(hjust=0, angle=90))
p + opts(axis.text.x=theme_text(hjust=0.5 angle=90))
p + opts(axis.text.x=theme_text(hjust=1, angle=90))
p + opts(axis.text.x=theme_text(hjust=2, angle=90))
The first has the labels left justified (against the bottom), the second has them centered in some box so their centers line up, and the third has them right justified (so their right sides line up next to the axis). The last one, well, I can't explain in a coherent way. It has something to do with the size of the text, the size of the widest text, and I'm not sure what else.
For your specific example, you don't actually need to nest them. If the expression in the try
block succeeds, the function will return, so any code after the whole try/except block will only be run if the first attempt fails. So you can just do:
def __getattribute__(self, item):
try:
return object.__getattribute__(item)
except AttributeError:
pass
# execution only reaches here when try block raised AttributeError
try:
return self.dict[item]
except KeyError:
print "The object doesn't have such attribute"
Nesting them isn't bad, but I feel like leaving it flat makes the structure more clear: you're sequentially trying a series of things and returning the first one that works.
Incidentally, you might want to think about whether you really want to use __getattribute__
instead of __getattr__
here. Using __getattr__
will simplify things because you'll know that the normal attribute lookup process has already failed.
This is an answer I've already given some time ago:
It depends entirely on the domain-specific application needs. A lot of times direct text file/binary files access can be extremely fast, efficient, as well as providing you all the file access capabilities of your OS's file system.
Furthermore, your programming language most likely already has a built-in module (or is easy to make one) for specific parsing.
If what you need is many appends (INSERTS?) and sequential/few access little/no concurrency, files are the way to go.
On the other hand, when your requirements for concurrency, non-sequential reading/writing, atomicity, atomic permissions, your data is relational by the nature etc., you will be better off with a relational or OO database.
There is a lot that can be accomplished with SQLite3, which is extremely light (under 300kb), ACID compliant, written in C/C++, and highly ubiquitous (if it isn't already included in your programming language -for example Python-, there is surely one available). It can be useful even on db files as big as 140 terabytes, or 128 tebibytes (Link to Database Size), possible more.
If your requirements where bigger, there wouldn't even be a discussion, go for a full-blown RDBMS.
As you say in a comment that "the system" is merely a bunch of scripts, then you should take a look at pgbash.
A date-time object is supposed to store the information about the date, time, timezone etc., not about the formatting. You can format a date-time object into a String
with the pattern of your choice using date-time formatting API.
java.time.format
e.g. java.time.format.DateTimeFormatter
, java.time.format.DateTimeFormatterBuilder
etc.java.text
e.g. java.text.SimpleDateFormat
, java.text.DateFormat
etc.Demo using modern API:
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(2012, Month.DECEMBER, 1).atStartOfDay(),
ZoneId.of("Europe/London"));
// Default format returned by Date#toString
System.out.println(zdt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = dtf.format(zdt);
System.out.println(formattedDate);
}
}
Output:
2012-12-01T00:00Z[Europe/London]
2012-12-01
Learn about the modern date-time API from Trail: Date Time.
Demo using legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeInMillis(0);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date date = calendar.getTime();
// Default format returned by Date#toString
System.out.println(date);
// Custom format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
Output:
Sat Dec 01 00:00:00 GMT 2012
2012-12-01
Some more important points:
java.util.Date
object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970
. When you print an object of java.util.Date
, its toString
method returns the date-time calculated from this milliseconds value. Since java.util.Date
does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat
and obtain the formatted string from it.java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
Yes, you can do ajax request to server with your data in request parameters, like this (very simple):
Note that the following code uses jQuery
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
dataType: 'json',
data: {functionname: 'add', arguments: [1, 2]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
and your_functions_address.php like this:
<?php
header('Content-Type: application/json');
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'add':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$aResult['result'] = add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
?>
Bootstrap datepicker (the first result from bootstrap datepickcer search) has a method to get the selected date.
https://bootstrap-datepicker.readthedocs.io/en/latest/methods.html#getdate
getDate: Returns a localized date object representing the internal date object of the first datepicker in the selection. For multidate pickers, returns the latest date selected.
$('.datepicker').datepicker("getDate")
or
$('.datepicker').datepicker("getDate").valueOf()
This will detect any version of Firefox:
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
more specifically:
if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
// Do Firefox-related activities
}
You may want to consider using feature-detection ala Modernizr, or a related tool, to accomplish what you need.
First, you need to obtain the public certificate from the server you're trying to connect to. That can be done in a variety of ways, such as contacting the server admin and asking for it, using OpenSSL to download it, or, since this appears to be an HTTP server, connecting to it with any browser, viewing the page's security info, and saving a copy of the certificate. (Google should be able to tell you exactly what to do for your specific browser.)
Now that you have the certificate saved in a file, you need to add it to your JVM's trust store. At $JAVA_HOME/jre/lib/security/
for JREs or $JAVA_HOME/lib/security
for JDKs, there's a file named cacerts
, which comes with Java and contains the public certificates of the well-known Certifying Authorities. To import the new cert, run keytool as a user who has permission to write to cacerts:
keytool -import -file <the cert file> -alias <some meaningful name> -keystore <path to cacerts file>
It will most likely ask you for a password. The default password as shipped with Java is changeit
. Almost nobody changes it. After you complete these relatively simple steps, you'll be communicating securely and with the assurance that you're talking to the right server and only the right server (as long as they don't lose their private key).
I have tried this and it worked:
define PROPp_START_DT = TO_DATE('01-SEP-1999')
select * from proposal where prop_start_dt = &PROPp_START_DT
Arguments and parameters are different in that parameters are used to different values in the program and The arguments are passed the same value in the program so they are used in c++. But no difference in c. It is the same for arguments and parameters in c.
type sqlplus/"as sysdba" in cmd for connection in cmd prompt
There is now (as of v1.10.7) a fourth way to instantiate mocks, which is using a JUnit4 rule called MockitoRule.
@RunWith(JUnit4.class) // or a different runner of your choice
public class YourTest
@Rule public MockitoRule rule = MockitoJUnit.rule();
@Mock public YourMock yourMock;
@Test public void yourTestMethod() { /* ... */ }
}
JUnit looks for subclasses of TestRule annotated with @Rule, and uses them to wrap the test Statements that the Runner provides. The upshot of this is that you can extract @Before methods, @After methods, and even try...catch wrappers into rules. You can even interact with these from within your test, the way that ExpectedException does.
MockitoRule behaves almost exactly like MockitoJUnitRunner, except that you can use any other runner, such as Parameterized (which allows your test constructors to take arguments so your tests can be run multiple times), or Robolectric's test runner (so its classloader can provide Java replacements for Android native classes). This makes it strictly more flexible to use in recent JUnit and Mockito versions.
In summary:
Mockito.mock()
: Direct invocation with no annotation support or usage validation.MockitoAnnotations.initMocks(this)
: Annotation support, no usage validation.MockitoJUnitRunner
: Annotation support and usage validation, but you must use that runner.MockitoRule
: Annotation support and usage validation with any JUnit runner.See also: How JUnit @Rule works?
Most likely, somewhere on your webserver will be an Alias directive like this;
Alias /phpmyadmin "c:/wamp/apps/phpmyadmin3.1.3.1/"
In my wampserver / localhost setup, it was in c:/wamp/alias/phpmyadmin.conf.
Just change the alias directive and you should be good to go.
Android uses the Roboto font, which is a really nice looking font, with several different weights (regular, light, thin, condensed) that look great on high density screens.
Check below link to check roboto fonts:
How to use Roboto in xml layout
Back to your question, if you want to change the font for all of the TextView/Button in your app, try adding below code into your styles.xml to use Roboto-light font:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
......
<item name="android:buttonStyle">@style/MyButton</item>
<item name="android:textViewStyle">@style/MyTextView</item>
</style>
<style name="MyButton" parent="@style/Widget.AppCompat.Button">
<item name="android:textAllCaps">false</item>
<item name="android:fontFamily">sans-serif-light</item>
</style>
<style name="MyTextView" parent="@style/TextAppearance.AppCompat">
<item name="android:fontFamily">sans-serif-light</item>
</style>
And don't forget to use 'AppTheme' in your AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
......
</application>
This works very well for java. It uses bitwise exclusive OR and assignment operator
public int solution(int[] A) {
// write your code in Java SE 8
int sol = 0;
for(int val:A){
sol ^= val;
}
return sol;
}
}
In order to resolve this issue make all your data flow tasks in one sequence. It means it should not execute parallel. One data flow task sequence should contain only one data flow task and for this another data flow task as sequence.
Ex:-
When you need to debug, use printf with %p
option is really helpful. You see 0x0 when you have a NULL value.
Not exactly zipping, but you can compact files in Windows with the compact command:
compact /c /s:<directory or file>
And to uncompress:
compact /u /s:<directory or file>
NOTE: These commands only mark/unmark files or directories as compressed in the file system. They do not produces any kind of archive (like zip, 7zip, rar, etc.)
In my mind I have to consider that the foo
folder is a stand-alone library. I might want to consider moving it to the Lib\site-packages
folder within a python installation. I might want to consider adding a foo.pth
file there.
I know it's a library since the ./programs/my_python_program.py
contains the following line:
from foo.tasks import my_function
So it doesn't matter that ./programs
is a sibling folder to ./foo
. It's the fact that my_python_program.py
is run as a script like this:
python ./programs/my_python_program.py
I needed to indent two rows to allow for a larger first word in a para. A cumbersome one-off solution is to place text in an SVG element and position this the same as an <img>. Using float and the SVG's height tag defines how many rows will be indented e.g.
<p style="color: blue; font-size: large; padding-top: 4px;">
<svg height="44" width="260" style="float:left;margin-top:-8px;"><text x="0" y="36" fill="blue" font-family="Verdana" font-size="36">Lorum Ipsum</text></svg>
dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
Yes it is cumbersome but it is also independent of the width of the containing div.
The above answer was to my own query to allow the first word(s) of a para to be larger and positioned over two rows. To simply indent the first two lines of a para you could replace all the SVG tags with the following single pixel img:
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" style="float:left;width:260px;height:44px;" />
First up, this has got nothing to do with String
, it is about arrays.. and that too specifically about declarative initialization of arrays.
As discussed by everyone in almost every answer here, you can, while declaring a variable, use:
String names[] = {"x","y","z"};
However, post declaration, if you want to assign an instance of an Array:
names = new String[] {"a","b","c"};
AFAIK, the declaration syntax is just a syntactic sugar and it is not applicable anymore when assigning values to variables because when values are assigned you need to create an instance properly.
However, if you ask us why it is so? Well... good luck getting an answer to that. Unless someone from the Java committee answers that or there is explicit documentation citing the said syntactic sugar.
It will be different for different browsers:
This works in ff:
var t =$("#INPUT");
var l=$("#INPUT").val().length;
$(t).focus();
var r = $("#INPUT").get(0).createTextRange();
r.moveStart("character", l);
r.moveEnd("character", l);
r.select();
More details are in these articles here at SitePoint, AspAlliance.
I hope this complete example will help you.
This is the TaxiInfo class which holds information about a taxi ride:
namespace Taxi.Models
{
public class TaxiInfo
{
public String Driver { get; set; }
public Double Fare { get; set; }
public Double Distance { get; set; }
public String StartLocation { get; set; }
public String EndLocation { get; set; }
}
}
We also have a convenience model which holds a List of TaxiInfo(s):
namespace Taxi.Models
{
public class TaxiInfoSet
{
public List<TaxiInfo> TaxiInfoList { get; set; }
public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
{
TaxiInfoList = new List<TaxiInfo>();
foreach(var TaxiInfo in TaxiInfos)
{
TaxiInfoList.Add(TaxiInfo);
}
}
}
}
Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:
public ActionResult Index()
{
var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };
return View(new TaxiInfoSet(taxi1,taxi2));
}
The code for the view is as follows:
@model Taxi.Models.TaxiInfoSet
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach(var TaxiInfo in Model.TaxiInfoList){
<form>
<h1>Cost: [email protected]</h1>
<h2>Distance: @(TaxiInfo.Distance) km</h2>
<p>
Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
</p>
@Html.ActionLink("Home","Booking",TaxiInfo)
</form>
}
The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:
public ActionResult Booking(TaxiInfo Taxi)
{
return View(Taxi);
}
This returns a the following view:
@model Taxi.Models.TaxiInfo
@{
ViewBag.Title = "Booking";
}
<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>
A visual tour:
You can use lambda expression like this.
int index = listOfElements.FindIndex(item => item.Id == id);
if (index != -1)
{
listOfElements[index] = newValue;
}
If your img folder is inside your theme folder, just follow the example below:
<img src="<?php echo get_theme_file_uri(); ?>/img/yourimagename.jpg" class="story-img" alt="your alt text">
One solution could be to wrap the options inside optgroup:
optgroup { font-size:40px; }
_x000D_
<select>
<optgroup>
<option selected="selected" class="service-small">Service area?</option>
<option class="service-small">Volunteering</option>
<option class="service-small">Partnership & Support</option>
<option class="service-small">Business Services</option>
</optgroup>
</select>
_x000D_
Another solution that it is similar to those already exposed here is this one. Just before the closing body tag place this html:
<div id="resultLoading" style="display: none; width: 100%; height: 100%; position: fixed; z-index: 10000; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto;">
<div style="width: 340px; height: 200px; text-align: center; position: fixed; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; z-index: 10; color: rgb(255, 255, 255);">
<div class="uil-default-css">
<img src="/images/loading-animation1.gif" style="max-width: 150px; max-height: 150px; display: block; margin-left: auto; margin-right: auto;" />
</div>
<div class="loader-text" style="display: block; font-size: 18px; font-weight: 300;"> </div>
</div>
<div style="background: rgb(0, 0, 0); opacity: 0.6; width: 100%; height: 100%; position: absolute; top: 0px;"></div>
</div>
Finally, replace .loader-text element's
content on the fly on every navigation event and turn on the #resultloading
div, note that it is initially hidden.
var showLoader = function (text) {
$('#resultLoading').show();
$('#resultLoading').find('.loader-text').html(text);
};
jQuery(document).ready(function () {
jQuery(window).on("beforeunload ", function () {
showLoader('Loading, please wait...');
});
});
This can be applied to any html based project with jQuery where you don't know which pages of your administration area will take too long to finish loading.
The gif image is 176x176px but you can use any transparent gif animation, please take into account that the image size is not important as it will be maxed to 150x150px.
Also, the function showLoader can be called on an element's click to perform an action that will further redirect the page, that is why it is provided ad an individual function. i hope this can also help anyone.
To check the status of a service on linux operating system :
//in case of super user(admin) requires
sudo service {service_name} status
// in case of normal user
service {service_name} status
To stop or start service
// in case of admin requires
sudo service {service_name} start/stop
// in case of normal user
service {service_name} start/stop
To get the list of all services along with PID :
sudo service --status-all
You can use systemctl instead of directly calling service :
systemctl status/start/stop {service_name}
In my case I have moved plugins folder mistakenly to another folder while taking backup of my unnecessary projects. Then while I was trying to run the eclipse.exe I was getting the error-
The Eclipse executable launcher was unable to locate its companion shared library.
I have simply copied the plugins folder to eclipse root directory, and it was working fine for me.
If you have the folders backup in your computer then just copy and paste the folders on eclipse directory, you don't need to reinstall or change the ini file so far I realized.
Just compare the column with that value:
In [9]: df = pandas.DataFrame([1,2,3,4], columns=["data"])
In [10]: df
Out[10]:
data
0 1
1 2
2 3
3 4
In [11]: df["desired"] = df["data"] > 2.5
In [11]: df
Out[12]:
data desired
0 1 False
1 2 False
2 3 True
3 4 True
Here's an implementation that converts a two-dimensional array or an array of columns into a properly escaped CSV string. The functions do not check for valid string/number input or column counts (ensure your array is valid to begin with). The cells can contain commas and quotes!
Here's a script for decoding CSV strings.
Here's my script for encoding CSV strings:
// Example
var csv = new csvWriter();
csv.del = '\t';
csv.enc = "'";
var nullVar;
var testStr = "The comma (,) pipe (|) single quote (') double quote (\") and tab (\t) are commonly used to tabulate data in plain-text formats.";
var testArr = [
false,
0,
nullVar,
// undefinedVar,
'',
{key:'value'},
];
console.log(csv.escapeCol(testStr));
console.log(csv.arrayToRow(testArr));
console.log(csv.arrayToCSV([testArr, testArr, testArr]));
/**
* Class for creating csv strings
* Handles multiple data types
* Objects are cast to Strings
**/
function csvWriter(del, enc) {
this.del = del || ','; // CSV Delimiter
this.enc = enc || '"'; // CSV Enclosure
// Convert Object to CSV column
this.escapeCol = function (col) {
if(isNaN(col)) {
// is not boolean or numeric
if (!col) {
// is null or undefined
col = '';
} else {
// is string or object
col = String(col);
if (col.length > 0) {
// use regex to test for del, enc, \r or \n
// if(new RegExp( '[' + this.del + this.enc + '\r\n]' ).test(col)) {
// escape inline enclosure
col = col.split( this.enc ).join( this.enc + this.enc );
// wrap with enclosure
col = this.enc + col + this.enc;
}
}
}
return col;
};
// Convert an Array of columns into an escaped CSV row
this.arrayToRow = function (arr) {
var arr2 = arr.slice(0);
var i, ii = arr2.length;
for(i = 0; i < ii; i++) {
arr2[i] = this.escapeCol(arr2[i]);
}
return arr2.join(this.del);
};
// Convert a two-dimensional Array into an escaped multi-row CSV
this.arrayToCSV = function (arr) {
var arr2 = arr.slice(0);
var i, ii = arr2.length;
for(i = 0; i < ii; i++) {
arr2[i] = this.arrayToRow(arr2[i]);
}
return arr2.join("\r\n");
};
}
This will print stars in triangle:
`
public class printstar{
public static void main (String args[]){
int m = 0;
for(int i=1;i<=4;i++){
for(int j=1;j<=4-i;j++){
System.out.print("");}
for (int n=0;n<=i+m;n++){
if (n%2==0){
System.out.print("*");}
else {System.out.print(" ");}
}
m = m+1;
System.out.println("");
}
}
}'
Reading and understanding this should help you with designing the logic next time..
At the time of this writing (which is with SonarQube 4.5.1), the correct property to set is sonar.coverage.exclusions
, e.g.:
<properties>
<sonar.coverage.exclusions>foo/**/*,**/bar/*</sonar.coverage.exclusions>
</properties>
This seems to be a change from just a few versions earlier. Note that this excludes the given classes from coverage calculation only. All other metrics and issues are calculated.
In order to find the property name for your version of SonarQube, you can try going to the General Settings section of your SonarQube instance and look for the Code Coverage item (in SonarQube 4.5.x, that's General Settings → Exclusions → Code Coverage). Below the input field, it gives the property name mentioned above ("Key: sonar.coverage.exclusions").
As mentioned by Klap "android.R.layout.simple_list_item_1 is a reference to an built-in XML layout document that is part of the Android OS"
All the layouts are located in: sdk\platforms\android-xx\data\res\layout
To view the XML of layout :
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select "Open declaration in layout/simple_list_item_1.xml". It'll direct you to the contents of the XML.
Android Studio: Project Window -> External Libraries -> Android X Platform -> res -> layout, and here you will see a list of available layouts.
Structure packing is only done when you tell your compiler explicitly to pack the structure. Padding is what you're seeing. Your 32-bit system is padding each field to word alignment. If you had told your compiler to pack the structures, they'd be 6 and 5 bytes, respectively. Don't do that though. It's not portable and makes compilers generate much slower (and sometimes even buggy) code.
To get the current Id on a View:
ViewContext.RouteData.Values["id"].ToString()
To get the current controller:
ViewContext.RouteData.Values["controller"].ToString()
Two options:
Firstly, you can escape it using a backslash -- \(
Alternatively, since it's a single character, you can put it in a character class, where it doesn't need to be escaped -- [(]
Joze's way also need LINQ, ToList()
is in System.Linq
namespace.
You can convert Array to List without Linq by passing the array to List constructor:
List<int> numbers = new List<int>( Array.ConvertAll(sNumbers.Split(','), int.Parse) );
Note (Oct 2020): AsyncTask used in the following answer has been deprecated in Android API level 30. Please refer to Official documentation or this blog post for a more updated example
Updated (June 2017) Answer which works on Android 6.0+. Thanks to @Rohit Suthar, @Tamis Bolvari and @sudhiskr for the comments.
public class CallAPI extends AsyncTask<String, String, String> {
public CallAPI(){
//set context variables if required
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String urlString = params[0]; // URL to call
String data = params[1]; //data to post
OutputStream out = null;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();
urlConnection.connect();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
References:
Original Answer (May 2010)
Note: This solution is outdated. It only works on Android devices up to 5.1. Android 6.0 and above do not include the Apache http client used in this answer.
Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Try using the key
keyword with sorted()
.
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=lambda x: x[1])
key
should be a function that identifies how to retrieve the comparable element from your data structure. In your case, it is the second element of the tuple, so we access [1]
.
For optimization, see jamylak's response using itemgetter(1)
, which is essentially a faster version of lambda x: x[1]
.
window
object is made available through $window
service for easier testing and mocking, you can go with something like:
$scope.reloadPage = function(){$window.location.reload();}
And :
<a ng-click="reloadPage" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
As a side note, i don't think $route.reload() actually reloads the page, but only the route.
do not make headaches for yourself, want a simple, one line solution to add a permanent environment variable (open powershell in elevated mode):
[Environment]::SetEnvironmentVariable("NewEnvVar", "NewEnvValue", "Machine")
close the session and open it again to make things done
in case that u want to modify/change that:
[Environment]::SetEnvironmentVariable("oldEnvVar", "NewEnvValue", "Machine")
in case that u want to delete/remove that:
[Environment]::SetEnvironmentVariable("oldEnvVar", "", "Machine")
As others have said, you posted 3 characters instead of one. I suggest you run this little snippet of code to see what's actually in your string:
public static void dumpString(String text)
{
for (int i=0; i < text.length(); i++)
{
System.out.println("U+" + Integer.toString(text.charAt(i), 16)
+ " " + text.charAt(i));
}
}
If you post the results of that, it'll be easier to work out what's going on. (I haven't bothered padding the string - we can do that by inspection...)
Download xcode 10.2 from below link https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10.2/Xcode_10.2.xip
Edit: Minimum System Version* to 10.13.6 in Info.plist at below paths
Xcode.app/Contents/Info.plist
Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/Info.plist
Replace: Xcode.app/Contents/Developer/usr/bin/xcodebuild
from Xcode 10
****OR*****
you can install disk image of 12.2 in your existing xcode to run on 12.2 devices Download disk image from here https://github.com/xushuduo/Xcode-iOS-Developer-Disk-Image/releases/download/12.2/12.2.16E5191d.zip
And paste at Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
Note: Restart the Xcode
This is a circular dependency issue. Golang programs must be acyclic. In Golang cyclic imports are not allowed (That is its import graph must not contain any loops)
Lets say your project go-circular-dependency
have 2 packages "package one" & it has "one.go" & "package two" & it has "two.go" So your project structure is as follows
+--go-circular-dependency
+--one
+-one.go
+--two
+-two.go
This issue occurs when you try to do something like following.
Step 1 - In one.go
you import package two
(Following is one.go
)
package one
import (
"go-circular-dependency/two"
)
//AddOne is
func AddOne() int {
a := two.Multiplier()
return a + 1
}
Step 2 - In two.go
you import package one
(Following is two.go
)
package two
import (
"fmt"
"go-circular-dependency/one"
)
//Multiplier is going to be used in package one
func Multiplier() int {
return 2
}
//Total is
func Total() {
//import AddOne from "package one"
x := one.AddOne()
fmt.Println(x)
}
In Step 2, you will receive an error "can't load package: import cycle not allowed" (This is called "Circular Dependency" error)
Technically speaking this is bad design decision and you should avoid this as much as possible, but you can "Break Circular Dependencies via implicit interfaces" (I personally don't recommend, and highly discourage this practise, because by design Go programs must be acyclic)
Try to keep your import dependency shallow. When the dependency graph becomes deeper (i.e package x imports y, y imports z, z imports x) then circular dependencies become more likely.
Sometimes code repetition is not bad idea, which is exactly opposite of DRY (don't repeat yourself)
So in Step 2 that is in two.go
you should not import package one. Instead in two.go
you should actually replicate the functionality of AddOne()
written in one.go
as follows.
package two
import (
"fmt"
)
//Multiplier is going to be used in package one
func Multiplier() int {
return 2
}
//Total is
func Total() {
// x := one.AddOne()
x := Multiplier() + 1
fmt.Println(x)
}
If you add the extension .SH
to the environment variable PATHEXT
, you will be able to run shell scripts from PowerShell by only using the script name with arguments:
PS> .\script.sh args
If you store your scripts in a directory that is included in your PATH environment variable, you can run it from anywhere, and omit the extension and path:
PS> script args
Note: sh.exe or another *nix shell must be associated with the .sh extension.
This is what I like to do:
$files = array_values(array_filter(scandir($path), function($file) use ($path) {
return !is_dir($path . '/' . $file);
}));
foreach($files as $file){
echo $file;
}
let pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*]{6,16}$/;
//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format
let reee =pattern .test("helLo123@"); //true as it contains all the above
Posting answer to my own question as I found it here and was hidden in bottom somewhere -
This is because the OS failed to install the required update Windows8.1-KB2999226-x64.msu.
However, you can install it by extracting that update to a folder (e.g. XXXX), and execute following cmdlet. You can find the Windows8.1-KB2999226-x64.msu at below.
C:\ProgramData\Package Cache\469A82B09E217DDCF849181A586DF1C97C0C5C85\packages\Patch\amd64\Windows8.1-KB2999226-x64.msu
copy this file to a folder you like, and
Create a folder XXXX in that and execute following commands from Admin command propmt
wusa.exe Windows8.1-KB2999226-x64.msu /extract:XXXX
DISM.exe /Online /Add-Package /PackagePath:XXXX\Windows8.1-KB2999226-x64.cab
vc_redist.x64.exe /repair
(last command need not be run. Just execute vc_redist.x64.exe once again)
this worked for me.
SELECT <select_list>
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL
Full image of join
From aticle : http://www.codeproject.com/KB/database/Visual_SQL_Joins.aspx
From a posting by Matz:
(1) ++ and -- are NOT reserved operator in Ruby.
(2) C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
(3) self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.
matz.
Since you are using C++11, lambda-expression is a nice&clean solution.
class blub {
void test() {}
public:
std::thread spawn() {
return std::thread( [this] { this->test(); } );
}
};
since this->
can be omitted, it could be shorten to:
std::thread( [this] { test(); } )
or just (deprecated)
std::thread( [=] { test(); } )
You can use a semitransparent pixel, which you can generate for example here, even in base64 Here is an example with white 50%:
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8Xw8AAoMBgDTD2qgAAAAASUVORK5CYII=),
url(../img/leftpanel/intro1.png);
background-size: cover, cover;
without uploading
without extra html
i guess the loading should be quicker than box-shadow or linear gradient
You have to specify project_id
:
reverse('edit_project', kwargs={'project_id':4})
Doc here
You could use dataframe method notnull or inverse of isnull, or numpy.isnan:
In [332]: df[df.EPS.notnull()]
Out[332]:
STK_ID RPT_Date STK_ID.1 EPS cash
2 600016 20111231 600016 4.3 NaN
4 601939 20111231 601939 2.5 NaN
In [334]: df[~df.EPS.isnull()]
Out[334]:
STK_ID RPT_Date STK_ID.1 EPS cash
2 600016 20111231 600016 4.3 NaN
4 601939 20111231 601939 2.5 NaN
In [347]: df[~np.isnan(df.EPS)]
Out[347]:
STK_ID RPT_Date STK_ID.1 EPS cash
2 600016 20111231 600016 4.3 NaN
4 601939 20111231 601939 2.5 NaN
SQLite supports replacing a row if it already exists:
INSERT OR REPLACE INTO [...blah...]
You can shorten this to
REPLACE INTO [...blah...]
This shortcut was added to be compatible with the MySQL REPLACE INTO
expression.
I'm able to get the Class of the generic type this way:
class MyList<T> {
Class<T> clazz = (Class<T>) DAOUtil.getTypeArguments(MyList.class, this.getClass()).get(0);
}
You need two functions from this file: http://code.google.com/p/hibernate-generic-dao/source/browse/trunk/dao/src/main/java/com/googlecode/genericdao/dao/DAOUtil.java
For more explanation: http://www.artima.com/weblogs/viewpost.jsp?thread=208860
You will have to define the functions inside your header file.
You cannot separate definition of template functions in to the source file and declarations in to header file.
When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared.
Reference:
C++03 standard, § 14.7.2.4:
The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.
EDIT:
To clarify the discussion on the comments:
Technically, there are three ways to get around this linking problem:
.cpp
file. #include
the .cpp
file defining the template at the .cpp
file using the template. Each of them have their pros and cons,
Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure.
Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance.
While including cpp files is confusing at the same time shares the problems of both above approaches.
I find first method the easiest to follow and implement and hence advocte using it.
I could fix this problem removing the jquery bundle on the _Layout.cshtml
Header
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/kendo/2015.2.902/kendo.all.min.js"></script>
...
Footer
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
Change footer to
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
OpenCV HSV range is: H: 0 to 179 S: 0 to 255 V: 0 to 255
On Gimp (or other photo manipulation sw) Hue range from 0 to 360, since opencv put color info in a single byte, the maximum number value in a single byte is 255 therefore openCV Hue values are equivalent to Hue values from gimp divided by 2.
I found when trying to do object detection based on HSV color space that a range of 5 (opencv range) was sufficient to filter out a specific color. I would advise you to use an HSV color palate to figure out the range that works best for your application.
You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.
used like: window.Promise
https://www.npmjs.com/package/promise-polyfill
If you want more information on Polyfills check out the following MDN web doc https://developer.mozilla.org/en-US/docs/Glossary/Polyfill
You have to do two things:
The method to get the rendered HTML I prefer is the following:
driver.get("http://www.google.com")
body_html = driver.find_element_by_xpath("/html/body")
print body_html.text
However, the above method removes all the tags (yes, the nested tags as well) and returns only text content. If you interested in getting the HTML markup as well, then use the method below.
print body_html.getAttribute("innerHTML")
You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.
Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.
Do you mean something like this:
s1 = '00000001'
s2 = '11111110'
int(s1,2) ^ int(s2,2)
VanillaJS === JavaScript i.e.VanillaJS is native JavaScript
Why, Vanilla says it all!!!
Computer software, and sometimes also other computing-related systems like computer hardware or algorithms, are called vanilla when not customized from their original form, meaning that they are used without any customization or updates applied to them (Refer this article). So Vanilla often refers to pure or plain.
In the English language Vanilla has a similar meaning, In information technology, vanilla (pronounced vah-NIHL-uh ) is an adjective meaning plain or basic. Or having no special or extra features, ordinary or standard.
So why name it VanillaJS? As the accepted answer says some bosses want to work with a framework (because it's more organized and flexible and do all the things we want??) but simply JavaScript will do the job. Yet you need to add a framework somewhere. Use VanillaJS...
Is it a Joke? YES
Want some fun?
Where can you find it, http://vanilla-js.com/ Download and see for yourself!!! It's 0 bytes uncompressed, 25 bytes gzipped
:D
Found this pun on internet regarding JS frameworks (Not to condemn the existing JS frameworks though, they'll make life really easy :)),
Also refer,
function getValue(obj)
{
// it will return the selected text
// obj variable will contain the object of check box
var text = obj.options[obj.selectedIndex].innerHTML ;
}
HTML Snippet
<asp:DropDownList ID="ddl" runat="server" CssClass="ComboXXX"
onchange="getValue(this)">
</asp:DropDownList>
If there is space between the letters of the font, you need to use quote.
font-family:"Calibri (Body)";
IF all this dont work, your .htaccess is correct, and permalinks trick didnt work, you may have not enabled your apache2 rewite mod.
I ran this and my issue was solved:
sudo a2enmod rewrite
Use the PackageResourceViewer plugin installed via Package Control (as mentioned by MattDMo). This allows you to override the compressed resources by simply opening it in Sublime Text and saving the file. It automatically saves only the edited resources to %APPDATA%/Roaming/Sublime Text 3/Packages/ or ~/.config/sublime-text-3/Packages/.
Specific to the op, once the plugin is installed, execute the PackageResourceViewer: Open Resource
command. Then select JavaScript
followed by JavaScript.tmLanguage
. This will open an xml file in the editor. You can edit any of the language definitions and save the file. This will write an override copy of the JavaScript.tmLanguage file in the user directory.
The same method can be used to edit the language definition of any language in the system.
For each iteration of the ng-repeat loop, line
is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}
.
Similarly, to databind to the text, databind to the same: ng-model="line.text"
. You don't need to use value
when using ng-model (actually you shouldn't).
For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.
You use ttk.Frame
, bg
option does not work for it. You should create style and apply it to the frame.
from tkinter import *
from tkinter.ttk import *
root = Tk()
s = Style()
s.configure('My.TFrame', background='red')
mail1 = Frame(root, style='My.TFrame')
mail1.place(height=70, width=400, x=83, y=109)
mail1.config()
root.mainloop()
A good place to look at is the man page of bash. Here's an online version. Look for "INVOCATION" section.
Create a separate ul.nav
for just that list item and float that ul
right.
In addtion to align-self
you can also consider auto margin which will do almost the same thing
.container {_x000D_
background: red;_x000D_
height: 200px;_x000D_
flex-direction: column;_x000D_
padding: 10px;_x000D_
display: flex;_x000D_
}_x000D_
a {_x000D_
margin-right:auto;_x000D_
padding: 10px 40px;_x000D_
background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
<a href="#">Test</a>_x000D_
</div>
_x000D_
You are also able to set some XSS related HTTP response headers via header(...)
X-XSS-Protection "1; mode=block"
to be sure, the browser XSS protection mode is enabled.
Content-Security-Policy "default-src 'self'; ..."
to enable browser-side content security. See this one for Content Security Policy (CSP) details: http://content-security-policy.com/ Especially setting up CSP to block inline-scripts and external script sources is helpful against XSS.
for a general bunch of useful HTTP response headers concerning the security of you webapp, look at OWASP: https://www.owasp.org/index.php/List_of_useful_HTTP_headers
Window -> Preferences -> Java -> Code Style -> Code Templates -> Comments -> Types Chnage the tage infront ${user} to your name.
Before
/**
* @author ${user}
*
* ${tags}
*/
After
/**
* @author Waqas Ahmed
*
* ${tags}
*/
if you are trying to execute mysql query withouth defining connectionstring, you will get this error.
Probably you forgat to define connection string before execution. have you check this out? (sorry for bad english)
I recommend using the python bindings to OpenImageIO, it's the standard for dealing with various image formats in the vfx world. I've ovten found it more reliable in reading various compression types compared to PIL.
import OpenImageIO as oiio
input = oiio.ImageInput.open ("/path/to/image.tif")
I only know a way around this. The idea is to export that list of pdf files you have into a file. Then split that file into several parts. Then remove pdf files listed in each part.
ls | grep .pdf > list.txt
wc -l list.txt
wc -l is to count how many line the list.txt contains. When you have the idea of how long it is, you can decide to split it in half, forth or something. Using split -l command For example, split it in 600 lines each.
split -l 600 list.txt
this will create a few file named xaa,xab,xac and so on depends on how you split it. Now to "import" each list in those file into command rm, use this:
rm $(<xaa)
rm $(<xab)
rm $(<xac)
Sorry for my bad english.
You can use ${!a}
:
var1="this is the real value"
a="var1"
echo "${!a}" # outputs 'this is the real value'
This is an example of indirect parameter expansion:
The basic form of parameter expansion is
${parameter}
. The value ofparameter
is substituted.If the first character of
parameter
is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest ofparameter
as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value ofparameter
itself.
well I think I have something interesting for you... https://github.com/whizzzkid/phpimageresize. I wrote it for the exact same purpose. Highly customizable, and does it in a great way.
I did this inside the render() method:
render() {
const project = () => {
switch(this.projectName) {
case "one": return <ComponentA />;
case "two": return <ComponentB />;
case "three": return <ComponentC />;
case "four": return <ComponentD />;
default: return <h1>No project match</h1>
}
}
return (
<div>{ project() }</div>
)
}
I tried to keep the render() return clean, so I put my logic in a 'const' function right above. This way I can also indent my switch cases neatly.
As Adirael suggested objectForKey
to check key existance but When you call objectForKey
in nullable dictionary, app gets crashed so I fixed this from following way.
- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;
if (dictionary && (object != [NSNull null])) {
self.name = [dictionary objectForKey:@"name"];
self.age = [dictionary objectForKey:@"age"];
}
return self;
}
If you set a variable via SETX, you cannot use this variable or its changes immediately. You have to restart the processes that want to use it.
Use the following sequence to directly set it in the setting process too (works for me perfectly in scripts that do some init stuff after setting global variables):
SET XYZ=test
SETX XYZ test
For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.
If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.
Good luck!
(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)
mx.iloc[0].idxmax()
This one line of code will give you how to find the maximum value from a row in dataframe, here mx
is the dataframe and iloc[0]
indicates the 0th index.
You are not evaluating a condition for the IF. I am guessing you want to not copy if you find stringToCheck in fileToCheck. You need to do something like (code untested but you get the idea):
CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF NOT ERRORLEVEL 0 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y
EDIT by dbenham
The above test is WRONG, it always evaluates to FALSE.
The correct test is IF ERRORLEVEL 1 XCOPY ...
Update: I can't test the code, but I am not sure what return value findstr actually returns if it doesn't find anything. You might have to do something like:
CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat > tempfindoutput.txt
set /p FINDOUTPUT= < tempfindoutput.txt
IF "%FINDOUTPUT%"=="" XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y
del tempfindoutput.txt
Rather than giving background-size:100%;
We can give background-size:contain;
Check out this for different options avaliable: http://www.css3.info/preview/background-size/
select * into mytable_backup from mytable
Makes a copy of table mytable, and every row in it, called mytable_backup.
on Ubuntu Bionic (18.04), six is already install for python2 and python3 but I have the error launching Wammu. @3ygun solution worked for me to solve
ImportError: No module named six
when launching Wammu
If it's occurred for python3 program, six come with
pip3 install six
and if you don't have pip3:
apt install python3-pip
with sudo under Ubuntu!
It seems like an IllegalArgumentException
is called for if you don't want null
to be an allowed value, and the NullPointerException
would be thrown if you were trying to use a variable that turns out to be null
.
While the post of Oka is working great, it might be a bit outdated. I figured out that lodash can tackle it with one single function. If you have lodash installed, it might save you a few lines.
Just try:
import { startsWith } from lodash;
. . .
if (startsWith(yourVariable, 'REP')) {
return yourVariable;
return yourVariable;
}
}
Yeah, it is quite vague.
You should use it whenever for readers of the documentation of your method it may be useful to also look at some other method. If the documentation of your methodA says "Works like methodB but ...", then you surely should put a link.
An alternative to @see
would be the inline {@link ...}
tag:
/**
* ...
* Works like {@link #methodB}, but ...
*/
When the fact that methodA calls methodB is an implementation detail and there is no real relation from the outside, you don't need a link here.
As ephemient said, the C library libc is linked by default and this library contains the implementations of stdlib.h, stdio.h and several other standard header files. Just to add to it, according to "An Introduction to GCC" the linker command for a basic "Hello World" program in C is as below:
ld -dynamic-linker /lib/ld-linux.so.2 /usr/lib/crt1.o
/usr/lib/crti.o /usr/libgcc-lib /i686/3.3.1/crtbegin.o
-L/usr/lib/gcc-lib/i686/3.3.1 hello.o -lgcc -lgcc_eh -lc
-lgcc -lgcc_eh /usr/lib/gcc-lib/i686/3.3.1/crtend.o /usr/lib/crtn.o
Notice the option -lc in the third line that links the C library.
It's possible that other tables have FK constraint to your [table]. So the DB needs to check these tables to maintain the referential integrity. Even if you have all needed indexes corresponding these FKs, check their amount.
I had the situation when NHibernate incorrectly created duplicated FKs on the same columns, but with different names (which is allowed by SQL Server). It has drastically slowed down running of the DELETE statement.
It's not necessary to use nested form groups and a custom ErrorStateMatcher for confirm password validation. These steps were added to facilitate coordination between the password fields, but you can do that without all the overhead.
Here is an example:
this.registrationForm = this.fb.group({
username: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password1: ['', [Validators.required, (control) => this.validatePasswords(control, 'password1') ] ],
password2: ['', [Validators.required, (control) => this.validatePasswords(control, 'password2') ] ]
});
Note that we are passing additional context to the validatePasswords method (whether the source is password1 or password2).
validatePasswords(control: AbstractControl, name: string) {
if (this.registrationForm === undefined || this.password1.value === '' || this.password2.value === '') {
return null;
} else if (this.password1.value === this.password2.value) {
if (name === 'password1' && this.password2.hasError('passwordMismatch')) {
this.password1.setErrors(null);
this.password2.updateValueAndValidity();
} else if (name === 'password2' && this.password1.hasError('passwordMismatch')) {
this.password2.setErrors(null);
this.password1.updateValueAndValidity();
}
return null;
} else {
return {'passwordMismatch': { value: 'The provided passwords do not match'}};
}
Note here that when the passwords match, we coordinate with the other password field to have its validation updated. This will clear any stale password mismatch errors.
And for completeness sake, here are the getters that define this.password1
and this.password2
.
get password1(): AbstractControl {
return this.registrationForm.get('password1');
}
get password2(): AbstractControl {
return this.registrationForm.get('password2');
}
Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR
The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.
For example:
{ "things": ["a", "b", "c"] }
Would Unmarshal into a:
type Item struct {
Things []string
}
And not into:
type Item struct {
Things string
}
The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int
or float
field -- "1"
needs to Unmarshal into a string
, not into an int
like we saw with ShippingAdditionalCost int
[Route("api/controller/{one}/{two}")]
public string Get(int One, int Two)
{
return "both params of the root link({one},{two}) and Get function parameters (one, two) should be same ";
}
Both params of the root link({one},{two}) and Get function parameters (one, two) should be same
Work out what specific properties of a list
you want the items to have. Do they need to be indexable? Sliceable? Do they need an .append()
method?
Look up the abstract base class which describes that particular type in the collections
module.
Use isinstance
:
isinstance(x, collections.MutableSequence)
You might ask "why not just use type(x) == list
?" You shouldn't do that, because then you won't support things that look like lists. And part of the Python mentality is duck typing:
I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck
In other words, you shouldn't require that the objects are list
s, just that they have the methods you will need. The collections
module provides a bunch of abstract base classes, which are a bit like Java interfaces. Any type that is an instance of collections.Sequence
, for example, will support indexing.
I had the same problem... If you have set your DB name and username and pass correctly in .env file and its still not working run the blow code in terminal:(this will clean the caches that left from previous apps)
php artisan cache:clear
and then run the command php artisan serve
again (if you are running it stop and run it again)
Just updating here solution suggested by @ken-kinder for Python 2 to work for Python 3:
import urllib
urllib.request.urlopen(target_url).read()
cv2 vs. "opencv3"
To get a potential misunderstanding out of the way:
The python OpenCV module is named and imported via import cv2
in all versions > 2.0, including > 3.0. If you want to work with cv2
, installing OpenCV versions > 3 is fine - unless you're looking for specific compatibility with older versions or are a fan of the 2.4.x versions. The switch from 2.4.x to 3.x was in 2015 and in terms of features, speed and transparency, it makes much sense to use the newer versions. You can read here and here about major differences. 2.4.x versions are still supported though, current release is 2.4.13.5.
Installing a specific version, e.g. OpenCV 2.4.9
That said:
If you want to install a specific version that neither pip install opencv-python==2.4.X
, sudo apt-get install opencv
nor conda install opencv=2.4.x
provide (as explained by other answers here), you can always install from sources. In the sourceforge repository you can find all major versions for each operating system. Although for unxeperienced users this might be scary, it is well explained in some tutorials. E.g. here for 2.4.9 on Ubuntu 14.04. Or here is the official Linux install doc for the latest release 2.4.13.5.
In essence, the install process boils down to:
install dependencies, refer to docs (e.g. here) for required packages
get sources from OpenCVs sourceforge
e.g. wget http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/2.4.9/opencv-2.4.9.zip
unzip sources and prepare build by creating build directory and running cmake
mkdir build
cd build
cmake (... your build options ...)
build in the created build directory with:
make
sudo make install
To know the actual date format, insert a record by using sysdate. That way you can find the actual date format. for example
insert into emp values(7936, 'Mac', 'clerk', 7782, sysdate, 1300, 300, 10);
now, select the inserted record.
select ename, hiredate from emp where ename='Mac';
the result is
ENAME HIREDATE
Mac 06-JAN-13
voila, now your actual date format is found.
Java 8 provides a set of unsigned long operations that allows you to directly treat those Long variables as unsigned Long, here're some commonly used ones:
And additions, subtractions, and multiplications are the same for signed and unsigned longs.
First things first, i'd not like that as a user.
The best way to do is probably using a small flash applet that plays your sound in the background.
Also answered here: Cross-platform, cross-browser way to play sound from Javascript?
From what I can tell, the MVVM maps to the MV of MVC - meaning that in a traditional MVC pattern the V does not communicate directly with the M. In the second version of MVC, there is a direct link between M and V. MVVM appears to take all tasks related to M and V communication, and couple it to decouple it from the C. In effect, there's still the larger scope application workflow (or implementation of the use scenarios) that are not fully accounted for in MVVM. This is the role of the controller. By removing these lower level aspects from the controllers, they are cleaner and makes it easier to modify the application's use scenario and business logic, also making controllers more reusable.
You can create mappings that work in insert mode. The way to do that is via inoremap. Note the 'i' at the beginning of the command (noremap is useful to avoid key map collisions). The corollary is 'n' for 'normal' mode. You can surmise what vim thinks is 'normal' ;)
HOWEVER, you really want to navigate around in text using 'normal' mode. Vim is super at this kind of thing and all that power is available from normal mode. Vim already provides easy ways to get from normal mode to insert mode (e.g., i, I, a, A, o, O). The trick is to make it easy to get into normal mode. The way to do that is to remap escape to a more convient key. But you need one that won't conflict with your regular typing. I use:
inoremap jj <Esc>
Since jj (that's 2 j's typed one after the other quickly) doesn't seem to appear in my vocabulary. Other's will remap to where it's comfortable.
The other essential change I make is to switch the CAPSLOCK and CONTROL keys on my keyboard (using the host computer's keyboard configuration) since I almost never use CAPSLOCK and it has that big, beautiful button right where I want it. (This is common for Emacs users. The downside is when you find yourself on an 'unfixed' keyboard! Aaarggh!)
Once you remap CAPSLOCK, you can comfortably use the following insert mode remappings:
Keeping in mind that some keys are already mapped in insert mode (backwards-kill-word is C-w (Control-w) by default, you might already have the bindings you want. That said, I prefer C-h so in my .vimrc I have:
inoremap <C-h> <C-w>
BUT, you probably want the same muscle memory spasm in normal mode, so I also map C-h as:
nnoremap <C-h> db
(d)elete (b)ackwards accomplishes the same thing with the same key chord. This kind of quick edit is one that I find useful in practice for typos. But stick to normal mode for moving around in text and anything more than killing the previous word. Once you get into the habit of changing modes (using a remap of course), it will be much more efficient than remapping insert mode.
As I understand it, in Linq the method FirstOrDefault() can return a Default value of something other than null.
No. Or rather, it always returns the default value for the element type... which is either a null reference, the null value of a nullable value type, or the natural "all zeroes" value for a non-nullable value type.
Is there any particular way that this can be set up so that if there is no value for a particular query some predefined value is returned as the default value?
For reference types, you can just use:
var result = query.FirstOrDefault() ?? otherDefaultValue;
Of course this will also give you the "other default value" if the first value is present, but is a null reference...
Many of the other answers are all well but if you want an informational tooltip instead of a fullblown window then do this: after enabling it using @Ahmad's answer then click on the little pin on the upper right corner:
After this the method information will appear on a tooltip like almost every other mainstream IDE.
If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);
You can use the familiar Matplotlib style calling a figure
and subplot
, but you simply need to specify the current axis using plt.gca()
. An example:
plt.figure(1)
plt.subplot(2,2,1)
df.A.plot() #no need to specify for first axis
plt.subplot(2,2,2)
df.B.plot(ax=plt.gca())
plt.subplot(2,2,3)
df.C.plot(ax=plt.gca())
etc...
for github pages I Use
ng build --prod --base-href "https://<username>.github.io/<RepoName>/" --output-path=docs
This is what that copies output into the docs folder : --output-path=docs
A lot of people, including me, use sqlfiddle.com to test SQL.
SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
FROM DBA_SEGMENTS DS
WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES) AND SEGMENT_NAME='YOUR_TABLE_NAME'
GROUP BY DS.TABLESPACE_NAME, SEGMENT_NAME;
Here are the simple ways to every date format confusions:
for current date:
var current_date=new Date();
to get the Timestamp of current date:
var timestamp=new Date().getTime();
to convert a particular Date into Timestamp:
var timestamp_formation=new Date('mm/dd/yyyy').getTime();
to convert timestamp into Date:
var timestamp=new Date('02/10/2016').getTime();
var todate=new Date(timestamp).getDate();
var tomonth=new Date(timestamp).getMonth()+1;
var toyear=new Date(timestamp).getFullYear();
var original_date=tomonth+'/'+todate+'/'+toyear;
OUTPUT:
02/10/2016
just add display: inline-block; property and removed width.
It doesn't work because you didn't attach the ScrollPane to the JFrame.
Also, you don't need 2 JScrollPanes:
JFrame frame = new JFrame ("Test");
JTextArea textArea = new JTextArea ("Test");
JScrollPane scroll = new JScrollPane (textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.add(scroll);
frame.setVisible (true);
It is quite possible in HTML 5. Your options are: Embedded SVG and <canvas>
tag.
To draw circle in embedded SVG:
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
<circle cx="50" cy="50" r="50" fill="red" />_x000D_
</svg>
_x000D_
Circle in <canvas>
:
var canvas = document.getElementById("circlecanvas");_x000D_
var context = canvas.getContext("2d");_x000D_
context.arc(50, 50, 50, 0, Math.PI * 2, false);_x000D_
context.fillStyle = "red";_x000D_
context.fill()
_x000D_
<canvas id="circlecanvas" width="100" height="100"></canvas>
_x000D_
Prakash is correct that the declarations are the same, although a little more explanation of the pointer case might be in order.
"const int* p" is a pointer to an int that does not allow the int to be changed through that pointer. "int* const p" is a pointer to an int that cannot be changed to point to another int.
See https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-ptr-const.
I searched for a solution to parse very large files (gbs) line by line using a stream. All the third-party libraries and examples did not suit my needs since they processed the files not line by line (like 1 , 2 , 3 , 4 ..) or read the entire file to memory
The following solution can parse very large files, line by line using stream & pipe. For testing I used a 2.1 gb file with 17.000.000 records. Ram usage did not exceed 60 mb.
First, install the event-stream package:
npm install event-stream
Then:
var fs = require('fs')
, es = require('event-stream');
var lineNr = 0;
var s = fs.createReadStream('very-large-file.csv')
.pipe(es.split())
.pipe(es.mapSync(function(line){
// pause the readstream
s.pause();
lineNr += 1;
// process line here and call s.resume() when rdy
// function below was for logging memory usage
logMemoryUsage(lineNr);
// resume the readstream, possibly from a callback
s.resume();
})
.on('error', function(err){
console.log('Error while reading file.', err);
})
.on('end', function(){
console.log('Read entire file.')
})
);
Please let me know how it goes!
As long as there are no identity columns you can just
INSERT INTO TableNew
SELECT * FROM TableOld
WHERE [Conditions]
Try using the following pattern in scanf
. It will read until the end of the line:
scanf("%d\n", &n)
You won't need the getchar()
inside the loop since scanf
will read the whole line. The floats won't match the scanf
pattern and the prompt will ask for an integer again.
Specify the Class Card for the constructor-:
void Card::Card(Card::Rank rank, Card::Suit suit) {
And also define the default constructor and destructor.
In pyspark,SparkSql syntax:
where column_n like 'xyz%'
might not work.
Use:
where column_n RLIKE '^xyz'
This works perfectly fine.
String to byte array: "FooBar".split('').map(c => c.charCodeAt(0));
Byte array to string: [102, 111, 111, 98, 97, 114].map(c => String.fromCharCode(c)).join('');
On Visual Studio if you right click on the solution and Manage nuget packages theres a "Consolidate" tab which sets all the packages to the same version.
Hi,
Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.
Here how I do that...
# Accesible Index Page
<IfModule dir_module>
DirectoryIndex index.php index.html
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>
The above code simply captures any index.* and redirect it to the main domain.
Thank you
We have a react application and our development machines are both mac and pc. The start command doesn't work for PC so here is how we got around it:
"start": "PORT=3001 react-scripts start",
"start-pc": "set PORT=3001&& react-scripts start",
On my mac:
npm start
On my pc:
npm run start-pc
Sadly, this is not possible by default to use section
as another user suggested, since a section
is only available to the immediate child
of a View
.
What works however is implementing and redefining the section
in every view, meaning:
section Head
{
@RenderSection("Head", false)
}
This way every view can implement a head section, not just the immediate children. This only works partly though, especially with multiple partials the troubles begin (as you have mentioned in your question).
So the only real solution to your problem is using the ViewBag
. The best would probably be a seperate collection (list) for CSS and scripts. For this to work, you need to ensure that the List
used is initialized before any of the views are executed. Then you can can do things like this in the top of every view/partial (without caring if the Scripts
or Styles
value is null:
ViewBag.Scripts.Add("myscript.js");
ViewBag.Styles.Add("mystyle.css");
In the layout you can then loop through the collections and add the styles based on the values in the List
.
@foreach (var script in ViewBag.Scripts)
{
<script type="text/javascript" src="@script"></script>
}
@foreach (var style in ViewBag.Styles)
{
<link href="@style" rel="stylesheet" type="text/css" />
}
I think it's ugly, but it's the only thing that works.
******UPDATE****
Since it starts executing the inner views first and working its way out to the layout and CSS styles are cascading, it would probably make sense to reverse the style list via ViewBag.Styles.Reverse()
.
This way the most outer style is added first, which is inline with how CSS style sheets work anyway.
function validateDate($date, $format = 'Y-m-d H:i:s')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
This is the simple example to use both of them:
import {
Directive, HostListener, HostBinding
}
from '@angular/core';
@Directive({
selector: '[Highlight]'
})
export class HighlightDirective {
@HostListener('mouseenter') mouseover() {
this.backgroundColor = 'green';
};
@HostListener('mouseleave') mouseleave() {
this.backgroundColor = 'white';
}
@HostBinding('style.backgroundColor') get setColor() {
return this.backgroundColor;
};
private backgroundColor = 'white';
constructor() {}
}
Introduction:
HostListener can bind an event to the element.
HostBinding can bind a style to the element.
this is directive, so we can use it for
Some TextSo according to the debug, we can find that this div has been binded style = "background-color:white"
Some Textwe also can find that EventListener of this div has two event: mouseenter
and mouseleave
. So when we move the mouse into the div, the colour will become green, mouse leave, the colour will become white.
My suggestion to you is to write your own utility service. You can include the service in each controller or create a parent controller, assign the utility service to your scope and then every child controller will inherit this without you having to include it.
Example: http://plnkr.co/edit/NI7V9cLkQmEtWO36CPXy?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, Utils) {
$scope.utils = Utils;
});
app.controller('ChildCtrl', function($scope, Utils) {
$scope.undefined1 = Utils.isUndefinedOrNull(1); // standard DI
$scope.undefined2 = $scope.utils.isUndefinedOrNull(1); // MainCtrl is parent
});
app.factory('Utils', function() {
var service = {
isUndefinedOrNull: function(obj) {
return !angular.isDefined(obj) || obj===null;
}
}
return service;
});
Or you could add it to the rootScope as well. Just a few options for extending angular with your own utility functions.
This is a bit confusing, but follow these steps to save the session.
To open the session, double click on particular saved session.
It depends if you know the given variable Type. If you expect it to be an Object than you could check if myVar is an empty Object like this:
public isEmpty(myVar): boolean {
return (myVar && (Object.keys(myVar).length === 0));
}
Otherwise: if (!myVar) {}, should do the job
If "budget" has any NaN values but you don't want it to sum to NaN then try:
def fun (b, a):
if math.isnan(b):
return a
else:
return b + a
f = np.vectorize(fun, otypes=[float])
df['variance'] = f(df['budget'], df_Lp['actual'])
Simplest solution is the following:
=(NEW/OLD-1)*SIGN(OLD)
The SIGN()
function will result in -1
if the value is negative and 1
if the value is positive. So multiplying by that will conditionally invert the result if the previous value is negative.
In pre-7 how about:
Boolean caught = true;
Exception e;
try {
...
caught = false;
} catch (TransformerException te) {
e = te;
} catch (SocketException se) {
e = se;
} catch (IOException ie) {
e = ie;
}
if (caught) {
someCode(); // You can reference Exception e here.
}
I've run into this problem a few times opening old projects that include other Android libraries. What works for me is to:
move Android to the top in the Order and Export tab and deselecting it.
Yes, this really makes the difference. Maybe it's time for me to ditch ADT for Android Studio!
In my case, I had the variable named "AWS_PROFILE" on Environment variables with an old value.
if (str == null || str.trim().length() == 0) {
// str is empty
}
APScheduler might be what you are after.
from datetime import date
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
# Define the function that is to be executed
def my_job(text):
print text
# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)
# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])
# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])
https://apscheduler.readthedocs.io/en/latest/
You can just get it to schedule another run by building that into the function you are scheduling.
If you would like to remove active session/project/folder then you can follow
Click the "Remove Active Session" button in the toolbar of the "Coverage" view.
According to Mozilla MDN: "The X-Forwarded-For (XFF) header is a de-facto standard header for identifying the originating IP address of a client."
They publish clear information in their X-Forwarded-For article.
a very common try_files line which can be applied on your condition is
location / {
try_files $uri $uri/ /test/index.html;
}
you probably understand the first part, location /
matches all locations, unless it's matched by a more specific location, like location /test
for example
The second part ( the try_files
) means when you receive a URI that's matched by this block try $uri
first, for example http://example.com/images/image.jpg
nginx will try to check if there's a file inside /images
called image.jpg
if found it will serve it first.
Second condition is $uri/
which means if you didn't find the first condition $uri
try the URI as a directory, for example http://example.com/images/
, ngixn will first check if a file called images
exists then it wont find it, then goes to second check $uri/
and see if there's a directory called images
exists then it will try serving it.
Side note: if you don't have autoindex on
you'll probably get a 403 forbidden error, because directory listing is forbidden by default.
EDIT: I forgot to mention that if you have
index
defined, nginx will try to check if the index exists inside this folder before trying directory listing.
Third condition /test/index.html
is considered a fall back option, (you need to use at least 2 options, one and a fall back), you can use as much as you can (never read of a constriction before), nginx will look for the file index.html
inside the folder test
and serve it if it exists.
If the third condition fails too, then nginx will serve the 404 error page.
Also there's something called named locations, like this
location @error {
}
You can call it with try_files
like this
try_files $uri $uri/ @error;
TIP: If you only have 1 condition you want to serve, like for example inside folder images
you only want to either serve the image or go to 404 error, you can write a line like this
location /images {
try_files $uri =404;
}
which means either serve the file or serve a 404 error, you can't use only $uri
by it self without =404
because you need to have a fallback option.
You can also choose which ever error code you want, like for example:
location /images {
try_files $uri =403;
}
This will show a forbidden error if the image doesn't exist, or if you use 500 it will show server error, etc ..
Visual Studio Express for Windows needs Windows 8.1. Having a look at the requirements page you might want to try the Web or Windows Desktop version which are able to run under Windows 7.
Add theme @style/Theme.AppCompat.Light.NoActionBar in your activity on AndroidManifest.xml like this
<activity
android:name=".activities.MainActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>
Simple method to do this approach. Firstly implements the OnClickListeners
in your Activity class.
Code:
class MainActivity extends Activity implements OnClickListeners{
protected void OnCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(R.layout.activity_main.xml);
Button b1=(Button)findViewById(R.id.sipsi);
Button b2=(Button)findViewById(R.id.pipsi);
b1.SetOnClickListener(this);
b2.SetOnClickListener(this);
}
public void OnClick(View V)
{
int i=v.getId();
switch(i)
{
case R.id.sipsi:
{
//you can do anything from this button
break;
}
case R.id.pipsi:
{
//you can do anything from this button
break;
}
}
}
select *
from my_table
where length( Name ) = (
select max( length( Name ) )
from my_table
limit 1
);
It this involves two table scans, and so might not be very fast !
It's easy to create this yourself
In your layout include the following ProgressBar
with a specific drawable (note you should get the width from dimensions instead). The max value is important here:
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:max="500"
android:progress="0"
android:progressDrawable="@drawable/circular" />
Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius
instead of innerRadiusRatio
) and thickness values.
circular (Pre Lollipop OR API Level < 21)
<shape
android:innerRadiusRatio="2.3"
android:shape="ring"
android:thickness="3.8sp" >
<solid android:color="@color/yourColor" />
</shape>
circular ( >= Lollipop OR API Level >= 21)
<shape
android:useLevel="true"
android:innerRadiusRatio="2.3"
android:shape="ring"
android:thickness="3.8sp" >
<solid android:color="@color/yourColor" />
</shape>
useLevel is "false" by default in API Level 21 (Lollipop) .
Start Animation
Next in your code use an ObjectAnimator
to animate the progress field of the ProgessBar
of your layout.
ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();
Stop Animation
progressBar.clearAnimation();
P.S. unlike examples above, it give smooth animation.
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
My own experience with this problem is as follows. Most Spring-related web pages and books seem to suggest that the most appropriate syntax is the following.
<mvc:resources mapping="/resources/**" location="/resources/" />
The above syntax suggests that you can place your static resources (CSS, JavaScript, images) in a folder named "resources" in the root of your application, i.e. /webapp/resources/.
However, in my experience (I am using Eclipse and the Tomcat plugin), the only approach that works is if you place your resources folder inside WEB_INF (or META-INF). So, the syntax I recommend is the following.
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
In your JSP (or similar) , reference the resource as follows.
<script type="text/javascript"
src="resources/my-javascript.js">
</script>
Needless to mention, the entire question only arose because I wanted my Spring dispatcher servlet (front controller) to intercept everything, everything dynamic, that is. So I have the following in my web.xml.
<servlet>
<servlet-name>front-controller</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
<!-- spring automatically discovers /WEB-INF/<servlet-name>-servlet.xml -->
</servlet>
<servlet-mapping>
<servlet-name>front-controller</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Finally, since I'm using current best practices, I have the following in my front controller servlet xml (see above).
<mvc:annotation-driven/>
And I have the following in my actual controller implementation, to ensure that I have a default method to handle all incoming requests.
@RequestMapping("/")
I hope this helps.
> and <
is a character entity reference for the >
and <
character in HTML.
It is not possible to use the less than (<) or greater than (>) signs in your file, because the browser will mix them with tags.
for these difficulties you can use entity names(>
) and entity numbers(<
).
Here are a few things you need to do:
1-Download the library if you haven't already done that.
2- Import into Eclipse.
3- Set you project to use the library: Project-> Properties -> Android -> Scroll down to Library section, click Add... and select viewpagerindicator.
4- Now you should be able to import com.viewpagerindicator.TitlePageIndicator
.
Now about implementing this without using fragments:
In the sample that comes with viewpagerindicatior, you can see that the library is being used with a ViewPager
which has a FragmentPagerAdapter
.
But in fact the library itself is Fragment
independant. It just needs a ViewPager
.
So just use a PagerAdapter
instead of a FragmentPagerAdapter
and you're good to go.
For me It worked by passing html tag in props children
<MyComponent>This is <strong>not</strong> working.</MyComponent>
var MyComponent = React.createClass({
render: function() {
return (
<div>this.props.children</div>
);
},
Quote from the Spring reference doc:
Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there...
Your servlet is called spring-dispatcher
, so it looks for /WEB-INF/spring-dispatcher-servlet.xml
. You need to have this servlet configuration, and define web related beans in there (like controllers, view resolvers, etc). See the linked documentation for clarification on the relation of servlet contexts to the global application context (which is the app-config.xml
in your case).
One more thing, if you don't like the naming convention of the servlet config xml, you can specify your config explicitly:
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Here is a working solution:
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
char str1[16];
char str2[16];
strcpy(str1, "sssss");
strcpy(str2, "kkkk");
strcat(str1, str2);
printf("%s", str1);
return 0;
}
Output:
ssssskkkk
You have to allocate memory for your strings. In the above code, I declare str1
and str2
as character arrays containing 16 characters. I used strcpy
to copy characters of string literals into them, and strcat
to append the characters of str2
to the end of str1
. Here is how these character arrays look like during the execution of the program:
After declaration (both are empty):
str1: [][][][][][][][][][][][][][][][][][][][]
str2: [][][][][][][][][][][][][][][][][][][][]
After calling strcpy (\0 is the string terminator zero byte):
str1: [s][s][s][s][s][\0][][][][][][][][][][][][][][]
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
After calling strcat:
str1: [s][s][s][s][s][k][k][k][k][\0][][][][][][][][][][]
str2: [k][k][k][k][\0][][][][][][][][][][][][][][][]
If you're on the New Google Sheets, this is all you need to do, according to the docs:
change your recalculation setting to "On change and every minute" in your spreadsheet at File > Spreadsheet settings.
This will make the entire sheet update itself every minute, on the server side, regardless of whether you have the spreadsheet up in your browser or not.
If you're on the old Google Sheets, you'll want to add a cell with this formula to achieve the same functionality:
=GoogleClock()
EDIT to include old and new Google Sheets and change to =GoogleClock()
.
Use Point data type to store Longitude and Latitude in a single column:
CREATE TABLE table_name (
id integer NOT NULL,
name text NOT NULL,
location point NOT NULL,
created_on timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT table_name_pkey PRIMARY KEY (id)
)
Create an Indexing on a 'location' column :
CREATE INDEX ON table_name USING GIST(location);
GiST index is capable of optimizing “nearest-neighbor” search :
SELECT * FROM table_name ORDER BY location <-> point '(-74.013, 40.711)' LIMIT 10;
Note: The point first element is longitude and the second element is latitude.
For more info check this Query Operators.
Another case I just had - when the request size is bigger than the request size set in IIS as a limit, then you can get that error too.
Check the IIS request limit and increase it if it's lower than you need. Here is how you can check and change the IIS request limit:
I just found also another thread in stack IIS 7.5 hosted WCF service throws EndpointNotFoundException with 404 only for large requests
Thanks - this is one of 2 links that com up if you google for php apache windows absolute path.
As a newbie to intermed PHP developer I didnt understand why absolute paths on apache windopws systems would be c:\xampp\htdocs (apache document root - XAMPP default) instead of /
thus if in http//localhost/myapp/subfolder1/subfolder2/myfile.php I wanted to include a file from http//localhost/myapp
I would need to specify it as: include("c:\xampp\htdocs\myapp\includeme.php") or include("../../includeme.php")
AND NOT include("/myapp/includeme.php")
Better just create a XLSX file with field names on top row. Create it manually or using Mockaroo. Export it to Excel(or CSV) and then import it to Access using New Data Source -> From File
IMHO it's the best and most performant way to do it in Access.
As you probably already know, there's no "foreach"-style loop in C.
Although there are already tons of great macros provided here to work around this, maybe you'll find this macro useful:
// "length" is the length of the array.
#define each(item, array, length) \
(typeof(*(array)) *p = (array), (item) = *p; p < &((array)[length]); p++, (item) = *p)
...which can be used with for
(as in for each (...)
).
Advantages of this approach:
item
is declared and incremented within the for statement (just like
in Python!).p
, item
), aren't visible outside the
scope of the loop (since they're declared in the for loop header).Disadvantages:
typeof()
, which is a GNU extension, not part of standard CJust to save you some time, here's how you could test it:
typedef struct {
double x;
double y;
} Point;
int main(void) {
double some_nums[] = {4.2, 4.32, -9.9, 7.0};
for each (element, some_nums, 4)
printf("element = %lf\n", element);
int numbers[] = {4, 2, 99, -3, 54};
// Just demonstrating it can be used like a normal for loop
for each (number, numbers, 5) {
printf("number = %d\n", number);
if (number % 2 == 0)
printf("%d is even.\n", number);
}
char* dictionary[] = {"Hello", "World"};
for each (word, dictionary, 2)
printf("word = '%s'\n", word);
Point points[] = {{3.4, 4.2}, {9.9, 6.7}, {-9.8, 7.0}};
for each (point, points, 3)
printf("point = (%lf, %lf)\n", point.x, point.y);
// Neither p, element, number or word are visible outside the scope of
// their respective for loops. Try to see if these printfs work
// (they shouldn't):
// printf("*p = %s", *p);
// printf("word = %s", word);
return 0;
}
Seems to work on gcc and clang by default; haven't tested other compilers.
I would just do a table.
<div class="elastic">
<div class="elastic_col valign-bottom">
bottom-aligned content.
</div>
</div>
And the CSS:
.elastic {
display: table;
}
.elastic_col {
display: table-cell;
}
.valign-bottom {
vertical-align: bottom;
}
See it in action:
http://jsfiddle.net/mLphM/1/
I can' t comment yet but, just a hint: use try/catch clauses to avoid breaking the pipeline (if you are sure the file exists, disregard)
pipeline {
agent any
stages {
stage("foo") {
steps {
script {
try {
env.FILENAME = readFile 'output.txt'
echo "${env.FILENAME}"
}
catch(Exception e) {
//do something, e.g. echo 'File not found'
}
}
}
}
Another hint (this was commented by @hao, and think is worth to share): you may want to trim like this readFile('output.txt').trim()
You could use a negative look-ahead assertion:
^(?!tbd_).+
Or a negative look-behind assertion:
(^.{1,3}$|^.{4}(?<!tbd_).*)
Or just plain old character sets and alternations:
^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*
Same problem, I have just purged cache
rm -rf var/cache/*
Et voila ! I don't understand what it was...
Two quick possibilities:
if(!('foo' in myObj)) { ... }
or
if(myObj['foo'] === undefined) { ... }
In addition to the most upvoted answer here, one can also chain axhline
after calling plot
on a pandas
's DataFrame
.
import pandas as pd
(pd.DataFrame([1, 2, 3])
.plot(kind='bar', color='orange')
.axhline(y=1.5));
To improve on Johnny's answer, this can now be done using the public API as follows :
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let moreRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "More", handler:{action, indexpath in
print("MORE•ACTION");
});
moreRowAction.backgroundColor = UIColor(red: 0.298, green: 0.851, blue: 0.3922, alpha: 1.0);
let deleteRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "Delete", handler:{action, indexpath in
print("DELETE•ACTION");
});
return [deleteRowAction, moreRowAction];
}
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> items, int maxItems)
{
return items.Select((item, index) => new { item, index })
.GroupBy(x => x.index / maxItems)
.Select(g => g.Select(x => x.item));
}
You could also use a CTE to grab groups of information you want and join them together, if you wanted them in the same row. Example, depending on which SQL syntax you use, here:
WITH group1 AS (
SELECT testA
FROM tableA
),
group2 AS (
SELECT testB
FROM tableB
)
SELECT *
FROM group1
JOIN group2 ON group1.testA = group2.testB --your choice of join
;
You decide what kind of JOIN you want based on the data you are pulling, and make sure to have the same fields in the groups you are getting information from in order to put it all into a single row. If you have multiple columns, make sure to name them all properly so you know which is which. Also, for performance sake, CTE's are the way to go, instead of inline SELECT's and such. Hope this helps.
+----------------+-----------------------------+---------------------------+
| | val | var |
+----------------+-----------------------------+---------------------------+
| Reference type | Immutable(once initialized | Mutable(can able to change|
| | can't be reassigned) | value) |
+----------------+-----------------------------+---------------------------+
| Example | val n = 20 | var n = 20 |
+----------------+-----------------------------+---------------------------+
| In Java | final int n = 20; | int n = 20; |
+----------------+-----------------------------+---------------------------+
Try this replaceAll: http://dumpsite.com/forum/index.php?topic=4.msg8#msg8
String.prototype.replaceAll = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
}
It is very fast, and it will work for ALL these conditions that many others fail on:
"x".replaceAll("x", "xyz");
// xyz
"x".replaceAll("", "xyz");
// xyzxxyz
"aA".replaceAll("a", "b", true);
// bb
"Hello???".replaceAll("?", "!");
// Hello!!!
Let me know if you can break it, or you have something better, but make sure it can pass these 4 tests.
You can use the SelectedItem
property to get the currently selected object, which you can then cast into the correct type. For instance, if your DataGrid
is bound to a collection of Customer
objects you could do this:
Customer customer = (Customer)myDataGrid.SelectedItem;
Alternatively you can bind SelectedItem
to your source class or ViewModel
.
<Grid DataContext="MyViewModel">
<DataGrid ItemsSource="{Binding Path=Customers}"
SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
</Grid>
set one more property curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
There's a client profile usable version, System.Net.WebUtility class, present in client profile System.dll. Here's the MSDN Link:
Insert your fetched values into an array instead of echoing.
Use file_put_contents()
and insert json_encode($rows)
into that file, if $rows
is your data.
In cs file:
private DataTable _dataTable;
public DataTable DataTable
{
get { return _dataTable; }
set { _dataTable = value; }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this._dataTable = new DataTable("table");
this._dataTable.Columns.Add("col0");
this._dataTable.Columns.Add("col1");
this._dataTable.Columns.Add("col2");
this._dataTable.Rows.Add("data00", "data01", "data02");
this._dataTable.Rows.Add("data10", "data11", "data22");
this._dataTable.Rows.Add("data20", "data21", "data22");
this.grid1.DataContext = this;
}
In Xaml file:
<DataGrid x:Name="grid1"
Margin="10"
AutoGenerateColumns="True"
ItemsSource="{Binding Path=DataTable, Mode=TwoWay}" />
No.
An ArrayList can be empty (or with nulls as items) an not be null. It would be considered empty. You can check for am empty ArrayList with:
ArrayList arrList = new ArrayList();
if(arrList.isEmpty())
{
// Do something with the empty list here.
}
Or if you want to create a method that checks for an ArrayList with only nulls:
public static Boolean ContainsAllNulls(ArrayList arrList)
{
if(arrList != null)
{
for(object a : arrList)
if(a != null) return false;
}
return true;
}
You can use the ToString overload. Have a look at this page for more info
So just Use myDate.ToString("yyyy-MM-dd HH:mm:ss")
or something equivalent
If you are trying to load the image at your form_load, it's a better idea to use the code
pictureBox1.LoadAsync(@"http://google.com/test.png");
not only loading from web but also no lag in your form loading.
You can also use try...except
:
try:
int(string[0])
# do your stuff
except:
pass # or do your stuff
Both functions use the os.path.split(path)
function to split the pathname path
into a pair; (head, tail)
.
The os.path.dirname(path)
function returns the head of the path.
E.g.: The dirname of '/foo/bar/item'
is '/foo/bar'
.
The os.path.basename(path)
function returns the tail of the path.
E.g.: The basename of '/foo/bar/item'
returns 'item'
From: http://docs.python.org/2/library/os.path.html#os.path.basename
I resolved the issue changing the behavior of shouldChangeChractersInRange. If you return NO the changes won't be applied by iOS internally, instead you have the opportunity to change it manually and perform any actions after the changes.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//Replace the string manually in the textbox
textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
//perform any logic here now that you are sure the textbox text has changed
[self didChangeTextInTextField:textField];
return NO; //this make iOS not to perform any action
}
Here's an alternative since you don't like the cast to int:
foreach(byte b in System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()))
Console.Write(b.ToString());
I am working on a program that saves its data properly to %APPDATA%, but sometimes, there are system-wide settings that affect all users. So in these situations, it HAS to write to the programs installation directory.
And as far as I have read now, it's impossible to temporarily get write access to one directory. You can only run the whole application as administrator (which should be out of the question) or not be able to save that file. (all or nothing)
I guess, I will just write the file to %APPDATA% and launch an external program that copies the file into the installation folder and have THAT program demand admin privileges... dumb idea, but seems to be the only practical solution...
For me, all I had to do is add maxReceivedMessageSize="2147483647"
to the client app.config. The server left untouched.
The e
argument is short for the event object. For example, you might want to create code for anchors that cancels the default action. To do this you would write something like:
$('a').click(function(e) {
e.preventDefault();
}
This means when an <a>
tag is clicked, prevent the default action of the click event.
While you may see it often, it's not something you have to use within the function even though you have specified it as an argument.
Looking at your other question I assume you are trying to run a php or asp file or something on your webserver and this is your first attempt in webdesign.
Once you have installed php correctly (which you probably did when you got XAMPP) just place whatever file you want under your localhost (/www/var/html perhaps?) and it should run. You can check this of course at localhost/file.php in your browser.
When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1
Appending to and copying slices
The variadic function
append
appends zero or more valuesx
tos
of typeS
, which must be a slice type, and returns the resulting slice, also of typeS
. The valuesx
are passed to a parameter of type...T
whereT
is the element type ofS
and the respective parameter passing rules apply. As a special case, append also accepts a first argument assignable to type[]byte
with a second argument ofstring
type followed by...
. This form appends the bytes of the string.append(s S, x ...T) S // T is the element type of S s0 := []int{0, 0} s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2} s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7} s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
Passing arguments to ... parameters
If
f
is variadic with final parameter type...T
, then within the function the argument is equivalent to a parameter of type[]T
. At each call off
, the argument passed to the final parameter is a new slice of type[]T
whose successive elements are the actual arguments, which all must be assignable to the typeT
. The length of the slice is therefore the number of arguments bound to the final parameter and may differ for each call site.
The answer to your question is example s3 := append(s2, s0...)
in the Go Programming Language Specification. For example,
s := append([]int{1, 2}, []int{3, 4}...)
Before your </form>
tag put:
{{ form_rest(form) }}
It will automatically insert other important (hidden) inputs.
You can set this using the Sys.setenv()
function. My R session defaults to English, so I'll set it to French and then back again:
> Sys.setenv(LANG = "fr")
> 2 + x
Erreur : objet 'x' introuvable
> Sys.setenv(LANG = "en")
> 2 + x
Error: object 'x' not found
A list of the abbreviations can be found here.
Sys.getenv()
gives you a list of all the environment variables that are set.
You must need to also implement Parcelable interface and must add writeToParcel method to your Questions class with Parcel argument in Constructor in addition to Serializable. otherwise app will crash.
This worked for me, within an ASP.NET MVC3 site where I'd left the framework to setup unobtrusive validation etc., in case it's useful to anyone:
$("form").data("validator").settings.ignore = "";