I also lost a half of day trying to fix this.
It appeared that root was my project pom.xml file with dependency:
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
Other members of the team had no problems. At the end it appeared, that I got newer tomcat which has different version of jsp-api provided (in tomcat 7.0.60 and above it will be jsp-api 2.2).
So in this case, options would be:
a) installing different (older/newer) tomcat like (Exactly what I did, because team is on older version)
b) changing dependency scope to 'compile'
c) update whole project dependencies to the actual version of Tomcat/lib provided APIs
d) put matching version of the jsp-api.jar in {tomcat folder}/lib
via Reflection
var property = object.GetType().GetProperty("YourProperty")
property.SetValue(object,some_value,null);
Similar is for methods
try with this:
var c=new Image("Path to the background image");
c.onload=function(){
//render the form
}
With this code you preload the background image and render the form when it's loaded
I think SerializerMethodField is what you're looking for:
class FooSerializer(serializers.ModelSerializer):
my_field = serializers.SerializerMethodField('is_named_bar')
def is_named_bar(self, foo):
return foo.name == "bar"
class Meta:
model = Foo
fields = ('id', 'name', 'my_field')
http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
The best way depends a lot on the platform(s) being targeted, debug vs. release usage etc.
I don't think there is one best way, but to "force" a wait on enter type scenario in a fairly generic way, especially when debugging (typically this is either compiled in or out based on NDEBUG
or _DEBUG
), you could try std::getline
as follows
inline void wait_on_enter()
{
std::string dummy;
std::cout << "Enter to continue..." << std::endl;
std::getline(std::cin, dummy);
}
With our without the "enter to continue", as needed.
If you have a handle to an existing fragment you can just replace it with the fragment's ID.
Example in Kotlin:
fun aTestFuction() {
val existingFragment = MyExistingFragment() //Get it from somewhere, this is a dirty example
val newFragment = MyNewFragment()
replaceFragment(existingFragment, newFragment, "myTag")
}
fun replaceFragment(existing: Fragment, new: Fragment, tag: String? = null) {
supportFragmentManager.beginTransaction().replace(existing.id, new, tag).commit()
}
Overriding means, giving a different definition of an existing function with same parameters, and overloading means adding a different definition of an existing function with different parameters.
Example:
#include <iostream>
class base{
public:
//this needs to be virtual to be overridden in derived class
virtual void show(){std::cout<<"I am base";}
//this is overloaded function of the previous one
void show(int x){std::cout<<"\nI am overloaded";}
};
class derived:public base{
public:
//the base version of this function is being overridden
void show(){std::cout<<"I am derived (overridden)";}
};
int main(){
base* b;
derived d;
b=&d;
b->show(); //this will call the derived overriden version
b->show(6); // this will call the base overloaded function
}
Output:
I am derived (overridden)
I am overloaded
Use std::make_pair
:
revenue.push_back(std::make_pair("string",map[i].second));
You should be aware that values of fields could contain commas and quotation characters, so some of the suggested answers would not work, as the CSV output file would not be correct. To replace quotation characters in a field, and replace it with the double quotation character, you can use the REPLACE function that oracle provides, to change a single quote to double quote.
set echo off
set heading off
set feedback off
set linesize 1024 -- or some other value, big enough
set pagesize 50000
set verify off
set trimspool on
spool output.csv
select trim(
'"' || replace(col1, '"', '""') ||
'","' || replace(col2, '"', '""') ||
'","' || replace(coln, '"', '""') || '"' ) -- etc. for all the columns
from yourtable
/
spool off
Or, if you want the single quote character for the fields:
set echo off
set heading off
set feedback off
set linesize 1024 -- or some other value, big enough
set pagesize 50000
set verify off
set trimspool on
spool output.csv
select trim(
'"' || replace(col1, '''', '''''') ||
'","' || replace(col2, '''', '''''') ||
'","' || replace(coln, '''', '''''') || '"' ) -- etc. for all the columns
from yourtable
/
spool off
I think you might be looking for Except
:
The Except operator produces the set difference between two sequences. It will only return elements in the first sequence that don't appear in the second. You can optionally provide your own equality comparison function.
Check out this link, this link, or Google, for more information.
Implement your adapter Filterable:
public class vJournalAdapter extends ArrayAdapter<JournalModel> implements Filterable{
private ArrayList<JournalModel> items;
private Context mContext;
....
then create your Filter class:
private class JournalFilter extends Filter{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
List<JournalModel> allJournals = getAllJournals();
if(constraint == null || constraint.length() == 0){
result.values = allJournals;
result.count = allJournals.size();
}else{
ArrayList<JournalModel> filteredList = new ArrayList<JournalModel>();
for(JournalModel j: allJournals){
if(j.source.title.contains(constraint))
filteredList.add(j);
}
result.values = filteredList;
result.count = filteredList.size();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count == 0) {
notifyDataSetInvalidated();
} else {
items = (ArrayList<JournalModel>) results.values;
notifyDataSetChanged();
}
}
}
this way, your adapter is Filterable, you can pass filter item to adapter's filter and do the work. I hope this will be helpful.
Excel export script works on IE7+, Firefox and Chrome.
function fnExcelReport()
{
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('headerTable'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
Just create a blank iframe:
<iframe id="txtArea1" style="display:none"></iframe>
Call this function on:
<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>
You can escape shell metacharacters with ^
:
echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml
Note that since echo
is a shell built-in it doesn't follow the usual conventions regarding quoting, so just quoting the argument will output the quotes instead of removing them.
The other method that's not mentioned in the other comments is to bind to the service from the activity using bindService() and get an instance of the service in the ServiceConnection callback. As described here http://developer.android.com/guide/components/bound-services.html
In the case that you not only want to exclude a list of special characters, but to exclude all characters that are not letters or numbers, I would suggest that you use a char type comparison approach.
For each character in the String, I would check if the unicode character is between "A" and "Z", between "a" and "z" or between "0" and "9". This is the vba code:
Function cleanString(text As String) As String
Dim output As String
Dim c 'since char type does not exist in vba, we have to use variant type.
For i = 1 To Len(text)
c = Mid(text, i, 1) 'Select the character at the i position
If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or (c >= "A" And c <= "Z") Then
output = output & c 'add the character to your output.
Else
output = output & " " 'add the replacement character (space) to your output
End If
Next
cleanString = output
End Function
The Wikipedia list of Unicode characers is a good quick-start if you want to customize this function a little more.
This solution has the advantage to be functionnal even if the user finds a way to introduce new special characters. It also faster than comparing two lists together.
It's an encoding error - so if it's a unicode string, this ought to fix it:
text.encode("windows-1252").decode("utf-8")
If it's a plain string, you'll need an extra step:
text.decode("utf-8").encode("windows-1252").decode("utf-8")
Both of these will give you a unicode string.
By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:
>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}
you can go to mongoDB compass client and follow these steps: 1.Click Fill in connection fields individually:
2.In hostname type : 127.0.0.1
3. Click CONNECT.
export https_proxy=http://user:pswd@host:port
^^^^
Use http
for https_proxy instead of https
this worked fine for me:
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.ReadOnlyField(source='category.name')
class Meta:
model = Item
fields = "__all__"
Simplest way I can think of:
# checking whether foo is a boolean
!!foo == foo
Try this:
Project -> Properties -> Java Build Path -> Add Class Folder.
If it doesnt work, please be specific in what way your compilation fails, specifically post the error messages Eclipse returns, and i will know what to do about it.
I suspect that the following is as accurate as can be expected without knowing when the user's locale switched over from the Julian to the Gregorian calendars.
It accepts either '-', '/', or nothing as separators between year, month, and day, no matter the order.
MMddyyyy:
^(((0[13-9]|1[012])[-/]?(0[1-9]|[12][0-9]|30)|(0[13578]|1[02])[-/]?31|02[-/]?(0[1-9]|1[0-9]|2[0-8]))[-/]?[0-9]{4}|02[-/]?29[-/]?([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00))$
ddMMyyyy:
^(((0[1-9]|[12][0-9]|30)[-/]?(0[13-9]|1[012])|31[-/]?(0[13578]|1[02])|(0[1-9]|1[0-9]|2[0-8])[-/]?02)[-/]?[0-9]{4}|29[-/]?02[-/]?([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00))$
yyyyMMdd:
^([0-9]{4}[-/]?((0[13-9]|1[012])[-/]?(0[1-9]|[12][0-9]|30)|(0[13578]|1[02])[-/]?31|02[-/]?(0[1-9]|1[0-9]|2[0-8]))|([0-9]{2}(([2468][048]|[02468][48])|[13579][26])|([13579][26]|[02468][048]|0[0-9]|1[0-6])00)[-/]?02[-/]?29)$
Other than order, these all are accurate to the Julian Calendar (leap year every four years) until 1700, when the Gregorian Calendar diverges from the Julian. It has two issues:
This has been tested against Java's calendar implementation from the year 0001 until the year 9999 with the only discrepancy being the abovementioned 10 days in 1582.
Different versions of react between my shared libraries seemed to be the problem (16 and 17), changed both to 16.
Yes, you can use SQL IN
operator to search multiple absolute values:
SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );
If you want to use LIKE
you will need to use OR
instead:
SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';
Using AND
(as you tried) requires ALL conditions to be true, using OR
requires at least one to be true.
Try this piece of code:
$first = $string[0];
if($first == 'A' || $first == 'E' || $first == 'I' || $first == 'O' || $first == 'U') {
$v='starts with vowel';
}
else {
$v='does not start with vowel';
}
Addressing the question as updated.
#...part of script without redirection...
{
#...part of script with redirection...
} > file1 2>file2 # ...and others as appropriate...
#...residue of script without redirection...
The braces '{ ... }' provide a unit of I/O redirection. The braces must appear where a command could appear - simplistically, at the start of a line or after a semi-colon. (Yes, that can be made more precise; if you want to quibble, let me know.)
You are right that you can preserve the original stdout and stderr with the redirections you showed, but it is usually simpler for the people who have to maintain the script later to understand what's going on if you scope the redirected code as shown above.
The relevant sections of the Bash manual are Grouping Commands and I/O Redirection. The relevant sections of the POSIX shell specification are Compound Commands and I/O Redirection. Bash has some extra notations, but is otherwise similar to the POSIX shell specification.
If getFiles() returns a java.util.Collection
, !getFiles().isEmpty() && size<5 can be OK.
On the other hand, unless you encapsulate the container which provides method such as boolean sizeBetween(int min, int max)
.
As of May 2017, multiple FROM
s can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.
The general syntax involves adding
FROM
additional times within your Dockerfile - whichever is the lastFROM
statement is the final base image. To copy artifacts and outputs from intermediate images useCOPY --from=<base_image_number>
.
FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]
The result would be two images, one for building, one with just the resulting app (much, much smaller)
REPOSITORY TAG IMAGE ID CREATED SIZE
multi latest bcbbf69a9b59 6 minutes ago 10.3MB
golang 1.7.3 ef15416724f6 4 months ago 672MB
what is a base image?
A set of files, plus EXPOSE
'd ports, ENTRYPOINT
and CMD
.
You can add files and build a new image based on that base image, with a new Dockerfile
starting with a FROM
directive: the image mentioned after FROM
is "the base image" for your new image.
does it mean that if I declare
neo4j/neo4j
in aFROM
directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?
Only if you don't overwrite CMD
and ENTRYPOINT
.
But the image in itself is enough: you would use a FROM neo4j/neo4j
if you had to add files related to neo4j
for your particular usage of neo4j
.
var obj=[
{
id : "001",
name : "apple",
category : "fruit",
color : "red"
},
{
id : "002",
name : "melon",
category : "fruit",
color : "green"
},
{
id : "003",
name : "banana",
category : "fruit",
color : "yellow"
}
]
var tbl=$("<table/>").attr("id","mytable");
$("#div1").append(tbl);
for(var i=0;i<obj.length;i++)
{
var tr="<tr>";
var td1="<td>"+obj[i]["id"]+"</td>";
var td2="<td>"+obj[i]["name"]+"</td>";
var td3="<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr+td1+td2+td3);
}
This works on all current browsers on WinXP. Basically just checking what the current backgrond image is. If it's image1, show image2, otherwise show image1.
The jsapi stuff just loads jQuery from the Google CDN (easier for testing a misc file on the desktop).
The replace is for cross-browser compatibility (opera and ie add quotes to the url and firefox, chrome and safari remove quotes).
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
var original_image = 'url(http://stackoverflow.com/Content/img/wmd/link.png)';
var second_image = 'url(http://stackoverflow.com/Content/img/wmd/code.png)';
$('.mydiv').click(function() {
if ($(this).css('background-image').replace(/"/g, '') == original_image) {
$(this).css('background-image', second_image);
} else {
$(this).css('background-image', original_image);
}
return false;
});
});
</script>
<style>
.mydiv {
background-image: url('http://stackoverflow.com/Content/img/wmd/link.png');
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="mydiv"> </div>
</body>
</html>
Edit: It's been a few years since I originally posted this answer, and even though I got a few upvotes, I'm not really happy with my previous answer, so I have redone it completely. I hope this helps.
GET
and POST
:One way to get rid of this error message is to make your form use GET
instead of POST
. Just keep in mind that this is not always an appropriate solution (read below).
Always use POST if you are performing an action that you don't want to be repeated, if sensitive information is being transferred or if your form contains either a file upload or the length of all data sent is longer than ~2000 characters.
Examples of when to use POST
would include:
GET
with an <input type="file">
field, only the filename will be sent to the server, which 99.73% of the time is not what you want.)In any of these cases, you don't want people refreshing the page and re-sending the data. If you are sending sensitive information, using GET would not only be inappropriate, it would be a security issue (even if the form is sent by AJAX) since the sensitive item (e.g. user's password) is sent in the URL and will therefore show up in server access logs.
Use GET for basically anything else. This means, when you don't mind if it is repeated, for anything that you could provide a direct link to, when no sensitive information is being transferred, when you are pretty sure your URL lengths are not going to get out of control and when your forms don't have any file uploads.
Examples would include:
In these cases POST would be completely inappropriate. Imagine if search engines used POST for their searches. You would receive this message every time you refreshed the page and you wouldn't be able to just copy and paste the results URL to people, they would have to manually fill out the form themselves.
POST
:To me, in most cases even having the "Confirm form resubmission" dialog pop up shows that there is a design flaw. By the very nature of POST
being used to perform destructive actions, web designers should prevent users from ever performing them more than once by accidentally (or intentionally) refreshing the page. Many users do not even know what this dialog means and will therefore just click on "Continue". What if that was after a "submit payment" request? Does the payment get sent again?
So what do you do? Fortunately we have the Post/Redirect/Get design pattern. The user submits a POST request to the server, the server redirects the user's browser to another page and that page is then retrieved using GET.
Here is a simple example using PHP:
if(!empty($_POST['username'] && !empty($_POST['password'])) {
$user = new User;
$user->login($_POST['username'], $_POST['password']);
if ($user->isLoggedIn()) {
header("Location: /admin/welcome.php");
exit;
}
else {
header("Location: /login.php?invalid_login");
}
}
Notice how in this example even when the password is incorrect, I am still redirecting back to the login form. To display an invalid login message to the user, just do something like:
if (isset($_GET['invalid_login'])) {
echo "Your username and password combination is invalid";
}
If you are having this issue and you are performing a populate somewhere along the lines, see this Mongoose issue.
Update to Mongoose 4.0 and the issue has been fixed.
If both columns can contain NULL
, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
This way you won't have to check for NULL
-ness of each column separately.
Alternatively, if both columns are actually defined as NOT NULL
, CONCAT() will be quite enough:
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
As for COALESCE
, it's a bit different beast: given the list of arguments, it returns the first that's not NULL
.
<script type="text/javascript">
document.write(
"<iframe id='myframe' src='http://www.example.com/" +
window.location.search + "' height='100' width='100%' >"
)
</script>
This code takes the url-parameters (?a=1&b=2) from the page containing the iframe and attaches them to the base url of the iframe. It works for my purposes.
This is a FAQ:
//somexpression[$N]
means "Find every node selected by //somexpression
that is the $N
th child of its parent".
What you want is:
(//input[@id="search_query"])[2]
Remember: The []
operator has higher precedence (priority) than the //
abbreviation.
Try below, it will generate an app-debug.apk on your root/android/app/build/outputs/apk/debug folder
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
then go to android folder and run
./gradlew assembleDebug
I had also faced the same issue in which my FB app was automatically stopped and users were not able to login and were getting the message "app is in development mode.....".
Reason why FB automatically stopped my app was that I had not provided a valid PRIVACY policy & terms URL. So, make sure you enter these URLs on your app basic settings page and then make your app PUBLIC from app review page as described in above posts.
I had the same problem with latest Lampp with MariaDB on Ubuntu Server 14.04, and @iceberg's solution worked very well:
You just change following line in /etc/phpmyadmin/config.inc.php
$ Cfg ['Servers'] [$ i] ['table_uiprefs'] = ‘pma_table_uiprefs’;
to
$ cfg ['Servers'] [$ i] ['pma__table_uiprefs'] = ‘pma__table_uiprefs’;
And restart apache server with command,
sudo service apache2 restart
Lampp config.inc.php is located in /opt/lampp/phpmyadmin/config.inc.php and to make it work, I also needed to change
$ cfg ['Servers'] [$ i] ['tracking'] = ‘pma__tracking’;
to
$ cfg ['Servers'] [$ i] ['pma__tracking'] = ‘pma__tracking’;
and restart the lampp:
sudo /opt/lampp/lampp stop
sudo /opt/lampp/lampp start
If you want to add parameters without modifying the form, you have to serialize the form, add your parameters and send it with AJAX:
var formData = $("#commentForm").serializeArray();
formData.push({name: "url", value: window.location.pathname});
formData.push({name: "time", value: new Date().getTime()});
$.post("api/comment", formData, function(data) {
// request has finished, check for errors
// and then for example redirect to another page
});
See .serializeArray()
and $.post()
documentation.
GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.
The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.
I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).
For the test, I set:
the GoalSeek cell H18 = (G18^3)+(3*G18^2)+6
the Goal cell H32 = 11
the ChangingCell G18 = 0
The code was:
Sub GSeek()
With Worksheets("Sheet1")
.Range("H18").GoalSeek _
Goal:=.Range("H32").Value, _
ChangingCell:=.Range("G18")
End With
End Sub
And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.
Try out Vertabelo!
It's an online database modeler that supports reverse enginnering.
Just create free of charge Vertabelo account, import an existing database into Vertabelo and voila - your database is in Vertabelo!
It supports following databases:
Each control deriving from Panel
implements distinct layout logic performed in Measure()
and Arrange()
:
Measure()
determines the size of the panel and each of its childrenArrange()
determines the rectangle where each control rendersThe last child of the DockPanel
fills the remaining space. You can disable this behavior by setting the LastChild
property to false
.
The StackPanel
asks each child for its desired size and then stacks them. The stack panel calls Measure()
on each child, with an available size of Infinity
and then uses the child's desired size.
A Grid
occupies all available space, however, it will set each child to their desired size and then center them in the cell.
You can implement your own layout logic by deriving from Panel
and then overriding MeasureOverride()
and ArrangeOverride()
.
See this article for a simple example.
I have found this error can occur with traditional ASP.NET website when you create the Controller in non App_Code directory (sometimes Visual Studio prevents this).
It sets the file type to "Compile" whereas any code added to "App_Code" is set to "Content". If you copy or move the file into App_Code then it is still set as "Compile".
I suspect it has something to with Website Project operation as website projects do not have any build operation.Clearing the bin folder and changing to "Content" seems to fix it.
You can also use js map function:
$("#multipleSelect :selected").map(function(i, el) {
return $(el).val();
}).get();
And then you can get any property of the option
element:
return $(el).text();
return $(el).data("mydata");
return $(el).prop("disabled");
etc...
I think you can just cast to ObjectNode and use put
method. Like this
ObjectNode o = (ObjectNode) jsonNode;
o.put("value", "NO");
The Separator
you are using is a UI component. You would be better using a simple String sep = ", "
.
since df.save(path, source, mode)
is deprecated, (http://spark.apache.org/docs/1.5.0/api/scala/index.html#org.apache.spark.sql.DataFrame)
use df.write.format(source).mode("overwrite").save(path)
where df.write is DataFrameWriter
'source' can be ("com.databricks.spark.avro" | "parquet" | "json")
Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
The transcript mode is what you want and is used by Google Talk and the SMS/MMS application. Are you correctly calling notifyDatasetChanged() on your adapter when you add items?
You could combine them, use jQuery to bind the function to the click
<div id="myDiv">Some Content</div>
$('#myDiv').click(divFunction);
function divFunction(){
//some code
}
Here is a function that tells if an element is in visible in the current viewport of a parent element:
function inParentViewport(el, pa) {
if (typeof jQuery === "function"){
if (el instanceof jQuery)
el = el[0];
if (pa instanceof jQuery)
pa = pa[0];
}
var e = el.getBoundingClientRect();
var p = pa.getBoundingClientRect();
return (
e.bottom >= p.top &&
e.right >= p.left &&
e.top <= p.bottom &&
e.left <= p.right
);
}
Simply works as:
$("a. close").live("click",function(event){
return confirm("Do you want to delete?");
});
It is possible by recreating table.Its work for me please follow following step:
do all above steps in worker thread to reduce load on uithread
after you retrieve the first 50 rows in the query windows, simply click a column to get focus on the query window, then once selected do ctrl + pagedown
This will load the full result set (all rows)
try this:
<script src="https://maps.googleapis.com/maps/api/js"></script>
it works for me... the point is, change HTTP to HTTPS
For me, the issue was some plugin in my Visual Studio started forcing my application into x64 64bit mode, so the Oracle driver wasn't being found as I had Oracle 32bit installed.
So if you are having this issue, try running Visual Studio in safemode (devenv /safemode). I could find that it was looking in SYSWOW64 for the ic.dll file by using the ProcMon app by SysInternals/Microsoft.
Update: For me it was the Telerik JustTrace product that was causing the issue, it was probably hooking in and affecting the runtime version somehow to do tracing.
Update2: It's not just JustTrace causing an issue, JustMock is causing the same processor mode issue. JustMock is easier to fix though: Click JustMock-> Disable Profiler and then my web app's oracle driver runs in the correct CPU mode. This might be fixed by Telerik in the future.
Are you using any other JavaScript libraries? If so, you will probably need to use jQuery in compatibility mode:
Create your file then return a reference to it with the correct header to trigger the Save As - edit the following as needed. Put your CSV data into $csvdata.
$fname = 'myCSV.csv';
$fp = fopen($fname,'wb');
fwrite($fp,$csvdata);
fclose($fp);
header('Content-type: application/csv');
header("Content-Disposition: inline; filename=".$fname);
readfile($fname);
C99 is available online. Quoted from www.open-std.org:
The lastest publically available version of the standard is the combined C99 + TC1 + TC2 + TC3, WG14 N1256, dated 2007-09-07. This is a WG14 working paper, but it reflects the consolidated standard at the time of issue.
Old, but this will do what you're after without need for jquery. The hidden overflow gets rid of the scrollbar, and the javascript makes it the right size.
<select multiple='multiple' id='select' style='overflow:hidden'>
<option value='foo'>foo</option>
<option value='bar'>bar</option>
<option value='abc'>abc</option>
<option value='def'>def</option>
<option value='xyz'>xyz</option>
</select>
And just a tiny amount of javascript
var select = document.getElementById('select');
select.size = select.length;
Try docker inspect
, for example:
$ docker inspect --type=image treeder/hello.rb:nada
Error: No such image: treeder/hello.rb:nada
[]
But now with an image that exists, you'll get a bunch of information, eg:
$ docker inspect --type=image treeder/hello.rb:latest
[
{
"Id": "85c5116a2835521de2c52f10ab5dda0ff002a4a12aa476c141aace9bc67f43ad",
"Parent": "ecf63f5eb5e89e5974875da3998d72abc0d3d0e4ae2354887fffba037b356ad5",
"Comment": "",
"Created": "2015-09-23T22:06:38.86684783Z",
...
}
]
And it's in a nice json format.
This is a nice example: The Repository Pattern Example in C#
Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:
Xcode 6 beta 4 added two functions to iterate on ranges with a step other than one:
stride(from: to: by:)
, which is used with exclusive ranges and stride(from: through: by:)
, which is used with inclusive ranges.
To iterate on a range in reverse order, they can be used as below:
for index in stride(from: 5, to: 1, by: -1) {
print(index)
}
//prints 5, 4, 3, 2
for index in stride(from: 5, through: 1, by: -1) {
print(index)
}
//prints 5, 4, 3, 2, 1
Note that neither of those is a Range
member function. They are global functions that return either a StrideTo
or a StrideThrough
struct, which are defined differently from the Range
struct.
A previous version of this answer used the by()
member function of the Range
struct, which was removed in beta 4. If you want to see how that worked, check the edit history.
Here's an alternate way of finding height. Add an additional attribute to your node called height:
class Node
{
data value; //data is a custom data type
node right;
node left;
int height;
}
Now, we'll do a simple breadth-first traversal of the tree, and keep updating the height value for each node:
int height (Node root)
{
Queue<Node> q = Queue<Node>();
Node lastnode;
//reset height
root.height = 0;
q.Enqueue(root);
while(q.Count > 0)
{
lastnode = q.Dequeue();
if (lastnode.left != null){
lastnode.left.height = lastnode.height + 1;
q.Enqueue(lastnode.left);
}
if (lastnode.right != null){
lastnode.right.height = lastnode.height + 1;
q.Enqueue(lastnode.right);
}
}
return lastnode.height; //this will return a 0-based height, so just a root has a height of 0
}
Cheers,
Now we can easily do this using the aspect-ratio
ref property
.container {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr)); /* 3 columns */
grid-gap: 10px;
}
.container>* {
aspect-ratio: 1 / 1; /* a square ratio */
border: 1px solid;
/* center content */
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
img {
max-width: 100%;
display: block;
}
_x000D_
<div class="container">
<div> some content here </div>
<div><img src="https://picsum.photos/id/25/400/400"></div>
<div>
<h1>a title</h1>
</div>
<div>more and more content <br>here</div>
<div>
<h2>another title</h2>
</div>
<div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
Also like below where we can have a variable number of columns
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-gap: 10px;
}
.container>* {
aspect-ratio: 1 / 1; /* a square ratio */
border: 1px solid;
/* center content */
display: flex;
align-items: center;
justify-content: center;
text-align: center;
}
img {
max-width: 100%;
display: block;
}
_x000D_
<div class="container">
<div> some content here </div>
<div><img src="https://picsum.photos/id/25/400/400"></div>
<div>
<h1>a title</h1>
</div>
<div>more and more content <br>here</div>
<div>
<h2>another title</h2>
</div>
<div><img src="https://picsum.photos/id/104/400/400"></div>
<div>more and more content <br>here</div>
<div>
<h2>another title</h2>
</div>
<div><img src="https://picsum.photos/id/104/400/400"></div>
</div>
_x000D_
It's impossible without CSS. In fact, the <u>
tag is simply adding text-decoration:underline
to the text with the browser's built-in CSS.
Here's what you can do:
<html>
<head>
<!-- Other head stuff here, like title or meta -->
<style type="text/css">
u {
border-bottom: 1px dotted #000;
text-decoration: none;
}
</style>
</head>
<!-- Body, content here -->
</html>
There are both zip and unzip executables (as well as a boat load of other useful applications) in the UnxUtils package available on SourceForge (http://sourceforge.net/projects/unxutils). Copy them to a location in your PATH, such as 'c:\windows', and you will be able to include them in your scripts.
This is not the perfect solution (or the one you asked for) but a decent work-a-round.
You can try this:
Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);
I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar
from a Date
and just get the month's diff.
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Where str
is your XML string. See the MSDN article for more info.
Most of these answers are invalid after the 6/1/2016 Instagram API changes. The best solution now is here. Go to your feed on instagram.com, copy the link address for any of your pictures, and paste it into the textbox on that page. Worked like a charm.
Instead of using the ScrimInsetsFrameLayout
... Isn't it easier to just add a view with a fixed height of 24dp
and a background of primaryColor
?
I understand that this involves adding a dummy view in the hierarchy, but it seems cleaner to me.
I already tried it and it's working well.
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_base_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- THIS IS THE VIEW I'M TALKING ABOUT... -->
<View
android:layout_width="match_parent"
android:layout_height="24dp"
android:background="?attr/colorPrimary" />
<android.support.v7.widget.Toolbar
android:id="@+id/activity_base_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="2dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark" />
<FrameLayout
android:id="@+id/activity_base_content_frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<fragment
android:id="@+id/activity_base_drawer_fragment"
android:name="com.myapp.drawer.ui.DrawerFragment"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:elevation="4dp"
tools:layout="@layout/fragment_drawer" />
</android.support.v4.widget.DrawerLayout>
Have you tried the __name__
attribute of the class? ie type(x).__name__
will give you the name of the class, which I think is what you want.
>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'
If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:
x.__class__.__name__
Based on the example here: http://drupal.org/node/550488
The following will probably work in .htaccess
<IfModule mod_expires.c>
# Enable expirations.
ExpiresActive On
# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600
<FilesMatch (\.js|\.html)$>
ExpiresActive Off
</FilesMatch>
</IfModule>
if you want to rotate inline elements, you should set the inline element to inline-block
first.
i {
display: inline-block;
}
i:hover {
animation: rotate-btn .5s linear 3;
-webkit-animation: rotate-btn .5s linear 3;
}
@keyframes rotate-btn {
0% {
transform: rotate(0);
}
100% {
transform: rotate(-360deg);
}
}
Your questions seems to be about deleting entire keys in a database. In this case you should try:
redis-cli
(if running on port 6379), else you will have to specify the port number also.select {Index}
)flushdb
If you want to flush keys in all databases, then you should try flushall
.
[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]
Here's a complete example using Java 8:
import java.util.*;
public class Test {
public static void main(String args[]) {
int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };
Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
.reversed());
System.out.println(Arrays.deepToString(twoDim));
}
}
Output:
[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]
For Java 7 you can do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[0], o1[0]);
}
});
If you unfortunate enough to work on Java 6 or older, you'd do:
Arrays.sort(twoDim, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return ((Integer) o2[0]).compareTo(o1[0]);
}
});
That attribute is basically the persistence for the "Associated Activity" selection above the layout. At runtime, a layout is always associated with an activity. It can of course be associated with more than one, but at least one. In the tool, we need to know about this mapping (which at runtime happens in the other direction; an activity can call setContentView(layout) to display a layout) in order to drive certain features.
Right now, we're using it for one thing only: Picking the right theme to show for a layout (since the manifest file can register themes to use for an activity, and once we know the activity associated with the layout, we can pick the right theme to show for the layout). In the future, we'll use this to drive additional features - such as rendering the action bar (which is associated with the activity), a place to add onClick handlers, etc.
The reason this is a tools: namespace attribute is that this is only a designtime mapping for use by the tool. The layout itself can be used by multiple activities/fragments etc. We just want to give you a way to pick a designtime binding such that we can for example show the right theme; you can change it at any time, just like you can change our listview and fragment bindings, etc.
(Here's the full changeset which has more details on this)
And yeah, the link Nikolay listed above shows how the new configuration chooser looks and works
One more thing: The "tools" namespace is special. The android packaging tool knows to ignore it, so none of those attributes will be packaged into the APK. We're using it for extra metadata in the layout. It's also where for example the attributes to suppress lint warnings are stored -- as tools:ignore.
Use time()
and localtime()
to get the time:
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("now: %d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
}
but.onclick = callJavascriptFunction;
no double quotes no parentheses.
Try like below
select
split.field(column_name,1,',','"') name1,
split.field(column_name,2,',','"') name2
from table_name
X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!
There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.
Source: classroomm.com
internal members are accessible within the assembly (only accessible in the same project)
private members are accessible within the same class
There are 2 projects in a solution (Project1, Project2) and Project1 has a reference to Project2.
All the Above solution doesnot work for me in Android Api 26 & 27 (Oreo)
, was gettting Error: exposed beyond app through ClipData.Item.getUri
. The solution that fits in my situation was
FileProvider.getUriForFile(Context,packagename,File)
as void shareImage() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(this,getPackageName(),deleteFilePath));
startActivity(Intent.createChooser(intent,"Share with..."));
}
<provider>
in your Manifest.xml
as<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.stickerapplication"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths">
</meta-data>
</provider>
resource
file for your directorys<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="." />
</paths>
*Note this solution is for `external storage` `uri`
In my case, my button's type is submit
not button
and I change the Click
to Sumbit
then every work good. Something like below,
from driver.FindElement(By.Id("btnLogin")).Click();
to driver.FindElement(By.Id("btnLogin")).Submit();
BTW, I have been tried all the answer in this post but not work for me.
For anyone else reading this (in 2019 onwards) unfortunately most JS RSS reading implementations don't now work. Firstly Google API has shut down so this is no longer an option and because of the CORS security policy you generally cannot now request RSS feeds cross-domains.
Using the example on https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options (2015) I get the following:
Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is correct and is a security precaution by the end website but does now mean that the answers above are unlikely to work.
My workaround will probably be to parse the RSS feed through PHP and allow the javascript to access my PHP rather than trying to access the end-destination feed itself.
these methods can help setTitle("your new title"); or super("your new title");
I found the best and easiest way to do it is this one because you don't need to add labels, divs or whatsoever.
input { vertical-align: middle; margin-top: -1px;}
1st: Get personal access token. https://github.com/settings/tokens
2nd: Put account & the token. Example is here:
$ git push
Username for 'https://github.com': # Put your GitHub account name
Password for 'https://{USERNAME}@github.com': # Put your Personal access token
Link on how to create a personal access token: https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line
What could the reason be
A query cancel is immediate, provided that your attention can reach the server and be processed. A query must be in a cancelable state, which is almost always true except if you do certain operations like calling a web service from SQLCLR. If your attention cannot reach the server it's usually due to scheduler overload.
But if your query is part of a transaction that must rollback, then rollback cannot be interrupted. If it takes 10 minutes then it needs 10 minutes and there's nothing you can do about it. Even restarting the server will not help, it will only make startup longer since recovery must finish the rollback.
To answer which specific reason applies to your case, you'll need to investigate yourself.
You can use timespan
TimeSpan timeSpan = new TimeSpan(2, 14, 18);
Console.WriteLine(timeSpan.ToString()); // Displays "02:14:18".
[Edit]
Considering the other answers and the edit to the question, I would still use TimeSpan. No point in creating a new structure where an existing one from the framework suffice.
On these lines you would end up duplicating many native data types.
It's because you're calling doGet()
without actually implementing doGet()
. It's the default implementation of doGet() that throws the error saying the method is not supported.
isinstance(X, type)
Return True
if X
is class and False
if not.
Is key-value pair available in Typescript?
If you think of a C# KeyValuePair<string, string>: No, but you can easily define one yourself:
interface KeyValuePair {
key: string;
value: string;
}
Usage:
let foo: KeyValuePair = { key: "k", value: "val" };
E.g. by naming the fields like
<input type="text" name="item[0][name]" />
<input type="text" name="item[0][email]" />
<input type="text" name="item[1][name]" />
<input type="text" name="item[1][email]" />
<input type="text" name="item[2][name]" />
<input type="text" name="item[2][email]" />
(which is also possible when adding elements via javascript)
The corresponding php script might look like
function show_Names($e)
{
return "The name is $e[name] and email is $e[email], thank you";
}
$c = array_map("show_Names", $_POST['item']);
print_r($c);
For people looking at this today, I would recommend the Seaborn heatmap()
as documented here.
The example above would be done as follows:
import numpy as np
from pandas import DataFrame
import seaborn as sns
%matplotlib inline
Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)
sns.heatmap(df, annot=True)
Where %matplotlib
is an IPython magic function for those unfamiliar.
Arrays are special objects in java, they have a simple attribute named length
which is final
.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
10.7. Array Members
The members of an array type are all of the following:
- The
public
final
fieldlength
, which contains the number of components of the array.length
may be positive or zero.The
public
methodclone
, which overrides the method of the same name in classObject
and throws no checked exceptions. The return type of theclone
method of an array typeT[]
isT[]
.A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
- All the members inherited from class
Object
; the only method ofObject
that is not inherited is itsclone
method.
Resources:
For AngularJs you have to use "angular-datatables.min.js" file for datatable settings. You will get this from http://l-lin.github.io/angular-datatables/#/welcome.
After that you can write code like below,
<script>
var app = angular.module('AngularWayApp', ['datatables']);
</script>
<div ng-app="AngularWayApp" ng-controller="AngularWayCtrl">
<table id="example" datatable="ng" class="table">
<thead>
<tr>
<th><b>UserID</b></th>
<th><b>Firstname</b></th>
<th><b>Lastname</b></th>
<th><b>Email</b></th>
<th><b>Actions</b></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" ng-click="testingClick(user)">
<td>
{{user.UserId}}
</td>
<td>
{{user.FirstName}}
</td>
<td>
{{user.Lastname}}
</td>
<td>
{{user.Email}}
</td>
<td>
<span ng-click="editUser(user)" style="color:blue;cursor: pointer; font-weight:500; font-size:15px" class="btnAdd" data-toggle="modal" data-target="#myModal">Edit</span> |
<span ng-click="deleteUser(user)" style="color:red; cursor: pointer; font-weight:500; font-size:15px" class="btnRed">Delete</span>
</td>
</tr>
</tbody>
</table>
</div>
In case someone needs to run over a table and split a field:
CREATE DEFINER=`root`@`localhost` FUNCTION `fn_split_str`($str VARCHAR(800), $delimiter VARCHAR(12), $position INT) RETURNS varchar(800) CHARSET utf8
DETERMINISTIC
BEGIN
RETURN REPLACE(
SUBSTRING(
SUBSTRING_INDEX($str, $delimiter, $position),
LENGTH(
SUBSTRING_INDEX($str, $delimiter, $position -1)
) + 1
),
$delimiter, '');
END
CREATE DEFINER=`root`@`localhost` FUNCTION `fn_split_str_to_rows`($id INT, $str VARCHAR(800), $delimiter VARCHAR(12), $empty_table BIT) RETURNS int(11)
BEGIN
DECLARE position INT;
DECLARE val VARCHAR(800);
SET position = 1;
IF $empty_table THEN
DROP TEMPORARY TABLE IF EXISTS tmp_rows;
END IF;
SET val = fn_split_str($str, ',', position);
CREATE TEMPORARY TABLE IF NOT EXISTS tmp_rows AS (SELECT $id as id, val as val where 1 = 2);
WHILE (val IS NOT NULL and val != '') DO
INSERT INTO tmp_rows
SELECT $id, val;
SET position = position + 1;
SET val = fn_split_str($str, ',', position);
END WHILE;
RETURN position - 1;
END
DROP TEMPORARY TABLE IF EXISTS tmp_rows;
SELECT SUM(fn_split_str_to_rows(ID, FieldToSplit, ',', 0))
FROM MyTable;
SELECT * FROM tmp_rows;
You can use the id to join to other table.
In case you are only splitting one value you can use it like that
SELECT fn_split_str_to_rows(null, 'AAA,BBB,CCC,DDD,EEE,FFF,GGG', ',', 1);
SELECT * FROM tmp_rows;
We don't need to empty the temporary table, the function will take care of that.
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t st;
void *fun_t(void *arg);
void *fun_t(void *arg)
{
printf("Linux\n");
sem_post(&st);
//pthread_exit("Bye");
while(1);
pthread_exit("Bye");
}
int main()
{
pthread_t pt;
void *res_t;
if(pthread_create(&pt,NULL,fun_t,NULL) == -1)
perror("pthread_create");
if(sem_init(&st,0,0) != 0)
perror("sem_init");
if(sem_wait(&st) != 0)
perror("sem_wait");
printf("Sanoundry\n");
//Try commenting out join here.
if(pthread_join(pt,&res_t) == -1)
perror("pthread_join");
if(sem_destroy(&st) != 0)
perror("sem_destroy");
return 0;
}
Copy and paste this code on a gdb. Onlinegdb would work and see for yourself.
Make sure you understand once you have created a thread, the process run along with main together at the same time.
void *fun_t(void *arg)
{
printf("Linux\n");
sem_post(&st);
if(2-1 == 1)
pthread_exit("Bye");
else
{
printf("We have a problem. Computer is bugged");
pthread_exit("Bye"); //This is redundant since the thread will exit at the end
//of scope. But there are instances where you have a bunch
//of else if here.
}
}
I would want to demonstrate how sometimes you would need to have a segment of code running first using semaphore in this example.
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t st;
void* fun_t (void* arg)
{
printf("I'm thread\n");
sem_post(&st);
}
int main()
{
pthread_t pt;
pthread_create(&pt,NULL,fun_t,NULL);
sem_init(&st,0,0);
sem_wait(&st);
printf("before_thread\n");
pthread_join(pt,NULL);
printf("After_thread\n");
}
Noticed how fun_t is being ran after "before thread" The expected output if it is linear from top to bottom would be before thread, I'm thread, after thread. But under this circumstance, we block the main from running any further until the semaphore is released by func_t. The result can be verified with https://www.onlinegdb.com/
Just simply use:
docker rmi <image:tag> -f
for example:
docker rmi ubuntu:latest -f
will remove image name ubuntu
with tag name latest
and -f
is for forcefully removal.
it worked for me
Maybe this will satisfy you -
something.xml
<CheckBox
android:text="Custom CheckBox"
android:button="@drawable/checkbox_selector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/star_down" />
<item android:state_checked="false" android:drawable="@drawable/star" />
</selector>
For, the reference just refer here
From the error, I infer that referenceElement
is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).
>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'
You probably meant either for element in referenceElement.keys()
or for element in json['referenceElement'].keys()
. With more context on what types json
and referenceElement
are and what they contain, we will be able to better help you if neither solution works.
SQL Server was not configured to allow mixed authentication.
Here are steps to fix:
Select the SQL Server and Windows Authentication mode radio button, and click OK.
Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).
This is also incredibly helpful for IBM Connections users, my wizards were not able to connect until I fxed this setting.
Some special characters give this type of error, so use
$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";
sqlplus / as SYSDBA
ALTER USER existing_account_name IDENTIFIED BY new_password ACCOUNT UNLOCK;
You can use lambda expressions
private void MyMethod(string param1,int param2)
{
//do stuff
}
Thread myNewThread = new Thread(() => MyMethod("param1",5));
myNewThread.Start();
this is so far the best answer i could find, it's fast and easy.
I think what you want is:
abstract class Component {
public deps: any = {};
public props: any = {};
public makePropSetter<T>(prop: string): (val: T) => T {
return function(val) {
this.props[prop] = val
return val
}
}
}
class Post extends Component {
public toggleBody: (val: boolean) => boolean;
constructor () {
super()
this.toggleBody = this.makePropSetter<boolean>('showFullBody')
}
showMore (): boolean {
return this.toggleBody(true)
}
showLess (): boolean {
return this.toggleBody(false)
}
}
The important change is in setProp
(i.e., makePropSetter
in the new code). What you're really doing there is to say: this is a function, which provided with a property name, will return a function which allows you to change that property.
The <T>
on makePropSetter
allows you to lock that function in to a specific type. The <boolean>
in the subclass's constructor is actually optional. Since you're assigning to toggleBody
, and that already has the type fully specified, the TS compiler will be able to work it out on its own.
Then, in your subclass, you call that function, and the return type is now properly understood to be a function with a specific signature. Naturally, you'll need to have toggleBody
respect that same signature.
On macOS, use subprocess.run
to pipe your text to pbcopy
:
import subprocess
data = "hello world"
subprocess.run("pbcopy", universal_newlines=True, input=data)
It will copy "hello world" to the clipboard.
I had met a similar problem, after i add a scope property of servlet dependency in pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
Then it was ok . maybe that will help you.
VBA does not have a Continue
or any other equivalent keyword to immediately jump to the next loop iteration. I would suggest a judicious use of Goto
as a workaround, especially if this is just a contrived example and your real code is more complicated:
For i = LBound(Schedule, 1) To UBound(Schedule, 1)
If (Schedule(i, 1) < ReferenceDate) Then
PrevCouponIndex = i
Goto NextIteration
End If
DF = Application.Run("SomeFunction"....)
PV = PV + (DF * Coupon / CouponFrequency)
'....'
'a whole bunch of other code you are not showing us'
'....'
NextIteration:
Next
If that is really all of your code, though, @Brian is absolutely correct. Just put an Else
clause in your If
statement and be done with it.
From the documentation (help copy-item -full
):
-force <SwitchParameter>
Allows cmdlet to override restrictions such as renaming existing files as long as security is not compromised.
Required? false
Position? named
Default value False
Accept pipeline input? false
Accept wildcard characters? false
using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) " +
"VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
int modified = cmd.ExecuteNonQuery();
if (con.State == System.Data.ConnectionState.Open) con.Close();
return modified;
}
SCOPE_IDENTITY : Returns the last identity value inserted into an identity column in the same scope. for more details http://technet.microsoft.com/en-us/library/ms190315.aspx
In your case, since you are only showing 3 columns:
Name Value Business
or
Name Business Ecommerce Pro
why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.
When I deal with this issue, I always use:
$(".bet").unbind("click").bind("click", function (e) {
// code goes here
}
This way I unbind and rebind in the same stroke.
Here is a version of @adabyron's answer that prevents the leaky EventArgs
abstraction.
First, the modified EventToCommandBehavior
class (now a generic abstract class and formatted with ReSharper code cleanup). Note the new GetCommandParameter
virtual method and its default implementation:
public abstract class EventToCommandBehavior<TEventArgs> : Behavior<FrameworkElement>
where TEventArgs : EventArgs
{
public static readonly DependencyProperty EventProperty = DependencyProperty.Register("Event", typeof(string), typeof(EventToCommandBehavior<TEventArgs>), new PropertyMetadata(null, OnEventChanged));
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(EventToCommandBehavior<TEventArgs>), new PropertyMetadata(null));
public static readonly DependencyProperty PassArgumentsProperty = DependencyProperty.Register("PassArguments", typeof(bool), typeof(EventToCommandBehavior<TEventArgs>), new PropertyMetadata(false));
private Delegate _handler;
private EventInfo _oldEvent;
public string Event
{
get { return (string)GetValue(EventProperty); }
set { SetValue(EventProperty, value); }
}
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public bool PassArguments
{
get { return (bool)GetValue(PassArgumentsProperty); }
set { SetValue(PassArgumentsProperty, value); }
}
protected override void OnAttached()
{
AttachHandler(Event);
}
protected virtual object GetCommandParameter(TEventArgs e)
{
return e;
}
private void AttachHandler(string eventName)
{
_oldEvent?.RemoveEventHandler(AssociatedObject, _handler);
if (string.IsNullOrEmpty(eventName))
{
return;
}
EventInfo eventInfo = AssociatedObject.GetType().GetEvent(eventName);
if (eventInfo != null)
{
MethodInfo methodInfo = typeof(EventToCommandBehavior<TEventArgs>).GetMethod("ExecuteCommand", BindingFlags.Instance | BindingFlags.NonPublic);
_handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, methodInfo);
eventInfo.AddEventHandler(AssociatedObject, _handler);
_oldEvent = eventInfo;
}
else
{
throw new ArgumentException($"The event '{eventName}' was not found on type '{AssociatedObject.GetType().FullName}'.");
}
}
private static void OnEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = (EventToCommandBehavior<TEventArgs>)d;
if (behavior.AssociatedObject != null)
{
behavior.AttachHandler((string)e.NewValue);
}
}
// ReSharper disable once UnusedMember.Local
// ReSharper disable once UnusedParameter.Local
private void ExecuteCommand(object sender, TEventArgs e)
{
object parameter = PassArguments ? GetCommandParameter(e) : null;
if (Command?.CanExecute(parameter) == true)
{
Command.Execute(parameter);
}
}
}
Next, an example derived class that hides DragCompletedEventArgs
. Some people expressed concern about leaking the EventArgs
abstraction into their view model assembly. To prevent this, I created an interface that represents the values we care about. The interface can live in the view model assembly with the private implementation in the UI assembly:
// UI assembly
public class DragCompletedBehavior : EventToCommandBehavior<DragCompletedEventArgs>
{
protected override object GetCommandParameter(DragCompletedEventArgs e)
{
return new DragCompletedArgs(e);
}
private class DragCompletedArgs : IDragCompletedArgs
{
public DragCompletedArgs(DragCompletedEventArgs e)
{
Canceled = e.Canceled;
HorizontalChange = e.HorizontalChange;
VerticalChange = e.VerticalChange;
}
public bool Canceled { get; }
public double HorizontalChange { get; }
public double VerticalChange { get; }
}
}
// View model assembly
public interface IDragCompletedArgs
{
bool Canceled { get; }
double HorizontalChange { get; }
double VerticalChange { get; }
}
Cast the command parameter to IDragCompletedArgs
, similar to @adabyron's answer.
Please download and add SOAP library file with your project File Name : ksoap2-android-assembly-3.4.0-jar-with-dependencies
Clean the application and then start program
Here is the code for SOAP service call
String SOAP_ACTION = "YOUR_ACTION_NAME";
String METHOD_NAME = "YOUR_METHOD_NAME";
String NAMESPACE = "YOUR_NAME_SPACE";
String URL = "YOUR_URL";
SoapPrimitive resultString = null;
try {
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
addPropertyForSOAP(Request);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
soapEnvelope.dotNet = true;
soapEnvelope.setOutputSoapObject(Request);
HttpTransportSE transport = new HttpTransportSE(URL);
transport.call(SOAP_ACTION, soapEnvelope);
resultString = (SoapPrimitive) soapEnvelope.getResponse();
Log.i("SOAP Result", "Result Celsius: " + resultString);
} catch (Exception ex) {
Log.e("SOAP Result", "Error: " + ex.getMessage());
}
if(resultString != null) {
return resultString.toString();
}
else{
return "error";
}
The results may be JSONObject or JSONArray Or String
For your better reference, https://trinitytuts.com/load-data-from-soap-web-service-in-android-application/
Thanks.
Why not measure it:
class Program
{
class NameComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x, y, true);
}
}
class Person
{
public Person(string id, string name)
{
Id = id;
Name = name;
}
public string Id { get; set; }
public string Name { get; set; }
}
static void Main()
{
List<Person> persons = new List<Person>();
persons.Add(new Person("P005", "Janson"));
persons.Add(new Person("P002", "Aravind"));
persons.Add(new Person("P007", "Kazhal"));
Sort(persons);
OrderBy(persons);
const int COUNT = 1000000;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
Sort(persons);
}
watch.Stop();
Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);
watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
OrderBy(persons);
}
watch.Stop();
Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
}
static void Sort(List<Person> list)
{
list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true));
}
static void OrderBy(List<Person> list)
{
var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray();
}
}
On my computer when compiled in Release mode this program prints:
Sort: 1162ms
OrderBy: 1269ms
UPDATE:
As suggested by @Stefan here are the results of sorting a big list fewer times:
List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
persons.Add(new Person("P" + i.ToString(), "Janson" + i.ToString()));
}
Sort(persons);
OrderBy(persons);
const int COUNT = 30;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
Sort(persons);
}
watch.Stop();
Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);
watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
OrderBy(persons);
}
watch.Stop();
Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
Prints:
Sort: 8965ms
OrderBy: 8460ms
In this scenario it looks like OrderBy performs better.
UPDATE2:
And using random names:
List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
persons.Add(new Person("P" + i.ToString(), RandomString(5, true)));
}
Where:
private static Random randomSeed = new Random();
public static string RandomString(int size, bool lowerCase)
{
var sb = new StringBuilder(size);
int start = (lowerCase) ? 97 : 65;
for (int i = 0; i < size; i++)
{
sb.Append((char)(26 * randomSeed.NextDouble() + start));
}
return sb.ToString();
}
Yields:
Sort: 8968ms
OrderBy: 8728ms
Still OrderBy is faster
(Not exactly an answer for you, since do you want avoid opening the files, but maybe this helps others).
I have been using the open source GNU PSPP package to convert the sav tile to csv. You can download the Windows version at least from SourceForge [1]. Once you have the software, you can convert sav file to csv with following command line:
pspp-convert <input.sav> <output.csv>
[1] http://sourceforge.net/projects/pspp4windows/files/?source=navbar
I've expanded on @Stuart Axon's idea to add two-way binding for the file input (i.e. allow resetting the input by resetting the model value back to null):
app.directive('bindFile', [function () {
return {
require: "ngModel",
restrict: 'A',
link: function ($scope, el, attrs, ngModel) {
el.bind('change', function (event) {
ngModel.$setViewValue(event.target.files[0]);
$scope.$apply();
});
$scope.$watch(function () {
return ngModel.$viewValue;
}, function (value) {
if (!value) {
el.val("");
}
});
}
};
}]);
This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.
You have to create service.That service should implement LocationListener. Then You have to use AlarmManager for calling service repeatedly with certain time limit.
I hope this one will help to you :)
echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
should work.
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
String dateStr = "2016-09-17T08:14:03+00:00";
String s = dateStr.replace("Z", "+00:00");
s = s.substring(0, 22) + s.substring(23);
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(s);
Timestamp createdOn = new Timestamp(date.getTime());
mcList.setCreated_on(createdOn);
Java 7 added support for time zone descriptors according to ISO 8601. This can be use in Java 7.
I ran into this a while ago. I found a good solution was to use the ASCII representation of carriage returns (CODE 13). JavaScript has a handy feature called String.fromCharCode()
which generates the string version of an ASCII code, or multiple codes separate by a comma. In my case, I needed to generate a CSV file from a long string and write it to a text area. I needed to be able to cut the text from the text area and save it into notepad. When I tried to use the <br />
method it would not preserve the carriage returns, however, using the fromCharCode method it does retain the returns. See my code below:
h1.innerHTML += "...I would like to insert a carriage return here..." + String.fromCharCode(13);
h1.innerHTML += "Ant the other line here..." + String.fromCharCode(13);
h1.innerHTML += "And so on..." + String.fromCharCode(13);
h1.innerHTML += "This prints hello: " + String.fromCharCode(72,69,76,76,79);
See here for more details on this method: w3Schools-fromCharCode()
See here for ASCII codes: ASCII Codes
SELECT *
FROM TableName
WHERE julianday(substr(date,7)||'-'||substr(date,4,2)||'-'||substr(date,1,2)) BETWEEN julianday('2011-01-11') AND julianday('2011-08-11')
Note that I use the format : dd/mm/yyyy
If you use d/m/yyyy, Change in substr()
Hope this will help you.
You can use the memcpy()
,
void * memcpy ( void * destination, const void * source, size_t num );
memcpy()
copies the values of num
bytes from the location pointed by source
directly to the memory block pointed by destination
.
If the destination
and source
overlap, then you can use memmove()
.
void * memmove ( void * destination, const void * source, size_t num );
memmove()
copies the values of num
bytes from the location pointed by source
to the memory block pointed by destination
. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.
Use:
if(comboBox.SelectedIndex > -1) //somthing was selected
To get the selected item you do:
Item m = comboBox.Items[comboBox.SelectedIndex];
As Matthew correctly states, to get the selected item you could also do
Item m = comboBox.SelectedItem;
If you are using server side rending, you can use StaticRouter
. With your context
as props
and then adding <Redirect path="/somewhere" />
component in your app. The idea is everytime react-router matches a redirect component it will add something into the context you passed into the static router to let you know your path matches a redirect component. now that you know you hit a redirect you just need to check if thats the redirect you are looking for. then just redirect through the server. ctx.redirect('https://example/com')
.
You can use @PropertySource
to externalize your configuration to a properties file. There is number of way to do get properties:
1.
Assign the property values to fields by using @Value
with PropertySourcesPlaceholderConfigurer
to resolve ${}
in @Value
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Value("${gMapReportUrl}")
private String gMapReportUrl;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
2.
Get the property values by using Environment
:
@Configuration
@PropertySource("file:config.properties")
public class ApplicationConfiguration {
@Autowired
private Environment env;
public void foo() {
env.getProperty("gMapReportUrl");
}
}
Hope this can help
Try fopen() http://www.php.net/manual/en/function.fopen.php
w as mode will truncate the file.
delete: delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:
splice: actually removes the element, reindexes the array, and changes its length.
Delete element from last
arrName.pop();
Delete element from first
arrName.shift();
Delete from middle
arrName.splice(starting index,number of element you wnt to delete);
Ex: arrName.splice(1,1);
Delete one element from last
arrName.splice(-1);
Delete by using array index number
delete arrName[1];
I just thought that I'd add that there is a notion of Z-order in Swing, see [java.awt.Component#setComponentZOrder][1]
which affects the positions of a component in its parents component array, which determines the painting order.
Note that you should override javax.swing.JComponent#isOptimizedDrawingEnabled to return false in the parent container to get your overlapping components to repaint correctly, otherwise their repaints will clobber each other. (JComponents assume no overlapping children unless isOptimizedDrawingEnabled returns false)
A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.
This happened to me when I upgraded from 9.3.4 to 9.5 as the databases are incompatible without upgrading.
I used pg_upgrade as follows:
Stop postgres
$ brew services stop postgresql
Upgrade the databases:
$ pg_upgrade \
-d /usr/local/var/postgres \
-D /usr/local/var/postgres9.5 \
-b /usr/local/Cellar/postgresql/9.3.4/bin/ \
-B /usr/local/Cellar/postgresql/9.5.0/bin/ \
-v
Archive the old databases:
$ mv /usr/local/var/postgres /usr/local/var/postgres9.3.save
$ mv /usr/local/var/postgres9.5 /usr/local/var/postgres
Restart postgres:
$ brew services start postgresql
Updated Gems (for rails / active record) :
$ gem uninstall pg
$ gem uninstall activerecord-postgresql-adapter
$ bundle install
Using Select2 4.0 with Meteor you can do something like this:
Template.TemplateName.rendered = ->
$("#select2-el").select2({
data : Session.get("select2Data")
})
@autorun ->
# Clear the existing list options.
$("#select2-el").select2().empty()
# Re-create with new options.
$("#select2-el").select2({
data : Session.get("select2Data")
})
What's happening:
This works for any reactive data source - such as a Collection.find().fetch() - not just Session.get().
NOTE: as of Select2 version 4.0 you must remove existing options before adding new onces. See this GitHub Issue for details. There is no method to 'update the options' without clearing the existing ones.
The above is coffeescript. Very similar for Javascript.
Wait!
There is a way to retrieve the password by using Brute-Force attack, have a look at the following tool from codeproject Retrieve SQL Server Password
To Retrieve the password of SQL Server user,run the following query in SQL Query Analyzer
"Select Password from SysxLogins Where Name = 'XXXX'" Where XXXX is the user
name for which you want to retrieve password.Copy the password field (Hashed Code) and
paste here (in Hashed code Field) and click on start button to retrieve
I checked the tool on SQLServer 2000 and it's working fine.
Here I am sharing the script, convert UTC timestamp to Indian timestamp:-
// create a $utc object with the UTC timezone
$IST = new DateTime('2016-12-12 12:12:12', new DateTimeZone('UTC'));
// change the timezone of the object without changing it's time
$IST->setTimezone(new DateTimeZone('Asia/Kolkata'));
// format the datetime
echo $IST->format('Y-m-d H:i:s T');
This is what we ended up using:
n = 3
d = dict(raw_input().split() for _ in range(n))
print d
Input:
A1023 CRT
A1029 Regulator
A1030 Therm
Output:
{'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
I'm neither a JSON expert nor a Swift expert, but the following is working for me. :) I have extracted the code from my current app, and only changed "MyLog to println", and indented with spaces to get it to show as a code block (hopefully I didn't break it).
func getServerCourseVersion(){
Alamofire.request(.GET,"\(PUBLIC_URL)/vtcver.php")
.responseJSON { (_,_, JSON, _) in
if let jsonResult = JSON as? Array<Dictionary<String,String>> {
let courseName = jsonResult[0]["courseName"]
let courseVersion = jsonResult[0]["courseVersion"]
let courseZipFile = jsonResult[0]["courseZipFile"]
println("JSON: courseName: \(courseName)")
println("JSON: courseVersion: \(courseVersion)")
println("JSON: courseZipFile: \(courseZipFile)")
}
}
}
Hope this helps.
Edit:
For reference, here is what my PHP Script returns:
[{"courseName": "Training Title","courseVersion": "1.01","courseZipFile": "101/files.zip"}]
With Postman, select Body tab and choose the raw option and type the following:
grant_type=password&username=yourusername&password=yourpassword
I prefer to have event listeners deployed in a modular function fashion rather than scripting a document
level event listener. So, I do like below. Note, you can't oversubscribe an element with the same event listener so don't worry about attaching a listener more than once - only one sticks.
var iterations = 4;_x000D_
var button;_x000D_
var body = document.querySelector("body");_x000D_
_x000D_
for (var i = 0; i < iterations; i++) {_x000D_
button = document.createElement("button");_x000D_
button.classList.add("my-button");_x000D_
button.appendChild(document.createTextNode(i));_x000D_
button.addEventListener("click", myButtonWasClicked);_x000D_
body.appendChild(button);_x000D_
}_x000D_
_x000D_
function myButtonWasClicked(e) {_x000D_
console.log(e.target); //access to this specific button_x000D_
}
_x000D_
You can do something like this to automatically register them all into a collection with which to then easily convert the integers to the corresponding enum. (BTW, adding them to the map in the enum constructor is not allowed. It's nice to learn new things even after many years of using Java. :)
public enum PcapLinkType {
DLT_NULL(0),
DLT_EN10MB(1),
DLT_EN3MB(2),
DLT_AX25(3),
/*snip, 200 more enums, not always consecutive.*/
DLT_UNKNOWN(-1);
private static final Map<Integer, PcapLinkType> typesByValue = new HashMap<Integer, PcapLinkType>();
static {
for (PcapLinkType type : PcapLinkType.values()) {
typesByValue.put(type.value, type);
}
}
private final int value;
private PcapLinkType(int value) {
this.value = value;
}
public static PcapLinkType forValue(int value) {
return typesByValue.get(value);
}
}
Sample code you can use to let Tika take care of container files for you. http://wiki.apache.org/tika/RecursiveMetadata
Form what I can tell, the accepted solution will not work for cases where there are nested zip files. Tika, however will take care of such situations as well.
To make my FFMPEG application I used this project (https://github.com/hiteshsondhi88/ffmpeg-android-java) so, I don't have to compile anything. I think it's the easy way to use FFMPEG in our Android applications.
More info on http://hiteshsondhi88.github.io/ffmpeg-android-java/
This one liner will exit your Bash session after 10s
$ TMOUT=10 && echo "foo bar"
Did you try showing your window using the ShowDialog method?
Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.
Another solution would be dictdiffer
(https://github.com/inveniosoftware/dictdiffer).
import dictdiffer
a_dict = {
'a': 'foo',
'b': 'bar',
'd': 'barfoo'
}
b_dict = {
'a': 'foo',
'b': 'BAR',
'c': 'foobar'
}
for diff in list(dictdiffer.diff(a_dict, b_dict)):
print diff
A diff is a tuple with the type of change, the changed value, and the path to the entry.
('change', 'b', ('bar', 'BAR'))
('add', '', [('c', 'foobar')])
('remove', '', [('d', 'barfoo')])
Try jCounter, it has a customRange setting where you can specify the start and end number, it can count up as well including the fallback you want at the end.
Use android:textStyle="bold"
4 ways to make Android TextView Bold
like this
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="12dip"
android:textStyle="bold"
/>
There are many ways to make Android TextView bold.
Try simple & lightweight PathJS lib.
Simple example:
Path.map("#/page").to(function(){
alert('page!');
});
function convertDatePickerTimeToMySQLTime(str) {
var month, day, year, hours, minutes, seconds;
var date = new Date(str),
month = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
hours = ("0" + date.getHours()).slice(-2);
minutes = ("0" + date.getMinutes()).slice(-2);
seconds = ("0" + date.getSeconds()).slice(-2);
var mySQLDate = [date.getFullYear(), month, day].join("-");
var mySQLTime = [hours, minutes, seconds].join(":");
return [mySQLDate, mySQLTime].join(" ");
}
a += b
is in this case the same as
a = a + b
In this case cnt += 1 means that cnt is increased by one.
Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.
Edit: quote Carl Meyer: ``[..] the answer is misleadingly mostly correct. There is a subtle but very significant difference between + and +=, see Bastien's answer.''.
Use window.open()
:
<a onclick="window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');">
Share Page
</a>
This will create a link titled Share Page
which opens the current url in a new window with a height of 570 and width of 520.
The most important difference is that robocopy
will (usually) retry when an error occurs, while xcopy
will not. In most cases, that makes robocopy
far more suitable for use in a script.
Addendum: for completeness, there is one known edge case issue with robocopy; it may silently fail to copy files or directories whose names contain invalid UTF-16 sequences. If that's a problem for you, you may need to look at third-party tools, or write your own.
Create WScript.Shell object and invoke Run() method on it.
http://msdn.microsoft.com/en-us/library/d5fk67ky(v=vs.85).aspx
const fs = require('fs');
fs.stat('input.txt', function (err, stats) {
if(err){
console.log(err);
} else {
console.log(stats);
console.log('Completed Reading File');
}
});
'fs' is a node module which helps you to read file. Callback function will make sure that your file named 'input.txt' is completely read before it gets executed. fs.stat() function is to get file information like file size, date created and date modified.
As in Oracle you can use NVL function in MySQL you can use IFNULL(columnaName, newValue) to achieve your desired result as in this example
SELECT column_name from table_name WHERE IFNULL(column_name,'') NOT LIKE '%_%';
firstDay = DateSerial(Year(DateAdd("m", -1, Now)), Month(DateAdd("m", -1, Now)), 1)
lastDay = DateAdd("d", -1, DateSerial(Year(Now), Month(Now), 1))
This is another way to do it, but I think Remou's version looks cleaner.
Assuming you have Manage Jenkins > Configure Global Security > Enable Security and Jenkins Own User Database checked you would go to:
I found a solution while tinkering around.
People who directly wanna see the results:
With click: https://jsfiddle.net/dt52jazg/
With Hover: https://jsfiddle.net/7gkufLsh/1/
Below is the code:
HTML
<ul class="list">
<li>Hey</li>
<li>This</li>
<li>is</li>
<li>just</li>
<li>a</li>
<li>test</li>
</ul>
<button class="click-me">
Click me
</button>
CSS
.list li {
min-height: 0;
max-height: 0;
opacity: 0;
-webkit-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.active li {
min-height: 20px;
opacity: 1;
}
JS
(function() {
$('.click-me').on('click', function() {
$('.list').toggleClass('active');
});
})();
Please let me know whether there is any problem with this solution 'coz I feel there would be no restriction of max-height with this solution.
The currenly accepted answer works only under important condition. Given...
/foo/bar/first.sh
:
function func1 {
echo "Hello $1"
}
and
/foo/bar/second.sh
:
#!/bin/bash
source ./first.sh
func1 World
this works only if the first.sh
is executed from within the same directory where the first.sh
is located. Ie. if the current working path of shell is /foo
, the attempt to run command
cd /foo
./bar/second.sh
prints error:
/foo/bar/second.sh: line 4: func1: command not found
That's because the source ./first.sh
is relative to current working path, not the path of the script. Hence one solution might be to utilize subshell and run
(cd /foo/bar; ./second.sh)
Given...
/foo/bar/first.sh
:
function func1 {
echo "Hello $1"
}
and
/foo/bar/second.sh
:
#!/bin/bash
source $(dirname "$0")/first.sh
func1 World
then
cd /foo
./bar/second.sh
prints
Hello World
$0
returns relative or absolute path to the executed scriptdirname
returns relative path to directory, where the $0 script exists $( dirname "$0" )
the dirname "$0"
command returns relative
path to directory of executed script, which is then used as argument for source
command /first.sh
just appends the name of imported shell script source
loads content of specified file into current
shell<html>
<head>
<title>Login page</title>
</head>
<body>
<h1>Simple Login Page</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
window.open('target.html')/*opens the target page while Id & password matches*/
}
else {
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
Binding="{Binding YourColumn ,StringFormat='yyyy-MM-dd'}"
If you want to do something like the following example, you'd have to use nested if
s.
If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.
Here's how you'd do it:
=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))
use EndDialog
instead of sending WM_CLOSE
:
[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
# tar all files within and deeper in a given directory
# with no prefixes ( neither <directory>/ nor ./ )
# parameters: <source directory> <target archive file>
function tar_all_in_dir {
{ cd "$1" && find -type f -print0; } \
| cut --zero-terminated --characters=3- \
| tar --create --file="$2" --directory="$1" --null --files-from=-
}
Safely handles filenames with spaces or other unusual characters. You can optionally add a -name '*.sql'
or similar filter to the find command to limit the files included.
It greatly reduces your level of confidence about security.
You can use CSS3 media query for this. Write like this:
CSS
.wrapper {
border : 2px solid #000;
overflow:hidden;
}
.wrapper div {
min-height: 200px;
padding: 10px;
}
#one {
background-color: gray;
float:left;
margin-right:20px;
width:140px;
border-right:2px solid #000;
}
#two {
background-color: white;
overflow:hidden;
margin:10px;
border:2px dashed #ccc;
min-height:170px;
}
@media screen and (max-width: 400px) {
#one {
float: none;
margin-right:0;
width:auto;
border:0;
border-bottom:2px solid #000;
}
}
HTML
<div class="wrapper">
<div id="one">one</div>
<div id="two">two</div>
</div>
Check this for more http://jsfiddle.net/cUCvY/1/
First, you gotta put your font as either a .otf or .ttf somewhere on your server.
Then use CSS to declare the new font family like this:
@font-face {
font-family: MyFont;
src: url('pathway/myfont.otf');
}
If you link your document to the CSS file that you declared your font family in, you can use that font just like any other font.
Use this:
DateTime dateTime = DateTime.Now;
DateTime? newDateTime = null;
TimeSpan numberOfDays = new TimeSpan(2, 0, 0, 0, 0);
newDateTime = dateTime.Add(numberOfDays);
Finally got this error to go away on a restore. I moved to SQL2012 out of frustration, but I guess this would probably still work on 2008R2. I had to use the logical names:
RESTORE FILELISTONLY
FROM DISK = ‘location of your.bak file’
And from there I ran a restore statement with MOVE
using logical names.
RESTORE DATABASE database1
FROM DISK = '\\database path\database.bak'
WITH
MOVE 'File_Data' TO 'E:\location\database.mdf',
MOVE 'File_DOCS' TO 'E:\location\database_1.ndf',
MOVE 'file' TO 'E:\location\database_2.ndf',
MOVE 'file' TO 'E:\location\database_3.ndf',
MOVE 'file_Log' TO 'E:\location\database.ldf'
When it was done restoring, I almost wept with joy.
Good luck!
Have appended the html in componentDidMount using jQuery append. This should solve the problem.
var MyComponent = React.createClass({
render: function() {
return (
<div>
</div>
);
},
componentDidMount() {
$(ReactDOM.findDOMNode(this)).append(this.props.text);
}
});
I resolved this same problem in python using flask and with this library. flask_cors
Reference: https://flask-cors.readthedocs.io/en/latest/
// new example._x000D_
var str= [20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5];_x000D_
_x000D_
function findOdd(para) {_x000D_
var count = {};_x000D_
para.forEach(function(para) {_x000D_
count[para] = (count[para] || 0) + 1;_x000D_
});_x000D_
return count;_x000D_
}_x000D_
_x000D_
console.log(findOdd(str));
_x000D_
<input type="button" value="Click me" id="myButton" />
<script type="text/javascript">
var myButton = document.getElementById("myButton");
myButton.myMessage = "it's working";
myButton.onclick = function() { alert(this.myMessage); };
</script>
This works in my test suite which includes everything from IE6+. The anonymous function is aware of the object which it belongs to therefore you can pass data with the object that's calling it ( in this case myButton ).
The other methods will copy plain text to the clipboard. To copy HTML (i.e., you can paste results into a WYSIWYG editor), you can do the following in Internet Explorer only. This is is fundamentally different from the other methods, as the browser actually visibly selects the content.
// Create an editable DIV and append the HTML content you want copied
var editableDiv = document.createElement("div");
with (editableDiv) {
contentEditable = true;
}
editableDiv.appendChild(someContentElement);
// Select the editable content and copy it to the clipboard
var r = document.body.createTextRange();
r.moveToElementText(editableDiv);
r.select();
r.execCommand("Copy");
// Deselect, so the browser doesn't leave the element visibly selected
r.moveToElementText(someHiddenDiv);
r.select();
I have a bad time putting my war file at /etc/tomcat7/webapps
but the real path was /var/lib/tomcat7/webapps
. May you want to use sudo find / -type f -name "my-war-file.war"
to know where is it.
And remove this folders /tmp/hsperfdata_*
and /tmp/tomcat7-tomcat7-tmp
.
Look at this paper, "Learning the k in k-means" by Greg Hamerly, Charles Elkan. It uses a Gaussian test to determine the right number of clusters. Also, the authors claim that this method is better than BIC which is mentioned in the accepted answer.
here is a link to something l think can assist https://laraveldaily.com/dont-check-record-exists-methods-orcreate-ornew/
FirstOrDefault or SingleOrDefault might be useful, depending on your scenario, and whether you want to handle there being zero or more than one matches:
FirstOrDefault: Returns the first element of a sequence, or a default value if no element is found.
SingleOrDefault: Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence
I don't know how this works in a linq 'from' query but in lambda syntax it looks like this:
var item1 = Items.FirstOrDefault(x => x.Id == 123);
var item2 = Items.SingleOrDefault(x => x.Id == 123);
You could use the printf(1) command, e.g. like
printf "Hello times %d\nHere\n" $[2+3]
The printf
command may accept arguments and needs a format control string similar (but not exactly the same) to the one for the standard C printf(3) function...
<select>
<option selected="selected" class="Country">Country Name</option>
<option value="1">India</option>
<option value="2">us</option>
</select>
.country
{
display:none;
}
</style>
A modern ES6 approach. Select the form with any method you like. Use the spread operator to convert HTMLFormControlsCollection to an Array, then the forEach
method is available. [...form.elements].forEach
Update: Array.from
is a nicer alternative to spread Array.from(form.elements)
it's slightly clearer behaviour.
An example below iterates over every input in the form. You can filter out certain input types by checking input.type != "submit"
const forms = document.querySelectorAll('form');
const form = forms[0];
Array.from(form.elements).forEach((input) => {
console.log(input);
});
_x000D_
<div>
<h1>Input Form Selection</h1>
<form>
<label>
Foo
<input type="text" placeholder="Foo" name="Foo" />
</label>
<label>
Password
<input type="password" placeholder="Password" />
</label>
<label>
Foo
<input type="text" placeholder="Bar" name="Bar" />
</label>
<span>Ts & Cs</span>
<input type="hidden" name="_id" />
<input type="submit" name="_id" />
</form>
</div>
_x000D_
this is what i came up with as i was having issues with @asp8811 answer(maybe my own difficulties)
' this will do the put the first 2 sheets in a pdf ' Note each ws should be controlled with page breaks for printing which is a bit fiddly ' this will explicitly put the pdf in the current dir
Sub luxation2()
Dim Filename As String
Filename = "temp201"
Dim shtAry()
ReDim shtAry(1) ' this is an array of length 2
For i = 1 To 2
shtAry(i - 1) = Sheets(i).Name
Debug.Print Sheets(i).Name
Next i
Sheets(shtAry).Select
Debug.Print ThisWorkbook.Path & "\"
ActiveSheet.ExportAsFixedFormat xlTypePDF, ThisWorkbook.Path & "/" & Filename & ".pdf", , , False
End Sub
Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");
. See this.
You could try this :
var message="Sorry, right-click has been disabled";
function clickIE() {
if (document.all) {
(message);
return false;
}
}
function clickNS(e) {
if (document.layers || (document.getElementById && !document.all)) {
if (e.which == 2||e.which == 3) {
(message);
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = clickNS;
} else {
document.onmouseup = clickNS;
document.oncontextmenu = clickIE;
}
document.oncontextmenu = new Function("return false")
When you do this,
while((inputLine = buff_read.readLine())!= null){
System.out.println(inputLine);
}
You consume everything in instream, so instream is empty. Now when try to do this,
Document doc = builder.parse(instream);
The parsing will fail, because you have passed it an empty stream.
You could use coalesce:
insert into destination select coalesce(field1,'somedata'),... from source;
A quick way is to run a jQuery command in the developer console. On any browser hit F12 and try to access any of the element .
$("#sideTab2").css("background-color", "yellow");
You have included the dependency for sflj's api, but not the dependency for the implementation of the api, that is a separate jar, you could try slf4j-simple-1.6.1.jar.
If you want to fire the event only on changes of your input use:
$('.s').bind('input', function(){
console.log("search!");
doSearch();
});
My understanding is that the SQL standard calls for case-insensitivity. I don't believe any databases follow the standard completely, though.
MySQL has a configuration setting as part of its "strict mode" (a grab bag of several settings that make MySQL more standards-compliant) for case sensitive or insensitive table names. Regardless of this setting, column names are still case-insensitive, although I think it affects how the column-names are displayed. I believe this setting is instance-wide, across all databases within the RDBMS instance, although I'm researching today to confirm this (and hoping the answer is no).
I like how Oracle handles this far better. In straight SQL, identifiers like table and column names are case insensitive. However, if for some reason you really desire to get explicit casing, you can enclose the identifier in double-quotes (which are quite different in Oracle SQL from the single-quotes used to enclose string data). So:
SELECT fieldName
FROM tableName;
will query fieldname from tablename, but
SELECT "fieldName"
FROM "tableName";
will query fieldName from tableName.
I'm pretty sure you could even use this mechanism to insert spaces or other non-standard characters into an identifier.
In this situation if for some reason you found explicitly-cased table and column names desirable it was available to you, but it was still something I would highly caution against.
My convention when I used Oracle on a daily basis was that in code I would put all Oracle SQL keywords in uppercase and all identifiers in lowercase. In documentation I would put all table and column names in uppercase. It was very convenient and readable to be able to do this (although sometimes a pain to type so many capitals in code -- I'm sure I could've found an editor feature to help, here).
In my opinion MySQL is particularly bad for differing about this on different platforms. We need to be able to dump databases on Windows and load them into UNIX, and doing so is a disaster if the installer on Windows forgot to put the RDBMS into case-sensitive mode. (To be fair, part of the reason this is a disaster is our coders made the bad decision, long ago, to rely on the case-sensitivity of MySQL on UNIX.) The people who wrote the Windows MySQL installer made it really convenient and Windows-like, and it was great to move toward giving people a checkbox to say "Would you like to turn on strict mode and make MySQL more standards-compliant?" But it is very convenient for MySQL to differ so signficantly from the standard, and then make matters worse by turning around and differing from its own de facto standard on different platforms. I'm sure that on differing Linux distributions this may be further compounded, as packagers for different distros probably have at times incorporated their own preferred MySQL configuration settings.
Here's another SO question that gets into discussing if case-sensitivity is desirable in an RDBMS.
Yes, it prints GARBAGE unless you are lucky.
VERY IMPORTANT.
The type of the printf/sprintf/fprintf argument MUST match the associated format type char.
If the types don't match and it compiles, the results are very undefined.
Many newer compilers know about printf and issue warnings if the types do not match. If you get these warnings, FIX them.
If you want to convert types for arguments for variable functions, you must supply the cast (ie, explicit conversion) because the compiler can't figure out that a conversion needs to be performed (as it can with a function prototype with typed arguments).
printf("%d\n", (int) ch)
In this example, printf is being TOLD that there is an "int" on the stack. The cast makes sure that whatever thing sizeof returns (some sort of long integer, usually), printf will get an int.
printf("%d", (int) sizeof('\n'))
While using the disk utility graphically, it shows disk space used by all filesystem and it uses commands in the terminal such as df -H
. In other words, it uses powers of 1000, not 1024. (Note: there is difference between -h
and -H
.)
While also finding the unallocated space in a hard disk using command line
# fdisk /dev/sda
will display the total space and total cylinder value.
Now check the last cylinder value and subtract it from the total cylinder value. Hence the final value * 1000 gives you the unallocated disk space.
Note: the cylinder value shows up in df -H
as a power of 1000 or it might also show up using df -h
, a power of 1024.
a = [(0,2), (4,3), (9,9), (10,-1)]
print(list(map(lambda item: item[1], a)))
You can use Notepad++ to evaluate a file's encoding without needing to write code. The evaluated encoding of the open file will display on the bottom bar, far right side. The encodings supported can be seen by going to Settings -> Preferences -> New Document/Default Directory
and looking in the drop down.
For SQL Server version 9.0 (2005), you can use the code below:
select *
from
syscomments c
inner join sys.procedures p on p.object_id = c.id
where
p.name like '%usp_ConnectionsCount%';
Your rewrite rule looks almost ok.
First make sure that your .htaccess
file is in your document root (the same place as index.php
) or it'll only affect the sub-folder it's in (and any sub-folders within that - recursively).
Next make a slight change to your rule so it looks something like:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
At the moment you're just matching on .
which is one instance of any character, you need at least .*
to match any number of instances of any character.
The $_GET['path']
variable will contain the fake directory structure, so /mvc/module/test
for instance, which you can then use in index.php to determine the Controller and actions you want to perform.
If you want the whole shebang installed in a sub-directory, such as /mvc/
or /framework/
the least complicated way to do it is to change the rewrite rule slightly to take that into account.
RewriteRule ^(.*)$ /mvc/index.php?path=$1 [NC,L,QSA]
And ensure that your index.php
is in that folder whilst the .htaccess
file is in the document root.
Alternative to $_GET['path']
(updated Feb '18 and Jan '19)
It's not actually necessary (nor even common now) to set the path as a $_GET
variable, many frameworks will rely on $_SERVER['REQUEST_URI']
to retrieve the same information - normally to determine which Controller to use - but the principle is exactly the same.
This does simplify the RewriteRule
slightly as you don't need to create the path parameter (which means the OP's original RewriteRule
will now work):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]
However, the rule about installing in a sub-directory still applies, e.g.
RewriteRule ^.*$ /mvc/index.php [L,QSA]
The flags:
NC
= No Case (not case sensitive, not really necessary since there are no characters in the pattern)
L
= Last (it'll stop rewriting at after this Rewrite so make sure it's the last thing in your list of rewrites)
QSA
= Query String Append, just in case you've got something like ?like=penguins
on the end which you want to keep and pass to index.php.
Since Python 2.7 there's the timedelta.total_seconds() method. So, to get the elapsed milliseconds:
>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> delta = b - a
>>> print delta
0:00:05.077263
>>> int(delta.total_seconds() * 1000) # milliseconds
5077