public Point2D(Point2D point) : this(point.X, point.Y) { }
If you have a very complex class with a lot of options of which only some combinations are valid, consider using a Builder. Works very well both codewise but also logically.
The Builder is a nested class with methods only designed to set fields, and then the ComplexClass constructor only takes such a Builder as an argument.
Edit: The ComplexClass constructor can ensure that the state in the Builder is valid. This is very hard to do if you just use setters on ComplexClass.
fmt.SprintF function returns a string and you can format the string the very same way you would have with fmt.PrintF
Instead of using a margin, could you use a border? You should do this with <div>
, anyway.
Something like this?
Please try like this :
git clone --single-branch --branch <branchname> <url>
replace <branchname>
with your branch and <url>
with your url.
url will be like http://[email protected]:portno/yourrepo.git
.
you could add the following:
public float getAngle(Point target) {
float angle = (float) Math.toDegrees(Math.atan2(target.y - y, target.x - x));
if(angle < 0){
angle += 360;
}
return angle;
}
by the way, why do you want to not use a double here?
From CREATE FUNCTION
:
When a parameter of the function has a default value, the keyword
DEFAULT
must be specified when the function is called to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value.
So you need to do:
SELECT dbo.fCalculateEstimateDate(647,DEFAULT)
Use with:
{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}
You can do is this
CSS
.car {
font-weight: bold;
}
.benz {
background-color: blue;
}
.toyota {
background-color: white;
}
HTML
<div class="car benz">
<p>I'm bold and blue.</p>
</div>
<div class="car toyota">
<p>I'm bold and white.</p>
</div>
This
var verificaHorario = $("#tbIntervalos").find("#" + horaInicial);
will find you the td that needs to be blocked.
Actually this will also do:
var verificaHorario = $("#" + horaInicial);
Testing for the size() of the wrapped set will answer your question regarding the existence of the id.
Applies to Bootstrap 3 only.
Ignoring the letters (xs, sm, md, lg) for now, I'll start with just the numbers...
col-*-6
spans 6 of 12 columns (half the width), col-*-12
spans 12 of 12 columns (the entire width), etcSo, if you want two equal columns to span a div, write
<div class="col-xs-6">Column 1</div>
<div class="col-xs-6">Column 2</div>
Or, if you want three unequal columns to span that same width, you could write:
<div class="col-xs-2">Column 1</div>
<div class="col-xs-6">Column 2</div>
<div class="col-xs-4">Column 3</div>
You'll notice the # of columns always add up to 12. It can be less than twelve, but beware if more than 12, as your offending divs will bump down to the next row (not .row
, which is another story altogether).
You can also nest columns within columns, (best with a .row
wrapper around them) such as:
<div class="col-xs-6">
<div class="row">
<div class="col-xs-4">Column 1-a</div>
<div class="col-xs-8">Column 1-b</div>
</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-2">Column 2-a</div>
<div class="col-xs-10">Column 2-b</div>
</div>
</div>
Each set of nested divs also span up to 12 columns of their parent div. NOTE: Since each .col
class has 15px padding on either side, you should usually wrap nested columns in a .row
, which has -15px margins. This avoids duplicating the padding and keeps the content lined up between nested and non-nested col classes.
-- You didn't specifically ask about the xs, sm, md, lg
usage, but they go hand-in-hand so I can't help but touch on it...
In short, they are used to define at which screen size that class should apply:
Read the "Grid Options" chapter from the official Bootstrap documentation for more details.
You should usually classify a div using multiple column classes so it behaves differently depending on the screen size (this is the heart of what makes bootstrap responsive). eg: a div with classes col-xs-6
and col-sm-4
will span half the screen on the mobile phone (xs) and 1/3 of the screen on tablets(sm).
<div class="col-xs-6 col-sm-4">Column 1</div> <!-- 1/2 width on mobile, 1/3 screen on tablet) -->
<div class="col-xs-6 col-sm-8">Column 2</div> <!-- 1/2 width on mobile, 2/3 width on tablet -->
NOTE: as per comment below, grid classes for a given screen size apply to that screen size and larger unless another declaration overrides it (i.e. col-xs-6 col-md-4
spans 6 columns on xs
and sm
, and 4 columns on md
and lg
, even though sm
and lg
were never explicitly declared)
NOTE: if you don't define xs
, it will default to col-xs-12
(i.e. col-sm-6
is half the width on sm
, md
and lg
screens, but full-width on xs
screens).
NOTE: it's actually totally fine if your .row
includes more than 12 cols, as long as you are aware of how they will react. --This is a contentious issue, and not everyone agrees.
https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.
How about:
In [1]: l=[1,2,3,4,3,2,5,6,7]
In [2]: [i for i,val in enumerate(l) if val==3]
Out[2]: [2, 4]
Button inputs don't have a submit event. Try attaching the event handler to the form instead:
<script type="text/javascript">
$('#login_form').submit(function() {
$('#gif').show();
return true;
});
</script>
Use the tonumber
function. As in a = tonumber("10")
.
for anyone yet interested:
the best way I found is to use the inflate static method of View.
View inflatedView = View.inflate(context, yourViewXML, yourLinearLayout);
where yourViewXML is something like R.layout.myView
please notice that you need a ViewGroup in order to add a view (which is any layout you can think of)
so as an example lets say you have a fragment which it view already been inflated and you know that the root view is a layout, and you want to add a view to it:
View view = getView(); // returns base view of the fragment
if (view == null)
return;
if (!(view instanceof ViewGroup))
return;
ViewGroup viewGroup = (ViewGroup) view;
View popup = View.inflate(viewGroup.getContext(), R.layout.someView, viewGroup);
I know this was posted a long while ago, and it has been marked answered, but to me, the selected answer was not answering the question I thought the user was posing. It seemed to me he was looking for the approach one can take in ASP .Net that corresponds to his inline data binding previously performed in php.
Here was his php:
<p>Here is the username: <?php echo GetUserName(); ?></p>
Here is what one would do in ASP .Net:
<p>Here is the username: <%= GetUserName() %></p>
As Ciro Santilli notes using command substitutions will drop trailing newlines. Their workaround adding trailing characters is great, but after using it for quite some time I decided I needed a solution that didn't use command substitution at all.
My approach now uses read
along with the printf
builtin's -v
flag in order to read the contents of stdin directly into a variable.
# Reads stdin into a variable, accounting for trailing newlines. Avoids
# needing a subshell or command substitution.
# Note that NUL bytes are still unsupported, as Bash variables don't allow NULs.
# See https://stackoverflow.com/a/22607352/113632
read_input() {
# Use unusual variable names to avoid colliding with a variable name
# the user might pass in (notably "contents")
: "${1:?Must provide a variable to read into}"
if [[ "$1" == '_line' || "$1" == '_contents' ]]; then
echo "Cannot store contents to $1, use a different name." >&2
return 1
fi
local _line _contents=()
while IFS='' read -r _line; do
_contents+=("$_line"$'\n')
done
# include $_line once more to capture any content after the last newline
printf -v "$1" '%s' "${_contents[@]}" "$_line"
}
This supports inputs with or without trailing newlines.
Example usage:
$ read_input file_contents < /tmp/file
# $file_contents now contains the contents of /tmp/file
Pass it as an argument to Date():
var st = "date in some format"
var dt = new Date(st);
You can access the date, month, year using, for example: dt.getMonth()
.
There is a much simpler way in wordpress to create a redirection by using wordpress plugins. So here i found a better way through the plugin Redirection and also you can find other as well on this site Create Url redirect in wordpress through Plugin
Quick review,
From x86 assembly tutorial,
The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.
Your num is 1 byte. Try declaring it with DD
so that it becomes 4 bytes and matches with pop
semantics.
Merge commits: retains all of the commits in your branch and interleaves them with commits on the base branch
Merge Squash: retains the changes but omits the individual commits from history
Rebase: This moves the entire feature branch to begin on the tip of the master branch, effectively incorporating all of the new commits in master
More on here
Ideally you shouldn't be splitting strings in T-SQL at all.
Barring that change, on older versions before SQL Server 2016, create a split function:
CREATE FUNCTION dbo.SplitStrings
(
@List nvarchar(max),
@Delimiter nvarchar(2)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
RETURN ( WITH x(x) AS
(
SELECT CONVERT(xml, N'<root><i>'
+ REPLACE(@List, @Delimiter, N'</i><i>')
+ N'</i></root>')
)
SELECT Item = LTRIM(RTRIM(i.i.value(N'.',N'nvarchar(max)')))
FROM x CROSS APPLY x.nodes(N'//root/i') AS i(i)
);
GO
Now you can say:
DECLARE @Values varchar(1000);
SET @Values = 'A, B, C';
SELECT blah
FROM dbo.foo
INNER JOIN dbo.SplitStrings(@Values, ',') AS s
ON s.Item = foo.myField;
On SQL Server 2016 or above (or Azure SQL Database), it is much simpler and more efficient, however you do have to manually apply LTRIM()
to take away any leading spaces:
DECLARE @Values varchar(1000) = 'A, B, C';
SELECT blah
FROM dbo.foo
INNER JOIN STRING_SPLIT(@Values, ',') AS s
ON LTRIM(s.value) = foo.myField;
You could define a mapping of air pressure to servo angle, for example:
def calc_angle(pressure, min_p=1000, max_p=1200): return 360 * ((pressure - min_p) / float(max_p - min_p)) angle = calc_angle(pressure)
This will linearly convert pressure
values between min_p
and max_p
to angles between 0 and 360 (you could include min_a
and max_a
to constrain the angle, too).
To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:
d = {1000:0, 1001: 1.8, ...} angle = d[pressure]
but this would be rather time-consuming to type out!
Either allocate the string on the stack on the caller side and pass it to your function:
void getStr(char *wordd, int length) {
...
}
int main(void) {
char wordd[10 + 1];
getStr(wordd, sizeof(wordd) - 1);
...
}
Or make the string static in getStr
:
char *getStr(void) {
static char wordd[10 + 1];
...
return wordd;
}
Or allocate the string on the heap:
char *getStr(int length) {
char *wordd = malloc(length + 1);
...
return wordd;
}
Here's another sample using JQuery 1.10.2
$(".chkcc9").on('click', function() {
$(this)
.parents('table')
.find('.group1')
.prop('checked', $(this).is(':checked'));
});
Try this change border-color to anything which you want
.form-control:focus {
border-color: #666666;
-webkit-box-shadow: none;
box-shadow: none;
}
Implementation with Guzzle library:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$httpClient = new Client();
$response = $httpClient->post(
'https://postman-echo.com/post',
[
RequestOptions::BODY => 'POST raw request content',
RequestOptions::HEADERS => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
]
);
echo(
$response->getBody()->getContents()
);
PHP CURL extension:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify request content
*/
CURLOPT_POSTFIELDS => 'POST raw request content',
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
Visual Event is a nice little bookmarklet that you can use to view an element's event handlers. On online demo can be viewed here.
The way I usually do that is by creating a regular list, then append my stuff into it, and finally transform the list to a numpy array as follows :
import numpy as np
big_array = [] # empty regular list
for i in range(5):
arr = i*np.ones((2,4)) # for instance
big_array.append(arr)
big_np_array = np.array(big_array) # transformed to a numpy array
of course your final object takes twice the space in the memory at the creation step, but appending on python list is very fast, and creation using np.array() also.
Last column in your input file must have some data in it (be it space or char, but not null). I guess, 1st record contains null after last ',' which sqlldr won't recognize unless specifically asked to recognize nulls using TRAILING NULLCOLS option. Alternatively, if you don't want to use TRAILING NULLCOLS, you will have to take care of those NULLs before you pass the file to sqlldr. Hope this helps
Just create the variables in a class. And then inherit from that class to access its variables. But before accessing them, the parent class has to be called to initiate the variables.
class a:
def func1(self):
a.var1 = "Stack "
class b:
def func2(self):
b.var2 = "Overflow"
class c(a,b):
def func3(self):
c.var3 = a.var1 + b.var2
print(c.var3)
a().func1()
b().func2()
c().func3()
You are assigning to a function call:
invest(initial_amount,top_company(5,year,year+1)) = subsequent_amount
which is illegal in Python. The question is, what do you want to do? What does invest()
do? I suppose it returns a value, namely what you're trying to use as subsequent_amount
, right?
If so, then something like this should work:
amount = invest(amount,top_company(5,year,year+1),year)
For start Activity 2 from Activity 1 and get result, you could use startActivityForResult and implement onActivityResult in Activity 1 and use setResult in Activity2.
Intent intent = new Intent(this, Activity2.class);
intent.putExtra(NUMERO1, numero1);
intent.putExtra(NUMERO2, numero2);
//startActivity(intent);
startActivityForResult(intent, MI_REQUEST_CODE);
There are a couple of ways:
To delete it directly:
SomeModel.objects.filter(id=id).delete()
To delete it from an instance:
instance = SomeModel.objects.get(id=id)
instance.delete()
With the WebClient class:
using System.Net;
//...
WebClient Client = new WebClient ();
Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");
Though insertBefore()
(see MDN) is great and referenced by most answers here. For added flexibility, and to be a little more explicit, you can use:
insertAdjacentElement()
(see MDN) This lets you reference any element, and insert the to-be moved element exactly where you want:
<!-- refElem.insertAdjacentElement('beforebegin', moveMeElem); -->
<p id="refElem">
<!-- refElem.insertAdjacentElement('afterbegin', moveMeElem); -->
... content ...
<!-- refElem.insertAdjacentElement('beforeend', moveMeElem); -->
</p>
<!-- refElem.insertAdjacentElement('afterend', moveMeElem); -->
Others to consider for similar use cases: insertAdjacentHTML()
and insertAdjacentText()
References:
https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentText
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv
:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv
and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
This might be overkill, but it works for me.
Array.prototype.contains = function (item, prop) {
var arr = this.valueOf();
if (prop == undefined || prop == null) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == item) {
return true;
}
}
}
else {
for (var i = 0; i < arr.length; i++) {
if (arr[i][prop] == item) return true;
}
}
return false;
}
Array.prototype.distinct = function (prop) {
var arr = this.valueOf();
var ret = [];
for (var i = 0; i < arr.length; i++) {
if (!ret.contains(arr[i][prop], prop)) {
ret.push(arr[i]);
}
}
arr = [];
arr = ret;
return arr;
}
The distinct function depends on the contains function defined above. It can be called as array.distinct(prop);
where prop is the property you want to be distinct.
So you could just say $scope.places.distinct("category");
you can also do this:
section = "C_type"
new_section = "Sec_%s" % section
This allows you not only append, but also insert wherever in the string:
section = "C_type"
new_section = "Sec_%s_blah" % section
You put them in the workspace/projects
folder. You should put them directly in the workspace
folder and then do an Import Existing Projects into workspace.
Added simple code to save with readable date-time stamp.
Use sync2pst to sync all your data in outlook with all your devices, work like this:
Use ONLY ONE PST-file for all your accounts, make folders, subfolders and so ...
in VBA: refer to 'microsoft scripting runtime
'extra/references...'
here's the code
Private Sub Application_NewMail()
SaveAttachments
End Sub
Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String
Dim fs As FileSystemObject
' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next
' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")
' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection
' Set the Attachment folder.
strFolderpath = "F:\SkyDrive\Attachments\"
' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection
' This code only strips attachments from mail items.
' If objMsg.class=olMail Then
' Get the Attachments collection of the item.
Set objAttachments = objMsg.Attachments
lngCount = objAttachments.Count
strDeletedFiles = ""
If lngCount > 0 Then
' We need to use a count down loop for removing items
' from a collection. Otherwise, the loop counter gets
' confused and only every other item is removed.
Set fs = New FileSystemObject
For i = lngCount To 1 Step -1
' Save attachment before deleting from item.
' Get the file name.
strFile = Left(objAttachments.Item(i).FileName, Len(objAttachments.Item(i).FileName) - 4) + "_" + Right("00" + Trim(Str$(Day(Now))), 2) + "_" + Right("00" + Trim(Str$(Month(Now))), 2) + "_" + Right("0000" + Trim(Str$(Year(Now))), 4) + "_" + Right("00" + Trim(Str$(Hour(Now))), 2) + "_" + Right("00" + Trim(Str$(Minute(Now))), 2) + "_" + Right("00" + Trim(Str$(Second(Now))), 2) + Right((objAttachments.Item(i).FileName), 4)
' Combine with the path to the Temp folder.
strFile = strFolderpath & strFile
' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile strFile
' Delete the attachment.
objAttachments.Item(i).Delete
'write the save as path to a string to add to the message
'check for html and use html tags in link
If objMsg.BodyFormat <> olFormatHTML Then
strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
Else
strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
strFile & "'>" & strFile & "</a>"
End If
'Use the MsgBox command to troubleshoot. Remove it from the final code.
'MsgBox strDeletedFiles
Next i
' Adds the filename string to the message body and save it
' Check for HTML body
If objMsg.BodyFormat <> olFormatHTML Then
objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
Else
objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
End If
objMsg.Save
End If
Next
ExitSub:
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
Well, I believe it's an "Old but Gold" question. The answer is: "It depends!". The performances are such a delicate subject that it would be too much silly to say: "Never use subqueries, always join". In the following links, you'll find some basic best practices that I have found to be very helpful:
I have a table with 50000 elements, the result i was looking for was 739 elements.
My query at first was this:
SELECT p.id,
p.fixedId,
p.azienda_id,
p.categoria_id,
p.linea,
p.tipo,
p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND p.anno = (
SELECT MAX(p2.anno)
FROM prodotto p2
WHERE p2.fixedId = p.fixedId
)
and it took 7.9s to execute.
My query at last is this:
SELECT p.id,
p.fixedId,
p.azienda_id,
p.categoria_id,
p.linea,
p.tipo,
p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND (p.fixedId, p.anno) IN
(
SELECT p2.fixedId, MAX(p2.anno)
FROM prodotto p2
WHERE p.azienda_id = p2.azienda_id
GROUP BY p2.fixedId
)
and it took 0.0256s
Good SQL, good.
Let me summarise what you would like to version control and why:
What:
Why:
As others have posted here, there are a couple of solutions on top of existing version control systems such as:
If your only concern is the VBA code in your workbooks, then the approach Demosthenex above proposes or VbaGit (https://github.com/brucemcpherson/VbaGit) work very well working and are relatively simple to implement. The advantages are that you can rely on well proven version control systems and chose one according to your needs (have a look at https://help.github.com/articles/what-are-the-differences-between-svn-and-git/ for a brief comparison between Git and Subversion).
If you not only worry about code but also about the data in your sheets ("hardcoded" values and formula results), you can use a similar strategy for that: Serialise the contents of your sheets into some text format (via Range.Value) and use an existing version control system. Here's a very good blog post about this: https://wiki.ucl.ac.uk/display/~ucftpw2/2013/10/18/Using+git+for+version+control+of+spreadsheet+models+-+part+1+of+3
However, spreadsheet comparison is a non-trivial algorithmic problem. There are a few tools around, such as Microsoft's Spreadsheet Compare (https://support.office.com/en-us/article/Overview-of-Spreadsheet-Compare-13fafa61-62aa-451b-8674-242ce5f2c986), Exceldiff (http://exceldiff.arstdesign.com/) and DiffEngineX (https://www.florencesoft.com/compare-excel-workbooks-differences.html). But it's another challenge to integrate these comparison with a version control system like Git.
Finally, you have to settle on a workflow that suits your needs. For a simple, tailored Git for Excel workflow, have a look at https://www.xltrail.com/blog/git-workflow-for-excel.
You cannot use the Directory directive in .htaccess. However if you create a .htaccess file in the /system directory and place the following in it, you will get the same result
#place this in /system/.htaccess as you had before
deny from all
I would try to solve this without VBA. Just select this space and use replace (change to nothing) on that worksheet you're trying to get rid off those spaces.
If you really want to use VBA I believe you could select first character
strSpace = left(range("A1").Value,1)
and use replace function in VBA the same way
Range("A1").Value = Replace(Range("A1").Value, strSpace, "")
or
for each cell in selection.cells
cell.value = replace(cell.value, strSpace, "")
next
create new style in styles.xml
<style name="myDialog" parent="android:style/Theme.Dialog">
<item name="android:windowNoTitle">true</item>
</style>
then add this to your manifest:
<activity android:name=".youractivity" android:theme="@style/myDialog"></activity>
From the command line:
psql my_database -c 'SHOW SERVER_ENCODING'
From within psql
, an SQL IDE or an API:
SHOW SERVER_ENCODING
This is what I do:
First checkout your branch (for my case master
branch):
git checkout master
Then reset to remote HEAD^ (it'll remove all your local changes), force clean and pull:
git reset HEAD^ --hard && git clean -df && git pull
If you are truly dynamically setting this, you should set the .Url field of instance of the proxy class you are calling.
Setting the value in the .config file from within your program:
Is a mess;
Might not be read until the next application start.
If it is only something that needs to be done once per installation, I'd agree with the other posters and use the .config file and the dynamic setting.
If you don't have a Page.Redirect()
, use this
Response.Write("<script>alert('Inserted successfully!')</script>"); //works great
But if you do have Page.Redirect()
, use this
Response.Write("<script>alert('Inserted..');window.location = 'newpage.aspx';</script>"); //works great
works for me.
Hope this helps.
You have to insert the elements using the insert method present in vectors STL, check the below program to add the elements to it, and you can use in the same way in your program.
#include <iostream>
#include <vector>
#include <string.h>
int main ()
{
std::vector<std::string> myvector ;
std::vector<std::string>::iterator it;
it = myvector.begin();
std::string myarray [] = { "Hi","hello","wassup" };
myvector.insert (myvector.begin(), myarray, myarray+3);
std::cout << "myvector contains:";
for (it=myvector.begin(); it<myvector.end(); it++)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
My swagger XML file was not deployed into \bin:
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "SwaggerDemoApi");
c.IncludeXmlComments(string.Format(@"{0}\bin\SwaggerDemoApi.XML",
System.AppDomain.CurrentDomain.BaseDirectory));
c.DescribeAllEnumsAsStrings();
})
http://wmpratt.com/swagger-and-asp-net-web-api-part-1/
It had to be set in the Release Configuration as well as in the Debug Configuration.
The parent function needs the virtual
keyword, and the child function needs the override
keyword in front of the function definition.
The other answers cover the 2 most common approaches, Xinclude and XML external entities. Microsoft has a really great writeup on why one should prefer Xinclude, as well as several example implementations. I've quoted the comparison below:
Per http://msdn.microsoft.com/en-us/library/aa302291.aspx
Why XInclude?
The first question one may ask is "Why use XInclude instead of XML external entities?" The answer is that XML external entities have a number of well-known limitations and inconvenient implications, which effectively prevent them from being a general-purpose inclusion facility. Specifically:
- An XML external entity cannot be a full-blown independent XML document—neither standalone XML declaration nor Doctype declaration is allowed. That effectively means an XML external entity itself cannot include other external entities.
- An XML external entity must be well formed XML (not so bad at first glance, but imagine you want to include sample C# code into your XML document).
- Failure to load an external entity is a fatal error; any recovery is strictly forbidden.
- Only the whole external entity may be included, there is no way to include only a portion of a document. -External entities must be declared in a DTD or an internal subset. This opens a Pandora's Box full of implications, such as the fact that the document element must be named in Doctype declaration and that validating readers may require that the full content model of the document be defined in DTD among others.
The deficiencies of using XML external entities as an inclusion mechanism have been known for some time and in fact spawned the submission of the XML Inclusion Proposal to the W3C in 1999 by Microsoft and IBM. The proposal defined a processing model and syntax for a general-purpose XML inclusion facility.
Four years later, version 1.0 of the XML Inclusions, also known as Xinclude, is a Candidate Recommendation, which means that the W3C believes that it has been widely reviewed and satisfies the basic technical problems it set out to solve, but is not yet a full recommendation.
Another good site which provides a variety of example implementations is https://www.xml.com/pub/a/2002/07/31/xinclude.html. Below is a common use case example from their site:
<book xmlns:xi="http://www.w3.org/2001/XInclude">
<title>The Wit and Wisdom of George W. Bush</title>
<xi:include href="malapropisms.xml"/>
<xi:include href="mispronunciations.xml"/>
<xi:include href="madeupwords.xml"/>
</book>
In JS there are no simple and cross platform ways to format local date time, outside of converting each property as mentioned above.
Here is a quick hack I use to get the local YYYY-MM-DD. Note that this is a hack, as the final date will not have the correct timezone anymore (so you have to ignore timezone). If I need anything else more, I use moment.js.
var d = new Date();
d = new Date(d.getTime() - d.getTimezoneOffset() * 60000)
var yyyymmdd = t.toISOString().slice(0,0);
// 2017-05-09T08:24:26.581Z (but this is not UTC)
The d.getTimezoneOffset() returns the time zone offset in minutes, and the d.getTime() is in ms, hence the x 60,000.
I've discovered that if the filename has 300
in it, AdBlock blocks the page and throws a ERR_BLOCKED_BY_CLIENT
error.
Your specific case can simply be corrected to be working:
<script type="text/javascript">
var myButton = document.getElementById("myButton");
var myMessage = "it's working";
myButton.onclick = function() { alert(myMessage); };
</script>
This example will work because the anonymous function created and assigned as a handler to element will have access to variables defined in the context where it was created.
For the record, a handler (that you assign through setting onxxx property) expects single argument to take that is event object being passed by the DOM, and you cannot force passing other argument in there
Detecting IE and its versions actually is extremely easy, at least extremely intuitive:
var uA = navigator.userAgent;
var browser = null;
var ieVersion = null;
if (uA.indexOf('MSIE 6') >= 0) {
browser = 'IE';
ieVersion = 6;
}
if (uA.indexOf('MSIE 7') >= 0) {
browser = 'IE';
ieVersion = 7;
}
if (document.documentMode) { // as of IE8
browser = 'IE';
ieVersion = document.documentMode;
}
.
This way, ou're also catching high IE versions in Compatibility Mode/View. Next, its a matter of assigning conditional classes:
var htmlTag = document.documentElement;
if (browser == 'IE' && ieVersion <= 11)
htmlTag.className += ' ie11-';
Since you already have yarn installed and only want to upgrade/update. you can simply use
yarn self-update
Find ref here https://yarnpkg.com/en/docs/cli/self-update
Expanded answer, was my first answer so excuse if there wasn’t enough detail before.
For Bootstrap 3.x I personally prefer CSS animations and I've been using animate.css & along with the Bootstrap Dropdown Javascript Hooks. Although it might not have the exactly effect you're after it's a pretty flexible approach.
Step 1: Add animate.css to your page with the head tags:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.4.0/animate.min.css">
Step 2: Use the standard Bootstrap HTML on the trigger:
<div class="dropdown">
<button type="button" data-toggle="dropdown">Dropdown trigger</button>
<ul class="dropdown-menu">
...
</ul>
</div>
Step 3: Then add 2 custom data attributes to the dropdrop-menu element; data-dropdown-in for the in animation and data-dropdown-out for the out animation. These can be any animate.css effects like fadeIn or fadeOut
<ul class="dropdown-menu" data-dropdown-in="fadeIn" data-dropdown-out="fadeOut">
......
</ul>
Step 4: Next add the following Javascript to read the data-dropdown-in/out data attributes and react to the Bootstrap Javascript API hooks/events (http://getbootstrap.com/javascript/#dropdowns-events):
var dropdownSelectors = $('.dropdown, .dropup');
// Custom function to read dropdown data
// =========================
function dropdownEffectData(target) {
// @todo - page level global?
var effectInDefault = null,
effectOutDefault = null;
var dropdown = $(target),
dropdownMenu = $('.dropdown-menu', target);
var parentUl = dropdown.parents('ul.nav');
// If parent is ul.nav allow global effect settings
if (parentUl.size() > 0) {
effectInDefault = parentUl.data('dropdown-in') || null;
effectOutDefault = parentUl.data('dropdown-out') || null;
}
return {
target: target,
dropdown: dropdown,
dropdownMenu: dropdownMenu,
effectIn: dropdownMenu.data('dropdown-in') || effectInDefault,
effectOut: dropdownMenu.data('dropdown-out') || effectOutDefault,
};
}
// Custom function to start effect (in or out)
// =========================
function dropdownEffectStart(data, effectToStart) {
if (effectToStart) {
data.dropdown.addClass('dropdown-animating');
data.dropdownMenu.addClass('animated');
data.dropdownMenu.addClass(effectToStart);
}
}
// Custom function to read when animation is over
// =========================
function dropdownEffectEnd(data, callbackFunc) {
var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
data.dropdown.one(animationEnd, function() {
data.dropdown.removeClass('dropdown-animating');
data.dropdownMenu.removeClass('animated');
data.dropdownMenu.removeClass(data.effectIn);
data.dropdownMenu.removeClass(data.effectOut);
// Custom callback option, used to remove open class in out effect
if(typeof callbackFunc == 'function'){
callbackFunc();
}
});
}
// Bootstrap API hooks
// =========================
dropdownSelectors.on({
"show.bs.dropdown": function () {
// On show, start in effect
var dropdown = dropdownEffectData(this);
dropdownEffectStart(dropdown, dropdown.effectIn);
},
"shown.bs.dropdown": function () {
// On shown, remove in effect once complete
var dropdown = dropdownEffectData(this);
if (dropdown.effectIn && dropdown.effectOut) {
dropdownEffectEnd(dropdown, function() {});
}
},
"hide.bs.dropdown": function(e) {
// On hide, start out effect
var dropdown = dropdownEffectData(this);
if (dropdown.effectOut) {
e.preventDefault();
dropdownEffectStart(dropdown, dropdown.effectOut);
dropdownEffectEnd(dropdown, function() {
dropdown.dropdown.removeClass('open');
});
}
},
});
Step 5 (optional): If you want to speed up or alter the animation you can do so with CSS like the following:
.dropdown-menu.animated {
/* Speed up animations */
-webkit-animation-duration: 0.55s;
animation-duration: 0.55s;
-webkit-animation-timing-function: ease;
animation-timing-function: ease;
}
Wrote an article with more detail and a download if anyones interested: article: http://bootbites.com/tutorials/bootstrap-dropdown-effects-animatecss
Hope that’s helpful & this second write up has the level of detail that’s needed Tom
For version 19.1 and above goto specified directory and delete these mentioned files:
C:\Users\UserName\AppData\Roaming\syntevo\SmartGit\20.1<smart-git-version>
C:\Users\UserName\AppData\Roaming\syntevo\SmartGit\20.1\.backup
For the previous version goto specified directory and delete mentioned file:
C:\Users\UserName\AppData\Roaming\syntevo\SmartGit\17<smart-git-version>
Like this:
background-image:url(https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Dore_woodcut_Divine_Comedy_01.jpg/481px-Dore_woodcut_Divine_Comedy_01.jpg);
background-repeat:no-repeat;
background-position: center;
background-size: cover;
html{_x000D_
height:100%_x000D_
}_x000D_
_x000D_
body{_x000D_
background-image:url(https://upload.wikimedia.org/wikipedia/commons/thumb/8/8b/Dore_woodcut_Divine_Comedy_01.jpg/481px-Dore_woodcut_Divine_Comedy_01.jpg);_x000D_
background-repeat:no-repeat;_x000D_
background-position: center;_x000D_
background-size: cover;_x000D_
}
_x000D_
SELECT Top 1 sysobjects.[name], max(sysindexes.[rows]) AS TableRows,
CAST(
CASE max(sysindexes.[rows])
WHEN 0 THEN -0
ELSE LOG10(max(sysindexes.[rows]))
END
AS NUMERIC(5,2))
AS L10_TableRows
FROM sysindexes INNER JOIN sysobjects ON sysindexes.[id] = sysobjects.[id]
WHERE sysobjects.xtype = 'U'
GROUP BY sysobjects.[name]
ORDER BY max(rows) DESC
You are using the same connection for the DataReader
and the ExecuteNonQuery
. This is not supported, according to MSDN:
Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You cannot execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.
Updated 2018: link to MSDN
I solved the problem using this code:
_x000D_
<button onclick="email()">Contact me !</button> _x000D_
_x000D_
<script>_x000D_
function email() {_x000D_
var str = window.open('mailto:[email protected]', '_blank');_x000D_
}_x000D_
</script>
_x000D_
It worked for me like a charm !
I took the idiot route. Added these to the end of /etc/profile
for environment in `find /etc/environments.d -type f`
do
. $environment
done
created a folder /etc/environments create a file in it called "oracle" or "whatever" and added the stuff I needed set globally to it.
/etc$ cat /etc/environments.d/Oracle
export PATH=$PATH:/Library/Oracle/instantclient_11_2
export DYLD_LIBRARY_PATH=/Library/Oracle/instantclient_11_2
export SQLPATH=/Library/Oracle/instantclient_11_2
export PATH=$PATH:/Library/Oracle/instantclient_11_2
export TNS_ADMIN=/Library/Oracle/instantclient_11_2/network/admin
%run YourNotebookfile.ipynb is working fine;
if you want to import a specific module then just add the import command after the ipynb i.e YourNotebookfile.ipynb having def Add()
then you can just use it
%run YourNotebookfile.ipynb import Add
The below code should apply different CSS classes based on your Model's CanEdit
Property value .
<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>
But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.
@if(Model.CanEdit)
{
<div>Edit/Delete link goes here</div>
}
jQuery.fn
is defined shorthand for jQuery.prototype
. From the source code:
jQuery.fn = jQuery.prototype = {
// ...
}
That means jQuery.fn.jquery
is an alias for jQuery.prototype.jquery
, which returns the current jQuery version. Again from the source code:
// The current version of jQuery being used
jquery: "@VERSION",
You can reference those remote tracking branches ~(listed with git branch -r
) with the name of their remote.
You need to fetch the remote branch:
git fetch origin aRemoteBranch
If you want to merge one of those remote branches on your local branch:
git checkout master
git merge origin/aRemoteBranch
Note 1: For a large repo with a long history, you will want to add the --depth=1
option when you use git fetch
.
Note 2: These commands also work with other remote repos so you can setup an origin
and an upstream
if you are working on a fork.
Note 3: user3265569 suggests the following alias in the comments:
From
aLocalBranch
, rungit combine remoteBranch
Alias:combine = !git fetch origin ${1} && git merge origin/${1}
Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:
git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch
The idea here, is to merge "one of your local branch" (here anotherLocalBranch
) to a remote branch (origin/aBranch
).
For that, you create first "myBranch
" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch
part.
And then you can merge anotherLocalBranch
to it (to myBranch
).
Alex Martelli's solution set(queries) <= set(my_dict)
is the shortest code but may not be the fastest. Assume Q = len(queries) and D = len(my_dict).
This takes O(Q) + O(D) to make the two sets, and then (one hopes!) only O(min(Q,D)) to do the subset test -- assuming of course that Python set look-up is O(1) -- this is worst case (when the answer is True).
The generator solution of hughdbrown (et al?) all(k in my_dict for k in queries)
is worst-case O(Q).
Complicating factors:
(1) the loops in the set-based gadget are all done at C-speed whereas the any-based gadget is looping over bytecode.
(2) The caller of the any-based gadget may be able to use any knowledge of probability of failure to order the query items accordingly whereas the set-based gadget allows no such control.
As always, if speed is important, benchmarking under operational conditions is a good idea.
If there is no instance available then .class
syntax is used to get the corresponding Class object for a class otherwise you can use getClass() method to get Class object. Since, there is no instance of primitive data type, we have to use .class
syntax for primitive data types.
package test;
public class Test {
public static void main(String[] args)
{
//there is no instance available for class Test, so use Test.class
System.out.println("Test.class.getName() ::: " + Test.class.getName());
// Now create an instance of class Test use getClass()
Test testObj = new Test();
System.out.println("testObj.getClass().getName() ::: " + testObj.getClass().getName());
//For primitive type
System.out.println("boolean.class.getName() ::: " + boolean.class.getName());
System.out.println("int.class.getName() ::: " + int.class.getName());
System.out.println("char.class.getName() ::: " + char.class.getName());
System.out.println("long.class.getName() ::: " + long.class.getName());
}
}
What works best for me is using quote()
and eval()
together.
For example, let's print each column using a for loop
:
Columns <- names(dat)
for (i in 1:ncol(dat)){
dat[, eval(quote(Columns[i]))] %>% print
}
.icon{
background: url(1.jpg) no-repeat;
padding-left:25px;
}
add above tags into your CSS file and use the specified class.
try to get out grafics with x11()
or win.graph()
and solve this trouble.
SQL Server 2008:
SELECT cast(AttDate as time) [time]
FROM yourtable
Earlier versions:
SELECT convert(char(5), AttDate, 108) [time]
FROM yourtable
class Program
{
Variable va = new Variable();
static void Main(string[] args)
{
va.name = "Stackoverflow";
}
}
var dtRegex = new RegExp(/[1-9\-]{4}[0-9\-]{2}[0-9\-]{2}/);
if(dtRegex.test(date) == true){
var evalDate = date.split('-');
if(evalDate[0] != '0000' && evalDate[1] != '00' && evalDate[2] != '00'){
return true;
}
}
The way in which the amount of storage space required by an algorithm varies with the size of the problem it is solving. Space complexity is normally expressed as an order of magnitude, e.g. O(N^2) means that if the size of the problem (N) doubles then four times as much working storage will be needed.
If the database engine for tables differ you will get this error so change them to InnoDB
ALTER TABLE my_table ENGINE = InnoDB;
Why not do it with one method call:
File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });
which will do the newline for you, and allow you to insert multiple lines at once if you want.
Well, from my understanding, simply for matching this format in a given string, I prefer this regular expression:
pattern='[0-9|/]+'
to match the format in a more strict way, the following works:
pattern='(?:[0-9]{2}/){2}[0-9]{2}'
Personally, I cannot agree with unutbu's answer since sometimes we use regular expression for "finding" and "extract", not only "validating".
If you want to convert any bytes, not just string converted to bytes:
with open("bytesfile", "rb") as infile:
str = base64.b85encode(imageFile.read())
with open("bytesfile", "rb") as infile:
str2 = json.dumps(list(infile.read()))
This is not very efficient, however. It will turn a 2 MB picture into 9 MB.
If we see logically programming language and scripting language so this is 99.09% same . because we use same concept like loop , control condition ,variable and all so we can say yes both are same but there is only one thing is different between them that is in C/C++ and other programming language we compile the code before execution . but in the PHP , JavaScript and other scripting language we don't need to compile we directly execute in the browser.
Thanks Nitish K. Jha
Visual Studio has got now integrated support for range checking and type checking :-
Try this :- For RANGE CHECKING Before validating/checking for a particular range of numbers Switch on to design view from markup view .Then :-
View>Toolbox>Validation
Now Drag on RangeValidator to your design page where you want to show the error message(ofcourse if user is inputting out of range value) now click on your RangeValidator control . Right click and select properties . In the Properties window (It is usually opened below solution bar) select on ERROR MESSAGE . Write :-
Number must be in range.
Now select on Control to validate and select your TextboxID (or write it anyways) from the drop down.Locate Type in the property bar itself and select down Integer.
Just above it you will find maximum and minimum value .Type in your desired number .
For Type checking (without any Range)
Before validating/checking for a particular range of numbers Switch on to design view from markup view .Then :-
View>Toolbox>Validation
Now Drag on CompareValidator to your design page where you want to show the error message(ofcourse if user is inputting some text in it). now click on your CompareValidator control . Right click and select properties . In the Properties window (It is usually opened below solution bar) select on ERROR MESSAGE . Write:-
Value must be a number .
Now locate ControltoValidate option and write your controlID name in it(alternatively you can also select from drop down).Locate the Operator option and write DataTypeCheck(alternatively you can also select from drop down)in it .Again locate the Type option and write Integer in it .
That's sit.
Alternatively you can write the following code in your aspx page :- <%--to validate without any range--%>
As a supplementary to the two previous answers (of user "sudo rm -rf" and "Evan Mulawski"), if you don't want to do anything when your alert view is clicked, you can just allocate, show and release it. You don't have to declare the delegate protocol.
If you want the object_name prefixed to any ID you should call form helpers on the form object:
- form_for(@message) do |f|
= f.label :email
This also makes sure any submitted data is stored in memory should there be any validation errors etc.
If you can't call the form helper method on the form object, for example if you're using a tag helper (radio_button_tag etc.) you can interpolate the name using:
= radio_button_tag "#{f.object_name}[email]", @message.email
In this case you'd need to specify the value manually to preserve any submissions.
It means, essentially, what it says; that 'this is important, ignore subsequent rules, and any usual specificity issues, apply this rule!'
In normal use a rule defined in an external stylesheet is overruled by a style defined in the head
of the document, which, in turn, is overruled by an in-line style within the element itself (assuming equal specificity of the selectors). Defining a rule with the !important
'attribute' (?) discards the normal concerns as regards the 'later' rule overriding the 'earlier' ones.
Also, ordinarily, a more specific rule will override a less-specific rule. So:
a {
/* css */
}
Is normally overruled by:
body div #elementID ul li a {
/* css */
}
As the latter selector is more specific (and it doesn't, normally, matter where the more-specific selector is found (in the head
or the external stylesheet) it will still override the less-specific selector (in-line style attributes will always override the 'more-', or the 'less-', specific selector as it's always more specific.
If, however, you add !important
to the less-specific selector's CSS declaration, it will have priority.
Using !important
has its purposes (though I struggle to think of them), but it's much like using a nuclear explosion to stop the foxes killing your chickens; yes, the foxes will be killed, but so will the chickens. And the neighbourhood.
It also makes debugging your CSS a nightmare (from personal, empirical, experience).
If you want to set the form size programmatically, set the form's StartPosition
property to Manual
. Otherwise the form's own positioning and sizing algorithm will interfere with yours. This is why you are experiencing the problems mentioned in your question.
Example: Here is how I resize the form to a size half-way between its original size and the size of the screen's working area. I also center the form in the working area:
public MainView()
{
InitializeComponent();
// StartPosition was set to FormStartPosition.Manual in the properties window.
Rectangle screen = Screen.PrimaryScreen.WorkingArea;
int w = Width >= screen.Width ? screen.Width : (screen.Width + Width) / 2;
int h = Height >= screen.Height ? screen.Height : (screen.Height + Height) / 2;
this.Location = new Point((screen.Width - w) / 2, (screen.Height - h) / 2);
this.Size = new Size(w, h);
}
Note that setting WindowState
to FormWindowState.Maximized
alone does not change the size of the restored window. So the window might look good as long as it is maximized, but when restored, the window size and location can still be wrong. So I suggest setting size and location even when you intend to open the window as maximized.
Here's another solution that mixes ideas from the previous answers. It takes the "kill process" approach while addressing the concern about platform independence.
It relies on the tree-kill package to handle killing the server process tree. I found killing the entire process tree necessary in my projects because some tools (e.g. babel-node
) spawn child processes. If you only need to kill a single process, you can replace tree-kill with the built-in process.kill()
method.
The solution follows (the first two arguments to spawn()
should be modified to reflect the specific recipe for running your server):
build/start-server.js
import { spawn } from 'child_process'
import fs from 'fs'
const child = spawn('node', [
'dist/server.js'
], {
detached: true,
stdio: 'ignore'
})
child.unref()
if (typeof child.pid !== 'undefined') {
fs.writeFileSync('.server.pid', child.pid, {
encoding: 'utf8'
})
}
build/stop-server.js
import fs from 'fs'
import kill from 'tree-kill'
const serverPid = fs.readFileSync('.server.pid', {
encoding: 'utf8'
})
fs.unlinkSync('.server.pid')
kill(serverPid)
package.json
"scripts": {
"start": "babel-node build/start-server.js",
"stop": "babel-node build/stop-server.js"
}
Note that this solution detaches the start script from the server (i.e. npm start
will return immediately and not block until the server is stopped). If you prefer the traditional blocking behavior, simply remove the options.detached
argument to spawn()
and the call to child.unref()
.
Use the modulus operator %
, it returns the remainder.
int a = 5;
int b = 3;
if (a % b != 0) {
printf("The remainder is: %i", a%b);
}
Just one more alternative using URL
var theUrl = new URL(window.location.href);
theUrl.search = ""; //Remove any params
theUrl //as URL object
theUrl.href //as a string
As many have suggested, JRE v1.7 and above has File.toPath();
File yourFile = ...;
Path yourPath = yourFile.toPath();
On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;
File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());
There are also 2 (quick) workarounds:
The shape
attribute for numpy arrays returns the dimensions of the array. If Y
has n
rows and m
columns, then Y.shape
is (n,m)
. So Y.shape[0]
is n
.
In [46]: Y = np.arange(12).reshape(3,4)
In [47]: Y
Out[47]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [48]: Y.shape
Out[48]: (3, 4)
In [49]: Y.shape[0]
Out[49]: 3
Try this:
> data[match(as.character(data$Code), selected, nomatch = FALSE), ]
Code Value
1 A 1
2 B 2
1.1 A 1
1.2 A 1
List<T>.Remove() and List<T>.RemoveAt() do not return the item that is being removed.
Therefore you have to use this:
var item = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, item);
Sounds like a job for the UNIX command split:
split MyBigFile.csv
Just split my 55 GB csv file in 21k chunks in less than 10 minutes.
It's not native to PowerShell though, but comes with, for instance, the git for windows package https://git-scm.com/download/win
In brief:
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
try {
Date date = formatter.parse("01/29/02");
} catch (ParseException e) {
e.printStackTrace();
}
See SimpleDateFormat
javadoc for more.
And to turn it into a Calendar
, do:
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
JavaScript, as defined in your question, can't directly work with MySql. This is because it isn't running on the same computer.
JavaScript runs on the client side (in the browser), and databases usually exist on the server side. You'll probably need to use an intermediate server-side language (like PHP, Java, .Net, or a server-side JavaScript stack like Node.js) to do the query.
Here's a tutorial on how to write some code that would bind PHP, JavaScript, and MySql together, with code running both in the browser, and on a server:
http://www.w3schools.com/php/php_ajax_database.asp
And here's the code from that page. It doesn't exactly match your scenario (it does a query, and doesn't store data in the DB), but it might help you start to understand the types of interactions you'll need in order to make this work.
In particular, pay attention to these bits of code from that article.
Bits of Javascript:
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
Bits of PHP code:
mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
// ...
$row = mysql_fetch_array($result)
mysql_close($con);
Also, after you get a handle on how this sort of code works, I suggest you use the jQuery JavaScript library to do your AJAX calls. It is much cleaner and easier to deal with than the built-in AJAX support, and you won't have to write browser-specific code, as jQuery has cross-browser support built in. Here's the page for the jQuery AJAX API documentation.
HTML/Javascript code:
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
PHP code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
DataBase :- OLTP(online transaction process)
Datawarehouse
None of the other answers seemed correct in my case, however I found the real answer here
My id_rsa
file was already in PEM format, I just needed to add the .pem
extension to the filename.
The possible options to the openssl rsa -inform
parameter are one of: PEM
DER
A
PEM
encoded file is a plain-text encoding that looks something like:-----BEGIN RSA PRIVATE KEY----- MIGrAgEAAiEA0tlSKz5Iauj6ud3helAf5GguXeLUeFFTgHrpC3b2O20CAwEAAQIh ALeEtAIzebCkC+bO+rwNFVORb0bA9xN2n5dyTw/Ba285AhEA9FFDtx4VAxMVB2GU QfJ/2wIRANzuXKda/nRXIyRw1ArE2FcCECYhGKRXeYgFTl7ch7rTEckCEQDTMShw 8pL7M7DsTM7l3HXRAhAhIMYKQawc+Y7MNE4kQWYe -----END RSA PRIVATE KEY-----
While
DER
is a binary encoding format.
There are the following ways by which you can achieve this:
These units will autoresize depending upon the width and height of the screen.
pst.setDate(6, new java.sql.Date(txtDate.getDate().getTime()));
this is the code I used to save date into the database using jdbc works fine for me
pst
is a variable for preparedstatementtxtdate
is the name for the JDateChooser The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
I seem to be able to get along with simply:
$gpg <path_to_file>
Which outputs like this:
$ gpg /tmp/keys/something.asc
pub 1024D/560C6C26 2014-11-26 Something <[email protected]>
sub 2048g/0C1ACCA6 2014-11-26
The op didn't specify in particular what key info is relevant. This output is all I care about.
You've already discovered the simplest way to specify a shallow clone in Git-SVN, by specifying the SVN revision number that you want to start your clone at ( -r$REV:HEAD
).
For example: git svn clone -s -r1450:HEAD some/svn/repo
Git's data structure is based on pointers in a directed acyclic graph (DAG), which makes it trivial to walk back n
commits. But in SVN ( and therefore in Git-SVN) you will have to find the revision number yourself.
If anyone like me is searching to read only a specific line, example only line 18 here is the code:
filename = "C:\log.log"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
For i = 1 to 17
f.ReadLine
Next
strLine = f.ReadLine
Wscript.Echo strLine
f.Close
I wanted to add my fiddle here for this:
http://jsfiddle.net/bladnman/EhUm3/
I tested this is chrome, safari and IE (10 and 8). Works fine. There is only 1 function that matters, so if you get scared by the big fiddle, read below.
Note: There is a fair amount of my own "boilerplate" in this fiddle. You can remove all of that and use split's if you like. It's just an ultra-safe" set of functions I've come to rely on.
There is also a "JSFiddle" template in there that I use for many fiddles to simply quick fiddling.
I think it may help you-
Read your error carefully-./src/App.js Module not found: Can't resolve './src/components/header/header' in '/home/wiseman/Desktop/React_Components/github-portfolio/src'
just write- ./header/header instead ./src/components/header/header in App.js
if it doesnt work try to change header file name may be head
Very Easy. Just change to () => this.showCancel() like below:
<TextInput
onFocus={() => this.showCancel() }
onChangeText={(text) => this.doSearch({input: text})} />
<TouchableHighlight
onPress={this.hideCancel()}>
<View>
<Text style={styles.cancelButtonText}>Cancel</Text>
</View>
</TouchableHighlight>
This answer is counting that the second parameter is useless when calling removeAttr! (as it was when this answer was posted) Do not use this otherwise!
Can't beat RienNeVaPlus's clean answer, but it does the job as well, it's basically a more compressed way to do the ternary operation:
$('.list-sort')[$('.list-sort').hasAttr('colspan') ?
'removeAttr' : 'attr']('colspan', 6);
an extra variable can be used in these cases, when you need to use the reference more than once:
var $listSort = $('.list-sort');
$listSort[$listSort.hasAttr('colspan') ? 'removeAttr' : 'attr']('colspan', 6);
I think we can modify the UsedRange
code from @Readify's answer above to get the last used column even if the starting columns are blank or not.
So this lColumn = ws.UsedRange.Columns.Count
modified to
this lColumn = ws.UsedRange.Column + ws.UsedRange.Columns.Count - 1
will give reliable results always
?Sheet1.UsedRange.Column + Sheet1.UsedRange.Columns.Count - 1
Above line Yields 9
in the immediate window.
As for the workaround (without using non-portable -P
), you can temporary replace a new-line character with the different one and change it back, e.g.:
grep -o "_foo_" <(paste -sd_ file) | tr -d '_'
Basically it's looking for exact match _foo_
where _
means \n
(so __
= \n\n
). You don't have to translate it back by tr '_' '\n'
, as each pattern would be printed in the new line anyway, so removing _
is enough.
The accepted answer didn't work for me so I've found this solution.
It may be related to the HTML version as the most voted solution there states:
If you need your document to validate against HTML5 use this instead:
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
See the link for more info.
It is not legal to declare an instance member in a static class. Static class's cannot be instantiated hence it makes no sense to have an instance members (they'd never be accessible).
private static NetworkUtil mInstance;
private volatile boolean mIsOnline;
private NetworkUtil() {
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
boolean reachable = false;
try {
Process process = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = process.waitFor();
reachable = (returnVal==0);
} catch (Exception e) {
e.printStackTrace();
}
mIsOnline = reachable;
}
}, 0, 5, TimeUnit.SECONDS);
}
public static NetworkUtil getInstance() {
if (mInstance == null) {
synchronized (NetworkUtil.class) {
if (mInstance == null) {
mInstance = new NetworkUtil();
}
}
}
return mInstance;
}
public boolean isOnline() {
return mIsOnline;
}
Hope the above code helps you, also make sure you have internet permission in ur app.
This worked for me
<input
(input)="$event.target.value = toSnakeCase($event.target.value)"
[(ngModel)]="table.name" />
In Typescript
toSnakeCase(value: string) {
if (value) {
return value.toLowerCase().replace(/[\W_]+/g, "");
}
}
You open the variable "file" as a read only then attempt to write to it:
file = open('ValidEmails.txt','r')
Instead, use the 'w' flag.
file = open('ValidEmails.txt','w')
...
file.write(email)
You can use a plugin available here..
https://plugins.jquery.com/cookie/
and then to write a cookie do
$.cookie("test", 1);
to access the set cookie do
$.cookie("test");
Here's how you do it:
If the accepted answer isn't working right for you then you might try.
str.replace(new RegExp('\n','g'), '<br />')
It worked for me.
A simpler solution (based on code in question):
JSONArray json = new JSONArray();
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()) {
int numColumns = rsmd.getColumnCount();
JSONObject obj = new JSONObject();
for (int i=1; i<=numColumns; i++) {
String column_name = rsmd.getColumnName(i);
obj.put(column_name, rs.getObject(column_name));
}
json.put(obj);
}
return json;
Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.
Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?
This seems to be related to Unable to install Python libraries
See Dominique Barton's answer:
Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.
On Debian-based systems I'd try:
apt-get update && apt-get upgrade python-pip
On Red Hat Linux-based systems:
yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)
On Mac:
sudo easy_install -U pip
You can also try to update
openssl
separately.
In my case TLS1_2 was enabled both on client and server but the server was using MD5 while client disabled it. So, test both client and server on http://ssllabs.com or test using openssl/s_client to see what's happening. Also, check the selected cipher using Wireshark.
An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view
Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'
The best way to do this:
ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);
in devices which has Android 4.3 and above you should follow these steps:
How to enable Developer Options:
Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.
In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.
I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->
return .Cell(i,1) <> Empty
If you have Qt/KDE installed, you can use kdialog, which pops up a Qt dialog window. You can easily specify to display a Yes/No dialog, OK/Cancel, simple text input, password input etc. You then have access to the return values from these dialogs at the shell.
If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.
For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11
To edit the Compatibility View list:
Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.
You are trying to return an object. Because there is no good way to represent an object as a string, the object's .toString()
value is automatically set as "[object Object]"
.
_MSC_VER should be defined to a specific version number. You can either #ifdef on it, or you can use the actual define and do a runtime test. (If for some reason you wanted to run different code based on what compiler it was compiled with? Yeah, probably you were looking for the #ifdef. :))
SHOW TABLES
will show all the tables in your db. If you want to filter the names you use LIKE
and wildcard %
SHOW TABLES FROM my_database LIKE '%user%'
will give you all tables that's name include 'user', for example
users
user_pictures
mac_users
etc.
It's probably because your SSH key has been removed/revoked. Make a new one and add it to your GitHub account.
Not sure if that's exactly what you need, but we are using profiles to define the environment we are running at and specific bean for each environment, so it's something like that:
<bean name="myBean" class="myClass">
<constructor-arg name="name" value="originalValue" />
</bean>
<beans profile="DEV, default">
<!-- Specific DEV configurations, also default if no profile defined -->
<bean name="myBean" class="myClass">
<constructor-arg name="name" value="overrideValue" />
</bean>
</beans>
<beans profile="CI, UAT">
<!-- Specific CI / UAT configurations -->
</beans>
<beans profile="PROD">
<!-- Specific PROD configurations -->
</beans>
So in this case, if I don't define a profile or if I define it as "DEV" myBean will get "overrideValue" for it's name argument. But if I set the profile to "CI", "UAT" or "PROD" it will get "originalValue" as the value.
TLDR; Visual Studio 2019 may simply need a restart.
I encountered this situation using projects based on Microsoft.NET.Sdk project.
<Project Sdk="Microsoft.NET.Sdk">
Specifically:
Project1
: targets .netstandard2.1
Microsoft.Extensions.Logging.Console
via NugetProject2
: targets .netstandard2.1
Project1
via a Project referenceProject2Tests
: targets .netcoreapp3.1
Project2
via a Project referenceAt test execution, I received the error messaging indicating that Microsoft.Extensions.Logging.Console
could not be found, and it was indeed not in the output directory.
I decided to work around the issue by adding Microsoft.Extensions.Logging.Console
to Project2
, only to discover that Visual Studio's Nuget Manager did not list Microsoft.Extensions.Logging.Console
as installed in Project1
, despite it's presence in the Project1.csproj
file.
A simple shut down and restart of Visual Studio resolved the problem without the need to add an extra reference. Perhaps this will save someone 45 minutes of lost productivity :-)
What you can do to resolve your conflict is
svn resolve --accept working -R <path>
where <path>
is where you have your conflict (can be the root of your repo).
Explanations:
resolve
asks svn
to resolve the conflictaccept working
specifies to keep your working files-R
stands for recursiveHope this helps.
EDIT:
To sum up what was said in the comments below:
<path>
should be the directory in conflict (C:\DevBranch\
in the case of the OP)svn switch
commandSwitch working copy to new branch/tag
option at branch creationIf you are using maven, adding below dependency should work
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
try:
thevariable
except NameError:
print("well, it WASN'T defined after all!")
else:
print("sure, it was defined.")
public static string XmlSerializeToString(this object objectInstance)
{
var serializer = new XmlSerializer(objectInstance.GetType());
var sb = new StringBuilder();
using (TextWriter writer = new StringWriter(sb))
{
serializer.Serialize(writer, objectInstance);
}
return sb.ToString();
}
public static T XmlDeserializeFromString<T>(this string objectData)
{
return (T)XmlDeserializeFromString(objectData, typeof(T));
}
public static object XmlDeserializeFromString(this string objectData, Type type)
{
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
return result;
}
To use it:
//Make XML
var settings = new ObjectCustomerSettings();
var xmlString = settings.XmlSerializeToString();
//Make Object
var settings = xmlString.XmlDeserializeFromString<ObjectCustomerSettings>();
the best way to uninstall VS 2010 is to use Microsoft Visual Studio 2010 Uninstall Utility on this link http://archive.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=vs2010uninstall&DownloadId=11182
An HTML parser will treat everything between <script>
and </script>
as part of the script. Some implementations don't even need a correct closing tag; they stop script interpretation at ". </
", which is correct according to the specs
Update In HTML5, and with current browsers, that is not the case anymore.
So, in HTML, this is not possible:
<script>
var x = '</script>';
alert(x)
</script>
A CDATA
section has no effect at all. That's why you need to write
var x = '<' + '/script>'; // or
var x = '<\/script>';
or similar.
This also applies to XHTML files served as text/html
. (Since IE does not support XML content types, this is mostly true.)
In XML, different rules apply. Note that (non IE) browsers only use an XML parser if the XHMTL document is served with an XML content type.
To the XML parser, a script
tag is no better than any other tag. Particularly, a script node may contain non-text child nodes, triggered by "<
"; and a "&
" sign denotes a character entity.
So, in XHTML, this is not possible:
<script>
if (a<b && c<d) {
alert('Hooray');
}
</script>
To work around this, you can wrap the whole script in a CDATA
section. This tells the parser: 'In this section, don't treat "<
" and "&
" as control characters.' To prevent the JavaScript engine from interpreting the "<![CDATA[
" and "]]>
" marks, you can wrap them in comments.
If your script does not contain any "<
" or "&
", you don't need a CDATA
section anyway.
You should use tags:
as documented in https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html
If you have a large playbook it may become useful to be able to run a specific part of the configuration without running the whole playbook.
Both plays and tasks support a “tags:” attribute for this reason.
Example:
tasks:
- yum: name={{ item }} state=installed
with_items:
- httpd
- memcached
tags:
- packages
- template: src=templates/src.j2 dest=/etc/foo.conf
tags:
- configuration
If you wanted to just run the “configuration” and “packages” part of a very long playbook, you could do this:
ansible-playbook example.yml --tags "configuration,packages"
On the other hand, if you want to run a playbook without certain tasks, you could do this:
ansible-playbook example.yml --skip-tags "notification"
You may also apply tags to roles:
roles:
- { role: webserver, port: 5000, tags: [ 'web', 'foo' ] }
And you may also tag basic include statements:
- include: foo.yml tags=web,foo
Both of these have the function of tagging every single task inside the include statement.
No, you can't!
However, having bumped into that issue should make you rethink on how you organize your code.
Before ES6 modules, we had CommonJS modules which used the require() syntax. These modules were "dynamic", meaning that we could import new modules based on conditions in our code. - source: https://bitsofco.de/what-is-tree-shaking/
I guess one of the reasons they dropped that support on ES6 onward is the fact that compiling it would be very difficult or impossible.
This has worked for me.....
Private Sub Worksheet_Change(ByVal Target As Range)
If Mid(Target.Address, 3, 1) = "$" And Mid(Target.Address, 2, 1) < "E" Then
' The logic in the if condition will filter for a specific cell or block of cells
Application.ScreenUpdating = False
'MsgBox "You just changed " & Target.Address
'all conditions are true .... DO THE FUNCTION NEEDED
Application.ScreenUpdating = True
End If
' if clicked cell is not in the range then do nothing (if condttion is not run)
End Sub
NOTE: this function in actual use recalculated a pivot table if a user added a item in a data range of A4 to D500. The there were protected and unprotected sections in the sheet so the actual check for the click is if the column is less that "E" The logic can get as complex as you want to include or exclude any number of areas
block1 = row > 3 and row < 5 and column column >"b" and < "d"
block2 = row > 7 and row < 12 and column column >"b" and < "d"
block3 = row > 10 and row < 15 and column column >"e" and < "g"
If block1 or block2 or block 3 then
do function .....
end if
Better use $_SERVER['REQUEST_METHOD']
:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
C++17
simplified this a bit more with an If statement with initializer
.
This way you can have your cake and eat it too.
if ( auto it{ m.find( "key" ) }; it != std::end( m ) )
{
// Use `structured binding` to get the key
// and value.
auto[ key, value ] { *it };
// Grab either the key or value stored in the pair.
// The key is stored in the 'first' variable and
// the 'value' is stored in the second.
auto mkey{ it->first };
auto mvalue{ it->second };
// That or just grab the entire pair pointed
// to by the iterator.
auto pair{ *it };
}
else
{
// Key was not found..
}
Check out Datejs. Their built in formatters can do this: http://code.google.com/p/datejs/wiki/APIDocumentation#toString
It's a really handy library, especially if you are planning on doing other things with date objects.
If you implement explicitly, you will only be able to reference the interface members through a reference that is of the type of the interface. A reference that is the type of the implementing class will not expose those interface members.
If your implementing class is not public, except for the method used to create the class (which could be a factory or IoC container), and except for the interface methods (of course), then I don't see any advantage to explicitly implementing interfaces.
Otherwise, explicitly implementing interfaces makes sure that references to your concrete implementing class are not used, allowing you to change that implementation at a later time. "Makes sure", I suppose, is the "advantage". A well-factored implementation can accomplish this without explicit implementation.
The disadvantage, in my opinion, is that you will find yourself casting types to/from the interface in the implementation code that does have access to non-public members.
Like many things, the advantage is the disadvantage (and vice-versa). Explicitly implementing interfaces will ensure that your concrete class implementation code is not exposed.
May be these two links can help you Associate IP addresses with countries
How to get the last N rows of a pandas DataFrame?
If you are slicing by position, __getitem__
(i.e., slicing with[]
) works well, and is the most succinct solution I've found for this problem.
pd.__version__
# '0.24.2'
df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df
A B
0 a 1
1 a 2
2 a 3
3 b 4
4 b 5
5 b 6
6 b 7
7 c 8
df[-3:]
A B
5 b 6
6 b 7
7 c 8
This is the same as calling df.iloc[-3:]
, for instance (iloc
internally delegates to __getitem__
).
As an aside, if you want to find the last N rows for each group, use groupby
and GroupBy.tail
:
df.groupby('A').tail(2)
A B
1 a 2
2 a 3
5 b 6
6 b 7
7 c 8
When you parse the JSON representation, it'll become a JavaScript array of objects.
Because of this, you can use the .length
property of the JavaScript array to see how many elements are contained, and use a for
loop to enumerate it.
Try the following:
$.ajax({
url: _saveDeviceUrl
, type: 'POST'
, contentType: 'application/json'
, dataType: 'json'
, data: {'myArray': postData}
, success: _madeSave.bind(this)
//, processData: false //Doesn't help
});
I must add one more point in this thread. To install/uninstall 64-bit
version of assemblies one should use 64-bit
version of tool. To install a service, the command should be:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe"
"C:\YourFolder\YourService.exe"
and to uninstall the command should be:
"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe" -u
"C:\YourFolder\YourService.exe"
As vim's own help on set background
says, "Setting this option does not change the background color, it tells Vim what the background color looks like. For changing the background color, see |:hi-normal|."
For example
:highlight Normal ctermfg=grey ctermbg=darkblue
will write in white on blue on your color terminal.
audio { display:none;}
_x000D_
<audio autoplay="true" src="https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg">
_x000D_
No, but it's been requested many times.
setting the content-type to undefined would make javascript pass the header data As it is , and over writing the default angular $httpProvider header configurations. Angular $http Documentation
$http({url:url,method:"POST", headers:{'Content-Type':undefined}).then(success,failure);
This is really helpful if you want to create a multimap without resorting to the Google Guava library for its implementation of MultiMap
.
For example, suppose you want to store a list of students who enrolled for a particular subject.
The normal solution for this using JDK library is:
Map<String,List<String>> studentListSubjectWise = new TreeMap<>();
List<String>lis = studentListSubjectWise.get("a");
if(lis == null) {
lis = new ArrayList<>();
}
lis.add("John");
//continue....
Since it have some boilerplate code, people tend to use Guava Mutltimap
.
Using Map.computeIfAbsent, we can write in a single line without guava Multimap as follows.
studentListSubjectWise.computeIfAbsent("a", (x -> new ArrayList<>())).add("John");
Stuart Marks & Brian Goetz did a good talk about this https://www.youtube.com/watch?v=9uTVXxJjuco
If you want just the summary of the exception use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
If you want to see the whole stack trace (usually better for debugging) use:
try
{
test();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Another method I sometime use is:
private DoSomthing(int arg1, int arg2, out string errorMessage)
{
int result ;
errorMessage = String.Empty;
try
{
//do stuff
int result = 42;
}
catch (Exception ex)
{
errorMessage = ex.Message;//OR ex.ToString(); OR Free text OR an custom object
result = -1;
}
return result;
}
And In your form you will have something like:
string ErrorMessage;
int result = DoSomthing(1, 2, out ErrorMessage);
if (!String.IsNullOrEmpty(ErrorMessage))
{
MessageBox.Show(ErrorMessage);
}
Easier is subjective, but maybe the switch statement would be easier? You don't have to repeat the variable, so more values can fit on the line, and a line with many comparisons is more legible than the counterpart using the if statement.
I wrote a very tiny plugin called "once" which do that. Execute off and on in element.
$.fn.once = function(a, b) {
return this.each(function() {
$(this).off(a).on(a,b);
});
};
And simply:
$(element).once('click', function(){
});
If I want tranfer only the response variable y instead of a linear model with x specified, eg I wanna transfer/normalize a list of data, I can take 1 for x, then the object becomes a linear model:
library(MASS)
y = rf(500,30,30)
hist(y,breaks = 12)
result = boxcox(y~1, lambda = seq(-5,5,0.5))
mylambda = result$x[which.max(result$y)]
mylambda
y2 = (y^mylambda-1)/mylambda
hist(y2)
there are four types of strings available in php. They are single quotes ('), double quotes (") and Nowdoc (<<<'EOD')
and heredoc(<<<EOD)
strings
you can use both single quotes and double quotes inside heredoc string. Variables will be expanded just as double quotes.
nowdoc strings will not expand variables just like single quotes.
ref: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
I preferred using !=
instead of <>
because sometimes I use the <s></s>
syntax to write SQL commands. Using !=
is more handy to avoid syntax errors in this case.
I follow Kelsey's first set of steps to add the installer classes to my service project, but instead of creating an MSI or setup.exe installer I make the service self installing/uninstalling. Here's a bit of sample code from one of my services you can use as a starting point.
public static int Main(string[] args)
{
if (System.Environment.UserInteractive)
{
// we only care about the first two characters
string arg = args[0].ToLowerInvariant().Substring(0, 2);
switch (arg)
{
case "/i": // install
return InstallService();
case "/u": // uninstall
return UninstallService();
default: // unknown option
Console.WriteLine("Argument not recognized: {0}", args[0]);
Console.WriteLine(string.Empty);
DisplayUsage();
return 1;
}
}
else
{
// run as a standard service as we weren't started by a user
ServiceBase.Run(new CSMessageQueueService());
}
return 0;
}
private static int InstallService()
{
var service = new MyService();
try
{
// perform specific install steps for our queue service.
service.InstallService();
// install the service with the Windows Service Control Manager (SCM)
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
}
catch (Exception ex)
{
if (ex.InnerException != null && ex.InnerException.GetType() == typeof(Win32Exception))
{
Win32Exception wex = (Win32Exception)ex.InnerException;
Console.WriteLine("Error(0x{0:X}): Service already installed!", wex.ErrorCode);
return wex.ErrorCode;
}
else
{
Console.WriteLine(ex.ToString());
return -1;
}
}
return 0;
}
private static int UninstallService()
{
var service = new MyQueueService();
try
{
// perform specific uninstall steps for our queue service
service.UninstallService();
// uninstall the service from the Windows Service Control Manager (SCM)
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
}
catch (Exception ex)
{
if (ex.InnerException.GetType() == typeof(Win32Exception))
{
Win32Exception wex = (Win32Exception)ex.InnerException;
Console.WriteLine("Error(0x{0:X}): Service not installed!", wex.ErrorCode);
return wex.ErrorCode;
}
else
{
Console.WriteLine(ex.ToString());
return -1;
}
}
return 0;
}
Now you can use either of those options. And it is going to work in any case. Your color can be a HEX code, like this:
myView.setBackgroundResource(ContextCompat.getColor(context, Color.parseColor("#FFFFFF")));
A color resource, like this:
myView.setBackgroundResource(ContextCompat.getColor(context,R.color.blue_background));
Or a custom xml resource, like so:
myView.setBackgroundResource(R.drawable.my_custom_background);
Hope it helps!
All of above can be avoided by simply declaring a friend value for runtime on the starting form.
Public Class Form1
Friend sharevalue as string = "Boo"
Then access this variable from all forms simply using Form1.sharevalue
I did it! Using <intent-filter>
. Put the following into your manifest file:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>
This works perfectly!
public long millis() {
return (long.MaxValue + DateTime.Now.ToBinary()) / 10000;
}
If you want microseconds, just change 10000
to 10
, and if you want the 10th of micro, delete / 10000
.
You need to move the unique_ptr
:
vec.push_back(std::move(ptr2x));
unique_ptr
guarantees that a single unique_ptr
container has ownership of the held pointer. This means that you can't make copies of a unique_ptr
(because then two unique_ptr
s would have ownership), so you can only move it.
Note, however, that your current use of unique_ptr
is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:
std::unique_ptr<int> ptr(new int(1));
In C++14 we have an even better way to do so:
make_unique<int>(5);
Option 1: Use a nullable DateTime?
Option 2: Use DateTime.MinValue
Personally, I'd prefer option 1.
simplest way(and even works from api 1) that tested is:
getResources().getDimensionPixelSize(R.dimen.example_dimen);
From documentations:
Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This is the same as getDimension(int), except the returned value is converted to integer pixels for use as a size. A size conversion involves rounding the base value, and ensuring that a non-zero base value is at least one pixel in size.
Yes it rounding the value but it's not very bad(just in odd values on hdpi and ldpi devices need to add a little value when ldpi is not very common) I tested in a xxhdpi device that converts 4dp to 16(pixels) and that is true.
I have created a module for anuglar2 autocomplete In this module you can use array, or url npm link : ang2-autocomplete
iOS 5 added the following style that can be added to the parent div so that scrolling works.
-webkit-overflow-scrolling:touch
A simple way of reading variables from a text file using the standard library:
# Get vars from conf file
var = {}
with open("myvars.conf") as conf:
for line in conf:
if ":" in line:
name, value = line.split(":")
var[name] = str(value).rstrip()
globals().update(var)
If you are developing on Netbeans, you will not get the Third-Party add-ons. You can download the Skins directly from Samsung here: http://developer.samsung.com/android/tools-sdks
After download, unzip to ...\Android\android-sdk\add-ons[name of device]
Restart the Android SDK Manager, and the new device should be there under Extras.
It would be better to add the download site directly to the SDK...if anyone knows it, please post it.
Scott
Careful - append()
will append HTML, and you may run into cross-site-scripting problems if you use it all the time and a user makes you append('<script>alert("Hello")</script>')
.
Use text()
to replace element content with text, or append(document.createTextNode(x))
to append a text node.
Adding to the other answers and doing nothing more of what @Maleta explained in a comment on https://stackoverflow.com/a/28481374/1626594, doing alpha*255 then round then to hex. Here's a quick converter http://jsfiddle.net/8ajxdLap/4/
function rgb2hex(rgb) {_x000D_
var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?((?:[0-9]*[.])?[0-9]+)[\s+]?\)/i);_x000D_
if (rgbm && rgbm.length === 5) {_x000D_
return "#" +_x000D_
('0' + Math.round(parseFloat(rgbm[4], 10) * 255).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
} else {_x000D_
var rgbm = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);_x000D_
if (rgbm && rgbm.length === 4) {_x000D_
return "#" +_x000D_
("0" + parseInt(rgbm[1], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[2], 10).toString(16).toUpperCase()).slice(-2) +_x000D_
("0" + parseInt(rgbm[3], 10).toString(16).toUpperCase()).slice(-2);_x000D_
} else {_x000D_
return "cant parse that";_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
$('button').click(function() {_x000D_
var hex = rgb2hex($('#in_tb').val());_x000D_
$('#in_tb_result').html(hex);_x000D_
});
_x000D_
body {_x000D_
padding: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
Convert RGB/RGBA to hex #RRGGBB/#AARRGGBB:<br>_x000D_
<br>_x000D_
<input id="in_tb" type="text" value="rgba(200, 90, 34, 0.75)"> <button>Convert</button><br>_x000D_
<br> Result: <span id="in_tb_result"></span>
_x000D_
One method you might want to consider if you're going to be working with the values a lot is to write them to a temporary table first. Then you just join on it like normal.
This way, you're only parsing once.
It's easiest to use one of the 'Split' UDFs, but so many people have posted examples of those, I figured I'd go a different route ;)
This example will create a temporary table for you to join on (#tmpDept) and fill it with the department id's that you passed in. I'm assuming you're separating them with commas, but you can -- of course -- change it to whatever you want.
IF OBJECT_ID('tempdb..#tmpDept', 'U') IS NOT NULL
BEGIN
DROP TABLE #tmpDept
END
SET @DepartmentIDs=REPLACE(@DepartmentIDs,' ','')
CREATE TABLE #tmpDept (DeptID INT)
DECLARE @DeptID INT
IF IsNumeric(@DepartmentIDs)=1
BEGIN
SET @DeptID=@DepartmentIDs
INSERT INTO #tmpDept (DeptID) SELECT @DeptID
END
ELSE
BEGIN
WHILE CHARINDEX(',',@DepartmentIDs)>0
BEGIN
SET @DeptID=LEFT(@DepartmentIDs,CHARINDEX(',',@DepartmentIDs)-1)
SET @DepartmentIDs=RIGHT(@DepartmentIDs,LEN(@DepartmentIDs)-CHARINDEX(',',@DepartmentIDs))
INSERT INTO #tmpDept (DeptID) SELECT @DeptID
END
END
This will allow you to pass in one department id, multiple id's with commas in between them, or even multiple id's with commas and spaces between them.
So if you did something like:
SELECT Dept.Name
FROM Departments
JOIN #tmpDept ON Departments.DepartmentID=#tmpDept.DeptID
ORDER BY Dept.Name
You would see the names of all of the department IDs that you passed in...
Again, this can be simplified by using a function to populate the temporary table... I mainly did it without one just to kill some boredom :-P
-- Kevin Fairchild
To work around this problem, use SQL statements to make the changes to the metadata structure of a table.
This problem occurs when "Prevent saving changes that require table re-creation" option is enabled.
Source: Error message when you try to save a table in SQL Server 2008: "Saving changes is not permitted"
DECLARE @TB TABLE(NAME VARCHAR(100));
INSERT INTO @TB VALUES ('Red'),('Red'),('Green'),('Blue'),('White'),('White')
--**Delete by Rank**
;WITH CTE AS(SELECT NAME,DENSE_RANK() OVER (PARTITION BY NAME ORDER BY NEWID()) ID FROM @TB)
DELETE FROM CTE WHERE ID>1
SELECT NAME FROM @TB;
--**Delete by Row Number**
;WITH CTE AS(SELECT NAME,ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY NAME) ID FROM @TB)
DELETE FROM CTE WHERE ID>1;
SELECT NAME FROM @TB;
You could use Mono for Android
:
http://xamarin.com/monoforandroid
An alternative is dot42
:
dot42 provides a free community licence as well as a professional licence for $399.
To fix the overlap, you only need modify the .navbar-toggle in your own css styles
something like this, it works for me:
.navbar-toggle{
z-index: 10;
}
Here I get only three specific columns from mainDataTable and use the filter
DataTable checkedParams = mainDataTable.Select("checked = true").CopyToDataTable()
.DefaultView.ToTable(false, "lagerID", "reservePeriod", "discount");
You can use a TreeMap data structure
. TreeMap
is implemented as a red black tree, which is a self-balancing binary search tree.
If you are getting the JSON string from the form using $_REQUEST
, $_GET
, or $_POST
the you will need to use the function html_entity_decode()
. I didn't realize this until I did a var_dump
of what was in the request vs. what I copied into and echo
statement and noticed the request string was much larger.
Correct Way:
$jsonText = $_REQUEST['myJSON'];
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode($decodedText, true);
With Errors:
$jsonText = $_REQUEST['myJSON'];
$myArray = json_decode($jsonText, true);
echo json_last_error(); //Returns 4 - Syntax error;
You can use the concept of multiple queries in the FROM keyword. Let me show you one example:
SELECT DISTINCT e.id,e.name,d.name,lap.lappy LAPTOP_MAKE,c_loc.cnty COUNTY
FROM (
SELECT c.id cnty,l.name
FROM county c, location l
WHERE c.id=l.county_id AND l.end_Date IS NOT NULL
) c_loc, emp e
INNER JOIN dept d ON e.deptno =d.id
LEFT JOIN
(
SELECT l.id lappy, c.name cmpy
FROM laptop l, company c
WHERE l.make = c.name
) lap ON e.cmpy_id=lap.cmpy
You can use as many tables as you want to. Use outer joins and union where ever it's necessary, even inside table subqueries.
That's a very easy method to involve as many as tables and fields.
I'm afraid there is no "better" way to get this size, however it's not that much pain.
Of course your code should be safe for both binary/mono images as well as multi-channel ones, but the principal dimensions of the image always come first in the numpy array's shape. If you opt for readability, or don't want to bother typing this, you can wrap it up in a function, and give it a name you like, e.g. cv_size
:
import numpy as np
import cv2
# ...
def cv_size(img):
return tuple(img.shape[1::-1])
If you're on a terminal / ipython, you can also express it with a lambda:
>>> cv_size = lambda img: tuple(img.shape[1::-1])
>>> cv_size(img)
(640, 480)
Writing functions with def
is not fun while working interactively.
Edit
Originally I thought that using [:2]
was OK, but the numpy shape is (height, width[, depth])
, and we need (width, height)
, as e.g. cv2.resize
expects, so - we must use [1::-1]
. Even less memorable than [:2]
. And who remembers reverse slicing anyway?
I didn't have any real luck with any of the solutions above. I'm using NIB files for my tables cells. I "fixed" this by adding a label with a height of 1. I changed the background of the label to black, pinned the label to the bottom of the nib, and then pinned the bottom of the rest of my contents to the added label. Now I have a black border running along the bottom of my cells.
To me, this feels like more of a hack, but it does work.
My only other choice was to just eliminate the border completely. I'm still deciding whether I'll just go with that.
To complete Raymond's answer
Bootstrap 2.3.2
<ul class="inline">
<li>...</li>
</ul>
Bootstrap 3
<ul class="list-inline">
<li>...</li>
</ul>
Bootstrap 4
<ul class="list-inline">
<li class="list-inline-item">Lorem ipsum</li>
<li class="list-inline-item">Phasellus iaculis</li>
<li class="list-inline-item">Nulla volutpat</li>
</ul>
source: http://v4-alpha.getbootstrap.com/content/typography/#inline
This should work reliably:
source_relative() {
local dir="${BASH_SOURCE%/*}"
[[ -z "$dir" ]] && dir="$PWD"
source "$dir/$1"
}
source_relative incl.sh
Here's a generic multidimensional sort, allowing for reversing and/or mapping on each level.
Written in Typescript. For Javascript, check out this JSFiddle
type itemMap = (n: any) => any;
interface SortConfig<T> {
key: keyof T;
reverse?: boolean;
map?: itemMap;
}
export function byObjectValues<T extends object>(keys: ((keyof T) | SortConfig<T>)[]): (a: T, b: T) => 0 | 1 | -1 {
return function(a: T, b: T) {
const firstKey: keyof T | SortConfig<T> = keys[0];
const isSimple = typeof firstKey === 'string';
const key: keyof T = isSimple ? (firstKey as keyof T) : (firstKey as SortConfig<T>).key;
const reverse: boolean = isSimple ? false : !!(firstKey as SortConfig<T>).reverse;
const map: itemMap | null = isSimple ? null : (firstKey as SortConfig<T>).map || null;
const valA = map ? map(a[key]) : a[key];
const valB = map ? map(b[key]) : b[key];
if (valA === valB) {
if (keys.length === 1) {
return 0;
}
return byObjectValues<T>(keys.slice(1))(a, b);
}
if (reverse) {
return valA > valB ? -1 : 1;
}
return valA > valB ? 1 : -1;
};
}
Sorting a people array by last name, then first name:
interface Person {
firstName: string;
lastName: string;
}
people.sort(byObjectValues<Person>(['lastName','firstName']));
Sort language codes by their name, not their language code (see map
), then by descending version (see reverse
).
interface Language {
code: string;
version: number;
}
// languageCodeToName(code) is defined elsewhere in code
languageCodes.sort(byObjectValues<Language>([
{
key: 'code',
map(code:string) => languageCodeToName(code),
},
{
key: 'version',
reverse: true,
}
]));
redis-dump finally worked for me. Its documentation provides an example how to dump a Redis database and insert the data into another one.
HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();
public synchronized void addToList(String mapKey, Item myItem) {
List<Item> itemsList = items.get(mapKey);
// if list does not exist create it
if(itemsList == null) {
itemsList = new ArrayList<Item>();
itemsList.add(myItem);
items.put(mapKey, itemsList);
} else {
// add if item is not already in list
if(!itemsList.contains(myItem)) itemsList.add(myItem);
}
}
In Oracle:
This gets the key of the max(high_val) in the table according to the range.
select high_val, my_key
from (select high_val, my_key
from mytable
where something = 'avalue'
order by high_val desc)
where rownum <= 1
In case if you want to implement your own Array.Copy method.
Static method which is of generic type.
static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
{
long totaltraversal = sourceIndex + copyNoOfElements;
long sourceArrayLength = sourceArray.Length;
//to check all array's length and its indices properties before copying
CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
for (long i = sourceIndex; i < totaltraversal; i++)
{
destinationArray[destinationIndex++] = sourceArray[i];
}
}
Boundary method implementation.
private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
{
if (sourceIndex >= sourceArray.Length)
{
throw new IndexOutOfRangeException();
}
if (copyNoOfElements > sourceArrayLength)
{
throw new IndexOutOfRangeException();
}
if (destinationArray.Length < copyNoOfElements)
{
throw new IndexOutOfRangeException();
}
}
$location / switching between html5 and hashbang mode / link rewriting
What's wrong with DateTime.AddSeconds method where you can add or substract seconds?
I guess you're searching for this custom function. It takes a data-toggle attribute and creates dynamically the necessary div to place the remote content. Just place the data-toggle="ajaxModal" on any link you want to load via AJAX.
The JS part:
$('[data-toggle="ajaxModal"]').on('click',
function(e) {
$('#ajaxModal').remove();
e.preventDefault();
var $this = $(this)
, $remote = $this.data('remote') || $this.attr('href')
, $modal = $('<div class="modal" id="ajaxModal"><div class="modal-body"></div></div>');
$('body').append($modal);
$modal.modal({backdrop: 'static', keyboard: false});
$modal.load($remote);
}
);
Finally, in the remote content, you need to put the entire structure to work.
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<a href="#" class="btn btn-white" data-dismiss="modal">Close</a>
<a href="#" class="btn btn-primary">Button</a>
<a href="#" class="btn btn-primary">Another button...</a>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
"Day of Week" is actually something you can get directly from the php date() function with the format "l" or "N" respectively. Have a look at the manual
edit: Sorry I didn't read the posts of Kalium properly, he already explained that. My bad.