While it may or may not work in your situation, I have found it useful to generate a public / private key using Putty's Pageant.
If you are also working with bitbucket (.org) it should give you the ability to provide a public key to your user account and then commands that reach out to the repository will be secured automatically.
If Pageant doesn't start up for you upon a reboot, you can add a shortcut to Pageant to your Windows "Start menu" and the shortcut may need to have a 'properties' populated with the location of your private (.ppk) file.
With this in place Mercurial and your local repositories will need to be set up to push/pull using the SSH format.
Here are some detailed instructions on Atlassian's site for Windows OR Mac/Linux.
You don't have to take my word for it and there are no doubt other ways to do it. Perhaps these steps described here are more for you:
- Start PuttyGen from Start -> PuTTY-> PuttyGen
- Generate a new key and save it as a .ppk file without a passphrase
- Use Putty to login to the server you want to connect to
- Append the Public Key text from PuttyGen to the text of ~/.ssh/authorized_keys
- Create a shortcut to your .ppk file from Start -> Putty to Start -> Startup
- Select the .ppk shortcut from the Startup menu (this will happen automatically at every startup)
- See the Pageant icon in the system tray? Right-click it and select “New session”
- Enter username@hostname in the “Host name” field
- You will now log in automatically.
You can submit any form automatically on page load simply by adding a snippet of javascript code to your body tag referencing the form name like this....
<body onload="document.form1.submit()">
For openSUSE 42.1 Leap Linux use this
sudo zypper install python3-devel
As stated in dotnet CLI issue 6583 the issue should be solved with dotnet nuget locals --clear all
command.
You can use a FileOutputStream for this.
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("myFile"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Put data in your baos
baos.writeTo(fos);
} catch(IOException ioe) {
// Handle exception here
ioe.printStackTrace();
} finally {
fos.close();
}
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
[i for i in enumerate(['a','b','c'])]
Result:
[(0, 'a'), (1, 'b'), (2, 'c')]
$?
is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep
command succeeded.
The grep
manpage states:
The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)
So in this case it's checking whether any ERROR lines were found.
Diffrence between Foreach & map :
Map() : If you use map then map can return new array by iterating main array.
Foreach() : If you use Foreach then it can not return anything for each can iterating main array.
useFul link : use this link for understanding diffrence
Expanding on mjswensen's answer, the command without the filter could take minutes, but the filtered command is almost instant.
PowerShell - List local user accounts
Fast way
Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True'" | select name, fullname
Slow way
Get-WmiObject -Class Win32_UserAccount |? {$_.localaccount -eq $true} | select name, fullname
Select Eventname,
count(Eventname) as 'Counts'
INTO #TEMPTABLE
FROM tblevent
where Eventname like 'A%'
Group by Eventname
order by count(Eventname)
Here by using the into clause the table is directly created
The above answers do not fully answer the question (specifically the millisec part). My solution to this is to use gettimeofday before strftime. Note the care to avoid rounding millisec to "1000". This is based on Hamid Nazari's answer.
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>
int main() {
char buffer[26];
int millisec;
struct tm* tm_info;
struct timeval tv;
gettimeofday(&tv, NULL);
millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
if (millisec>=1000) { // Allow for rounding up to nearest second
millisec -=1000;
tv.tv_sec++;
}
tm_info = localtime(&tv.tv_sec);
strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
printf("%s.%03d\n", buffer, millisec);
return 0;
}
Take a look at my jquery videoBG plugin
http://syddev.com/jquery.videoBG/
Make any HTML5 video a site background... has an image fallback for browsers that don't support html5
Really easy to use
Let me know if you need any help.
Are you sure you correctly applied the styles, or that there isn't another stylesheet interfering with your lists? I tried this:
<ol type="A">
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
</ol>
Then in the stylesheet:
ol {font-weight: bold;}
ol li span.label {font-weight:normal;}
And it bolded the A
, B
, C
etc and not the text.
(Tested it in Opera 9.6, FF 3, Safari 3.2 and IE 7)
I'm a little late to the game on this one, but I thought I should post an updated answer since I just encountered this issue for myself. Please note that this will only apply to a Mac-based setup (I haven't tried it with Windows or any flavor of Linux).
The simplest way to get this working is to install Python via Brew. If you don't have brew installed, you will need to do that first. Once installed, do the following in at the terminal:
brew install python
This will install Python 3. After it's installed, run this:
ls -l /usr/local/bin/python*
You will see all of the links created by brew to its Python install. It will look something like this:
lrwxr-xr-x 1 username admin 36 Oct 1 13:35 /usr/local/bin/python3@ -> ../Cellar/python/3.7.4_1/bin/python3
lrwxr-xr-x 1 username admin 43 Oct 1 13:35 /usr/local/bin/python3-config@ -> ../Cellar/python/3.7.4_1/bin/python3-config
lrwxr-xr-x 1 username admin 38 Oct 1 13:35 /usr/local/bin/python3.7@ -> ../Cellar/python/3.7.4_1/bin/python3.7
lrwxr-xr-x 1 username admin 45 Oct 1 13:35 /usr/local/bin/python3.7-config@ -> ../Cellar/python/3.7.4_1/bin/python3.7-config
lrwxr-xr-x 1 username admin 39 Oct 1 13:35 /usr/local/bin/python3.7m@ -> ../Cellar/python/3.7.4_1/bin/python3.7m
lrwxr-xr-x 1 username admin 46 Oct 1 13:35 /usr/local/bin/python3.7m-config@ -> ../Cellar/python/3.7.4_1/bin/python3.7m-config
The first row in this example shows the python3
symlink. To set it as the default python
symlink run the following:
ln -s -f /usr/local/bin/python3 /usr/local/bin/python
Once set, you can do:
which python
and it should show:
/usr/local/bin/python
You will have to reload your current terminal shell for it to use the new symlink in that shell, however, all newly opened shell sessions will (should) automatically use it. To test this, open a new terminal shell and run the following:
python --version
<iframe src="URL" frameborder="0" width="100%" height="200">
<p>Your browser does not support iframes.</p>
</iframe>
<iframe frameborder="1|0">
(OR)
<iframe src="URL" width="100%" height="300" style="border: none">Your browser
does not support iframes.</iframe>
The <iframe> frameborder attribute is not supported in HTML5. Use CSS
instead.
listView1.View = View.Details;
listView1.Columns.Add("Target No.", 83, HorizontalAlignment.Center);
listView1.Columns.Add(" Range ", 100, HorizontalAlignment.Center);
listView1.Columns.Add(" Azimuth ", 100, HorizontalAlignment.Center);
i also had same problem .. i drag column to left .. but now ok .. so let's say i have 283*196 size of listview ..... We declared in the column width -2 for auto width .. For fitting in the listview ,we can divide listview width into 3 parts (83,100,100) ...
JavaScript Pure:
<script type="text/javascript">
document.getElementById("modal").click();
</script>
JQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#modal").trigger('click');
});
</script>
or
<script type="text/javascript">
$(document).ready(function(){
$("#modal").click();
});
</script>
As others have pointed out, the cd
command needs to start with a percentage sign:
%cd SwitchFrequencyAnalysis
%
and !
Google Colab seems to inherit these syntaxes from Jupyter (which inherits them from IPython). Jake VanderPlas explains this IPython behaviour here. You can see the excerpt below.
If you play with IPython's shell commands for a while, you might notice that you cannot use
!cd
to navigate the filesystem:In [11]: !pwd /home/jake/projects/myproject In [12]: !cd .. In [13]: !pwd /home/jake/projects/myproject
The reason is that shell commands in the notebook are executed in a temporary subshell. If you'd like to change the working directory in a more enduring way, you can use the
%cd
magic command:In [14]: %cd .. /home/jake/projects
Another way to look at this: you need %
because changing directory is relevant to the environment of the current notebook but not to the entire server runtime.
In general, use !
if the command is one that's okay to run in a separate shell. Use %
if the command needs to be run on the specific notebook.
#!/bin/sh
wc -m $1 | awk '{print $1}'
wc -m
counts the number of characters; the awk
command prints the number of characters only, omitting the filename.
wc -c
would give you the number of bytes (which can be different to the number of characters, as depending on the encoding you may have a character encoded on several bytes).
You can use the below change event to which will trigger when the combobox value will change.
Private Sub ComboBox1_Change()
'your code here
End Sub
Also you can get the selected value using below
ComboBox1.Value
In Windows 10 you might also want to delete Windows Explorer's override for file extension association:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ps1\UserChoice
in addition to the HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command
change mentioned in other answers.
Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL
UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";
Hope this helps someone else.
Tensorflow version in Jupyter Notebook:-
!pip list | grep tensorflow
I've just created a little example showing how to implement commands in convention over configuration style. However it requires Reflection.Emit() to be available. The supporting code may seem a little weird but once written it can be used many times.
Teaser:
public class SampleViewModel: BaseViewModelStub
{
public string Name { get; set; }
[UiCommand]
public void HelloWorld()
{
MessageBox.Show("Hello World!");
}
[UiCommand]
public void Print()
{
MessageBox.Show(String.Concat("Hello, ", Name, "!"), "SampleViewModel");
}
public bool CanPrint()
{
return !String.IsNullOrEmpty(Name);
}
}
}
UPDATE: now there seem to exist some libraries like http://www.codeproject.com/Articles/101881/Executing-Command-Logic-in-a-View-Model that solve the problem of ICommand boilerplate code.
Here's the code by Sinetheta converted to a jQuery plugin: Save below code to a js file.
$.fn.collapsible = function() {
$(this).addClass("ui-accordion ui-widget ui-helper-reset");
var headers = $(this).children("h3");
headers.addClass("accordion-header ui-accordion-header ui-helper-reset ui-state-active ui-accordion-icons ui-corner-all");
headers.append('<span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-s">');
headers.click(function() {
var header = $(this);
var panel = $(this).next();
var isOpen = panel.is(":visible");
if(isOpen) {
panel.slideUp("fast", function() {
panel.hide();
header.removeClass("ui-state-active")
.addClass("ui-state-default")
.children("span").removeClass("ui-icon-triangle-1-s")
.addClass("ui-icon-triangle-1-e");
});
}
else {
panel.slideDown("fast", function() {
panel.show();
header.removeClass("ui-state-default")
.addClass("ui-state-active")
.children("span").removeClass("ui-icon-triangle-1-e")
.addClass("ui-icon-triangle-1-s");
});
}
});
};
Refer it in your UI page and call similar to jQuery accordian call:
$("#accordion").collapsible();
Looks cleaner and avoids any classes to be added to the markup.
Here, a simple function in Pascal (Delphi).
function GetColLetterFromNum(Sheet : Variant; Col : Integer) : String;
begin
Result := Sheet.Columns[Col].Address; // from Col=100 --> '$CV:$CV'
Result := Copy(Result, 2, Pos(':', Result) - 2);
end;
You need to make sure that you add forward slash before your link to socket.io:
<script src="/socket.io/socket.io.js"></script>
Then in the view/controller just do:
var socket = io.connect()
That should solve your problem.
& is bitwise AND operator comparing bits of each operand.
For example,
int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
&& is logical AND operator comparing boolean values of operands only. It takes two operands indicating a boolean value and makes a lazy evaluation on them.
You can use a checkbox
to simulate onClick with CSS:
input[type=checkbox]:checked + p {
display: none;
}
This is my best solution if I understood the question well:
Use of $object->first()
method to run the code inside if
statement once, that is when on the first loop. The same concept is true with $object->last()
.
@if($object->first())
<div class="panel user-list">
<table id="myCustomTable" class="table table-hover">
<thead>
<tr>
<th class="col-email">Email</th>
</tr>
</thead>
<tbody>
@endif
@foreach ($object as $data)
<tr class="gradeX">
<td class="col-name"><strong>{{ $data->email }}</strong></td>
</tr>
@endforeach
@if($object->last())
</tbody>
</table>
</div>
@endif
find . -mindepth 1 -maxdepth 1 -type d -printf "%P\n"
With Help from here
function get_result(some_value) {
var ret_val = {};
$.ajax({
url: '/some/url/to/fetch/from',
type: 'GET',
data: {'some_key': some_value},
async: false,
dataType: 'json'
}).done(function (response) {
ret_val = response;
}).fail(function (jqXHR, textStatus, errorThrown) {
ret_val = null;
});
return ret_val;
}
Hope this helps someone somewhere a bit.
Just be aware also that catalina.out can be renamed - it can be set in /bin/catalina.sh with the CATALINA_OUT environment variable.
The rules for new
are analogous to what happens when you initialize an object with automatic storage duration (although, because of vexing parse, the syntax can be slightly different).
If I say:
int my_int; // default-initialize ? indeterminate (non-class type)
Then my_int
has an indeterminate value, since it is a non-class type. Alternatively, I can value-initialize my_int
(which, for non-class types, zero-initializes) like this:
int my_int{}; // value-initialize ? zero-initialize (non-class type)
(Of course, I can't use ()
because that would be a function declaration, but int()
works the same as int{}
to construct a temporary.)
Whereas, for class types:
Thing my_thing; // default-initialize ? default ctor (class type)
Thing my_thing{}; // value-initialize ? default-initialize ? default ctor (class type)
The default constructor is called to create a Thing
, no exceptions.
So, the rules are more or less:
{}
) or default-initialized (without {}
). (There is some additional prior zeroing behavior with value-initialization, but the default constructor is always given the final say.){}
used?
These rules translate precisely to new
syntax, with the added rule that ()
can be substituted for {}
because new
is never parsed as a function declaration. So:
int* my_new_int = new int; // default-initialize ? indeterminate (non-class type)
Thing* my_new_thing = new Thing; // default-initialize ? default ctor (class type)
int* my_new_zeroed_int = new int(); // value-initialize ? zero-initialize (non-class type)
my_new_zeroed_int = new int{}; // ditto
my_new_thing = new Thing(); // value-initialize ? default-initialize ? default ctor (class type)
(This answer incorporates conceptual changes in C++11 that the top answer currently does not; notably, a new scalar or POD instance that would end up an with indeterminate value is now technically now default-initialized (which, for POD types, technically calls a trivial default constructor). While this does not cause much practical change in behavior, it does simplify the rules somewhat.)
I prefer to use
RadioButton b = (RadioButton) findViewById(R.id.option1);
b.performClick();
instead of using the accepted answer.
RadioButton b = (RadioButton) findViewById(R.id.option1);
b.setChecked(true);
The reason is setChecked(true)
only changes the checked state of radio button. It does not trigger the onClick()
method added to your radio button. Sometimes this might waste your time to debug why the action related to onClick()
not working.
You want the NPGSQL library. Your only other alternative is ODBC.
ALTER TABLE myTable ALTER COLUMN myColumn {DataType} NULL
where {DataType}
is the current data type of that column (For example int
or varchar(10)
)
The option you're looking for is -R
.
cp -R path_to_source path_to_destination/
destination
doesn't exist, it will be created.-R
means copy directories recursively
. You can also use -r
since it's case-insensitive./
as per @muni764's comment.The pg documentation at NOTES say
The path will be interpreted relative to the working directory of the server process (normally the cluster's data directory), not the client's working directory.
So, gerally, using psql
or any client, even in a local server, you have problems ... And, if you're expressing COPY command for other users, eg. at a Github README, the reader will have problems ...
The only way to express relative path with client permissions is using STDIN,
When STDIN or STDOUT is specified, data is transmitted via the connection between the client and the server.
as remembered here:
psql -h remotehost -d remote_mydb -U myuser -c \
"copy mytable (column1, column2) from STDIN with delimiter as ','" \
< ./relative_path/file.csv
imo the best approach is using GraphicsMagick Image Processing System with im4java as a comand-line interface for Java.
There are a lot of advantages of GraphicsMagick, but one for all:
You should return json always, but change its status, or in following example the ResponseCode property:
if(callbackResults.ResponseCode!="200"){
/* Some error, you can add a message too */
} else {
/* All fine, proceed with code */
};
Good to see lots of love for zip
in the answers here.
However it should be noted that if you are using a python version before 3.0, the itertools
module in the standard library contains an izip
function which returns an iterable, which is more appropriate in this case (especially if your list of latt/longs is quite long).
In python 3 and later zip
behaves like izip
.
<form name="myForm" method="post">
<p>Activity</p>
skiing: <input type="checkbox" name="activity" value="skiing" checked="yes" /><br />
skating: <input type="checkbox" name="activity" value="skating" /><br />
running: <input type="checkbox" name="activity" value="running" /><br />
hiking: <input type="checkbox" name="activity" value="hiking" checked="yes" />
</form>
@AHegde - To get the tab delimited output use separator sep='\t'.
For df.to_csv:
df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep='\t', mode='a')
For np.savetxt:
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d', delimiter='\t')
One way is to just leave merged feature branches open (and inactive):
$ hg up default
$ hg merge feature-x
$ hg ci -m merge
$ hg heads
(1 head)
$ hg branches
default 43:...
feature-x 41:...
(2 branches)
$ hg branches -a
default 43:...
(1 branch)
Another way is to close a feature branch before merging using an extra commit:
$ hg up feature-x
$ hg ci -m 'Closed branch feature-x' --close-branch
$ hg up default
$ hg merge feature-x
$ hg ci -m merge
$ hg heads
(1 head)
$ hg branches
default 43:...
(1 branch)
The first one is simpler, but it leaves an open branch. The second one leaves no open heads/branches, but it requires one more auxiliary commit. One may combine the last actual commit to the feature branch with this extra commit using --close-branch
, but one should know in advance which commit will be the last one.
Update: Since Mercurial 1.5 you can close the branch at any time so it will not appear in both hg branches
and hg heads
anymore. The only thing that could possibly annoy you is that technically the revision graph will still have one more revision without childen.
Update 2: Since Mercurial 1.8 bookmarks have become a core feature of Mercurial. Bookmarks are more convenient for branching than named branches. See also this question:
To link from a page to another section just use
<a href="index.php#firstdiv">my first div</a>
had same problem today, Your topic helped me so here goes solution ;)
alert(result.d[0].EmployeeTitle);
The simple and versatile way is (as Michielvoo's table approach):
[ctrv]{
display:table !important;
}
[ctrv] > *{ /* adressing direct discendents */
display: table-cell;
vertical-align: middle;
// text-align: center; /* optional */
}
Using this attribute (or a equivalent class) on a parent tag works even for many children to align:
<parent ctrv> <ch1/> <ch2/> </parent>
Several good solutions here. If you're still on Win2K and can't install anything on the remote computer, this also works:
Open the Computer Management Console (right click My Computer, choose Manage; open from Administrative Tools in the Start Menu; or open from the MMC using the snap-in).
Right click on your computer name and choose "Connect to Remote Computer"
Put in the computer name and credentials and you have full access to many admin functions including the services control panel.
Try '\1'
for the replacement (single quotes are important, otherwise you need to escape the \
):
"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"
But since you only seem to be interested in the capture group, note that you can index a string with a regex:
"foo"[/oo/]
#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"
as.name(char[1])
will work, although I'm not sure why you'd ever really want to do this -- the quotes won't get carried over in a paste
for example:
> paste("I am counting to", char[1], char[2], char[3])
[1] "I am counting to one two three"
The code below does just that. The below is a working example to log into a game. I made a similar file to log in into Yahoo and a kurzweilai.net forum.
Just copy the login form from any webpage's source code. Add value= "your user name" and value = "your password". Normally the -input- elements in the source code do not have the value attribute, and sometime, you will see something like that: value=""
Save the file as a html on a local machine double click it, or make a bat/cmd file to launch and close them as required.
<!doctype html>
<!-- saved from url=(0014)about:internet -->
<html>
<title>Ikariam Autologin</title>
</head>
<body>
<form id="loginForm" name="loginForm" method="post" action="http://s666.en.ikariam.com/index.php?action=loginAvatar&function=login">
<select name="uni_url" id="logServer" class="validate[required]">
<option class="" value="s666.en.ikariam.com" fbUrl="" cookieName="" >
Test_en
</option>
</select>
<input id="loginName" name="name" type="text" value="PlayersName" class="" />
<input id="loginPassword" name="password" type="password" value="examplepassword" class="" />
<input type="hidden" id="loginKid" name="kid" value=""/>
</form>
<script>document.loginForm.submit();</script>
</body></html>
Note that -script- is just -script-. I found there is no need to specify that is is JavaScript. It works anyway. I also found out that a bare-bones version that contains just two input filds: userName and password also work. But I left a hidded input field etc. just in case. Yahoo mail has a lot of hidden fields. Some are to do with password encryption, and it counts login attempts.
Security warnings and other staff, like Mark of the Web to make it work smoothly in IE are explained here:
on your Promise response you requested
response.json()
but this works well if your server sends json response in return especially if you're using Node Js on the server side
So check again and make sure your server sends json as response as said if its NodeJS the response could be
res.json(YOUR-DATA-RESPONSE)
$q="SELECT * FROM projects WHERE YEAR(date) = 2012 AND MONTH(date) = 1;
To search for files in /target_directory and all its sub-directories, that have been modified in the last 60 minutes:
$ find /target_directory -type f -mmin -60
To find the most recently modified files, sorted in the reverse order of update time (i.e., the most recently updated files first):
$ find /etc -type f -printf '%TY-%Tm-%Td %TT %p\n' | sort -r
display: none
It will remove the element from the normal flow of the page, allowing other elements to fill in.
An element will not appear on the page at all but we can still interact with it through the DOM. There will be no space allocated for it between the other elements.
visibility: hidden
It will leave the element in the normal flow of the page such that is still occupies space.
An element is not visible and Element’s space is allocated for it on the page.
Some other ways to hide elements
Use z-index
#element {
z-index: -11111;
}
Move an element off the page
#element {
position: absolute;
top: -9999em;
left: -9999em;
}
Interesting information about visibility: hidden and display: none properties
visibility: hidden
and display: none
will be equally performant since they both re-trigger layout, paint and composite. However, opacity: 0
is functionality equivalent to visibility: hidden
and does not re-trigger the layout step.
And CSS-transition property is also important thing that we need to take care. Because toggling from visibility: hidden
to visibility: visible
allow for CSS-transitions to be use, whereas toggling from display: none
to display: block
does not. visibility: hidden
has the additional benefit of not capturing JavaScript events, whereas opacity: 0
captures events
if you use Windows 10, this is the directory:
C:\Users<UserName>\AppData\Local\
+
<ProjectName.exe_Url_somedata>\1.0.0.0<filename.config>
Certainly, though it will only work if it's a fast forward of BRANCH2 or if you force it. The correct syntax to do such a thing is
git push <remote> <source branch>:<dest branch>
See the description of a "refspec" on the git push man page for more detail on how it works. Also note that both a force push and a reset are operations that "rewrite history", and shouldn't be attempted by the faint of heart unless you're absolutely sure you know what you're doing with respect to any remote repositories and other people who have forks/clones of the same project.
If they really absolutely have to remain unsorted (which they really don't.. and if you're dealing with hundreds of thousands of elements then I have to ask why you would be comparing vectors like this), you can hack together a compare method which works with unsorted arrays.
The only way I though of to do that was to create a temporary vector3
and pretend to do a set_intersection
by adding all elements of vector1
to it, then doing a search for each individual element of vector2
in vector3
and removing it if found. I know that sounds terrible, but that's why I'm not writing any C++ standard libraries anytime soon.
Really, though, just sort them first.
Try with paramter
.....................
.....................
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + @IDNumber, con))
{
command.Paramter.Add("@IDNumber",IDNumber)
command.ExecuteNonQuery();
}
.....................
.....................
No need to close connection in using statement
The github project JavaScript-Load-Image provides a complete solution to the EXIF orientation problem, correctly rotating/mirroring images for all 8 exif orientations. See the online demo of javascript exif orientation
The image is drawn onto an HTML5 canvas. Its correct rendering is implemented in js/load-image-orientation.js through canvas operations.
Hope this saves somebody else some time, and teaches the search engines about this open source gem :)
I thought I'd contribute this answer to add more details from the Specifications.
First, What's the difference between passing by reference vs. passing by value?
Passing by reference means the called functions' parameter will be the same as the callers' passed argument (not the value, but the identity - the variable itself).
Pass by value means the called functions' parameter will be a copy of the callers' passed argument.
Or from wikipedia, on the subject of pass-by-reference
In call-by-reference evaluation (also referred to as pass-by-reference), a function receives an implicit reference to a variable used as argument, rather than a copy of its value. This typically means that the function can modify (i.e. assign to) the variable used as argument—something that will be seen by its caller.
And on the subject of pass-by-value
In call-by-value, the argument expression is evaluated, and the resulting value is bound to the corresponding variable in the function [...]. If the function or procedure is able to assign values to its parameters, only its local copy is assigned [...].
Second, we need to know what Java uses in its method invocations. The Java Language Specification states
When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor.
So it assigns (or binds) the value of the argument to the corresponding parameter variable.
What is the value of the argument?
Let's consider reference types, the Java Virtual Machine Specification states
There are three kinds of reference types: class types, array types, and interface types. Their values are references to dynamically created class instances, arrays, or class instances or arrays that implement interfaces, respectively.
The Java Language Specification also states
The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.
The value of an argument (of some reference type) is a pointer to an object. Note that a variable, an invocation of a method with a reference type return type, and an instance creation expression (new ...
) all resolve to a reference type value.
So
public void method (String param) {}
...
String var = new String("ref");
method(var);
method(var.toString());
method(new String("ref"));
all bind the value of a reference to a String
instance to the method's newly created parameter, param
. This is exactly what the definition of pass-by-value describes. As such, Java is pass-by-value.
The fact that you can follow the reference to invoke a method or access a field of the referenced object is completely irrelevant to the conversation. The definition of pass-by-reference was
This typically means that the function can modify (i.e. assign to) the variable used as argument—something that will be seen by its caller.
In Java, modifying the variable means reassigning it. In Java, if you reassigned the variable within the method, it would go unnoticed to the caller. Modifying the object referenced by the variable is a different concept entirely.
Primitive values are also defined in the Java Virtual Machine Specification, here. The value of the type is the corresponding integral or floating point value, encoded appropriately (8, 16, 32, 64, etc. bits).
You can use map
, which is a functional programming technique that's also available in other languages like Python and Haskell.
[1,2,3,4].map( function(item) {
alert(item);
})
The general syntax is:
array.map(func)
In general func
would take one parameter, which is an item of the array. But in the case of JavaScript, it can take a second parameter which is the item's index, and a third parameter which is the array itself.
The return value of array.map
is another array, so you can use it like this:
var x = [1,2,3,4].map( function(item) {return item * 10;});
And now x is [10,20,30,40]
.
You don't have to write the function inline. It could be a separate function.
var item_processor = function(item) {
// Do something complicated to an item
}
new_list = my_list.map(item_processor);
which would be sort-of equivalent to:
for (item in my_list) {item_processor(item);}
Except you don't get the new_list
.
Using PostgreSQL like
(see accepted answer above) somehow didn't work for me although cases matched, but ilike
(case insensisitive like) does.
Hi it is also possible for Strings with XML-Table
SELECT trim(COLUMN_VALUE) str FROM xmltable(('"'||REPLACE('a1, b2, a2, c1', ',', '","')||'"'));
http://onerkaya.blogspot.com/2013/03/register-com-dll-on-windows-64-bit.html
Retrieving the COM class factory for component with CLSID {...} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
if you try this;
c:\windows\system32\regsvr32.exe < filename >.dll
you can still take this exception. so IIS- pool Advanced settings, Enable 32 bit application : true ;)
Avoid non-standard compiler extensions and implement it as a completely type-safe macro in pure standard C (ISO 9899:2011).
Solution
#define GENERIC_MAX(x, y) ((x) > (y) ? (x) : (y))
#define ENSURE_int(i) _Generic((i), int: (i))
#define ENSURE_float(f) _Generic((f), float: (f))
#define MAX(type, x, y) \
(type)GENERIC_MAX(ENSURE_##type(x), ENSURE_##type(y))
Usage
MAX(int, 2, 3)
Explanation
The macro MAX creates another macro based on the type
parameter. This control macro, if implemented for the given type, is used to check that both parameters are of the correct type. If the type
is not supported, there will be a compiler error.
If either x or y is not of the correct type, there will be a compiler error in the ENSURE_
macros. More such macros can be added if more types are supported. I've assumed that only arithmetic types (integers, floats, pointers etc) will be used and not structs or arrays etc.
If all types are correct, the GENERIC_MAX macro will be called. Extra parenthesis are needed around each macro parameter, as the usual standard precaution when writing C macros.
Then there's the usual problems with implicit type promotions in C. The ?:
operator balances the 2nd and 3rd operand against each other. For example, the result of GENERIC_MAX(my_char1, my_char2)
would be an int
. To prevent the macro from doing such potentially dangerous type promotions, a final type cast to the intended type was used.
Rationale
We want both parameters to the macro to be of the same type. If one of them is of a different type, the macro is no longer type safe, because an operator like ?:
will yield implicit type promotions. And because it does, we also always need to cast the final result back to the intended type as explained above.
A macro with just one parameter could have been written in a much simpler way. But with 2 or more parameters, there is a need to include an extra type parameter. Because something like this is unfortunately impossible:
// this won't work
#define MAX(x, y) \
_Generic((x), \
int: GENERIC_MAX(x, ENSURE_int(y)) \
float: GENERIC_MAX(x, ENSURE_float(y)) \
)
The problem is that if the above macro is called as MAX(1, 2)
with two int
, it will still try to macro-expand all possible scenarios of the _Generic
association list. So the ENSURE_float
macro will get expanded too, even though it isn't relevant for int
. And since that macro intentionally only contains the float
type, the code won't compile.
To solve this, I created the macro name during the pre-processor phase instead, with the ## operator, so that no macro gets accidentally expanded.
Examples
#include <stdio.h>
#define GENERIC_MAX(x, y) ((x) > (y) ? (x) : (y))
#define ENSURE_int(i) _Generic((i), int: (i))
#define ENSURE_float(f) _Generic((f), float: (f))
#define MAX(type, x, y) \
(type)GENERIC_MAX(ENSURE_##type(x), ENSURE_##type(y))
int main (void)
{
int ia = 1, ib = 2;
float fa = 3.0f, fb = 4.0f;
double da = 5.0, db = 6.0;
printf("%d\n", MAX(int, ia, ib)); // ok
printf("%f\n", MAX(float, fa, fb)); // ok
//printf("%d\n", MAX(int, ia, fa)); compiler error, one of the types is wrong
//printf("%f\n", MAX(float, fa, ib)); compiler error, one of the types is wrong
//printf("%f\n", MAX(double, fa, fb)); compiler error, the specified type is wrong
//printf("%f\n", MAX(float, da, db)); compiler error, one of the types is wrong
//printf("%d\n", MAX(unsigned int, ia, ib)); // wont get away with this either
//printf("%d\n", MAX(int32_t, ia, ib)); // wont get away with this either
return 0;
}
You can achieve this with pattern matching with the switch expression in C#8/9
FooTextBox.Text = strFoo switch
{
{ Length: >0 } s => s, // If the length of the string is greater than 0
_ => "0" // Anything else
};
Try this!
1 - Install dependencies for show save/open file pop-up
npm install file-saver --save
npm install @types/file-saver --save
2- Create a service with this function to recive the data
downloadFile(id): Observable<Blob> {
let options = new RequestOptions({responseType: ResponseContentType.Blob });
return this.http.get(this._baseUrl + '/' + id, options)
.map(res => res.blob())
.catch(this.handleError)
}
3- In the component parse the blob with 'file-saver'
import {saveAs as importedSaveAs} from "file-saver";
this.myService.downloadFile(this.id).subscribe(blob => {
importedSaveAs(blob, this.fileName);
}
)
This works for me!
If anyone has a problem to import a Bacpac of a DB that uses Azure SQL Sync, Sandrino Di Mattia developed a great simple application to solve this.
In Eztrieve it's really easy, below is an example how you could code it:
//STEP01 EXEC PGM=EZTPA00
//FILEA DD DSN=FILEA,DISP=SHR
//FILEB DD DSN=FILEB,DISP=SHR
//FILEC DD DSN=FILEC.DIF,
// DISP=(NEW,CATLG,DELETE),
// SPACE=(CYL,(100,50),RLSE),
// UNIT=PRMDA,
// DCB=(RECFM=FB,LRECL=5200,BLKSIZE=0)
//SYSOUT DD SYSOUT=*
//SRTMSG DD SYSOUT=*
//SYSPRINT DD SYSOUT=*
//SYSIN DD *
FILE FILEA
FA-KEY 1 7 A
FA-REC1 8 10 A
FA-REC2 18 5 A
FILE FILEB
FB-KEY 1 7 A
FB-REC1 8 10 A
FB-REC2 18 5 A
FILE FILEC
FILE FILED
FD-KEY 1 7 A
FD-REC1 8 10 A
FD-REC2 18 5 A
JOB INPUT (FILEA KEY FA-KEY FILEB KEY FB-KEY)
IF MATCHED
FD-KEY = FB-KEY
FD-REC1 = FA-REC1
FD-REC2 = FB-REC2
PUT FILED
ELSE
IF FILEA
PUT FILEC FROM FILEA
ELSE
PUT FILEC FROM FILEB
END-IF
END-IF
/*
Try
safeRunCommand() {
"$@"
if [ $? != 0 ]; then
printf "Error when executing command: '$1'"
exit $ERROR_CODE
fi
}
This is caused when your request response is not received in given time(by timeout
request module option).
Basically to catch that error first, you need to register a handler on error
, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ })
. Some more explanation here.
In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }
.
If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.
If you want to wait longer, you can set timeout
option of request yourself. You can set it to 0 for no timeout.
Illumination in case of confusion...
def quit(self):
self.destroy()
exit()
A) destroy() stops the mainloop and kills the window, but leaves python running
B) exit() stops the whole process
Just to clarify in case someone missed what destroy() was doing, and the OP also asked how to "end" a tkinter program.
If you look at the code for the component you can see that it uses the className
prop passed to it to combine with the row
class to get the resulting set of classes (<Row className="aaa bbb"...
works).Also, if you provide the id
prop like <Row id="444" ...
it will actually set the id attribute for the element.
Further, people usually want to remove all *.pyc
, *.pyo
files and __pycache__
directories recursively in the current directory.
Command:
find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf
From your original code it looks like what you want is to check if the list was empty:
var getResult= keyValueList.SingleOrDefault();
if (keyValueList.Count == 0)
{
/* default */
}
else
{
}
You can do this with a table value parameters.
Have a look at the following article:
http://www.codeproject.com/Articles/39161/C-and-Table-Value-Parameters
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
I asked the same question to Xamarin support team, they replied with following:
You can develop an app with Xamarin for commercial usage - there is no extra charge! We only require you to comply with Visual Studio's licensing terms,
which means that in companies of less than 250 employees with less than $1million USD annual revenue, you may use Visual Studio completely free (including Xamarin) for up to 5 developers.
However after you pass those barriers, you would need a Visual Studio license (which includes Xamarin).
Refer the screenshot below.
In the spirit of functional programming, let's make our components a bit easier to work with by using abstractions.
// converts components into mappable functions
var mappable = function(component){
return function(x, i){
return component({key: i}, x);
}
}
// maps on 2-dimensional arrays
var map2d = function(m1, m2, xss){
return xss.map(function(xs, i, arr){
return m1(xs.map(m2), i, arr);
});
}
var td = mappable(React.DOM.td);
var tr = mappable(React.DOM.tr);
var th = mappable(React.DOM.th);
Now we can define our render like this:
render: function(){
return (
<table>
<thead>{this.props.titles.map(th)}</thead>
<tbody>{map2d(tr, td, this.props.rows)}</tbody>
</table>
);
}
An alternative to our map2d would be a curried map function, but people tend to shy away from currying.
Go to : File > Project Structure > Modules -> app > Properties
please choose : Compile 'SDK' version = API26
Build Tools
Version = 27.0.0 Source Compatibility = 1.8 Target Compatibility =
1.8
This problem happened with me and sovled by just add
respond_to :html, :json
to ApplicationController file
You can Check Devise issues on Github: https://github.com/plataformatec/devise/issues/2667
Another error can be not having your app listed in the INSTALLED_APPS
listing like:
INSTALLED_APPS = [
# ...
'your_app',
]
Without having it in, you can face problems like not detecting your static files, basically all the files involving your app. Even though it can be correct as suggested in the correct answer by using:
STATICFILES_DIRS = (adding/path/of/your/app)
Can be one of the errors and should be reviewed if getting this error.
If you are working in XAMPP and your query of drop database doesn't work then you can go to the operations tag where you find the column (drop the database(drop)), click that button and your database will be deleted.
Use the start and end delimiters: ^abc$
What you are currently doing is checking whether neither the start_date nor the end_date fall within the range of the dates given.
I guess what you are really looking for is a record which does not fit in the date range given. If so, use the query below.
SELECT *
FROM `test_table`
WHERE CAST('2009-12-15' AS DATE) > start_date AND CAST('2010-01-02' AS DATE) < end_date
you can use script module
Example
- name: Transfer and execute a script.
hosts: all
tasks:
- name: Copy and Execute the script
script: /home/user/userScript.sh
I had the same problem. And finally it was a double include. One include in a file named X. And another include in a file named Y. Knowing that in file Y I had include ('X')
You can declare globals by augmenting the window interface:
import jQuery from '@types/jquery';
declare global {
interface Window {
jQuery: typeof jQuery;
$: typeof jQuery;
}
}
Sources:
I am trying to write a class that is "both" a list
or a dict
. I want the programmer to be able to both "cast" this object to a list
(dropping the keys) or dict
(with the keys).
Looking at the way Python currently does the dict()
cast: It calls Mapping.update()
with the object that is passed. This is the code from the Python repo:
def update(self, other=(), /, **kwds):
''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k, v in F.items(): D[k] = v
'''
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
The last subcase of the if statement, where it is iterating over other
is the one most people have in mind. However, as you can see, it is also possible to have a keys()
property. That, combined with a __getitem__()
should make it easy to have a subclass be properly casted to a dictionary:
class Wharrgarbl(object):
def __init__(self, a, b, c, sum, version='old'):
self.a = a
self.b = b
self.c = c
self.sum = 6
self.version = version
def __int__(self):
return self.sum + 9000
def __keys__(self):
return ["a", "b", "c"]
def __getitem__(self, key):
# have obj["a"] -> obj.a
return self.__getattribute__(key)
Then this will work:
>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> dict(w)
{'a': 'one', 'c': 'three', 'b': 'two'}
Returning false from the code you're calling will work and in a number of circumstances is the preferred method but you can also so this
<a href="javascript:;">Link Title</a>
When it comes to SEO it really depends on what your link is going to be used for. If you are going to actually use it to link to some other content then I would agree ideally you would want something meaningful here but if you are using the link for functionality purposes maybe like Stack Overflow does for the post toolbar (bold, italic, hyperlink, etc) then it probably doesn't matter.
You may use a local variable, like:
float[] values = new float[3];
float[] v = {0.1f, 0.2f, 0.3f};
float[] values = v;
Check for the presence of words like "ad", "banner" or "popup" within your file. I removed these and it worked. Based on this post here: Failed to load resource under Chrome it seems like Ad Block Plus was the culprit in my case.
if you're on osx and want to be able to click on your tabs, use MouseTerm and SIMBL (taken from here). Also, check out this related discussion.
This will work 100%:
<script type="text/javascript">
function calculate() {
var result = document.getElementById('result');
var el, i = 0, total = 0;
while(el = document.getElementById('v'+(i++)) ) {
el.value = el.value.replace(/\\D/,"");
total = total + Number(el.value);
}
result.value = total;
if(document.getElementById('v0').value =="" &&
document.getElementById('v1').value =="" &&
document.getElementById('v2').value =="" ) {
result.value ="";
}
}
}
</script>
Some number:<input type="text" id ="v0" onkeyup="calculate()">
Some number:<input type="text" id ="v1" onkeyup="calculate()">
Some number:<input type="text" id ="v2" onkeyup="calculate()">
Result: <input type="text" id="result" onkeyup="calculate()" readonly>
None is a special value in Python which usually designates an uninitialized variable. To test whether A does not have this particular value you use:
if A is not None
Falsey values are a special class of objects in Python (e.g. false, []). To test whether A is falsey use:
if not A
Thus, the two expressions are not the same And you'd better not treat them as synonyms.
P.S. None is also falsey, so the first expression implies the second. But the second covers other falsey values besides None. Now... if you can be sure that you can't have other falsey values besides None in A, then you can replace the first expression with the second.
In Java 7+ a few of the previous answers can be combined to allow retrieval of any path segment from a URI, rather than just the last segment. We can convert the URI to a java.nio.file.Path
object, to take advantage of its getName(int)
method.
Unfortunately, the static factory Paths.get(uri)
is not built to handle the http scheme, so we first need to separate the scheme from the URI's path.
URI uri = URI.create("http://base_path/some_segment/id");
Path path = Paths.get(uri.getPath());
String last = path.getFileName().toString();
String secondToLast = path.getName(path.getNameCount() - 2).toString();
To get the last segment in one line of code, simply nest the lines above.
Paths.get(URI.create("http://base_path/some_segment/id").getPath()).getFileName().toString()
To get the second-to-last segment while avoiding index numbers and the potential for off-by-one errors, use the getParent()
method.
String secondToLast = path.getParent().getFileName().toString();
Note the getParent()
method can be called repeatedly to retrieve segments in reverse order. In this example, the path only contains two segments, otherwise calling getParent().getParent()
would retrieve the third-to-last segment.
The document looks fine to me but I suspect that it contains invisible characters. Open it in a hex editor to check that there really isn't anything before the very first "<". Make sure the spaces in the XML header are spaces. Maybe delete the space before "?>". Check which line breaks are used.
Make sure the document is proper UTF-8. Some windows editors save the document as UTF-16 (i.e. every second byte is 0).
SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.
The specific keys you have to set are below:
javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.
javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).
javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes,
/
, in place of backslashes,\
.If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):
$JAVA_HOME/lib/security/jssecacerts
$JAVA_HOME/lib/security/cacerts
javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by
javax.net.ssl.trustStore
.javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.
javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.
You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:
SELECT Name,
SUM(Value) AS "SUM(VALUE)",
SUM(Value) / totals.total AS "% of Total"
FROM table1,
(
SELECT Name,
SUM(Value) AS total
FROM table1
GROUP BY Name
) AS totals
WHERE table1.Name = totals.Name
AND Year BETWEEN 2000 AND 2001
GROUP BY Name;
Note that the subquery does not have the WHERE clause filtering the years.
First, regarding this solution:
# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')
It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone.
A better solution is to change sys.stdout
at the start of your program, to encode with a selected encoding. Here is one solution I found on Python: How is sys.stdout.encoding chosen?, in particular a comment by "toka":
import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
You want the php function "asort":
http://php.net/manual/en/function.asort.php
it sorts the array, maintaining the index associations.
Edit: I've just noticed you're using a standard array (non-associative). if you're not fussed about preserving index associations, use sort():
Why are you doing a group by on an update statement? Are you sure that's not the part that's causing the query to fail? Try this:
update
MasterTbl
set
TotalX = Sum(DetailTbl.X),
TotalY = Sum(DetailTbl.Y),
TotalZ = Sum(DetailTbl.Z)
from
DetailTbl
where
DetailTbl.MasterID = MasterID
Use the re.escape()
function for this:
escape(string)
Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.
A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.
def simplistic_plural(word, text):
word_or_plural = re.escape(word) + 's?'
return re.match(word_or_plural, text)
let
is interesting, because it allows us to do something like this:
(() => {
var count = 0;
for (let i = 0; i < 2; ++i) {
for (let i = 0; i < 2; ++i) {
for (let i = 0; i < 2; ++i) {
console.log(count++);
}
}
}
})();
Which results in counting [0, 7].
Whereas
(() => {
var count = 0;
for (var i = 0; i < 2; ++i) {
for (var i = 0; i < 2; ++i) {
for (var i = 0; i < 2; ++i) {
console.log(count++);
}
}
}
})();
Only counts [0, 1].
If the database engine for tables differ you will get this error so change them to InnoDB
ALTER TABLE my_table ENGINE = InnoDB;
Bind an event handler to the focus event of the select
to capture the previous value. Then set the value of the select
to the previous value when reset is clicked.
var previousValue = "";
$("#my_select").on("focus",function(){
previousValue = $(this).val();
});
$("#reset").on("click", function () {
$("#my_select").val(previousValue);
});
Working Example: http://jsfiddle.net/T8sCf/17/
The wb
indicates that the file is opened for writing in binary mode.
When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b
is excluded as in just w
or when you specify text mode with wt
), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n
) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe
or png
file.
Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.
References:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open
You can open multiple windows on single click... Try this..
<a href="http://--"
onclick=" window.open('http://--','','width=700,height=700');
window.open('http://--','','width=700,height=500'); ..// add more"
>Click Here</a>`
Check what's the CONSTRAINT name and the FOREIGN KEY name:
SHOW CREATE TABLE table_name;
Remove both the CONSTRAINT name and the FOREIGN KEY name:
ALTER TABLE table_name
DROP FOREIGN KEY the_name_after_CONSTRAINT,
DROP KEY the_name_after_FOREIGN_KEY;
Hope this helps!
You are using a relative path. You should use the absolute path, url(/assets/css/style.css).
Not a direct answer to this question but rather to the "issue" of $event.currentTarget
apparently be set to null.
This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.
You can check this for more information: Consecutive calls to console.log produce inconsistent results
This site has great examples check it out
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"
// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008"
// two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"
Standard DateTime Formatting
String.Format("{0:t}", dt); // "4:05 PM" ShortTime
String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime
/*
Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTimePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSortableDateTimePattern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent
*/
Update using c# 6 string interpolation format
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
$"{dt:y yy yyy yyyy}"; // "8 08 008 2008" year
$"{dt:M MM MMM MMMM}"; // "3 03 Mar March" month
$"{dt:d dd ddd dddd}"; // "9 09 Sun Sunday" day
$"{dt:h hh H HH}"; // "4 04 16 16" hour 12/24
$"{dt:m mm}"; // "5 05" minute
$"{dt:s ss}"; // "7 07" second
$"{dt:f ff fff ffff}"; // "1 12 123 1230" sec.fraction
$"{dt:F FF FFF FFFF}"; // "1 12 123 123" without zeroes
$"{dt:t tt}"; // "P PM" A.M. or P.M.
$"{dt:z zz zzz}"; // "-6 -06 -06:00" time zone
// month/day numbers without/with leading zeroes
$"{dt:M/d/yyyy}"; // "3/9/2008"
$"{dt:MM/dd/yyyy}"; // "03/09/2008"
// day/month names
$"{dt:ddd, MMM d, yyyy}"; // "Sun, Mar 9, 2008"
$"{dt:dddd, MMMM d, yyyy}"; // "Sunday, March 9, 2008"
// two/four digit year
$"{dt:MM/dd/yy}"; // "03/09/08"
$"{dt:MM/dd/yyyy}"; // "03/09/2008"
If you declared your button in the xml file similar to this:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="next activity"
android:onClick="goToActivity2"
/>
then you can use it to change the activity by putting this at the java file:
public void goToActivity2 (View view){
Intent intent = new Intent (this, Main2Activity.class);
startActivity(intent);
}
Note that my second activity is called "Main2Activity"
say you define the static getFactorial
function inside a CodeController
then this is the way you need to call a static function, because static properties and methods exists with in the class, not in the objects created using the class.
CodeController::getFactorial($index);
----------------UPDATE----------------
To best practice I think you can put this kind of functions inside a separate file so you can maintain with more easily.
to do that
create a folder inside app
directory and name it as lib
(you can put a name you like).
this folder to needs to be autoload to do that add app/lib
to composer.json
as below. and run the composer dumpautoload
command.
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
............
"app/lib"
]
},
then files inside lib
will autoloaded.
then create a file inside lib
, i name it helperFunctions.php
inside that define the function.
if ( ! function_exists('getFactorial'))
{
/**
* return the factorial of a number
*
* @param $number
* @return string
*/
function getFactorial($date)
{
$fact = 1;
for($i = 1; $i <= $num ;$i++)
$fact = $fact * $i;
return $fact;
}
}
and call it anywhere within the app as
$fatorial_value = getFactorial(225);
Check for undefined:
if (typeof response.photo == "undefined")
{
// do something
}
This would do the equivelant of vb's IsEmpty
. If myvar contains any value, even null, empty string, or 0, it is not "empty".
To check if a variable or property exists, eg it's been declared, though it may be not have been defined, you can use the in
operator.
if ("photo" in response)
{
// do something
}
Many of the above mentioned solutions might suite different people.
I would like to suggest a slightly modified code than most accepted solution by "MusiGenesis".
DateTime firstTime = DateTime.Parse( TextBox1.Text );
DateTime secondTime = DateTime.Parse( TextBox2.Text );
double milDiff = secondTime.Subtract(firstTime).TotalMilliseconds;
Considerations:
- earlierTime.Subtract(laterTime)
you will get a negative value.
- use int milDiff = (int)DateTime.Now.Subtract(StartTime).TotalMilliseconds;
if you need integer value instead of double
- Same code can be used to get difference between two Date values and you may get .TotalDays
or .TotalHours
insteaf of .TotalMilliseconds
If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn't exist.
Use the Settings tab to create application settings. Visual Studio creates the files Settings.settings
and Settings.Designer.settings
that contain the singleton class Settings
inherited from ApplicationSettingsBase. You can access this class from your code to read/write application settings:
Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file
This technique is applicable both for console, Windows Forms, and other project types.
Note that you need to set the scope property of your settings. If you select Application scope then Settings.Default.<your property> will be read-only.
Reference: How To: Write User Settings at Run Time with C# - Microsoft Docs
Assuming you want to remove key=val parameter from URI:
function removeParam(uri) {
return uri.replace(/([&\?]key=val*$|key=val&|[?&]key=val(?=#))/, '');
}
Try this:
import os
import sys
Zeichen=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s",";t","u","v","w","x","y","z"]
def start(): input("Enter to start")
def Gen(stellen): if stellen==1: for i in Zeichen: print(i) elif stellen==2: for i in Zeichen: for r in Zeichen: print(i+r) elif stellen==3: for i in Zeichen: for r in Zeichen: for t in Zeichen: print(i+r+t) elif stellen==4: for i in Zeichen: for r in Zeichen: for t in Zeichen: for u in Zeichen: print(i+r+t+u) elif stellen==5: for i in Zeichen: for r in Zeichen: for t in Zeichen: for u in Zeichen: for o in Zeichen: print(i+r+t+u+o) else: print("done")
#*********************
start()
Gen(1)
Gen(2)
Gen(3)
Gen(4)
Gen(5)
Scale a bitmap with a target maximum size and width, while maintaining aspect ratio:
int maxHeight = 2000;
int maxWidth = 2000;
float scale = Math.min(((float)maxHeight / bitmap.getWidth()), ((float)maxWidth / bitmap.getHeight()));
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
/// <reference types="@types/googlemaps" />
import {ChangeDetectorRef, Component, ElementRef, EventEmitter, Inject, Input, NgZone, OnInit, Output, ViewChild} from '@angular/core';
import {MapsAPILoader, MouseEvent} from '@agm/core';
import { Address } from 'src/@core/interfaces/address.model';
import { NotificationService } from 'src/@core/services/notification.service';
// import {} from 'googlemaps';
declare var google: any;
// @ts-ignore
@Component({
selector: 'app-search-address',
templateUrl: './search-address.component.html',
styleUrls: ['./search-address.component.scss']
})
export class SearchAddressComponent implements OnInit {
@Input('label') label: string;
@Input('addressObj') addressObj: Address = {};
zoom: number;
isSnazzyInfoWindowOpened = false;
private geoCoder;
// @ts-ignore
@Output() onAddressSelected = new EventEmitter<any>();
@Input('defaultAddress') defaultAddress = '';
@ViewChild('search', {static: true})
public searchElementRef: ElementRef = null;
constructor(
private mapsAPILoader: MapsAPILoader,
private ngZone: NgZone,
private notify: NotificationService,
@Inject(ChangeDetectorRef) private changeDetectorRef: ChangeDetectorRef
) { }
ngOnInit() {
// console.log('addressObj# ', this.addressObj);
if (this.defaultAddress !== '') {
this.searchElementRef.nativeElement.value = this.defaultAddress;
}
// load Places Autocomplete
this.mapsAPILoader.load().then(() => {
if (this.addressObj.address) {
this.setZoom();
} else {
this.setCurrentLocation();
}
this.geoCoder = new google.maps.Geocoder;
const autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
types: ['address']
});
autocomplete.setTypes(['(cities)']);
autocomplete.setComponentRestrictions({'country': 'in'});
autocomplete.addListener('place_changed', () => {
this.ngZone.run(() => {
// get the place result
const place: google.maps.places.PlaceResult = autocomplete.getPlace();
// verify result
if (place.geometry === undefined || place.geometry === null) {
return;
}
// set latitude, longitude and zoom
this.addressObj.latitude = place.geometry.location.lat();
this.addressObj.longitude = place.geometry.location.lng();
this.getAddress(this.addressObj.latitude, this.addressObj.longitude);
this.zoom = 12;
});
});
});
}
setZoom() {
this.zoom = 8;
}
// Get Current Location Coordinates
private setCurrentLocation() {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.addressObj.latitude = position.coords.latitude;
this.addressObj.longitude = position.coords.longitude;
this.zoom = 8;
this.getAddress(this.addressObj.latitude, this.addressObj.longitude);
});
}
}
markerDragEnd($event: MouseEvent) {
this.addressObj.latitude = $event.coords.lat;
this.addressObj.longitude = $event.coords.lng;
this.getAddress(this.addressObj.latitude, this.addressObj.longitude);
}
getAddress(latitude, longitude) {
this.addressObj.latitude = latitude;
this.addressObj.longitude = longitude;
this.geoCoder.geocode({ location: { lat: latitude, lng: longitude } }, (results, status) => {
if (status === 'OK') {
if (results[0]) {
console.log('results ', results);
this.zoom = 12;
this.addressObj.address = results[0].formatted_address;
this.showSnazzyInfoWindow();
this.addressObj.placeId = results[0].place_id;
for(let i = 0; i < results[0].address_components.length; i++) {
if (results[0].address_components[i].types[0] == 'locality') {
this.addressObj.city = results[0].address_components[i].long_name;
}
if (results[0].address_components[i].types[0] == 'administrative_area_level_1') {
this.addressObj.region = results[0].address_components[i].long_name;
}
if (results[0].address_components[i].types[0] == 'country') {
this.addressObj.country = results[0].address_components[i].long_name;
}
if (results[0].address_components[i].types[0] == 'postal_code') {
this.addressObj.zip = results[0].address_components[i].long_name;
}
}
this.transmitData();
} else {
this.notify.showMessage('No results found', 3000, 'OK');
}
} else {
this.notify.showMessage('Google maps location failed due to: ' + status, 3000, 'OK');
}
});
}
transmitData() {
// console.log(this.addressObj);
this.onAddressSelected.emit(this.addressObj);
}
toggleSnazzyInfoWindow() {
this.isSnazzyInfoWindowOpened = !this.isSnazzyInfoWindowOpened;
}
showSnazzyInfoWindow() {
this.isSnazzyInfoWindowOpened = true;
}
}
<mat-form-field class="full-width pt-2 flex-auto w-full">
<input matInput [(ngModel)]="addressObj.address" type="text" (keydown.enter)="$event.preventDefault()" placeholder="{{label ? label : 'Location'}}" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" #search>
</mat-form-field>
<agm-map
[latitude]="addressObj.latitude"
[longitude]="addressObj.longitude"
[zoom]="zoom">
<agm-marker
[latitude]="addressObj.latitude"
[longitude]="addressObj.longitude"
[markerDraggable]="true"
(dragEnd)="markerDragEnd($event)">
</agm-marker>
</agm-map>
This is a very old question, but I think I have a solution that is slightly easier to type than previous solutions and doesn't rely on external libraries:
function sortArguments() {
return Array.apply(null, arguments).sort();
}
Since Symfony 3.3,
You can use %kernel.project_dir%/web/
instead of %kernel.root_dir%/../web/
You should be using datetime.datetime.strptime
. Note that very old versions of Python (2.4 and older) don't have datetime.datetime.strptime
; use time.strptime
in that case.
input
being your <select>
element:
input.querySelectorAll(':not([selected])').forEach(option => {
option.disabled = true
})
This will keep the select in the data (as it's not disabled) and only the option
that are not selected are disabled, therefore not selectable.
The result is a readable select that cannot be changed (=> read only).
Adapted from here, building on scunliffe's answer:
function getStyle(className) {
var cssText = "";
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) {
if (classes[x].selectorText == className) {
cssText += classes[x].cssText || classes[x].style.cssText;
}
}
return cssText;
}
alert(getStyle('.test'));
If you'd like to know how to sort a linked list without using standard Java libraries, I'd suggest looking at different algorithms yourself. Examples here show how to implement an insertion sort, another StackOverflow post shows a merge sort, and ehow even gives some examples on how to create a custom compare function in case you want to further customize your sort.
It's not an answer, but...
To get datetime
components individually, better use datetime.timetuple:
time = datetime.now()
time.timetuple()
#-> time.struct_time(
# tm_year=2014, tm_mon=9, tm_mday=7,
# tm_hour=2, tm_min=38, tm_sec=5,
# tm_wday=6, tm_yday=250, tm_isdst=-1
#)
It's now easy to get the parts:
ts = time.timetuple()
ts.tm_year
ts.tm_mon
ts.tm_mday
ts.tm_hour
ts.tm_min
ts.tm_sec
The question is:
Is there a difference in ++i and i++ in a for loop?
The answer is: No.
Why does each and every other answer have to go into detailed explanations about pre and post incrementing when this is not even asked?
This for-loop:
for (int i = 0; // Initialization
i < 5; // Condition
i++) // Increment
{
Output(i);
}
Would translate to this code without using loops:
int i = 0; // Initialization
loopStart:
if (i < 5) // Condition
{
Output(i);
i++ or ++i; // Increment
goto loopStart;
}
Now does it matter if you put i++
or ++i
as increment here? No it does not as the return value of the increment operation is insignificant. i
will be incremented AFTER the code's execution that is inside the for loop body.
Swift 4
Add a view outlet
@IBOutlet weak var gradientView: UIView!
Add gradient to the view
func setGradient() {
let gradient: CAGradientLayer = CAGradientLayer()
gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
gradient.locations = [0.0 , 1.0]
gradient.startPoint = CGPoint(x: 0.0, y: 1.0)
gradient.endPoint = CGPoint(x: 1.0, y: 1.0)
gradient.frame = gradientView.layer.frame
gradientView.layer.insertSublayer(gradient, at: 0)
}
I like SciTE as a basic editor for C++/Python on Linux. It has keyboard bindings similar to VC so you do not have to reprogram your cut-and-paste fingers.
I use it together with Git for source code control and the very useful 'git grep' command for searching in your code base.
I played with Eclipse CDT but my source codebase was to big for it and I spend too much time waiting on the IDE. If your project is smaller it may be good for you though.
db2look -d <db_name> -e -z <schema_name> -t <table_name> -i <user_name> -w <password> > <file_name>.sql
For more information, please refer below:
db2look [-h]
-d: Database Name: This must be specified
-e: Extract DDL file needed to duplicate database
-xs: Export XSR objects and generate a script containing DDL statements
-xdir: Path name: the directory in which XSR objects will be placed
-u: Creator ID: If -u and -a are both not specified then $USER will be used
-z: Schema name: If -z and -a are both specified then -z will be ignored
-t: Generate statistics for the specified tables
-tw: Generate DDLs for tables whose names match the pattern criteria (wildcard characters) of the table name
-ap: Generate AUDIT USING Statements
-wlm: Generate WLM specific DDL Statements
-mod: Generate DDL statements for Module
-cor: Generate DDL with CREATE OR REPLACE clause
-wrap: Generates obfuscated versions of DDL statements
-h: More detailed help message
-o: Redirects the output to the given file name
-a: Generate statistics for all creators
-m: Run the db2look utility in mimic mode
-c: Do not generate COMMIT statements for mimic
-r: Do not generate RUNSTATS statements for mimic
-l: Generate Database Layout: Database partition groups, Bufferpools and Tablespaces
-x: Generate Authorization statements DDL excluding the original definer of the object
-xd: Generate Authorization statements DDL including the original definer of the object
-f: Extract configuration parameters and environment variables
-td: Specifies x to be statement delimiter (default is semicolon(;))
-i: User ID to log on to the server where the database resides
-w: Password to log on to the server where the database resides
simple approach:
List<int>[] a = new List<int>[100];
for (int i = 0; i < a.Length; i++)
{
a[i] = new List<int>();
}
or LINQ
approach
var b = Enumerable.Range(0,100).Select((i)=>new List<int>()).ToArray();
I just dealt with this problem, so I'll add my solution as a supplement on other answers given.
The problem here is that useEffect
doesn't really work as you would want it to, since the call only gets triggered after the first render so there is an unwanted delay.
If you use some state manager like redux, chances are that you will get a flicker on the screen because of lingering state in the store.
What you really want is to use useLayoutEffect
since this gets triggered immediately.
So I wrote a small utility function that I put in the same directory as my router:
export const callApis = (fn, path) => {
useLayoutEffect(() => {
fn();
}, [path]);
};
Which I call from within the component HOC like this:
callApis(() => getTopicById({topicId}), path);
path
is the prop that gets passed in the match
object when using withRouter
.
I'm not really in favour of listening / unlistening manually on history. That's just imo.
I find this quite tricky, but there is some information on it here at the MatPlotLib FAQ. It is rather cumbersome, and requires finding out about what space individual elements (ticklabels) take up...
Update:
The page states that the tight_layout()
function is the easiest way to go, which attempts to automatically correct spacing.
Otherwise, it shows ways to acquire the sizes of various elements (eg. labels) so you can then correct the spacings/positions of your axes elements. Here is an example from the above FAQ page, which determines the width of a very wide y-axis label, and adjusts the axis width accordingly:
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_yticks((2,5,7))
labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))
def on_draw(event):
bboxes = []
for label in labels:
bbox = label.get_window_extent()
# the figure transform goes from relative coords->pixels and we
# want the inverse of that
bboxi = bbox.inverse_transformed(fig.transFigure)
bboxes.append(bboxi)
# this is the bbox that bounds all the bboxes, again in relative
# figure coords
bbox = mtransforms.Bbox.union(bboxes)
if fig.subplotpars.left < bbox.width:
# we need to move it over
fig.subplots_adjust(left=1.1*bbox.width) # pad a little
fig.canvas.draw()
return False
fig.canvas.mpl_connect('draw_event', on_draw)
plt.show()
I was stucked with this problem for a long time (CORS does not work in FF, but works in Chrome and others). No advice could help. Finally, i found that my local dev subdomain (like sub.example.dev) was not explicitly mentioned in /etc/hosts, thus FF just is not able to find it and shows confusing error message 'Aborted...' in dev tools panel.
Putting the exact subdomain into my local /etc/hosts fixed the problem. /etc/hosts is just a plain-text file in unix systems, so you can open it under the root user and put your subdomain in front of '127.0.0.1' ip address.
This works for me
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;
run both:
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())
Here is one way of doing it:
<%
Dim message
message = "This is my message"
Response.Write("<script language=VBScript>MsgBox """ + message + """</script>")
%>
If you are running on a x86 or x86_64 processor, the big endian is native. so
for 16 bit values
unsigned short wBigE = value;
unsigned short wLittleE = ((wBigE & 0xFF) << 8) | (wBigE >> 8);
for 32 bit values
unsigned int iBigE = value;
unsigned int iLittleE = ((iBigE & 0xFF) << 24)
| ((iBigE & 0xFF00) << 8)
| ((iBigE >> 8) & 0xFF00)
| (iBigE >> 24);
This isn't the most efficient solution unless the compiler recognises that this is byte level manipulation and generates byte swapping code. But it doesn't depend on any memory layout tricks and can be turned into a macro pretty easily.
Try this regex:
^(\+?\d{1,4}[\s-])?(?!0+\s+,?$)\d{10}\s*,?$
Explanation of the regex using Perl's YAPE is as below:
NODE EXPLANATION
----------------------------------------------------------------------
(?-imsx: group, but do not capture (case-sensitive)
(with ^ and $ matching normally) (with . not
matching \n) (matching whitespace and #
normally):
----------------------------------------------------------------------
^ the beginning of the string
----------------------------------------------------------------------
( group and capture to \1 (optional
(matching the most amount possible)):
----------------------------------------------------------------------
\+? '+' (optional (matching the most amount
possible))
----------------------------------------------------------------------
\d{1,4} digits (0-9) (between 1 and 4 times
(matching the most amount possible))
----------------------------------------------------------------------
[\s-] any character of: whitespace (\n, \r,
\t, \f, and " "), '-'
----------------------------------------------------------------------
)? end of \1 (NOTE: because you are using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \1)
----------------------------------------------------------------------
(?! look ahead to see if there is not:
----------------------------------------------------------------------
0+ '0' (1 or more times (matching the most
amount possible))
----------------------------------------------------------------------
\s+ whitespace (\n, \r, \t, \f, and " ") (1
or more times (matching the most amount
possible))
----------------------------------------------------------------------
,? ',' (optional (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of
the string
----------------------------------------------------------------------
) end of look-ahead
----------------------------------------------------------------------
\d{10} digits (0-9) (10 times)
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
,? ',' (optional (matching the most amount
possible))
----------------------------------------------------------------------
$ before an optional \n, and the end of the
string
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
Use Google Guava AbstractScheduledService
as given below:
public class ScheduledExecutor extends AbstractScheduledService {
@Override
protected void runOneIteration() throws Exception {
System.out.println("Executing....");
}
@Override
protected Scheduler scheduler() {
return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
}
@Override
protected void startUp() {
System.out.println("StartUp Activity....");
}
@Override
protected void shutDown() {
System.out.println("Shutdown Activity...");
}
public static void main(String[] args) throws InterruptedException {
ScheduledExecutor se = new ScheduledExecutor();
se.startAsync();
Thread.sleep(15000);
se.stopAsync();
}
}
If you have more services like this, then registering all services in ServiceManager will be good as all services can be started and stopped together. Read here for more on ServiceManager.
Knockout's documentation also mentions a much cleaner way of passing extra parameters to functions bound using an on-click
binding using function.bind like this:
<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">
Click me
</button>
I've used IP*Works SSH and it is great. Easy to setup and use. Plus, their support is top-notch when you run into questions or problems.
There should be a line in your postgresql.conf
file that says:
port = 1486
Change that.
The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/
On Windows it is C:\Program Files\PostgreSQL\9.3\data
Don't forget to sudo service postgresql restart
for changes to take effect.
Though you already have an accepted answer, I figured I'd add this for anyone else interested in a different solution-
An implementation could be as follows:
import csv
with open('C:/mypath/to/csvfile.csv', 'r') as f:
d_reader = csv.DictReader(f)
#get fieldnames from DictReader object and store in list
headers = d_reader.fieldnames
for line in d_reader:
#print value in MyCol1 for each row
print(line['MyCol1'])
In the above, d_reader.fieldnames returns a list of your headers (assuming the headers are in the top row). Which allows...
>>> print(headers)
['MyCol1', 'MyCol2', 'MyCol3']
If your headers are in, say the 2nd row (with the very top row being row 1), you could do as follows:
import csv
with open('C:/mypath/to/csvfile.csv', 'r') as f:
#you can eat the first line before creating DictReader.
#if no "fieldnames" param is passed into
#DictReader object upon creation, DictReader
#will read the upper-most line as the headers
f.readline()
d_reader = csv.DictReader(f)
headers = d_reader.fieldnames
for line in d_reader:
#print value in MyCol1 for each row
print(line['MyCol1'])
This should work:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
Assembly asm = Assembly.GetCallingAssembly();
String path = Path.GetDirectoryName(new Uri(asm.EscapedCodeBase).LocalPath);
string strLog4NetConfigPath = System.IO.Path.Combine(path, "log4net.config");
I am using this to deploy DLL file libraries along with some configuration file (this is to use log4net from within the DLL file).
By full precision, I assume mean enough precision to show the best approximation to the intended value, but it should be pointed out that double
is stored using base 2 representation and base 2 can't represent something as trivial as 1.1
exactly. The only way to get the full-full precision of the actual double (with NO ROUND OFF ERROR) is to print out the binary bits (or hex nybbles).
One way of doing that is using a union
to type-pun the double
to a integer and then printing the integer, since integers do not suffer from truncation or round-off issues. (Type punning like this is not supported by the C++ standard, but it is supported in C. However, most C++ compilers will probably print out the correct value anyways. I think g++ supports this.)
union {
double d;
uint64_t u64;
} x;
x.d = 1.1;
std::cout << std::hex << x.u64;
This will give you the 100% accurate precision of the double... and be utterly unreadable because humans can't read IEEE double format ! Wikipedia has a good write up on how to interpret the binary bits.
In newer C++, you can do
std::cout << std::hexfloat << 1.1;
To formalize what has been pointed out, a reducer is a catamorphism which takes two arguments which may be the same type by coincidence, and returns a type which matches the first argument.
function reducer (accumulator: X, currentValue: Y): X { }
That means that the body of the reducer needs to be about converting currentValue
and the current value of the accumulator
to the value of the new accumulator
.
This works in a straightforward way, when adding, because the accumulator and the element values both happen to be the same type (but serve different purposes).
[1, 2, 3].reduce((x, y) => x + y);
This just works because they're all numbers.
[{ age: 5 }, { age: 2 }, { age: 8 }]
.reduce((total, thing) => total + thing.age, 0);
Now we're giving a starting value to the aggregator. The starting value should be the type that you expect the aggregator to be (the type you expect to come out as the final value), in the vast majority of cases. While you aren't forced to do this (and shouldn't be), it's important to keep in mind.
Once you know that, you can write meaningful reductions for other n:1 relationship problems.
Removing repeated words:
const skipIfAlreadyFound = (words, word) => words.includes(word)
? words
: words.concat(word);
const deduplicatedWords = aBunchOfWords.reduce(skipIfAlreadyFound, []);
Providing a count of all words found:
const incrementWordCount = (counts, word) => {
counts[word] = (counts[word] || 0) + 1;
return counts;
};
const wordCounts = words.reduce(incrementWordCount, { });
Reducing an array of arrays, to a single flat array:
const concat = (a, b) => a.concat(b);
const numbers = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
].reduce(concat, []);
Any time you're looking to go from an array of things, to a single value that doesn't match a 1:1, reduce is something you might consider.
In fact, map and filter can both be implemented as reductions:
const map = (transform, array) =>
array.reduce((list, el) => list.concat(transform(el)), []);
const filter = (predicate, array) => array.reduce(
(list, el) => predicate(el) ? list.concat(el) : list,
[]
);
I hope this provides some further context for how to use reduce
.
The one addition to this, which I haven't broken into yet, is when there is an expectation that the input and output types are specifically meant to be dynamic, because the array elements are functions:
const compose = (...fns) => x =>
fns.reduceRight((x, f) => f(x), x);
const hgfx = h(g(f(x)));
const hgf = compose(h, g, f);
const hgfy = hgf(y);
const hgfz = hgf(z);
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
TryParse is usually the most elegant way to handle this type of thing:
long temp = 0;
if (Int64.TryParse(dataAccCom.GetParameterValue(IDbCmd, "op_Id").ToString(), out temp))
{
DataTO.Id = temp;
}
In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].
Jenkins 2.x has the global variables. env
is one of them from any script...
println env.JOB_NAME
More at https://build.intuit.com/services-config/pipeline-syntax/globals#env
Generic function that is validated at compilation!
public static bool IsBetween<T>(this T item, T start, T end) where T : IComparable
{
return item.CompareTo(start) >= 0 && item.CompareTo(end) <= 0;
}
jQuery:
$('#container').append('<img src="/path/to/image.jpg"
width="16" height="16" alt="Test Image" title="Test Image" />');
I've found that this works even better because you don't have to worry about HTML escaping anything (which should be done in the above code, if the values weren't hard coded). It's also easier to read (from a JS perspective):
$('#container').append($('<img>', {
src : "/path/to/image.jpg",
width : 16,
height : 16,
alt : "Test Image",
title : "Test Image"
}));
If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.
javascript:
<script language="javascript">
setTimeout(function(){
window.location.reload(1);
}, 30000);
</script>
int match_position=text.indexOf(match);
If it were me, I would avoid any risky revision editing and do the following instead:
Create a new branch on the SHA where 222 was committed, basically as a bookmark.
Switch back to the main branch. In it, revert commit 222.
Push all the commits that have been made, which will push commit 111 only, because 222 was reverted.
Work on the branch from step #1 if needed. Merge from the trunk to it as needed to keep it up to date. I wouldn't bother with stash.
When it's time for the changes in commit 222 to go in, that branch can be merged to trunk.
It depends on what keeps your users happy. For example, Gmail takes quite a while to open at first, but users wait because it is worth waiting for.
Delaying showing the route is sure to lead to an asynchronous tangle... why not simply track the loading status of your main entity and use that in the view. For example in your controller you might use both the success and error callbacks on ngResource:
$scope.httpStatus = 0; // in progress
$scope.projects = $resource.query('/projects', function() {
$scope.httpStatus = 200;
}, function(response) {
$scope.httpStatus = response.status;
});
Then in the view you could do whatever:
<div ng-show="httpStatus == 0">
Loading
</div>
<div ng-show="httpStatus == 200">
Real stuff
<div ng-repeat="project in projects">
...
</div>
</div>
<div ng-show="httpStatus >= 400">
Error, not found, etc. Could distinguish 4xx not found from
5xx server error even.
</div>
- Abstract class
is one which can't be instantiated, i.e. its object
cannot be created.
- Abstract method
are method's declaration without its definition.
- A Non-abstract class
can only have Non-abstract methods.
- An Abstract class
can have both the Non-abstract as well as Abstract methods.
- If the Class
has an Abstract method
then the class must also be Abstract.
- An Abstract method
must be implemented by the very first Non-Abstract sub-class.
- Abstract class
in Design patterns
are used to encapsulate the behaviors that keeps changing.
It can be a mathematical convention in the definition of an interval where square brackets mean "extremal inclusive" and round brackets "extremal exclusive".
you can have a variable
DEBUG = 0
then you can use a conditional statement
ifeq ($(DEBUG),1)
else
endif
Use Date convert to compare with date: Try This:
select * from table
where TO_DATE(to_char(timespanColumn,'YYYY-MM-DD'),'YYYY-MM-DD') = to_timestamp('2018-03-26', 'YYYY-MM-DD')
You are expecting that your int
type is 16 bit wide, in which case you'd indeed get a negative value. But most likely it's 32 bits wide, so a signed int
can represent 65529 just fine. You can check this by printing sizeof(int)
.
Check the charset encoding of the file. Make sure that it is in ASCII.
Use the od
command to see if there is a UTF-8 BOM at the beginning, for example.
There should be no semicolon here:
class WordGame;
...but there should be one at the end of your class definition:
...
private:
string theWord;
}; // <-- Semicolon should be at the end of your class definition
The as keyword is good in asp.net when you use the FindControl method.
Hyperlink link = this.FindControl("linkid") as Hyperlink;
if (link != null)
{
...
}
This means you can operate on the typed variable rather then having to then cast it from object
like you would with a direct cast:
object linkObj = this.FindControl("linkid");
if (link != null)
{
Hyperlink link = (Hyperlink)linkObj;
}
It's not a huge thing, but it saves lines of code and variable assignment, plus it's more readable
To get the id of the parent div:
$(buttonSelector).parents('div:eq(0)').attr('id');
Also, you can refactor your code quite a bit:
$('button').click( function() {
var correct = Number($(this).attr('rel'));
validate(Number($(this).siblings('input').val()), correct);
$(this).parents('div:eq(0)').html(feedback);
});
Now there is no need for a button-class
explanation
eq(0), means that you will select one element from the jQuery object, in this case element 0, thus the first element. http://docs.jquery.com/Selectors/eq#index
$(selector).siblings(siblingsSelector) will select all siblings (elements with the same parent) that match the siblingsSelector http://docs.jquery.com/Traversing/siblings#expr
$(selector).parents(parentsSelector) will select all parents of the elements matched by selector that match the parent selector. http://docs.jquery.com/Traversing/parents#expr
Thus: $(selector).parents('div:eq(0)'); will match the first parent div of the elements matched by selector.
You should have a look at the jQuery docs, particularly selectors and traversing:
Handle the Worksheet_Change
event or the Workbook_SheetChange
event.
The event handlers take an argument "Target As Range", so you can check if the range that's changing includes the cell you're interested in.
You can encrypt your SQLite database with the SEE addon. This way you prevent unauthorized access/modification.
Quoting SQLite documentation:
The SQLite Encryption Extension (SEE) is an enhanced version of SQLite that encrypts database files using 128-bit or 256-Bit AES to help prevent unauthorized access or modification. The entire database file is encrypted so that to an outside observer, the database file appears to contain white noise. There is nothing that identifies the file as an SQLite database.
You can find more info about this addon in this link.
Android 3.2 introduces a new approach to screen sizes,the numbers describing the screen size are all in “dp” units.Mostly we can use
smallest width dp: the smallest width available for application layout in “dp” units; this is the smallest width dp that you will ever encounter in any rotation of the display.
To create one right click on res >>> new >>> Android resource directory
From Available qualifiers window move Smallest Screen Width to Chosen qualifiers
In Screen width window just write the "dp" value starting from you would like Android Studio to use that dimens.
Than change to Project view,right click on your new created resource directory
new >>> Values resource file enter a new file name dimens.xml and you are done.
Create an instance of Class B:
B b=new B();
b.method();
or define an static method in Class B:
class B
{
static void staticMethod();
}
and call it like this:
B.staticMethod();
None of them are "better" than the others. The third is, to me, more readable, but to someone who doesn't use foreaches it might look odd (they might prefer the first). All 3 are pretty clear to anyone who understands Java, so pick whichever makes you feel better about the code.
The first one is the most basic, so it's the most universal pattern (works for arrays, all iterables that I can think of). That's the only difference I can think of. In more complicated cases (e.g. you need to have access to the current index, or you need to filter the list), the first and second cases might make more sense, respectively. For the simple case (iterable object, no special requirements), the third seems the cleanest.
In addition to the answer from @WoLpH.
When using the LIKE
keyword you also have the ability to limit which direction the string matches. For example:
If you were looking for a string that starts with your $needle
:
... WHERE column LIKE '{$needle}%'
If you were looking for a string that ends with the $needle
:
... WHERE column LIKE '%{$needle}'
.border-blue.background { ... }
is for one item with multiple classes.
.border-blue, .background { ... }
is for multiple items each with their own class.
.border-blue .background { ... }
is for one item where '.background' is the child of '.border-blue'.
See Chris' answer for a more thorough explanation.
As I don't want to introduce alien-like new C++ syntax, and I simply want to build up on existing primitives, the below snippets seems to work:
#include <vector>
#include <iostream>
int main (int argc,char *argv[])
{
std::vector<int> arr{1,2,3,4,5};
std::vector<int>::iterator it;
// iterate forward
for (it = arr.begin(); it != arr.end(); it++) {
std::cout << *it << " ";
}
std::cout << "\n************\n";
if (arr.size() > 0) {
// iterate backward, simple Joe version
it = arr.end() - 1;
while (it != arr.begin()) {
std::cout << *it << " ";
it--;
}
std::cout << *it << " ";
}
// iterate backwards, the C++ way
std::vector<int>::reverse_iterator rit;
for (rit = arr.rbegin(); rit != arr.rend(); rit++) {
std::cout << *rit << " ";
}
return 0;
}
The function which you are specifying as initSelection
is called with the initial value
as argument. So if value
is empty, the function is not called.
When you specifiy value='[{"id":"IN","name":"India"}]'
instead of data-initvalue
the function gets called and the selection can get initialized.
localhost is a special hostname that almost always resolves to 127.0.0.1. If you ask someone else to connect to http://localhost
they'll be connecting to their computer instead or yours.
To share your web server with someone else you'll need to find your IP address or your hostname and provide that to them instead. On windows you can find this with ipconfig /all
on a command line.
You'll also need to make sure any firewalls you may have configured allow traffic on port 80 to connect to the WAMP server.
Use parse_url() and parse_str().
(You can use regexes for just about anything, but they are very easy to make an error in, so if there are PHP functions specifically for what you are trying to accomplish, use those.)
parse_url takes a string and cuts it up into an array that has a bunch of info. You can work with this array, or you can specify the one item you want as a second argument. In this case we're interested in the query, which is PHP_URL_QUERY
.
Now we have the query, which is v=C4kxS1ksqtw&feature=relate
, but we only want the part after v=
. For this we turn to parse_str
which basically works like GET
on a string. It takes a string and creates the variables specified in the string. In this case $v
and $feature
is created. We're only interested in $v
.
To be safe, you don't want to just store all the variables from the parse_url
in your namespace (see mellowsoon's comment). Instead store the variables as elements of an array, so that you have control over what variables you are storing, and you cannot accidentally overwrite an existing variable.
Putting everything together, we have:
<?php
$url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
echo $my_array_of_vars['v'];
// Output: C4kxS1ksqtw
?>
Edit:
hehe - thanks Charles. That made me laugh, I've never seen the Zawinski quote before:
Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.
– Jamie Zawinski
I'm not sure if this works for you, but when I do small solo PHP projects with Eclipse, the first thing I set up is an Ant script for deploying the project to a remote testing environment. I code away locally, and whenever I want to test it, I just hit the shortcut which updates the remote site.
Eclipse has good Ant support out of the box, and the scripts aren't hard to make.
Not sure why you need a Double in your map. In terms of what you're trying to do, you have an int[] and you just want counts of how many times each sequence occurs? Why would this required a Double anyway?
What I would do is to create a wrapper for the int array with a proper .equals and .hashCode methods to account for the fact that int[] object itself doesn't consider the data in it's version of these methods.
public class IntArrayWrapper {
private int values[];
public IntArrayWrapper(int[] values) {
super();
this.values = values;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(values);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
IntArrayWrapper other = (IntArrayWrapper) obj;
if (!Arrays.equals(values, other.values))
return false;
return true;
}
}
And then use google guava's multiset, which is meant exactly for the purpose of counting occurances, as long as the element type you put in it has proper .equals and .hashCode methods.
List<int[]> list = ...;
HashMultiset<IntArrayWrapper> multiset = HashMultiset.create();
for (int values[] : list) {
multiset.add(new IntArrayWrapper(values));
}
Then, to get the count for any particular combination:
int cnt = multiset.count(new IntArrayWrapper(new int[] { 0, 1, 2, 3 }));
When shifting left, there is no difference between arithmetic and logical shift. When shifting right, the type of shift depends on the type of the value being shifted.
(As background for those readers unfamiliar with the difference, a "logical" right shift by 1 bit shifts all the bits to the right and fills in the leftmost bit with a 0. An "arithmetic" shift leaves the original value in the leftmost bit. The difference becomes important when dealing with negative numbers.)
When shifting an unsigned value, the >> operator in C is a logical shift. When shifting a signed value, the >> operator is an arithmetic shift.
For example, assuming a 32 bit machine:
signed int x1 = 5;
assert((x1 >> 1) == 2);
signed int x2 = -5;
assert((x2 >> 1) == -3);
unsigned int x3 = (unsigned int)-5;
assert((x3 >> 1) == 0x7FFFFFFD);
var arr = [];
for(var i=1; i<=mynumber; i++) {
arr.push(i.toString());
}
I have had the same problem and came acrosse this site.
the solution to just set another "filename" in the
... for output as ... command was very simple and useful.
in addition (beyond the Application.GetSaveAsFilename() Dialog)
it is very simple to set a** new filename** just using
the replace command, so you may change the filename/extension
eg. (as from the first post)
sFileName = "C:\filelocation"
iFileNum = FreeFile
Open sFileName For Input As iFileNum
content = (...edit the content)
Close iFileNum
now just set:
newFilename = replace(sFilename, ".txt", ".csv") to change the extension
or
newFilename = replace(sFilename, ".", "_edit.") for a differrent filename
and then just as before
iFileNum = FreeFile
Open newFileName For Output As iFileNum
Print #iFileNum, content
Close iFileNum
I surfed over an hour to find out how to rename a txt-file,
with many different solutions, but it could be sooo easy :)
Well pandas use bitwise &
|
and each condition should be wrapped in a ()
For example following works
data_query = data[(data['year'] >= 2005) & (data['year'] <= 2010)]
But the same query without proper brackets does not
data_query = data[(data['year'] >= 2005 & data['year'] <= 2010)]
If you do not like assets folder you can edit .angular-cli.json
and add other folders you need.
"assets": [
"assets",
"img",
"favicon.ico"
]
I don't know if this is efficient as others but simple logic always works:
import sys
name = ["Sam", "Peter", "James", "Julian", "Ann"]
for i in range(0, len(names)):
sys.stdout.write(names[i])
if i != len(names)-1:
sys.stdout.write(", ")
Output:
Sam, Peter, James, Julian, Ann
Lukas Knuth have good solution, but on android 4.0.4 on Samsung Galaxy SII I still look zoom controls. And I solve it via
if (zoom_controll!=null && zoom_controll.getZoomControls()!=null)
{
// Hide the controlls AFTER they where made visible by the default implementation.
zoom_controll.getZoomControls().setVisibility(View.GONE);
}
instead of
if (zoom_controll != null){
// Hide the controlls AFTER they where made visible by the default implementation.
zoom_controll.setVisible(false);
}
In MongoDB, the db.collection.remove() method removes documents from a collection. You can remove all documents from a collection, remove all documents that match a condition, or limit the operation to remove just a single document.
Source: Mongodb.
If you are using mongo sheel, just do:
db.Datetime.remove({})
In your case, you need:
You didn't show me the delete button, so this button is just an example:
<a class="button__delete"></a>
Change the controller to:
exports.destroy = function(req, res, next) {
Datetime.remove({}, function(err) {
if (err) {
console.log(err)
} else {
res.end('success');
}
}
);
};
Insert this ajax delete method in your client js file:
$(document).ready(function(){
$('.button__delete').click(function() {
var dataId = $(this).attr('data-id');
if (confirm("are u sure?")) {
$.ajax({
type: 'DELETE',
url: '/',
success: function(response) {
if (response == 'error') {
console.log('Err!');
}
else {
alert('Success');
location.reload();
}
}
});
} else {
alert('Canceled!');
}
});
});
I stumbled on this question as I had the same error. Mine was due to a slightly different problem and since I resolved it on my own I thought it useful to share here. Original code with issue:
$comment = "$_POST['comment']";
Because of the enclosing double-quotes, the index is not dereferenced properly leading to the assignment error. In my case I chose to fix it like this:
$comment = "$_POST[comment]";
but dropping either pair of quotes works; it's a matter of style I suppose :)
Default locations:
Programs > Microsoft SQL Server 2008 R2 > SQL Server Management Studio for Query Analyzer. Programs > Microsoft SQL Server 2008 R2 > Performance Tools > SQL Server Profiler for profiler.
I too had OpenJDK on my Ubuntu machine:
$ java -version
java version "1.7.0_51"
OpenJDK Runtime Environment (IcedTea 2.4.4) (7u51-2.4.4-0ubuntu0.13.04.2)
OpenJDK 64-Bit Server VM (build 24.45-b08, mixed mode)
Replacing OpenJDK with the HotSpot VM works fine:
sudo apt-get autoremove openjdk-7-jre-headless
You should use data.response
in your JS instead of json.response
.
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
The follow fix work for me
Windos server 2003 64 Reporting Services Windows Vista and Windows XP
Fix KB967511 and KB953752
http://support.microsoft.com/kb/967511/es
work for me
My solution was to add a UIView
with height of 20 points on top of the window when on iOS 7.
Then I created a method in my AppDelegate class to show/hide the "solid" status bar background. In application:didFinishLaunchingWithOptions:
:
// ...
// Add a status bar background
self.statusBarBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.window.bounds.size.width, 20.0f)];
self.statusBarBackground.backgroundColor = [UIColor blackColor];
self.statusBarBackground.alpha = 0.0;
self.statusBarBackground.userInteractionEnabled = NO;
self.statusBarBackground.layer.zPosition = 999; // Position its layer over all other views
[self.window addSubview:self.statusBarBackground];
// ...
return YES;
Then I created a method to fade in/out the black status bar background:
- (void) showSolidStatusBar:(BOOL) solidStatusBar
{
[UIView animateWithDuration:0.3f animations:^{
if(solidStatusBar)
{
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
self.statusBarBackground.alpha = 1.0f;
}
else
{
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
self.statusBarBackground.alpha = 0.0f;
}
}];
}
All I have to do now is call is [appDelegate showSolidStatusBar:YES]
when needed.