You're already prepending the hash sign in your showDialog()
function, and you're missing single quotes in your second code snippet. You should also return false
from the handler to prevent a postback from occurring. Try:
<asp:Button ID="ButtonAdd" runat="server" Text="Add"
OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />
You can use jackson api for the conversion
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
add above maven dependency in your POM, In your main method create ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
later we nee to add our POJO class to the mapper
String json = mapper.writeValueAsString(pojo);
For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services
From the above referenced site:
Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.
Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.
Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.
You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.
Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx
If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx
If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx
If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx
If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx
Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx
Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx
Yes, assuming the account has appropriate permissions you can use:
SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;
You just need to prefix the table reference with the name of the database it resides in.
For me it was the JDK that was not set up correctly. I found a solution that I documented here: https://stackoverflow.com/a/40127871/808723
If you have Response Like This:
{
"registeration_method": "email",
"is_stucked": true,
"individual": {
"id": 24099,
"first_name": "ahmad",
"last_name": "zozoz",
"email": null,
"mobile_number": null,
"confirmed": false,
"avatar": "http://abc-abc-xyz.amazonaws.com/images/placeholder-profile.png",
"doctor_request_status": 0
},
"max_number_of_confirmation_trials": 4,
"max_number_of_invalid_confirmation_trials": 12
}
and you want to check for value is_stucked
which will be read as AnyObject, all you have to do is this
if let isStucked = response["is_stucked"] as? Bool{
if isStucked{
print("is Stucked")
}
else{
print("Not Stucked")
}
}
PORT 4369: Erlang makes use of a Port Mapper Daemon (epmd) for resolution of node names in a cluster. Nodes must be able to reach each other and the port mapper daemon for clustering to work.
PORT 35197 set by inet_dist_listen_min/max Firewalls must permit traffic in this range to pass between clustered nodes
RabbitMQ Management console:
PORT 5672
RabbitMQ main port.
For a cluster of nodes, they must be open to each other on 35197
, 4369
and 5672
.
For any servers that want to use the message queue, only 5672
is required.
Got to
gradle-wrapper.properties
Change the version of the below mentioned distribution (gradle-5.6.4-bin.zip)
distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-bin.zip
set vimdiff to ignore case
Having started vim diff with
gvim -d main.sql backup.sql &
I find that annoyingly one file has MySQL keywords in lowercase the other uppercase showing differences on practically every other line
:set diffopt+=icase
this updates the screen dynamically & you can just as easily switch it off again
Note that a select list is posted as null, hence your error complains that the viewdata property cannot be found.
Always reinitialize your select list within a POST action.
For further explanation: Persist SelectList in model on Post
Further to this, the return type is determined by
What the HTTP Request says it wants - in its Accept header. Try looking at the initial request as see what Accept is set to.
What HttpMessageConverters Spring sets up. Spring MVC will setup converters for XML (using JAXB) and JSON if Jackson libraries are on he classpath.
If there is a choice it picks one - in this example, it happens to be JSON.
This is covered in the course notes. Look for the notes on Message Convertors and Content Negotiation.
The working directory is a common concept across virtually all operating systems and program languages etc. It's the directory in which your program is running. This is usually (but not always, there are ways to change it) the directory the application is in.
Relative paths are ones that start without a drive specifier. So in linux they don't start with a /
, in windows they don't start with a C:\
, etc. These always start from your working directory.
Absolute paths are the ones that start with a drive (or machine for network paths) specifier. They always go from the start of that drive.
This will create a completely fullscreen window on mac (with no visible menubar) without messing up keybindings
import tkinter as tk
root = tk.Tk()
root.overrideredirect(True)
root.overrideredirect(False)
root.attributes('-fullscreen',True)
root.mainloop()
The no-op command in shell is :
(colon).
if [ "$a" -ge 10 ]
then
:
elif [ "$a" -le 5 ]
then
echo "1"
else
echo "2"
fi
From the bash manual:
:
(a colon)
Do nothing beyond expanding arguments and performing redirections. The return status is zero.
I suppose your p2vg table has also an id field , in that case , postgres cannot find if the id in the SELECT
refers to vg or p2vg.
you should use SELECT(vg.id,vg.name)
to remove ambiguity
pytest constantly evolves and with one of the nice changes in the recent past it is now possible to simultaneously test for
Two examples from the documentation:
with pytest.raises(ValueError, match='must be 0 or None'):
raise ValueError('value must be 0 or None')
with pytest.raises(ValueError, match=r'must be \d+$'):
raise ValueError('value must be 42')
I have been using that approach in a number of projects and like it very much.
I think this is what you want, I already tested this code and works
The tools used are: (all these tools can be downloaded as Nuget packages)
http://fluentassertions.codeplex.com/
http://autofixture.codeplex.com/
https://nuget.org/packages/AutoFixture.AutoMoq
var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();
var sut = fixture.CreateAnonymous<Transfer>();
myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
.Throws<System.IO.IOException>();
sut.Invoking(x =>
x.TransferFiles(
myInterface.Object,
It.IsAny<string>(),
It.IsAny<string>()
))
.ShouldThrow<System.IO.IOException>();
Edited:
Let me explain:
When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer
So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code
When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs
In this case your external dependency is IFileConnection
so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected
var fixture = new Fixture().Customize(new AutoMoqCustomization());
: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq
var myInterface = fixture.Freeze<Mock<IFileConnection>>();
: This freezes the IFileConnection
dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object
var sut = fixture.CreateAnonymous<Transfer>();
: Here AutoFixture is creating the SUT for us
myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>();
Here you are configuring the dependency to throw an exception whenever the Get
method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception
sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();
: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles
real method from the SUT and as parameters it receives the mocked IFileConnection
so whenever you call the IFileConnection.Get
in the normal flow of your SUT TransferFiles
method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>()
(from the FluentAssertions library)
References recommended:
http://martinfowler.com/articles/mocksArentStubs.html
http://misko.hevery.com/code-reviewers-guide/
http://misko.hevery.com/presentations/
http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded
http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded
The Oracle JDeveloper 11g built-in viewer is in my view superior to the one available for Eclipse (which, in addition to other unfavourable comparison points I could only get to install for Indigo but not for Juno). If I am not mistaken Oracle makes the JDeveloper available for free (only requires registration at the OTN).
This is called type methods, and are called with dot syntax, like instance methods. However, you call type methods on the type, not on an instance of that type. Here’s how you call a type method on a class called SomeClass:
Within Nano use Ctrl+O to save and Ctrl+X to exit if you were wondering
I found the following css in order to style a Bootstrap input for a jquery autocomplete:
https://gist.github.com/daz/2168334#file-style-scss
.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
_width: 160px;
padding: 4px 0;
margin: 2px 0 0 0;
list-style: none;
background-color: #ffffff;
border-color: #ccc;
border-color: rgba(0, 0, 0, 0.2);
border-style: solid;
border-width: 1px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
*border-right-width: 2px;
*border-bottom-width: 2px;
}
.ui-menu-item > a.ui-corner-all {
display: block;
padding: 3px 15px;
clear: both;
font-weight: normal;
line-height: 18px;
color: #555555;
white-space: nowrap;
}
.ui-state-hover, &.ui-state-active {
color: #ffffff;
text-decoration: none;
background-color: #0088cc;
border-radius: 0px;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
background-image: none;
}
Okay, everyone here as a different opinion as to the tradeoffs and advantages of xrange versus range. They're mostly correct, xrange is an iterator, and range fleshes out and creates an actual list. For the majority of cases, you won't really notice a difference between the two. (You can use map with range but not with xrange, but it uses up more memory.)
What I think you rally want to hear, however, is that the preferred choice is xrange. Since range in Python 3 is an iterator, the code conversion tool 2to3 will correctly convert all uses of xrange to range, and will throw out an error or warning for uses of range. If you want to be sure to easily convert your code in the future, you'll use xrange only, and list(xrange) when you're sure that you want a list. I learned this during the CPython sprint at PyCon this year (2008) in Chicago.
Another approach using the new Swift 2 syntax is to use guard and nest it all in one conditional.
guard let touch = object.AnyObject() as? UITouch, let picker = touch.view as? UIPickerView else {
return //Do Nothing
}
//Do something with picker
This shows the licence type and number of licences:
SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')
Here is my approach that you may try:
import numpy as np
import matplotlib.pyplot as plt
w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
img = np.random.randint(10, size=(h,w))
fig.add_subplot(rows, columns, i)
plt.imshow(img)
plt.show()
The resulting image:
(Original answer date: Oct 7 '17 at 4:20)
Edit 1
Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-
New code:
import numpy as np
import matplotlib.pyplot as plt
w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5
# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60) # from 0 to 2pi
ys = np.abs(np.sin(xs)) # absolute of sine
# ax enables access to manipulate each of subplots
ax = []
for i in range(columns*rows):
img = np.random.randint(10, size=(h,w))
# create subplot and append to ax
ax.append( fig.add_subplot(rows, columns, i+1) )
ax[-1].set_title("ax:"+str(i)) # set title
plt.imshow(img, alpha=0.25)
# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)
plt.show() # finally, render the plot
The resulting plot:
Edit 2
In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index]
, which is more suitable for manipulation of array of many sub-plots.
import matplotlib.pyplot as plt
import numpy as np
# settings
h, w = 10, 10 # for raster image
nrows, ncols = 5, 4 # array of sub-plots
figsize = [6, 8] # figure size, inches
# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60) # from 0 to 2pi
ys = np.abs(np.sin(xs)) # absolute of sine
# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)
# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
# i runs from 0 to (nrows*ncols-1)
# axi is equivalent with ax[rowid][colid]
img = np.random.randint(10, size=(h,w))
axi.imshow(img, alpha=0.25)
# get indices of row/column
rowid = i // ncols
colid = i % ncols
# write row/col indices as axes' title for identification
axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))
# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)
plt.tight_layout(True)
plt.show()
The resulting plot:
If you have Python in your environment variable then you can use the following command in cmd:
where python
or for Unix enviroment
which python
command line image :
If you really don't want to include top directory in the tarball (and that's generally bad idea):
tar czf workspace.tar.gz -C /path/to/workspace .
Go to Preferences
> User Settings
. (Alternatively, Ctrl + , / Cmd + , on macOS)
Then you can type inside the JSON object any settings you want to override. User settings are per user. You can also configure workspace settings, which are for the project that you are currently working on.
Here's an example:
// Controls the font family.
"editor.fontFamily": "Consolas",
// Controls the font size.
"editor.fontSize": 13
Useful links:
You may not pass str
to fit this kind of classifier.
For example, if you have a feature column named 'grade' which has 3 different grades:
A,B and C.
you have to transfer those str
"A","B","C" to matrix by encoder like the following:
A = [1,0,0]
B = [0,1,0]
C = [0,0,1]
because the str
does not have numerical meaning for the classifier.
In scikit-learn, OneHotEncoder
and LabelEncoder
are available in inpreprocessing
module.
However OneHotEncoder
does not support to fit_transform()
of string.
"ValueError: could not convert string to float" may happen during transform.
You may use LabelEncoder
to transfer from str
to continuous numerical values. Then you are able to transfer by OneHotEncoder
as you wish.
In the Pandas dataframe, I have to encode all the data which are categorized to dtype:object
. The following code works for me and I hope this will help you.
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for column_name in train_data.columns:
if train_data[column_name].dtype == object:
train_data[column_name] = le.fit_transform(train_data[column_name])
else:
pass
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
This may work:
jdialog.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.out.println("jdialog window closed event received");
}
public void windowClosing(WindowEvent e) {
System.out.println("jdialog window closing event received");
}
});
Source: https://alvinalexander.com/java/jdialog-close-closing-event
Color is not data.
The Get.cell technique has flaws.
That does not surprise, since the Get.cell uses an old XML command, i.e. a command from the macro language Excel used before VBA was introduced. At that time, Excel colors were limited to less than 60.
Again: Color is not data.
If you want to color-code your cells, use conditional formatting based on the cell values or based on rules that can be expressed with logical formulas. The logic that leads to conditional formatting can also be used in other places to report on the data, regardless of the color value of the cell.
Example: index = False
import pandas as pd
writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save()
It's simpler than I initially thought.. Basically you have a page that does nothing, until the data you want to send is available (say, a new message arrives).
Here is a really basic example, which sends a simple string after 2-10 seconds. 1 in 3 chance of returning an error 404 (to show error handling in the coming Javascript example)
msgsrv.php
<?php
if(rand(1,3) == 1){
/* Fake an error */
header("HTTP/1.0 404 Not Found");
die();
}
/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>
Note: With a real site, running this on a regular web-server like Apache will quickly tie up all the "worker threads" and leave it unable to respond to other requests.. There are ways around this, but it is recommended to write a "long-poll server" in something like Python's twisted, which does not rely on one thread per request. cometD is an popular one (which is available in several languages), and Tornado is a new framework made specifically for such tasks (it was built for FriendFeed's long-polling code)... but as a simple example, Apache is more than adequate! This script could easily be written in any language (I chose Apache/PHP as they are very common, and I happened to be running them locally)
Then, in Javascript, you request the above file (msg_srv.php
), and wait for a response. When you get one, you act upon the data. Then you request the file and wait again, act upon the data (and repeat)
What follows is an example of such a page.. When the page is loaded, it sends the initial request for the msgsrv.php
file.. If it succeeds, we append the message to the #messages
div, then after 1 second we call the waitForMsg function again, which triggers the wait.
The 1 second setTimeout()
is a really basic rate-limiter, it works fine without this, but if msgsrv.php
always returns instantly (with a syntax error, for example) - you flood the browser and it can quickly freeze up. This would better be done checking if the file contains a valid JSON response, and/or keeping a running total of requests-per-minute/second, and pausing appropriately.
If the page errors, it appends the error to the #messages
div, waits 15 seconds and then tries again (identical to how we wait 1 second after each message)
The nice thing about this approach is it is very resilient. If the clients internet connection dies, it will timeout, then try and reconnect - this is inherent in how long polling works, no complicated error-handling is required
Anyway, the long_poller.htm
code, using the jQuery framework:
<html>
<head>
<title>BargePoller</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css" media="screen">
body{ background:#000;color:#fff;font-size:.9em; }
.msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
.old{ background-color:#246499;}
.new{ background-color:#3B9957;}
.error{ background-color:#992E36;}
</style>
<script type="text/javascript" charset="utf-8">
function addmsg(type, msg){
/* Simple helper to add a div.
type is the name of a CSS class (old/new/error).
msg is the contents of the div */
$("#messages").append(
"<div class='msg "+ type +"'>"+ msg +"</div>"
);
}
function waitForMsg(){
/* This requests the url "msgsrv.php"
When it complete (or errors)*/
$.ajax({
type: "GET",
url: "msgsrv.php",
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){ /* called when request to barge.php completes */
addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
setTimeout(
waitForMsg, /* Request next message */
1000 /* ..after 1 seconds */
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg, /* Try again after.. */
15000); /* milliseconds (15seconds) */
}
});
};
$(document).ready(function(){
waitForMsg(); /* Start the inital request */
});
</script>
</head>
<body>
<div id="messages">
<div class="msg old">
BargePoll message requester!
</div>
</div>
</body>
</html>
for file in *.dat ; do mv $file ${file//ABC/XYZ} ; done
No rename
or sed
needed. Just bash parameter expansion.
What is
<=>
( The 'Spaceship' Operator )
<=>
$b - 0 if $a == $b
- -1 if $a < $b
- 1 if $a > $b
- Return 0 if values on either side are equal
- Return 1 if value on the left is greater
- Return -1 if the value on the right is greater
Example:
//Comparing Integers
echo 1 <=> 1; //ouputs 0
echo 3 <=> 4; //outputs -1
echo 4 <=> 3; //outputs 1
//String Comparison
echo "x" <=> "x"; // 0
echo "x" <=> "y"; //-1
echo "y" <=> "x"; //1
MORE:
// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1
// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1
// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1
// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1
// Objects
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 0
to take output in MySQL you can use if statement SYNTAX:
if(condition,if_true,if_false)
the if_true and if_false can be used to verify and to show output as there is no print statement in the MySQL
each
passes into your function index
and element
. Check index
against the length of the set and you're good to go:
var set = $('.requiredText');
var length = set.length;
set.each(function(index, element) {
thisVal = $(this).val();
if(parseInt(thisVal) !== 0) {
console.log('Valid Field: ' + thisVal);
if (index === (length - 1)) {
console.log('Last field, submit form here');
}
}
});
Take a look at class java.lang.Character
static member methods (isDigit, isLetter, isLowerCase, ...)
Example:
String str = "Hello World 123 !!";
int specials = 0, digits = 0, letters = 0, spaces = 0;
for (int i = 0; i < str.length(); ++i) {
char ch = str.charAt(i);
if (!Character.isDigit(ch) && !Character.isLetter(ch) && !Character.isSpace(ch)) {
++specials;
} else if (Character.isDigit(ch)) {
++digits;
} else if (Character.isSpace(ch)) {
++spaces;
} else {
++letters;
}
}
You can delete the browser cache by setting these headers:
<?php
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
Very simple ! Here is my suggestion :
If you want to select dataframes in your workspace, try this :
Filter(function(x) is.data.frame(get(x)) , ls())
or
ls()[sapply(ls(), function(x) is.data.frame(get(x)))]
all these will give the same result.
You can change is.data.frame
to check other types of variables like is.function
According to the MSDN documentation here, The basename argument specifies "The root name of the resource file without its extension but including any fully qualified namespace name. For example, the root name for the resource file named "MyApplication.MyResource.en-US.resources" is "MyApplication.MyResource"."
The ResourceManager will automatically try to retrieve the values for the current UI culture. If you want to use a specific language, you'll need to set the current UI culture to the language you wish to use.
==
has higher precedence than &
. You might want to wrap your operations in ()
to specify how you want your operands to bind to the operators.
((a[0] & 1) == 0)
Similarly for all parts of the if
condition.
This command worked for me,
sudo chmod +x ~/.ssh/known_hosts
16kb is about right; if you're using gigabit ethernet, each packet could be 9kb in size.
Instead of remotely putting popper js from CDN you can directly install it in your angular project.
Try this.
npm install popper.js --save
This query installs an updated version of popper.js Don't mention any version there, it will work for you.
Natural versus artificial keys to me is a matter of how much of the business logic you want in your database. Social Security number (SSN) is a great example.
"Each client in my database will, and must, have an SSN." Bam, done, make it the primary key and be done with it. Just remember when your business rule changes you're burned.
I don't like natural keys myself, due to my experience with changing business rules. But if your sure it won't change, it might prevent a few critical joins.
The __file__
attribute works for both the file containing the main execution code as well as imported modules.
See https://web.archive.org/web/20090918095828/http://pyref.infogami.com/__file__
You can compare class tokens to each other, so you could use value.getClass() == Integer.class
. However, the simpler and more canonical way is to use instanceof
:
if (value instanceof Integer) {
System.out.println("This is an Integer");
} else if(value instanceof String) {
System.out.println("This is a String");
} else if(value instanceof Float) {
System.out.println("This is a Float");
}
Notes:
instanceof C
matches for subclasses of C
too. However, in this case all the classes listed are final
, so they have no subclasses. Thus instanceof
is probably fine here.as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.
System.out.println("This is a(n) " + value.getClass().getSimpleName());
If you load URL from bitmap without using AsyncTask, write two lines after setContentView(R.layout.abc);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch(IOException e) {
System.out.println(e);
}
There might be a cleverer way to go about this, but
intersect(intersect(a,b),c)
will do the job.
EDIT: More cleverly, and more conveniently if you have a lot of arguments:
Reduce(intersect, list(a,b,c))
res/drawble/circle_shape.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="#e42828"/>
<stroke android:color="#3b91d7" android:width="5dp"/>
<!-- Set the same value for both width and height to get a circular shape -->
<size android:width="250dp" android:height="250dp"/>
</shape>
</item>
</selector>
I had the same problem, so I ended up making my own.
It has a template system built in, so you can make the results look like anything you want. Works on all major browsers and accepts arrays & json objects. http://code.google.com/p/custom-combobox/
This turned out to NOT be a bower problem, though it showed up for me with bower.
It seems to be a node-which problem. If a file is in the path, but has the setuid/setgid bit set, which will not find it.
Here is a files with the s bit set: (unix 'which' will find it with no problems).
ls -al /usr/local/bin -rwxrwsr-- 110 root nmt 5535636 Jul 17 2012 git
Here is a node-which attempt:
> which.sync('git')
Error: not found: git
I change the permissions (chomd 755 git). Now node-which can find it.
> which.sync('git')
'/usr/local/bin/git'
Hope this helps.
Personally I've always used if (ptr == NULL)
because it makes my intent explicit, but at this point it's just a habit.
Using =
in place of ==
will be caught by any competent compiler with the correct warning settings.
The important point is to pick a consistent style for your group and stick to it. No matter which way you go, you'll eventually get used to it, and the loss of friction when working in other people's code will be welcome.
My approach would be to use the clone()
method of jQuery. It creates a copy of your element, and that's what you want : a copy of your first unaltered modal, that you can replace at your wish : Demo (jsfiddle)
var myBackup = $('#myModal').clone();
// Delegated events because we make a copy, and the copied button does not exist onDomReady
$('body').on('click','#myReset',function() {
$('#myModal').modal('hide').remove();
var myClone = myBackup.clone();
$('body').append(myClone);
});
The markup I used is the most basic, so you just need to bind on the right elements / events, and you should have your wizard reset.
Be careful to bind with delegated events, or rebind at each reset the inner elements of your modal so that each new modal behave the same way.
if(target.matches("\\S"))
// then string contains at least one non-whitespace character
Note use of back-slash cap-S, meaning "non-whitespace char"
I'd wager this is the simplest (and perhaps the fastest?) solution.
Am Using windows Operating system.
I killed all the node process and restarted the app it worked.
try
taskkill /im node.exe
I know this is an old question, but new in 1.4 is union types; use these for all function overloads (including constructors). Example:
class foo {
private _name: any;
constructor(name: string | number) {
this._name = name;
}
}
var f1 = new foo("bar");
var f2 = new foo(1);
IF EXISTS (SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = N'YourDatabaseName')
BEGIN
-- Database exists, so do your stuff here.
END
If you are using MSSQL instead of MySQL, see this answer from a similar thread.
why not use twig's truncate or wordwrap filter? It belongs to twig extensions and lib is part of Symfony2.0 as i see.
{{ text|truncate(50) }}
require
for installed gemsrequire_relative
for local filesrequire
uses your $LOAD_PATH
to find the files.
require_relative
uses the current location of the file using the statement
Require relies on you having installed (e.g. gem install [package]
) a package somewhere on your system for that functionality.
When using require
you can use the "./
" format for a file in the current directory, e.g. require "./my_file"
but that is not a common or recommended practice and you should use require_relative
instead.
This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use
require_relative '../../../filename'
(up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).
Note that require_relative
uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative
path "stable" as it always be relative to the file requiring it in the same way.
Using time.time()/datetime.datetime.now() will break if the system time is changed (the user changes the time, it is corrected by a timesyncing services such as NTP or switching from/to dayligt saving time!).
time.monotonic() or time.perf_counter() seems to be the correct way to go, however they are only available from python 3.3. Another possibility is using threading.Timer. Whether or not this is more reliable than time.time() and friends depends on the internal implementation. Also note that creating a new thread is not completely free in terms of system resources, so this might be a bad choice in cases where a lot of timers has to be run in parallel.
It's a pointer, so instead try:
a->f();
Basically the operator .
(used to access an object's fields and methods) is used on objects and references, so:
A a;
a.f();
A& ref = a;
ref.f();
If you have a pointer type, you have to dereference it first to obtain a reference:
A* ptr = new A();
(*ptr).f();
ptr->f();
The a->b
notation is usually just a shorthand for (*a).b
.
The operator->
can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use ->
to refer to the pointed object:
auto ptr = make_unique<A>();
ptr->f();
I used the following code to create a temporary file for writing bytes. And its working fine.
File file = new File(Environment.getExternalStorageDirectory() + "/" + File.separator + "test.txt");
file.createNewFile();
byte[] data1={1,1,0,0};
//write the bytes in file
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write(data1);
fo.close();
System.out.println("file created: "+file);
}
//deleting the file
file.delete();
System.out.println("file deleted");
For new Qt users this is a little more confusing than it seems if you are using QT Designer and .ui
files.
Initially I tried to use ui->setWindowTitle
, but that doesn't exist. ui
is not a QDialog
or a QMainWindow
.
The owner of the ui
is the QDialog
or QMainWindow
, the .ui
just describes how to lay it out. In that case, you would use:
this->setWindowTitle("New Title");
I hope this helps someone else.
I used PdfSharp. It's free, open source and quite convenient to use, but I can't say whether it is the best or not, because I haven't really used anything else.
Just replace the first line with the below;
SqlConnection con = new SqlConnection("Server=localhost;Database=employeedetails;Trusted_Connection=True");
Regards.
[ -t <&0 ] || exec >> test.log
A 2016/2017 update will show you the bad value and column.
A new trace flag will swap the old error for a new 2628 error and will print out the column and offending value. Traceflag 460 is available in the latest cumulative update for 2016 and 2017:
Just make sure that after you've installed the CU that you enable the trace flag, either globally/permanently on the server:
...or with DBCC TRACEON:
If you need help with complex definitions, like
double (*(*pf)())[3][4];
take a look at my right-left rule here.
Try this.
Here is the service part.
[ServiceContract]
public interface IService
{
[OperationContract]
void HelloWorld();
}
public class Service : IService
{
public void HelloWorld()
{
//Hello World
}
}
Here is the Proxy
public class ServiceProxy : ClientBase<IService>
{
public ServiceProxy()
: base(new ServiceEndpoint(ContractDescription.GetContract(typeof(IService)),
new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyAppNameThatNobodyElseWillUse/helloservice")))
{
}
public void InvokeHelloWorld()
{
Channel.HelloWorld();
}
}
And here is the service hosting part.
var serviceHost = new ServiceHost
(typeof(Service), new Uri[] { new Uri("net.pipe://localhost/MyAppNameThatNobodyElseWillUse") });
serviceHost.AddServiceEndpoint(typeof(IService), new NetNamedPipeBinding(), "helloservice");
serviceHost.Open();
Console.WriteLine("Service started. Available in following endpoints");
foreach (var serviceEndpoint in serviceHost.Description.Endpoints)
{
Console.WriteLine(serviceEndpoint.ListenUri.AbsoluteUri);
}
As "skaffman" said, use AOP OR you can use run time bytecode weaving, just like unit test method coverage tools use to transparently add timing info to methods invoked.
You can look at code used by open source tools tools like Emma (http://downloads.sourceforge.net/emma/emma-2.0.5312-src.zip?modtime=1118607545&big_mirror=0). The other opensource coverage tool is http://prdownloads.sourceforge.net/cobertura/cobertura-1.9-src.zip?download.
If you eventually manage to do what you set out for, pls. share it back with the community here with your ant task/jars.
I don't know if you managed to resolve this but I have recently experienced a similar problem where the For loop left one view each time. I found this was because the self.subviews was mutated (maybe) when the removeFromSuperview() was called.
To fix this I did:
let subViews: Array = self.subviews.copy()
for (var subview: NSView!) in subViews
{
subview.removeFromSuperview()
}
By doing .copy(), I could perform the removal of each subview while mutating the self.subviews array. This is because the copied array (subViews) contains all of the references to the objects and is not mutated.
EDIT: In your case I think you would use:
let theSubviews: Array = container_view.subviews.copy()
for (var view: NSView!) in theSubviews
{
view.removeFromSuperview()
}
I noticed some issues with this that might be useful for someone just starting, or a somewhat inexperienced user, to know. First...
CD /D "C:\Documents and Settings\%username%\Start Menu\Programs\"
two things one is that a /D after the CD may prove to be useful in making sure the directory is changed but it's not really necessary, second, if you are going to pass this from user to user you have to add, instead of your name, the code %username%, this makes the code usable on any computer, as long as they have your setup.exe file in the same location as you do on your computer. of course making sure of that is more difficult. also...
start \\filer\repo\lab\"software"\"myapp"\setup.exe
the start code here, can be set up like that, but the correct syntax is
start "\\filter\repo\lab\software\myapp\" setup.exe
This will run: setup.exe, located in: \filter\repo\lab...etc.\
You can use the mask to copy only the region of interest of an original image to a destination one:
cvCopy(origImage,destImage,mask);
where mask
should be an 8-bit single channel array.
See more at the OpenCV docs
Use newid()
select newid()
or possibly this
select binary_checksum(newid())
# database Intraction
$SQLServer = "YourServerName" #use Server\Instance for named SQL instances!
$SQLDBName = "YourDBName"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName;
User ID= YourUserID; Password= YourPassword"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = 'StoredProcName'
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
#End :database Intraction
clear
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)
You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.
Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:
telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)
You should get a response like:
250 2.0.0 Ok: queued as 6E414C4643A
The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:
sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected] [email protected]
[email protected] [email protected]
@localdomain.local [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the
generic file)
Happy Trails
Your first CSS selector—social.h2
—is looking for the "social" element in the "h2", class, e.g.:
<social class="h2">
Class selectors are proceeded with a dot (.
). Also, use a space () to indicate that one element is inside of another. To find an
<h2>
descendant of an element in the social
class, try something like:
.social h2 {
color: pink;
font-size: 14px;
}
To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.
An optional prefix
!
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
http://schacon.github.com/git/gitignore.html
*.json
!spec/*.json
Using variable notation, you can do it without a temporary file:
${C:\file.txt} = ${C:\file.txt} | select -skip 1
function Remove-Topline ( [string[]]$path, [int]$skip=1 ) {
if ( -not (Test-Path $path -PathType Leaf) ) {
throw "invalid filename"
}
ls $path |
% { iex "`${$($_.fullname)} = `${$($_.fullname)} | select -skip $skip" }
}
I am going to use an example to add to the answers above.
I ran into proxy issues while trying to install packages via Web Platform Installer
That too uses a config file which is WebPlatformInstaller.exe.config
I tried the edits suggest in this IIS forum which is
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy enabled="True" useDefaultCredentials="True"/>
</system.net>
</configuration>
and
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy>
<proxy
proxyaddress="http://yourproxy.company.com:80"
usesystemdefault="True"
autoDetect="False" />
</defaultProxy>
</system.net>
</configuration>
None of these worked.
What worked for me was this -
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="false">
<module type="WebPI.Net.AuthenticatedProxy, WebPI.Net, Version=1.0.0.0, Culture=neutral, PublicKeyToken=79a8d77199cbf3bc" />
</defaultProxy>
</system.net>
The module needed to be registered with Web Platform Installer in order to use it.
I had the same problem with Angular CLI: 10.1.5 The code works fine, but the error was shown in the VScode v1.50
Resolved by killing the terminal (ng serve) and restarting VScode.
I Faced the same issue while installing a setup using a jar file. Solution thta worked for me is
java -jar <<jar fully qualified path>>
It worked for me :)
JavaScript btoa() function can be used to convert data into base64 encoded string
I can give an example commonly seen in project.
Here, option --no-ff
(i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff
(i.e. fast-forward merge) is by default.
$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature' // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk // => see details with graph
$ git checkout -b anotherFeature // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk // => see details with graph
(*) Note that here if the newFeature
branch is re-used, instead of creating a new branch, git will have to do a --no-ff
merge anyway. This means fast forward merge is not always eligible.
If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.
The innerHtml property did not work for me. So I experimented with ...
<div id=successAndErrorMessages-1>100% OK</div>
<div id=successAndErrorMessages-2>This is an error mssg!</div>
and toggled one of the two on/off ...
$("#successAndErrorMessages-1").css('display', 'none')
$("#successAndErrorMessages-2").css('display', '')
For some reason I had to fiddle around with the ordering before it worked in all types of browsers.
You can do it with a separate UPDATE statement
UPDATE report.TEST target
SET is Deleted = 'Y'
WHERE NOT EXISTS (SELECT 1
FROM main.TEST source
WHERE source.ID = target.ID);
I don't know of any way to integrate this into your MERGE statement.
It's already been answered a few times, but Python is a strongly typed language:
>>> x = 3
>>> y = '4'
>>> print(x+y)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
The following in JavaScript:
var x = 3
var y = '4'
alert(x + y) //Produces "34"
That's the difference between weak typing and strong typing. Weak types automatically try to convert from one type to another, depending on context (e.g. Perl). Strong types never convert implicitly.
Your confusion lies in a misunderstanding of how Python binds values to names (commonly referred to as variables).
In Python, names have no types, so you can do things like:
bob = 1
bob = "bob"
bob = "An Ex-Parrot!"
And names can be bound to anything:
>>> def spam():
... print("Spam, spam, spam, spam")
...
>>> spam_on_eggs = spam
>>> spam_on_eggs()
Spam, spam, spam, spam
For further reading:
https://en.wikipedia.org/wiki/Dynamic_dispatch
and the slightly related but more advanced:
The best way I can think of to answer this is to make a custom jquery plugin to do this:
jQuery.fn.getIdArray = function() {
var ret = [];
$('[id]', this).each(function() {
ret.push(this.id);
});
return ret;
};
Then do something like
var array = $("#mydiv").getIdArray();
In addition to the Python 2 approach here are the equivalents for Python 3:
# Create a range that does not contain 50
for i in [x for x in range(100) if x != 50]:
print(i)
# Create 2 ranges [0,49] and [51, 100]
from itertools import chain
concatenated = chain(range(50), range(51, 100))
for i in concatenated:
print(i)
# Create a iterator and skip 50
xr = iter(range(100))
for i in xr:
print(i)
if i == 49:
next(xr)
# Simply continue in the loop if the number is 50
for i in range(100):
if i == 50:
continue
print(i)
Ranges are lists in Python 2 and iterators in Python 3.
Try this
link_to "+ Service", my_services_new_path(:account_id => acct.id)
it will pass the account_id as you want.
For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
Similarly, I experienced this: Port 443 in use by "Unable to open process" with PID 6012! When starting XAMPP Control Panel v3.2.1 for the first time.
In Task Manager I found that PID 6012 was Apache web server. A copy of it was running in the background without the GUI, and when I invoked the GUI it was trying to start another copy. Killed the phantom copy and then XAMPP started up fine.
I didn't have to change any port settings.
I have solved this cool custom progress bar by creating the custom view. I have overriden the onDraw() method to draw the circles, filled arc and text on the canvas.
following is the custom progress bar
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import com.investorfinder.utils.UiUtils;
public class CustomProgressBar extends View {
private int max = 100;
private int progress;
private Path path = new Path();
int color = 0xff44C8E5;
private Paint paint;
private Paint mPaintProgress;
private RectF mRectF;
private Paint textPaint;
private String text = "0%";
private final Rect textBounds = new Rect();
private int centerY;
private int centerX;
private int swipeAndgle = 0;
public CustomProgressBar(Context context) {
super(context);
initUI();
}
public CustomProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
initUI();
}
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initUI();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initUI();
}
private void initUI() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(UiUtils.dpToPx(getContext(), 1));
paint.setStyle(Paint.Style.STROKE);
paint.setColor(color);
mPaintProgress = new Paint();
mPaintProgress.setAntiAlias(true);
mPaintProgress.setStyle(Paint.Style.STROKE);
mPaintProgress.setStrokeWidth(UiUtils.dpToPx(getContext(), 9));
mPaintProgress.setColor(color);
textPaint = new Paint();
textPaint.setAntiAlias(true);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setColor(color);
textPaint.setStrokeWidth(2);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
int viewHeight = MeasureSpec.getSize(heightMeasureSpec);
int radius = (Math.min(viewWidth, viewHeight) - UiUtils.dpToPx(getContext(), 2)) / 2;
path.reset();
centerX = viewWidth / 2;
centerY = viewHeight / 2;
path.addCircle(centerX, centerY, radius, Path.Direction.CW);
int smallCirclRadius = radius - UiUtils.dpToPx(getContext(), 7);
path.addCircle(centerX, centerY, smallCirclRadius, Path.Direction.CW);
smallCirclRadius += UiUtils.dpToPx(getContext(), 4);
mRectF = new RectF(centerX - smallCirclRadius, centerY - smallCirclRadius, centerX + smallCirclRadius, centerY + smallCirclRadius);
textPaint.setTextSize(radius * 0.5f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path, paint);
canvas.drawArc(mRectF, 270, swipeAndgle, false, mPaintProgress);
drawTextCentred(canvas);
}
public void drawTextCentred(Canvas canvas) {
textPaint.getTextBounds(text, 0, text.length(), textBounds);
canvas.drawText(text, centerX - textBounds.exactCenterX(), centerY - textBounds.exactCenterY(), textPaint);
}
public void setMax(int max) {
this.max = max;
}
public void setProgress(int progress) {
this.progress = progress;
int percentage = progress * 100 / max;
swipeAndgle = percentage * 360 / 100;
text = percentage + "%";
invalidate();
}
public void setColor(int color) {
this.color = color;
}
}
In layout XML
<com.your.package.name.CustomProgressBar
android:id="@+id/progress_bar"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentRight="true"
android:layout_below="@+id/txt_title"
android:layout_marginRight="15dp" />
in activity
CustomProgressBar progressBar = (CustomProgressBar)findViewById(R.id.progress_bar);
progressBar.setMax(9);
progressBar.setProgress(5);
The simplest make file can be
all : test
test : test.o
gcc -o test test.o
test.o : test.c
gcc -c test.c
clean :
rm test *.o
What if one of the values is negative? Wouldn't a better idea be:
double NextDouble(double min, double max)
{
if (min >= max)
throw new ArgumentOutOfRangeException();
return random.NextDouble() * (Math.Abs(max-min)) + min;
}
I give a supplementary answer based on @Frouo. I think his answer is the most beautiful way. Becuase it's a common control we can reuse. And there is no leak problem here.
private var kAssociationKeyMaxLength: Int = 0
extension UITextField {
@IBInspectable var maxLength: Int {
get {
if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
return length
} else {
return Int.max
}
}
set {
objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
self.addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
}
}
//The method is used to cancel the check when use Chinese Pinyin input method.
//Becuase the alphabet also appears in the textfield when inputting, we should cancel the check.
func isInputMethod() -> Bool {
if let positionRange = self.markedTextRange {
if let _ = self.position(from: positionRange.start, offset: 0) {
return true
}
}
return false
}
func checkMaxLength(textField: UITextField) {
guard !self.isInputMethod(), let prospectiveText = self.text,
prospectiveText.count > maxLength
else {
return
}
let selection = selectedTextRange
let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
text = prospectiveText.substring(to: maxCharIndex)
selectedTextRange = selection
}
}
You had a mistake on the statement below. Use . not ,
echo '<img src="', $dir, '/', $file, '" alt="', $file, $
to
echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $
and
echo 'Directory \'', $dir, '\' not found!';
to
echo 'Directory \''. $dir. '\' not found!';
Store it in a cookie that only lasts for the current browsing session
Try Access DataTable easiest way which can help you for getting perfect idea for accessing DataTable, DataSet using Linq...
Consider following example, suppose we have DataTable like below.
DataTable ObjDt = new DataTable("List");
ObjDt.Columns.Add("WorkName", typeof(string));
ObjDt.Columns.Add("Price", typeof(decimal));
ObjDt.Columns.Add("Area", typeof(string));
ObjDt.Columns.Add("Quantity",typeof(int));
ObjDt.Columns.Add("Breath",typeof(decimal));
ObjDt.Columns.Add("Length",typeof(decimal));
Here above is the code for DatTable, here we assume that there are some data are available in this DataTable, and we have to bind Grid view of particular by processing some data as shown below.
Area | Quantity | Breath | Length | Price = Quantity * breath *Length
Than we have to fire following query which will give us exact result as we want.
var data = ObjDt.AsEnumerable().Select
(r => new
{
Area = r.Field<string>("Area"),
Que = r.Field<int>("Quantity"),
Breath = r.Field<decimal>("Breath"),
Length = r.Field<decimal>("Length"),
totLen = r.Field<int>("Quantity") * (r.Field<decimal>("Breath") * r.Field<decimal>("Length"))
}).ToList();
We just have to assign this data variable as Data Source.
By using this simple Linq query we can get all our accepts, and also we can perform all other LINQ queries with this…
As of ISO7 at least you can easily do this with NSJSONSerialization.
You need to put the .jar file into your classpath when compiling/running your code. Then you just use standard imports of the classes in the .jar.
I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important. if you use export on a function directly i.e
export const addPost = (id) =>{
...
}
Note while importing you need to wrap it in curly braces
i.e. import {addPost} from '../URL';
But when using export default i.e
const addPost = (id) =>{
...
}
export default addPost
,
Then you can import without curly braces i.e.
import addPost from '../url';
export default addPost
I hope this helps anyone who got confused as me.
@agilityvision's answer is so good. I have sense used in swift projects so I thought I would share my take on his answer using swift 3.0
fileprivate class MyUIAlertController: UIAlertController {
typealias Handler = () -> Void
struct AssociatedKeys {
static var alertWindowKey = "alertWindowKey"
}
dynamic var _alertWindow: UIWindow?
var alertWindow: UIWindow? {
return objc_getAssociatedObject(self, &AssociatedKeys.alertWindowKey) as? UIWindow
}
func setAlert(inWindow window: UIWindow) {
objc_setAssociatedObject(self, &AssociatedKeys.alertWindowKey, _alertWindow, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
func show(completion: Handler? = nil) {
show(animated: true, completion: completion)
}
func show(animated: Bool, completion: Handler? = nil) {
_alertWindow = UIWindow(frame: UIScreen.main.bounds)
_alertWindow?.rootViewController = UIViewController()
if let delegate: UIApplicationDelegate = UIApplication.shared.delegate, let window = delegate.window {
_alertWindow?.tintColor = window?.tintColor
}
let topWindow = UIApplication.shared.windows.last
_alertWindow?.windowLevel = topWindow?.windowLevel ?? 0 + 1
_alertWindow?.makeKeyAndVisible()
_alertWindow?.rootViewController?.present(self, animated: animated, completion: completion)
}
fileprivate override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
_alertWindow?.isHidden = true
_alertWindow = nil
}
}
Today, I used this logic why I don't know getting the count of RS.
int chkSize = 0;
if (rs.next()) {
do { ..... blah blah
enter code here for each rs.
chkSize++;
} while (rs.next());
} else {
enter code here for rs size = 0
}
// good luck to u.
As the definition of Linkedlist says, it is a sequence and you are guaranteed to get the elements in order.
eg:
import java.util.LinkedList;
public class ForEachDemonstrater {
public static void main(String args[]) {
LinkedList<Character> pl = new LinkedList<Character>();
pl.add('j');
pl.add('a');
pl.add('v');
pl.add('a');
for (char s : pl)
System.out.print(s+"->");
}
}
And if you have more than one .css or .js file to call, just include them one after another, or:
<head>
<link href="css/grid.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
<script src="js/jquery-1.4.4.min.js"></script>
<script src="js/jquery.animate-colors-min.js"></script>
</head>
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:
Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng
is producing the same result as Joe's code.
If you need to switch sheets for some reasons, use Application.ScreenUpdating = False
at the beginning of your macro (and Application.ScreenUpdating=True
at the end). This will remove the screenflickering - and speed up the execution.
I am not an expert in python but you could try: say
i = (1,2)
res = lambda i: (i[1],i[0])
print 'res(1, 2) = {0}'.format(res(1, 2))
above would give o/p as:
res(1, 2) = (2,1)
The code can be cleaned up, but if you are using a list to store your tuples, any such lookup will be O(N).
If lookup speed is important, you should use a dict
to store your tuples. The key should be the 0th element of your tuples, since that's what you're searching on. You can easily create a dict from your list:
my_dict = dict(my_list)
Then, (VALUE, my_dict[VALUE])
will give you your matching tuple (assuming VALUE
exists).
Maybe better document.querySelectorAll(".col1")
because getElementsByClassName
doesn't works in IE 8 and querySelectorAll
does (althought CSS2 selectors only).
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll
If you want to show just numbers without characters, put this line of code inside your XML file android:inputType="number"
. The output:
If you want to show a number keyboard that also shows characters, put android:inputType="phone"
on your XML. The output (with characters):
And if you want to show a number keyboard that masks your input just like a password, put android:inputType="numberpassword"
. The output:
I'm really sorry if I only post the links of the screenshot, I want to do research on how to do really post images here but it might consume my time so here it is. I hope my post can help other people. Yes, my answer is duplicate with other answers posted here but to save other people's time that they might need to run their code before seeing the output, my post might save you some time.
Main() {
float rmvivek,arni,csc;
char *c="1234.00";
csc=atof(c);
csc+=55;
printf("the value is %f",csc);
}
In my situation, I only need the json result, and this works for me:
public interface SchoolRepository extends JpaRepository<School,Integer> {
@Query("select s.id, s.name from School s")
List<Object> getSchoolIdAndName();
}
in Controller:
@Autowired
private SchoolRepository schoolRepository;
@ResponseBody
@RequestMapping("getschoolidandname.do")
public List<Object> getSchool() {
List<Object> schools = schoolRepository.getSchoolIdAndName();
return schools;
}
Just use this after executing mongoimport
It will return number of objects imported
use db
db.collectionname.find().count()
will return the number of objects.
Add the JSON MIME type to IIS 6. Follow the directions at MSDN's Configure MIME Types (IIS 6.0).
Don't forget to restart IIS after the change.
UPDATE: There are easy ways to do this on IIS7 and newer. The op specifically asked for IIS6 help so I'm leaving this answer as-is. But this answer is still getting a lot of traffic even though IIS6 is very old now. Hopefully you're using something newer, so I wanted to mention that if you have a newer IIS7 or newer version see @ProVega's answer below for a simpler solution for those newer versions.
Thanks to Devin, I figured out the solution for my SLIM application with multi domain access.
In htaccess:
SetEnvIf Origin "http(s)?://(www\.)?(allowed.domain.one|allowed.domain.two)$" AccessControlAllowOrigin=$0$1
Header set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials true
in index.php
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
// instead of mapping:
$app->options('/(:x+)', function() use ($app) {
//...return correct headers...
$app->response->setStatus(200);
});
1.
<div class="one" [innerHtml]="htmlToAdd"></div>
this.htmlToAdd = '<div class="two">two</div>';
See also In RC.1 some styles can't be added using binding syntax
<div class="one" #one></div>
@ViewChild('one') d1:ElementRef;
ngAfterViewInit() {
d1.nativeElement.insertAdjacentHTML('beforeend', '<div class="two">two</div>');
}
or to prevent direct DOM access:
constructor(private renderer:Renderer) {}
@ViewChild('one') d1:ElementRef;
ngAfterViewInit() {
this.renderer.invokeElementMethod(this.d1.nativeElement', 'insertAdjacentHTML' ['beforeend', '<div class="two">two</div>']);
}
constructor(private elementRef:ElementRef) {}
ngAfterViewInit() {
var d1 = this.elementRef.nativeElement.querySelector('.one');
d1.insertAdjacentHTML('beforeend', '<div class="two">two</div>');
}
Another possible solution is:
const link = document.createElement('a');
link.target = '_blank';
link.href = 'https://www.google.es';
link.setAttribute('visibility', 'hidden');
link.click();
You can avoid much trouble by using this --
myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
myButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
This will align all your content automatically to left (or wherever you want it)
Swift 3:
myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left;
myButton.contentVerticalAlignment = UIControlContentVerticalAlignment.center;
As @layke said, it is the best practice to download the file from the S3 cli it is a safe and secure. But in some cases, people need to use wget to download the file and here is the solution
aws s3 presign s3://<your_bucket_name/>
This will presign will get you temporary public URL which you can use to download content from S3 using the presign_url, in your case using wget or any other download client.
/* Authentication type and info */
$cfg['Servers'][$i]['password'] = '';<----your password
or
/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = '';
to
/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'your user';
$cfg['Servers'][$i]['controlpass'] = 'your password';
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
Do you want to find elements that contain "match", or that equal "match"?
This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2
):
//*[text()='match']
This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2
):
//*[normalize-space(text())='match']
This will find all elements that contain 'match' in the text node value (matches random2
and random3
):
//*[contains(text(),'match')]
This XPATH 2.0 solution uses the matches()
function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^
) or a word boundary (i.e. \W
) and terminated by the end of the string (i.e. $
) or a word boundary. The third parameter i
evaluates the regex pattern case-insensitive. (matches random2
)
//*[matches(text(),'(^|\W)match($|\W)','i')]
Taken from: http://www.w3.org/Style/Examples/007/units:
The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.
em
is basically CSS property for font sizes.
clearfix
should contain the floating elements but in your html you have added clearfix
only after floating right that is your pull-right
so you should do like this:
<div class="clearfix">
<div id="sidebar">
<ul>
<li>A</li>
<li>A</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>...</li>
<li>Z</li>
</ul>
</div>
<div id="main">
<div>
<div class="pull-right">
<a>RIGHT</a>
</div>
</div>
<div>MOVED BELOW Z</div>
</div>
Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden;
as you have done in your main.
I was using above command but it was not working. This command worked for me:
python -m pip uninstall pip setuptools
docker volume create pgdata
or you can set it to the compose file
version: "3"
services:
db:
image: postgres
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgress
- POSTGRES_DB=postgres
ports:
- "5433:5432"
volumes:
- pgdata:/var/lib/postgresql/data
networks:
- suruse
volumes:
pgdata:
It will create volume name pgdata and mount this volume to container's path.
docker volume inspect pgdata
// output will be
[
{
"Driver": "local",
"Labels": {},
"Mountpoint": "/var/lib/docker/volumes/pgdata/_data",
"Name": "pgdata",
"Options": {},
"Scope": "local"
}
]
If your VARCHAR
column contains empty strings (which are not the same as NULL
for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:
ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
USING COALESCE(NULLIF(code, '')::NUMERIC, 0);
(found with the help of this answer)
I found an other resolution (reference appcompat-v7 ) that change the toolbarStyle ,following code:
<item name="toolbarStyle">@style/Widget.Toolbar</item>
<style name="Widget.Toolbar" parent="@style/Widget.AppCompat.Toolbar">
<item name="contentInsetStart">0dp</item>
</style>
public JSONObject makJsonObject(int id[], String name[], String year[],
String curriculum[], String birthday[], int numberof_students)
throws JSONException {
JSONObject obj = null;
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < numberof_students; i++) {
obj = new JSONObject();
try {
obj.put("id", id[i]);
obj.put("name", name[i]);
obj.put("year", year[i]);
obj.put("curriculum", curriculum[i]);
obj.put("birthday", birthday[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonArray.put(obj);
}
JSONObject finalobject = new JSONObject();
finalobject.put("student", jsonArray);
return finalobject;
}
"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types."
"The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."
Here is my source.
Because a string variable is a reference, not an instance.
Initializing it to Empty by default would have been possible but it would have introduced a lot of inconsistencies all over the board.
One is essentially a toy, designed for writing small pieces of code, and traditionally used and abused by inexperienced programmers.
The other is a scripting language for web browsers.
I have created a simple program for this and your question helped me complete the solution... I added one more feature and few configurations. In case you want to add a specific character/ string after every few lines (configurable). Please go through the notes. I have added the code files : https://github.com/mohitsharma779/FileSplit
Just use the 'Rebuild Project' from the 'Build' menu from the top menu bar.
I think the best way is to share an object with global variables throughout your application by exporting and importing it where you want.
First create a new .ts file for example globals.ts and declare an object. I gave it an Object type but you also could use an any type or {}
export let globalVariables: Object = {
version: '1.3.3.7',
author: '0x1ad2',
everything: 42
};
After that import it
import {globalVariables} from "path/to/your/globals.ts"
And use it
console.log(globalVariables);
I don't know that in case two there's any real concatenation done. Printing them back to back doesn't constitute concatenation.
Tell me though, which would be faster:
1) a) copy string A to new buffer b) copy string B to buffer c) copy buffer to output buffer
or
1)copy string A to output buffer b) copy string b to output buffer
This answer is directed in large part at a comment made by @RafalDowgird:
"The minimum size of operations is int." - This would be very strange (what about architectures that efficiently support char/short operations?) Is this really in the C++ spec?
Keep in mind that the C++ standard has the all-important "as-if" rule. See section 1.8: Program Execution:
3) This provision is sometimes called the "as-if" rule, because an implementation is free to disregard any requirement of the Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program.
The compiler cannot set an int
to be 8 bits in size, even if it were the fastest, since the standard mandates a 16-bit minimum int
.
Therefore, in the case of a theoretical computer with super-fast 8-bit operations, the implicit promotion to int
for arithmetic could matter. However, for many operations, you cannot tell if the compiler actually did the operations in the precision of an int
and then converted to a char
to store in your variable, or if the operations were done in char all along.
For example, consider unsigned char = unsigned char + unsigned char + unsigned char
, where addition would overflow (let's assume a value of 200 for each). If you promoted to int
, you would get 600, which would then be implicitly down cast into an unsigned char
, which would wrap modulo 256, thus giving a final result of 88. If you did no such promotions,you'd have to wrap between the first two additions, which would reduce the problem from 200 + 200 + 200
to 144 + 200
, which is 344, which reduces to 88. In other words, the program does not know the difference, so the compiler is free to ignore the mandate to perform intermediate operations in int
if the operands have a lower ranking than int
.
This is true in general of addition, subtraction, and multiplication. It is not true in general for division or modulus.
One way is to set the the div to position:absolute
and give it a top of 50px and bottom of 0px;
#div2
{
position:absolute;
bottom:0px;
top:50px
}
Usually it would be this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>='2010-10-01'
AND yourtimetimefield< '2010-11-01'
But because you have a unix timestamps, you'll need something like this:
SELECT *
FROM yourtable
WHERE yourtimetimefield>=unix_timestamp('2010-10-01')
AND yourtimetimefield< unix_timestamp('2010-11-01')
ES2015 onwards:
From ES6/ES2015, we have default parameters in the language specification. So we can just do something simple like,
function A(a, b = 4, c = 5) {
}
or combined with ES2015 destructuring,
function B({c} = {c: 2}, [d, e] = [3, 4]) {
}
For detailed explanation,
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
Pre ES2015:
If you're going to handle values which are NOT Numbers, Strings, Boolean, NaN
, or null
you can simply use
(So, for Objects, Arrays and Functions that you plan never to send null
, you can use)
param || DEFAULT_VALUE
for example,
function X(a) {
a = a || function() {};
}
Though this looks simple and kinda works, this is restrictive and can be an anti-pattern because ||
operates on all falsy values (""
, null
, NaN
, false
, 0
) too - which makes this method impossible to assign a param the falsy value passed as the argument.
So, in order to handle only undefined
values explicitly, the preferred approach would be,
function C(a, b) {
a = typeof a === 'undefined' ? DEFAULT_VALUE_A : a;
b = typeof b === 'undefined' ? DEFAULT_VALUE_B : b;
}
For Example :
http://character-code.com/arrows-html-codes.php
Example: If you want select your character , I selected "↬" "↬" (We use HEX values)
.breadcrumbs a:before {
content: '\0021ac';
}
Result : ↬
Thats it :)
OK, I'll take a stab at this. Python passes by object reference, which is different from what you'd normally think of as "by reference" or "by value". Take this example:
def foo(x):
print x
bar = 'some value'
foo(bar)
So you're creating a string object with value 'some value' and "binding" it to a variable named bar
. In C, that would be similar to bar
being a pointer to 'some value'.
When you call foo(bar)
, you're not passing in bar
itself. You're passing in bar
's value: a pointer to 'some value'. At that point, there are two "pointers" to the same string object.
Now compare that to:
def foo(x):
x = 'another value'
print x
bar = 'some value'
foo(bar)
Here's where the difference lies. In the line:
x = 'another value'
you're not actually altering the contents of x
. In fact, that's not even possible. Instead, you're creating a new string object with value 'another value'. That assignment operator? It isn't saying "overwrite the thing x
is pointing at with the new value". It's saying "update x
to point at the new object instead". After that line, there are two string objects: 'some value' (with bar
pointing at it) and 'another value' (with x
pointing at it).
This isn't clumsy. When you understand how it works, it's a beautifully elegant, efficient system.
This is not explicitly mentioned, but based on the following docs, I think it is implied that an app needs to declare and implement a BackupAgent in order for data backup to work, even in the case when allowBackup is set to true (which is the default value).
http://developer.android.com/reference/android/R.attr.html#allowBackup http://developer.android.com/reference/android/app/backup/BackupManager.html http://developer.android.com/guide/topics/data/backup.html
event.target
returns the node that was targeted by the function. This means you can do anything you would do with any other node like one you'd get from document.getElementById
Thank you for this example, SPRBRN. It helped me. And I can suggest the mixin, which I've used based on the code given above:
//multi-column-list( fixed columns width)
@mixin multi-column-list($column-width, $column-rule-style) {
-webkit-column-width: $column-width;
-moz-column-width: $column-width;
-o-column-width: $column-width;
-ms-column-width: $column-width;
column-width: $column-width;
-webkit-column-rule-style: $column-rule-style;
-moz-column-rule-style: $column-rule-style;
-o-column-rule-style: $column-rule-style;
-ms-column-rule-style: $column-rule-style;
column-rule-style: $column-rule-style;
}
Using:
@include multi-column-list(250px, solid);
I had the same error message so I went googling a bit I managed to fix it with the following code.
df<-data.frame(words = unlist(words))
words is a character list.
This just in case somebody else needs the output to be a data frame.
I'm the maintainer of Mongoose. findById()
is a built-in method on Mongoose models. findById(id)
is equivalent to findOne({ _id: id })
, with one caveat: findById()
with 0 params is equivalent to findOne({ _id: null })
.
You can read more about findById()
on the Mongoose docs and this findById()
tutorial.
Select top 2 [id] from table Order by [id] desc
should give you want you the latest two rows added.
However, you will have to pay particular attention to the order by
clause as that will determine the 1st and 2nd row returned.
If the query was to be changed like this:
Select top 2 [id] from table Order by ModifiedDate desc
You could get two different rows. You will have to decide which column to use in your order by statement.
One of the most convenient ways is usage of generic Collections.addAll() method, which takes a collection and varargs:
Set<String> h = new HashSet<String>();
Collections.addAll(h, "a", "b");
I had a simular issue and resolved it using android:adjustViewBounds="true"
on the ImageView.
<ImageView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/banner_alt"
android:src="@drawable/banner_portrait" />
In English:
It's a
List
of some type that extends the classHasWord
, includingHasWord
In general the ?
in generics means any class. And the extends SomeClass
specifies that that object must extend SomeClass
(or be that class).
Not sure of exact syntax (you use varchar2 type which means not SQL Server hence TOP) but you can use the LIMIT keyword for MySQL:
Select * FROM test_table WHERE user_id = value
ORDER BY DATE_ADDED DESC LIMIT 1
Or rownum in Oracle
SELECT * FROM
(Select rownum as rnum, * FROM test_table WHERE user_id = value ORDER BY DATE_ADDED DESC)
WHERE rnum = 1
If DB2, I'm not sure whether it's TOP, LIMIT or rownum...
I was able to resolve this in Visual Studio 2010, VB.net (ASP.NET) 4.0.
During the entity model wizard, you will be able to see the entity connection string. From there you can copy and paste into your connection string.
The only thing I was missing was the "App_Code." in the connections string.
entityBuilder.Metadata = "res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl"
The issue probably has to do with the time it takes to compile the query.
If you want to speed up the inserts, what you really need to do is wrap them in a transaction:
BEGIN TRAN;
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age)
VALUES ('6f3f7257-a3d8-4a78-b2e1-c9b767cfe1c1', 'First 0', 'Last 0', 0);
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age)
VALUES ('32023304-2e55-4768-8e52-1ba589b82c8b', 'First 1', 'Last 1', 1);
...
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age)
VALUES ('f34d95a7-90b1-4558-be10-6ceacd53e4c4', 'First 999', 'Last 999', 999);
COMMIT TRAN;
From C#, you might also consider using a table valued parameter. Issuing multiple commands in a single batch, by separating them with semicolons, is another approach that will also help.
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
public class FileFinder extends SimpleFileVisitor<Path> {
private PathMatcher matcher;
public ArrayList<Path> foundPaths = new ArrayList<>();
public FileFinder(String pattern) {
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path name = file.getFileName();
if (matcher.matches(name)) {
foundPaths.add(file);
}
return FileVisitResult.CONTINUE;
}
}
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
Path fileDir = Paths.get("files");
FileFinder finder = new FileFinder("*.txt");
Files.walkFileTree(fileDir, finder);
ArrayList<Path> foundFiles = finder.foundPaths;
if (foundFiles.size() > 0) {
for (Path path : foundFiles) {
System.out.println(path.toRealPath(LinkOption.NOFOLLOW_LINKS));
}
} else {
System.out.println("No files were founds!");
}
}
}
You are using getData() method as void.
You can not return values from void.
You have 2 choices:
1) Either specify the column name list (without the identity column).
2) SET IDENTITY_INSERT tablename ON, followed by insert statements that provide explicit values for the identity column, followed by SET IDENTITY_INSERT tablename OFF.
If you are avoiding a column name list, perhaps this 'trick' might help?:
-- Get a comma separated list of a table's column names
SELECT STUFF(
(SELECT
',' + COLUMN_NAME AS [text()]
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'TableName'
Order By Ordinal_position
FOR XML PATH('')
), 1,1, '')
Make sure you have a service started and listening on the port.
netstat -ln | grep 8080
and
sudo netstat -tulpn
I use numpy.fromiter to invert a 8-greyscale bitmap, yet no signs of side-effects
import Image
import numpy as np
im = Image.load('foo.jpg')
im = im.convert('L')
arr = np.fromiter(iter(im.getdata()), np.uint8)
arr.resize(im.height, im.width)
arr ^= 0xFF # invert
inverted_im = Image.fromarray(arr, mode='L')
inverted_im.show()
What finally worked for me is similar to what @????DJ suggested, but the tabBackground
should be in the layout
file and not inside the style
, so it looks like:
res/layout/somefile.xml
:
<android.support.design.widget.TabLayout
....
app:tabBackground="@drawable/tab_color_selector"
...
/>
and the selector
res/drawable/tab_color_selector.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/tab_background_selected" android:state_selected="true"/>
<item android:drawable="@color/tab_background_unselected"/>
</selector>
Here's a simple example with no jQuery. Use URL.createObjectURL
, which
creates a DOMString containing a URL representing the object given in the parameter
Then, you can simply set the src
of the image to that url:
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files && this.files[0]) {
var img = document.querySelector('img');
img.onload = () => {
URL.revokeObjectURL(img.src); // no longer needed, free memory
}
img.src = URL.createObjectURL(this.files[0]); // set src to blob url
}
});
});
_x000D_
<input type='file' />
<br><img id="myImg" src="#">
_x000D_
I have found that Android Studio gives me a warning that getColor()
is deprecated when trying to do this:
Button11.setBackgroundColor(getResources().getColor(R.color.red))
So I found doing the method below to be the simple, up-to-date solution:
Button11.setBackgroundColor(ContextCompat.getColor(context, R.color.red))
You want to avoid hard-coding in the color argument, as it is considered bad code style.
Edit: After using setBackgroundColor()
with my own button, I saw that the internal button padding expanded. I couldn't find any way of changing it back to having both height and width set to "wrap_content". Maybe its a bug.
Some time if lots if Test files are there then Eclipse failed to pass -classpath options for all libs and path due to classpath param lenght limitations. To Solve it go to Run
Configerations -> JUnit -> Your Project Config -> ClassPath -> Check "Use Temporary Jar Options"
At least it solved my problem.
The third statement in the for construct is only executed, but its evaluated value is discarded and not taken care of.
When the evaluated value is discarded, pre and post increment are equal.
They only differ if their value is taken.
You need to use an explicit java.util.Iterator
to iterate over the Map
's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map
of Integer
, String
pairs, removing any entry whose Integer
key is null or equals 0.
Map<Integer, String> map = ...
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
// Remove entry if key is null or equals 0.
if (entry.getKey() == null || entry.getKey() == 0) {
it.remove();
}
}
I've got this working after doing the following:
Note: This doesn't give me the runtime exceptions either, it works.
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
Check encoding and language:
$ echo $LC_CTYPE
ISO-8859-1
$ echo $LANG
pt_BR
Get all languages:
$ locale -a
Change to pt_PT.utf8:
$ export LC_ALL=pt_PT.utf8
$ export LANG="$LC_ALL"
Arrays are objects and they have a length field.
String[] haha = {"olle", "bulle"};
haha.length would be 2
You can't remove from list if you're browsing it with "for each" loop. You can use Iterator
. Replace:
for (DrugStrength aDrugStrength : aDrugStrengthList) {
if (!aDrugStrength.isValidDrugDescription()) {
aDrugStrengthList.remove(aDrugStrength);
}
}
With:
for (Iterator<DrugStrength> it = aDrugStrengthList.iterator(); it.hasNext(); ) {
DrugStrength aDrugStrength = it.next();
if (!aDrugStrength.isValidDrugDescription()) {
it.remove();
}
}
Or you can do like this:
your_df.to_excel( r'C:\Users\full_path\excel_name.xlsx',
sheet_name= 'your_sheet_name'
)
All three define the meaning of zero in different context.
These three are always different when you look at the memory:
NULL - 0x00000000 or 0x00000000'00000000 (32 vs 64 bit)
NUL - 0x00 or 0x0000 (ascii vs 2byte unicode)
'0' - 0x20
I hope this clarifies it.
Here's a handy site to test out your headers. You can see your browser headers and also use cURL to reflect back whatever headers you send.
For example, you can validate the content negotiation like this.
This Accept
header prefers plain text so returns in that format:-
$ curl -H "Accept: application/json;q=0.9,text/plain" http://gethttp.info/Accept
application/json;q=0.9,text/plain
Whereas this one prefers JSON and so returns in that format:-
$ curl -H "Accept: application/json,text/*;q=0.99" http://gethttp.info/Accept
{
"Accept": "application/json,text/*;q=0.99"
}
try this one :
public void itemClicked(View v) {
//code to check if this checkbox is checked!
CheckBox checkBox = (CheckBox)v;
if(checkBox.isChecked()){
}
}
That's the right way to go.
Generally constants are not kept in separate "Constants" classes because they're not discoverable. If the constant is relevant to the current class, keeping them there helps the next developer.
<%# (string)Eval("gender") =="M" ? "Male" :"Female"%>
Go here and find the version you want to install and then download the correct msi file and run the installer. You cannot install node by running this command, also the error you receive is stating that npm is not on your path which suggests machine doesn't currently have node installed on it
To stage all manually deleted files you can use:
git rm $(git ls-files --deleted)
To add an alias to this command as git rm-deleted
, run:
git config --global alias.rm-deleted '!git rm $(git ls-files --deleted)'
public class Mode {
public static void main(String[] args) {
int[] unsortedArr = new int[] { 3, 1, 5, 2, 4, 1, 3, 4, 3, 2, 1, 3, 4, 1 ,-1,-1,-1,-1,-1};
Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();
for (int i = 0; i < unsortedArr.length; i++) {
Integer value = countMap.get(unsortedArr[i]);
if (value == null) {
countMap.put(unsortedArr[i], 0);
} else {
int intval = value.intValue();
intval++;
countMap.put(unsortedArr[i], intval);
}
}
System.out.println(countMap.toString());
int max = getMaxFreq(countMap.values());
List<Integer> modes = new ArrayList<Integer>();
for (Entry<Integer, Integer> entry : countMap.entrySet()) {
int value = entry.getValue();
if (value == max)
modes.add(entry.getKey());
}
System.out.println(modes);
}
public static int getMaxFreq(Collection<Integer> valueSet) {
int max = 0;
boolean setFirstTime = false;
for (Iterator iterator = valueSet.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
if (!setFirstTime) {
max = integer;
setFirstTime = true;
}
if (max < integer) {
max = integer;
}
}
return max;
}
}
Test data
Modes {1,3} for { 3, 1, 5, 2, 4, 1, 3, 4, 3, 2, 1, 3, 4, 1 };
Modes {-1} for { 3, 1, 5, 2, 4, 1, 3, 4, 3, 2, 1, 3, 4, 1 ,-1,-1,-1,-1,-1};
There is something wrong in your setDelimiter()
function. You don't want to double quote the delimiters, do you?
public void setDelimiter(String delimiter) {
char[] c = delimiter.toCharArray();
this.delimiter = "\\" + c[0] + "\\" + c[1];
System.out.println("Delimiter string is: " + this.delimiter);
}
However, as other users have said, it's better to use the Pattern.quote() method to escape your delimiter if your requirements permit.
sometimes this message shown when you are calling a wrong api
check your api endpoint
You need to define $hidden
and $visible
attributes. They'll be set global (that means always return all attributes from $visible
array).
Using method makeVisible($attribute)
and makeHidden($attribute)
you can dynamically change hidden and visible attributes. More: Eloquent: Serialization -> Temporarily Modifying Property Visibility
You're missing #include <stdlib.h>
.
POJO : It is a java file(class) which doesn't extend or implement any other java file(class).
Bean: It is a java file(class) in which all variables are private, methods are public and appropriate getters and setters are used for accessing variables.
Normal class: It is a java file(class) which may consist of public/private/default/protected variables and which may or may not extend or implement another java file(class).
I like Consolas
a lot. This top-10 list is a good resource for others. It includes examples and descriptions.
I'd have thought you need to use a MessageFormat rather than DecimalFormat. That should be more flexible.
In general, you can add a View in a specific position using a FrameLayout as container by specifying the leftMargin and topMargin attributes.
The following example will place a 20x20px ImageView at position (100,200) using a FrameLayout as fullscreen container:
XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:background="#33AAFF"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
Activity / Fragment / Custom view
//...
FrameLayout root = (FrameLayout)findViewById(R.id.root);
ImageView img = new ImageView(this);
img.setBackgroundColor(Color.RED);
//..load something inside the ImageView, we just set the background color
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(20, 20);
params.leftMargin = 100;
params.topMargin = 200;
root.addView(img, params);
//...
This will do the trick because margins can be used as absolute (X,Y) coordinates without a RelativeLayout:
All you have to do is use the value attribute of input tags:
<input type="text" value="Your Value" />
Or, in the case of a textarea:
<textarea>Your Value</textarea>
On C# this works:
if (DDLAlmacen.Items.Count > 0)
{
if (DDLAlmacen.Items.FindByValue("AlmacenDefectoAndes").Value == "AlmacenDefectoAndes")
{
DDLAlmacen.SelectedValue = "AlmacenDefectoAndes";
}
}
Update:
Translating the code above to Visual Basic doesn't work. It throws "System.NullReferenceException: Object reference not set to an instance of an object.."
So. for this to work on Visual Basic, I had to change the code like this:
If DDLAlmacen.Items.Count > 0 Then
If DDLAlmacen.Items.Contains(New ListItem("AlmacenDefectoAndes")) Then
DDLAlmacen.SelectedValue = "AlmacenDefectoAndes"
End If
End If
There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.
Assuming
d <- read.table(text = "263807.0 1582
196190.5 1016
586689.0 3479
")
names(d) <- c("min", "count2.freq")
> d
min count2.freq
1 263807.0 1582
2 196190.5 1016
3 586689.0 3479
To add the desired division as a third variable I would use transform()
> d <- transform(d, new = min / count2.freq)
> d
min count2.freq new
1 263807.0 1582 166.7554
2 196190.5 1016 193.1009
3 586689.0 3479 168.6373
If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want
## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]
## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]
## 3. via `$`
d$new <- d$min / d$count2.freq
All of these can be used at the prompt too, but which is easier to read:
d <- transform(d, new = min / count2.freq)
or
d$new <- d$min / d$count2.freq ## or any of the above examples
Hopefully you think like I do and the first version is better ;-)
The reason we don't use the syntactic sugar of tranform()
et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform()
et al work just fine. But buried in function calls or within a call to one of the apply()
family of functions they can and often do break.
Likewise, be careful using numeric indices (## 2.
above); if you change the ordering of your data, you will select the wrong variables.
If you are just wanting to do the division (rather than insert the result back into the data frame, then use with()
, which allows us to isolate the simple expression you wish to evaluate
> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373
This is again much cleaner code than the equivalent
> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373
as it explicitly states that "using d
, execute the code min / count2.freq
. Your preference may be different to mine, so I have shown all options.
An often-used metaphor to describe Traits is Traits are interfaces with implementation.
This is a good way of thinking about it in most circumstances, but there are a number of subtle differences between the two.
For a start, the instanceof
operator will not work with traits (ie, a trait is not a real object), therefore you can't use that to see if a class has a certain trait (or to see if two otherwise unrelated classes share a trait). That's what they mean by it being a construct for horizontal code re-use.
There are functions now in PHP that will let you get a list of all the traits a class uses, but trait-inheritance means you'll need to do recursive checks to reliably check if a class at some point has a specific trait (there's example code on the PHP doco pages). But yeah, it's certainly not as simple and clean as instanceof
is, and IMHO it's a feature that would make PHP better.
Also, abstract classes are still classes, so they don't solve multiple-inheritance related code re-use problems. Remember you can only extend one class (real or abstract) but implement multiple interfaces.
I've found traits and interfaces are really good to use hand in hand to create pseudo multiple inheritance. Eg:
class SlidingDoor extends Door implements IKeyed
{
use KeyedTrait;
[...] // Generally not a lot else goes here since it's all in the trait
}
Doing this means you can use instanceof
to determine if the particular Door object is Keyed or not, you know you'll get a consistent set of methods, etc, and all the code is in one place across all the classes that use the KeyedTrait.