Why noy just use the theme styles in the table? i.e.
<table>
<thead class="ui-widget-header">
<tr>
<th>Id</th>
<th>Description</th>
</td>
</thead>
<tbody class="ui-widget-content">
<tr>
<td>...</td>
<td>...</td>
</tr>
.
.
.
</tbody>
</table>
And you don't need to use any code...
Yes, you can do it. An interface can extend multiple interfaces, as shown here:
interface Maininterface extends inter1, inter2, inter3 {
// methods
}
A single class can also implement multiple interfaces. What if two interfaces have a method defining the same name and signature?
There is a tricky point:
interface A {
void test();
}
interface B {
void test();
}
class C implements A, B {
@Override
public void test() {
}
}
Then single implementation works for both :).
Read my complete post here:
http://codeinventions.blogspot.com/2014/07/can-interface-extend-multiple.html
You could do this:
echo "<script>alert('Successfully Updated'); window.location = './edit.php';</script>";
You can also use regex.
let trimmedString = myString.stringByReplacingOccurrencesOfString("\\s", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil)
What you want to do is really important for unit testing. Basically you need to create a small local function in the view controller. Name the function anything, just include the performSegueWithIndentifier
.
func localFunc() {
println("we asked you to do it")
performSegueWithIdentifier("doIt", sender: self)
}
Next change your utility class FBManager
to include an initializer that takes an argument of a function and a variable to hold the ViewController's function that performs the segue.
public class UtilClass {
var yourFunction : () -> ()
init (someFunction: () -> ()) {
self.yourFunction = someFunction
println("initialized UtilClass")
}
public convenience init() {
func dummyLog () -> () {
println("no action passed")
}
self.init(dummyLog)
}
public func doThatThing() -> () {
// the facebook login function
println("now execute passed function")
self.yourFunction()
println("did that thing")
}
}
(The convenience init allows you to use this in unit testing without executing the segue.)
Finally, where you have //todo: segue to the next view???, put something along the lines of:
self.yourFunction()
In your unit tests, you can simply invoke it as:
let f = UtilClass()
f.doThatThing()
where doThatThing is your fbsessionstatechange and UtilClass
is FBManager.
For your actual code, just pass localFunc
(no parenthesis) to the FBManager class.
You can also use
$(document).ready(function() {
//some even that will run ajax request - for example click on a button
var uname = $('#username').val();
$.ajax({
type: 'POST',
url: 'func.php', //this should be url to your PHP file
dataType: 'html',
data: {func: 'toptable', user_id: uname},
beforeSend: function() {
$('#right').html('checking');
},
complete: function() {},
success: function(html) {
$('#right').html(html);
}
});
});
And your func.php:
function toptable()
{
echo 'something happens in here';
}
Hope it helps somebody
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
SOLVED: That's it!!!! For me was compiling with JDK6 but running Tomcat with JDK7, WST uses the system properties and not the eclipse settings. I also configure the same JDK Version in eclipse and in System (check it with java -version in cmd line)
Details: I try to configure eclipse like describe here, but it didn´t solve the problem, then I notice in eclipse´s error log that tomcat was started with jre 1.7. in spite of my configurations.
I also try, in cmd line, 'java -version' and obtained '1.7' instead of expected '1.6'.
I also decide to configure java 1.6 (like in eclipse) in system panel but it didn´t solve the problem. I also desinstall jre 1.7 restart eclipse AND IT SUCCESS!.. It was a very usefull clue, thank you.
ax.title.set_text('My Plot Title')
seems to work too.
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()
ALTER TABLE `0_ms_labdip_details` DROP INDEX column_tcx
Run this code in phpmyadmin and remove unique of column
For this particular purpose, $("span").show()
should be good enough.
The subquery is being run for each row because it is a correlated query. One can make a correlated query into a non-correlated query by selecting everything from the subquery, like so:
SELECT * FROM
(
SELECT relevant_field
FROM some_table
GROUP BY relevant_field
HAVING COUNT(*) > 1
) AS subquery
The final query would look like this:
SELECT *
FROM some_table
WHERE relevant_field IN
(
SELECT * FROM
(
SELECT relevant_field
FROM some_table
GROUP BY relevant_field
HAVING COUNT(*) > 1
) AS subquery
)
Those are different APIs to access a MySQL backend
So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...
My advice would be
Also my feeling, the mysql API would probably being deleted in future releases of PHP
.
For now no jquery or php needed. Use just "required" HTML5 input attrbute like here
<form>
<p>
<input class="form-control" type="text" name="email" />
<input type="submit" value="ok" class="btn btn-success" name="submit" />
<input type="hidden" name="action" value="0" />
</p>
<p><input type="checkbox" required name="terms">I have read and accept <a href="#">SOMETHING Terms and Conditions</a></p>
</form>
This will validate and prevent any submit before checkbox is opt in. Language independent solution because its generated by users web browser.
And if you want to create the list with some elements to start with:
var emailList = new List<EmailData>
{
new EmailData { FirstName = "John", LastName = "Doe", Location = "Moscow" },
new EmailData {.......}
};
This worked for me.
using System.IO;
//
string readStr = File.ReadAllText(file.FullName);
string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);
<asp:Panel ID="Panel2" runat="server" DefaultButton="bttxt">
<telerik:RadNumericTextBox ID="txt" runat="server">
</telerik:RadNumericTextBox>
<asp:LinkButton ID="bttxt" runat="server" Style="display: none;" OnClick="bttxt_Click" />
</asp:Panel>
protected void txt_TextChanged(object sender, EventArgs e)
{
//enter code here
}
Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:
WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
SELECT tableA.Id, COUNT(tableC.Id)
FROM tableC
RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
CompanyImageUrl,NumberOfUsers) AS (
SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
FROM tableA
INNER JOIN tableB ON tableB.Id = tableA.Owner
RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id
After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.
::-webkit-input-placeholder { /* WebKit browsers */
color: #999;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
color: #999;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
color: #999;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
color: #999;
}
I found this plugin to be doing what I was expecting: gulp-using
Simple usage example: Search all files in project with .jsx extension
gulp.task('reactify', function(){
gulp.src(['../**/*.jsx'])
.pipe(using({}));
....
});
Output:
[gulp] Using gulpfile /app/build/gulpfile.js
[gulp] Starting 'reactify'...
[gulp] Finished 'reactify' after 2.92 ms
[gulp] Using file /app/staging/web/content/view/logon.jsx
[gulp] Using file /app/staging/web/content/view/components/rauth.jsx
graphics.h
appears to something once bundled with Borland and/or Turbo C++, in the 90's.
http://www.daniweb.com/software-development/cpp/threads/17709/88149#post88149
It's unlikely that you will find any support for that file with modern compiler. For other graphics libraries check the list of "related" questions (questions related to this one). E.g., "A Simple, 2d cross-platform graphics library for c or c++?".
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.
Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.
First, click Slide Show > Set Up Show.
Put a checkmark to Loop continuously until 'Esc'.
Click Ok. Now, Click Slide Show > Custom Shows. Click New.
Select the slide you are looping, click Add. Click Ok and Close.
Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.
Right click on the thumbnail of the current slide, select Hide Slide.
Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"
This has worked for me.
If the frames are going to be the same size, why not create the frame and pass the frame then as a reference to it instead.
When you have passed the frame you can then decide how to populate it. It would be like having a method for calculating the average of a set of figures. Would you create the method over and over again?
For styling each directional arrows(left, right,top and bottom), we have to select each arrow using CSS attribute selector and then style them individually.
Trick: Top arrow must have border color only on top side and transparent on other 3 sides. Other directional arrows also need to be styled this way.
click here for Working Jsfiddle Link
Here is the simple CSS,
.tooltip-inner { background-color:#8447cf;}
[data-placement="top"] + .tooltip > .tooltip-arrow { border-top-color: #8447cf;}
[data-placement="right"] + .tooltip > .tooltip-arrow { border-right-color: #8447cf;}
[data-placement="bottom"] + .tooltip > .tooltip-arrow {border-bottom-color: #8447cf;}
[data-placement="left"] + .tooltip > .tooltip-arrow {border-left-color: #8447cf; }
You can try this script. :)
<html>
<head>
<title>Div BG color</title>
<script type="text/javascript">
function Off(idecko)
{
document.getElementById(idecko).style.background="rgba(0,0,0,0)"; <!--- Default --->
}
function cOn(idecko)
{
document.getElementById(idecko).style.background="rgb(0,60,255)"; <!--- New content color --->
}
function hOn(idecko)
{
document.getElementById(idecko).style.background="rgb(60,255,0)"; <!--- New h2 color --->
}
</script>
</head>
<body>
<div id="catestory">
<div class="content" id="myid1" onmouseover="cOn('myid1'); hOn('h21')" onmouseout="Off('myid1'); Off('h21')">
<h2 id="h21">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid2" onmouseover="cOn('myid2'); hOn('h22')" onmouseout="Off('myid2'); Off('h22')">
<h2 id="h22">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid3" onmouseover="cOn('myid3'); hOn('h23')" onmouseout="Off('myid3'); Off('h23')">
<h2 id="h23">some title here</h2>
<p>some content here</p>
</div>
</div>
</body>
<html>
I do it with boolean = !boolean;
std::atomic
exists because many ISAs have direct hardware support for it
What the C++ standard says about std::atomic
has been analyzed in other answers.
So now let's see what std::atomic
compiles to to get a different kind of insight.
The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic
basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.
This support allows for faster alternatives to more general methods such as std::mutex
, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic
because std::mutex
it makes futex
system calls in Linux, which is way slower than the userland instructions emitted by std::atomic
, see also: Does std::mutex create a fence?
Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.
main.cpp
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
size_t niters;
#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif
void threadMain() {
for (size_t i = 0; i < niters; ++i) {
#if LOCK
__asm__ __volatile__ (
"lock incq %0;"
: "+m" (global),
"+g" (i) // to prevent loop unrolling
:
:
);
#else
__asm__ __volatile__ (
""
: "+g" (i) // to prevent he loop from being optimized to a single add
: "g" (global)
:
);
global++;
#endif
}
}
int main(int argc, char **argv) {
size_t nthreads;
if (argc > 1) {
nthreads = std::stoull(argv[1], NULL, 0);
} else {
nthreads = 2;
}
if (argc > 2) {
niters = std::stoull(argv[2], NULL, 0);
} else {
niters = 10;
}
std::vector<std::thread> threads(nthreads);
for (size_t i = 0; i < nthreads; ++i)
threads[i] = std::thread(threadMain);
for (size_t i = 0; i < nthreads; ++i)
threads[i].join();
uint64_t expect = nthreads * niters;
std::cout << "expect " << expect << std::endl;
std::cout << "global " << global << std::endl;
}
Compile, run and disassemble:
comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out -DLOCK $common
./main_fail.out 4 100000
./main_std_atomic.out 4 100000
./main_lock.out 4 100000
gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out
Extremely likely "wrong" race condition output for main_fail.out
:
expect 400000
global 100000
and deterministic "right" output of the others:
expect 400000
global 400000
Disassembly of main_fail.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: mov 0x29b5(%rip),%rcx # 0x5140 <niters>
0x000000000000278b <+11>: test %rcx,%rcx
0x000000000000278e <+14>: je 0x27b4 <threadMain()+52>
0x0000000000002790 <+16>: mov 0x29a1(%rip),%rdx # 0x5138 <global>
0x0000000000002797 <+23>: xor %eax,%eax
0x0000000000002799 <+25>: nopl 0x0(%rax)
0x00000000000027a0 <+32>: add $0x1,%rax
0x00000000000027a4 <+36>: add $0x1,%rdx
0x00000000000027a8 <+40>: cmp %rcx,%rax
0x00000000000027ab <+43>: jb 0x27a0 <threadMain()+32>
0x00000000000027ad <+45>: mov %rdx,0x2984(%rip) # 0x5138 <global>
0x00000000000027b4 <+52>: retq
Disassembly of main_std_atomic.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a6 <threadMain()+38>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock addq $0x1,0x299f(%rip) # 0x5138 <global>
0x0000000000002799 <+25>: add $0x1,%rax
0x000000000000279d <+29>: cmp %rax,0x299c(%rip) # 0x5140 <niters>
0x00000000000027a4 <+36>: ja 0x2790 <threadMain()+16>
0x00000000000027a6 <+38>: retq
Disassembly of main_lock.out
:
Dump of assembler code for function threadMain():
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a5 <threadMain()+37>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock incq 0x29a0(%rip) # 0x5138 <global>
0x0000000000002798 <+24>: add $0x1,%rax
0x000000000000279c <+28>: cmp %rax,0x299d(%rip) # 0x5140 <niters>
0x00000000000027a3 <+35>: ja 0x2790 <threadMain()+16>
0x00000000000027a5 <+37>: retq
Conclusions:
the non-atomic version saves the global to a register, and increments the register.
Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000
.
std::atomic
compiles to lock addq
. The LOCK prefix makes the following inc
fetch, modify and update memory atomically.
our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic
, except that our inc
is used instead of add
. Not sure why GCC chose add
, considering that our INC generated a decoding 1 byte smaller.
ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?
Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.
Did you try cal.getTime()
? This gets the date representation.
You might also want to look at the javadoc.
You are referring to the section "2.3.5 Deploying the demo app" of this "Ruby on Rails Tutorial ":
In section 2.3.1 Planning the application, note that they did:
$ git remote add origin [email protected]:<username>/demo_app.git
$ git push origin master
That is why a simple git push
worked (using here an ssh address).
Did you follow that step and made that first push?
www.github.com/levelone/demo_app
wouldn't be a writable URI for pushing to a GitHub repo.
https://[email protected]/levelone/demo_app.git
should be more appropriate.
Check what git remote -v returns, and if you need to replace the remote address, as described in GitHub help page, use git remote --set-url
.
git remote set-url origin https://[email protected]/levelone/demo_app.git
or
git remote set-url origin [email protected]:levelone/demo_app.git
With the command:
sudo apt-get remove --purge mysql\*
you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).
You can list all installed mysql packages with the command:
sudo dpkg -l | grep -i mysql
For more cleanup of the package cache, you can use the command:
sudo apt-get clean
Also, remember to use the command:
sudo updatedb
Otherwise the "locate" command will display old data.
To install mysql again, use the following command:
sudo apt-get install libmysqlclient-dev mysql-client
This will install the mysql client, libmysql and its headers files.
To install the mysql server, use the command:
sudo apt-get install mysql-server
Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
To use it, simply do something like this:
var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);
The var alteredURL
will be the output you desire.
Hope it helps!
If you have VS 2013, you have to go to: %LOCALAPPDATA%\Microsoft\VisualStudio\12.0 then rename the ComponentModelCache folder.
OK - I had the same problem. I didn't want to use "config.assets.compile = true" - I had to add all of my .css files to the list in config/environments/production.rb:
config.assets.precompile += %w( carts.css )
Then I had to create (and later delete) tmp/restart.txt
I consistently used the stylesheet_link_tag helper, so I found all the extra css files I needed to add with:
find . \( -type f -o -type l \) -exec grep stylesheet_link_tag {} /dev/null \;
from ittoolbox blogs.
The following outlines the similarities and differences to past design techniques:
• SOA versus Structured Programming o Similarities: Most similar to subroutine calls where parameters are passed and the operation of the function is abstracted from the caller - e.g. CICS link and execute and the COBOL CALL reserved word. Copybooks are used to define data structure which is typically defined as an XML schema for services. o Differences: SOA is loosely coupled implying changes to a service have less impact to the consumer (the "calling" program) and services are interoperable across languages and platforms.
• SOA versus OOA/OOD o Similarities: Encapsulation, Abstraction and Defined Interfaces o Differences: SOA is loosely coupled with no class hierarchy or inheritance, Low-level abstractions - class level versus business service
• SOA versus legacy Component Based Development (CBD) - e.g. CORBA, DCOM, EJB o Similarities: Reuse through assembling components, Interfaces, Remote calls o Differences: Wide adoption of standards, XML Schemas vs. Marshaled Objects, Service Orchestration, Designing for reuse is easier, services are business focused vs. IT focused, business services are course grained (broad in scope)
• SOA (for integration) versus Enterprise Application Integration (EAI) o Similarities: Best practices (well defined interfaces, standardized schemas, event driven architecture), reusable interfaces, common schemas o Differences: Standards, adoption, and improved tools
Another way to change color of a button if you want to do multiple operations along with color change. Using the Tk().after
method and binding a change method allows you to change color and do other operations.
Label.destroy
is another example of the after method.
def export_win():
//Some Operation
orig_color = export_finding_graph.cget("background")
export_finding_graph.configure(background = "green")
tt = "Exported"
label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)
def change(orig_color):
export_finding_graph.configure(background = orig_color)
tab1_closed_observations.after(1000, lambda: change(orig_color))
tab1_closed_observations.after(500, label.destroy)
export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)
You can also revert to the original color.
To remove a specific container
docker rm CONTAINER_ID CONTAINER_ID
For single image
docker rm 70c0e19168cf
For multiple images
docker rm 70c0e19168cf c2ce80b62174
Remove exited containers
docker ps -a -f status=exited
Remove all the containers
docker ps -q -a | xargs docker rm
docker rmi IMAGE_ID
Remove specific images
for single image
docker rmi ubuntu
for multiple images
docker rmi ubuntu alpine
Remove dangling images
Dangling images are layers that have no relationship to any tagged images as the Docker images are constituted of multiple images.
docker rmi -f $(docker images -f dangling=true -q)
Remove all Docker images
docker rmi -f $(docker images -a -q)
To list volumes, run docker volume ls
Remove a specific volume
docker volume rm VOLUME_NAME
Remove dangling volumes
docker volume rm $(docker volume ls -f dangling=true -q)
Remove a container and its volumes
docker rm -v CONTAINER_NAME
select project to delete->settings->buttom click delete button->enter name of the repositories
MySQL is most likely in STRICT
mode, which isn't necessarily a bad thing, as you'll identify bugs/issues early and not just blindly think everything is working as you intended.
Change the column to allow null:
ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NULL
or, give it a default value as empty string:
ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NOT NULL DEFAULT ''
Have you tried overflow-y:auto
? It is not exactly what you want, as the scrollbar will appear only when needed.
You can also use the "timestamp" data type where it just needs "dd-mm-yyyy"
Like:
insert into emp values('12-12-2012');
considering there is just one column in the table... You can adjust the insertion values according to your table.
The following works in MVC5:
document.getElementById('theID').value = 'new value';
String s = "a.b.c.d";
int charCount = s.length() - s.replaceAll("\\.", "").length();
ReplaceAll(".") would replace all characters.
PhiLho's solution uses ReplaceAll("[^.]",""), which does not need to be escaped, since [.] represents the character 'dot', not 'any character'.
the "problem view" mentioned in previous answers was helpful, but i saw it didn't catch all the errors in project. After running application, it began populating other classes that had issues but didn't appear at first in that problems view.
For Ubuntu on HP (Intel processors),
Press F10 on booting the system, it will enter into system setup mode.
You will find tabs on top like Main, Security, Advanced.
Go into Advanced >> and click on System settings.
Mark the check boxes on Enable Virtualization Technology (VTx) and Virtualization Technology Directed I/O (VTd).
Back to Main, click on save changes and exit.
Try to check this free an open source alternative https://www.nuget.org/packages/AIM It is free to use and open source and uses the exact same way that System.Net.Mail is using To send email to implicit ssl ports you can use following code
public static void SendMail()
{
var mailMessage = new MimeMailMessage();
mailMessage.Subject = "test mail";
mailMessage.Body = "hi dude!";
mailMessage.Sender = new MimeMailAddress("[email protected]", "your name");
mailMessage.To.Add(new MimeMailAddress("[email protected]", "your friendd's name"));
// You can add CC and BCC list using the same way
mailMessage.Attachments.Add(new MimeAttachment("your file address"));
//Mail Sender (Smtp Client)
var emailer = new SmtpSocketClient();
emailer.Host = "your mail server address";
emailer.Port = 465;
emailer.SslType = SslMode.Ssl;
emailer.User = "mail sever user name";
emailer.Password = "mail sever password" ;
emailer.AuthenticationMode = AuthenticationType.Base64;
// The authentication types depends on your server, it can be plain, base 64 or none.
//if you do not need user name and password means you are using default credentials
// In this case, your authentication type is none
emailer.MailMessage = mailMessage;
emailer.OnMailSent += new SendCompletedEventHandler(OnMailSent);
emailer.SendMessageAsync();
}
// A simple call back function:
private void OnMailSent(object sender, AsyncCompletedEventArgs asynccompletedeventargs)
{
if (e.UserState!=null)
Console.Out.WriteLine(e.UserState.ToString());
if (e.Error != null)
{
MessageBox.Show(e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (!e.Cancelled)
{
MessageBox.Show("Send successfull!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
This is how you do if/else in Mustache (perfectly supported):
{{#repo}}
<b>{{name}}</b>
{{/repo}}
{{^repo}}
No repos :(
{{/repo}}
Or in your case:
{{#author}}
{{#avatar}}
<img src="{{avatar}}"/>
{{/avatar}}
{{^avatar}}
<img src="/images/default_avatar.png" height="75" width="75" />
{{/avatar}}
{{/author}}
Look for inverted sections in the docs: https://github.com/janl/mustache.js
I just uninstalled my Java8 update and tried again. It worked ok!
Yes you can do so and I have created a library for the same.
This allows you to connect up-to four devices to the main server device creating different channels for each client and running interactions on different threads.
To use this library simple add compile com.mdg.androble:library:0.1.2
in dependency section of your build.gradl
e .
In Android Studio, Click on 'Tools' on the top tab bar of android studio
Tools >> Android >> SDK Manager >> Launch Standalone Sdk manager
there you can clearly see which platform tool is missing , then just install that and your adb will start working properly.
Fully install at-least one Api package (Android Api 23 or 24) .
Here is another choice: Chaosreader
So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...
The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/
It worked like a treat, I did the following:
tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile
For anyone stumbling across this question that is not on a Mac: assuming you know that your server is running on port 3000, you can do this in one shot by executing the following:
fuser -k 3000/tcp
But as Toby has mentioned, the implementation of fuser in Mac OS is rather primitive and this command will not work on mac.
For someone who lands to this question. Using pandas with ‘chunksize’ and ‘usecols’ helped me to read a huge zip file faster than the other proposed options.
import pandas as pd
sample_cols_to_keep =['col_1', 'col_2', 'col_3', 'col_4','col_5']
# First setup dataframe iterator, ‘usecols’ parameter filters the columns, and 'chunksize' sets the number of rows per chunk in the csv. (you can change these parameters as you wish)
df_iter = pd.read_csv('../data/huge_csv_file.csv.gz', compression='gzip', chunksize=20000, usecols=sample_cols_to_keep)
# this list will store the filtered dataframes for later concatenation
df_lst = []
# Iterate over the file based on the criteria and append to the list
for df_ in df_iter:
tmp_df = (df_.rename(columns={col: col.lower() for col in df_.columns}) # filter eg. rows where 'col_1' value grater than one
.pipe(lambda x: x[x.col_1 > 0] ))
df_lst += [tmp_df.copy()]
# And finally combine filtered df_lst into the final lareger output say 'df_final' dataframe
df_final = pd.concat(df_lst)
If you have just a couple of shared preferences to clear, then this solution is much nicer.
@Override
protected void setUp() throws Exception {
super.setUp();
Instrumentation instrumentation = getInstrumentation();
SharedPreferences preferences = instrumentation.getTargetContext().getSharedPreferences(...), Context.MODE_PRIVATE);
preferences.edit().clear().commit();
solo = new Solo(instrumentation, getActivity());
}
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
I had to use this after the flush to get the last insert id:
$em->persist($user);
$em->flush();
$user->getId();
HashMap has initial capacity and HashMap's performance very very depends on hashCode that produce underlying objects.
Try to tweak both.
I do this is a bunch of my apps and I use a statement like this:
var inputDirectory = new DirectoryInfo("\\Directory_Path_here");
var myFile = inputDirectory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();
From here you will have the filename for the most recently saved/added/updated file in the Directory of the "inputDirectory" variable. Now you can access it and do what you want with it.
Hope that helps.
This should do the work:
.category_table tr:first-child td {
vertical-align: top;
}
The following from the msdn site should I think help provide some native functionality for what you are looking for. Please note it is specified for Windows 8. One such example from the site is listed below.
JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
double width = jsonValue.GetObject().GetNamedNumber("Width");
double height = jsonValue.GetObject().GetNamedNumber("Height");
string title = jsonValue.GetObject().GetNamedString("Title");
JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");
It utilizes the Windows.Data.JSON namespace.
I'm happy to add Moo as an option, although clearly I'm biased towards it: http://geoffreywiseman.github.com/Moo/
It's very easy to use for simple cases, reasonable capable for more complex cases, although there are still some areas where I can imagine enhancing it for even further complexities.
Step 1: Open "Maven Projects"
Step 2: Select the project you want to import:
Shnugo's answer is the ONLY one that works in Azure with Externa Tables. (1) Azure SQL doesn't support sp_MSforeachtable at all and (2) rows in sys.partitions for an External table is always 0.
You want the CASE
statement:
SELECT
CASE
WHEN @SelectField1 = 1 THEN Field1
WHEN @SelectField2 = 1 THEN Field2
ELSE NULL
END AS NewField
FROM Table
EDIT: My example is for combining the two fields into one field, depending on the parameters supplied. It is a one-or-neither solution (not both). If you want the possibility of having both fields in the output, use Quassnoi's solution.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void Decimal2Binary(long value,char *b,int len)
{
if(value>0)
{
do
{
if(value==1)
{
*(b+len-1)='1';
break;
}
else
{
*(b+len-1)=(value%2)+48;
value=value/2;
len--;
}
}while(1);
}
}
long Binary2Decimal(char *b,int len)
{
int i=0;
int j=0;
long value=0;
for(i=(len-1);i>=0;i--)
{
if(*(b+i)==49)
{
value+=pow(2,j);
}
j++;
}
return value;
}
int main()
{
char data[11];//????BIT????????
long value=1023;
memset(data,'0',sizeof(data));
data[10]='\0';//????
Decimal2Binary(value,data,10);
printf("%d->%s\n",value,data);
value=Binary2Decimal(data,10);
printf("%s->%d",data,value);
return 0;
}
Personally, I took the strangeness of the Java calendar API as an indication that I needed to divorce myself from the Gregorian-centric mindset and try to program more agnostically in that respect. Specifically, I learned once again to avoid hardcoded constants for things like months.
Which of the following is more likely to be correct?
if (date.getMonth() == 3) out.print("March");
if (date.getMonth() == Calendar.MARCH) out.print("March");
This illustrates one thing that irks me a little about Joda Time - it may encourage programmers to think in terms of hardcoded constants. (Only a little, though. It's not as if Joda is forcing programmers to program badly.)
Here's one explanation:
Once a socket is no longer required, the calling program can discard the socket by applying a close subroutine to the socket descriptor. If a reliable delivery socket has data associated with it when a close takes place, the system continues to attempt data transfer. However, if the data is still undelivered, the system discards the data. Should the application program have no use for any pending data, it can use the shutdown subroutine on the socket prior to closing it.
Use constraints with visual format and you get respect for the safe area for free.
class ViewController: UIViewController {
var greenView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
greenView.backgroundColor = .green
view.addSubview(greenView)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
greenView.translatesAutoresizingMaskIntoConstraints = false
let views : [String:Any] = ["greenView":greenView]
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[greenView]-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[greenView]-|", options: [], metrics: nil, views: views))
}
}
An alternative solution would be to use the Url
helper object to set the href
attribute of an <a>
tag like:
<a href="@Url.Action("Details", "Product",new { id=item.ID }) )">Details</a>
you can enter the jdk path required as th full path for java.exe in sql developer for oracle 11g.
I found the jdk at the following path in my system.
c:\app\sony\product\11.0.0\db_1\jdk
You can use this small library: https://github.com/ledfusion/php-rest-curl
Making a call is as simple as:
// GET
$result = RestCurl::get($URL, array('id' => 12345678));
// POST
$result = RestCurl::post($URL, array('name' => 'John'));
// PUT
$result = RestCurl::put($URL, array('$set' => array('lastName' => "Smith")));
// DELETE
$result = RestCurl::delete($URL);
And for the $result variable:
Hope it helps
hey dominic your answer was nice but if your have a site like http://localhost/project/index.php the 'project' link gets repeated since it's part of $base and also appears in the $path array. So I tweaked and removed the first item in the $path array.
//Trying to remove the first item in the array path so it doesn't repeat
array_shift($path);
I dont know if that is the most elegant way, but it now works for me.
I add that code before this one on line 13 or something
// Find out the index for the last value in our path array
$last = end(array_keys($path));
Easiest: http://www.addthis.com/
Best? Well. probably not, But If you don't want to design something bespoke this is the best there is...
Thanks for everyone who answered, and thanks for those who gave me the function-format idea, i'll really study it for future using.
But for this explicit case, the 'special yyyymm field' is not to be considered as a date field, but just as a tag, o whatever would be used for matching the exactly year-month researched value; there is already another date field, with the full timestamp, but if i need all the rows of january 2008, i think that is faster a select like
SELECT [columns] FROM table WHERE yearmonth = '200801'
instead of
SELECT [columns] FROM table WHERE date BETWEEN DATE('2008-01-01') AND DATE('2008-01-31')
You have to use @BotFather, send it command: /setjoingroups There will be dialog like this:
YOU: /setjoingroups
BotFather: Choose a bot to change group membership settings.
YOU: @YourBot
BotFather: 'Enable' - bot can be added to groups. 'Disable' - block group invitations, the bot can't be added to groups. Current status is: DISABLED
YOU: Enable
BotFather: Success! The new status is: ENABLED.
After this you will see button "Add to Group" in your bot's profile.
updated on May 26-2018
If the external library is in a folder that is under the project then
File -> Settings -> Project -> Project structure -> select the folder and Mark as Sources!
If not, add content root, and do similar things.
How to address your textbox depends on the HTML-code:
<!-- 1 --><input type="textbox" id="Tue" />
<!-- 2 --><input type="textbox" name="Tue" />
If you use the 'id' attribute:
var textbox = document.getElementById('Tue');
for 'name':
var textbox = document.getElementsByName('Tue')[0]
(Note that getElementsByName() returns all elements with the name as array, therefore we use [0] to access the first one)
Then, use the 'value' attribute:
textbox.value = 'Foobar';
You need to use WITH ROLLBACK IMMEDIATE
to boot other conections out with no regards to what or who is is already using it.
Or use WITH NO_WAIT
to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details
When Using let
The let
keyword attaches the variable declaration to the scope of whatever block (commonly a { .. }
pair) it's contained in. In other words,let
implicitly hijacks any block's scope for its variable declaration.
let
variables cannot be accessed in the window
object because they cannot be globally accessed.
function a(){
{ // this is the Max Scope for let variable
let x = 12;
}
console.log(x);
}
a(); // Uncaught ReferenceError: x is not defined
When Using var
var
and variables in ES5 has scopes in functions meaning the variables are valid within the function and not outside the function itself.
var
variables can be accessed in the window
object because they cannot be globally accessed.
function a(){ // this is the Max Scope for var variable
{
var x = 12;
}
console.log(x);
}
a(); // 12
If you want to know more continue reading below
one of the most famous interview questions on scope also can suffice the exact use of let
and var
as below;
When using let
for (let i = 0; i < 10 ; i++) {
setTimeout(
function a() {
console.log(i); //print 0 to 9, that is literally AWW!!!
},
100 * i);
}
This is because when using let
, for every loop iteration the variable is scoped and has its own copy.
When using var
for (var i = 0; i < 10 ; i++) {
setTimeout(
function a() {
console.log(i); //print 10 times 10
},
100 * i);
}
This is because when using var
, for every loop iteration the variable is scoped and has shared copy.
Have you tried running the code in the Page_Load() method?
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "test";
if (Request.QueryString["ID"] != null)
{
string test = Request.QueryString["ID"];
Label1.Text = "Du har nu lånat filmen:" + test;
}
}
The modulus operator. The remainder when you divide two number.
For Example:
>>> 5 % 2 = 1 # remainder of 5 divided by 2 is 1
>>> 7 % 3 = 1 # remainer of 7 divided by 3 is 1
>>> 3 % 1 = 0 # because 1 divides evenly into 3
Within PowerShell ISE you can hit Ctrl+J to open the Start Snipping menu and select Comment block:
Your code:
rules: {
phoneNumber: {
matches: "[0-9]+", // <-- no such method called "matches"!
minlength:10,
maxlength:10
}
}
There is no such callback function, option, method, or rule called matches
anywhere within the jQuery Validate plugin. (EDIT: OP failed to mention that matches
is his custom method.)
However, within the additional-methods.js
file, there are several phone number validation methods you can use. The one called phoneUS
should satisfy your pattern. Since the rule already validates the length, minlength
and maxlength
are redundantly unnecessary. It's also much more comprehensive in that area codes and prefixes can not start with a 1
.
rules: {
phoneNumber: {
phoneUS: true
}
}
DEMO: http://jsfiddle.net/eWhkv/
If, for whatever reason, you just need the regex for use in another method, you can take it from here...
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(\+?1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
If the modulus is a power of 2 then you can use a bitmask:
int i = -1 & ~-2; // -1 MOD 2 is 1
By comparison the Pascal language provides two operators; REM takes the sign of the numerator (x REM y
is x - (x DIV y) * y
where x DIV y
is TRUNC(x / y)
) and MOD requires a positive denominator and returns a positive result.
With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
class SampleController extends Controller
{
public function indexAction(Request $request) {
var_dump($request->request->all());
}
}
Edittext edittext = (EditText)findViewById(R.id.edit);
edittext.setEnabled(false);
None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.
The right way to select Alaska and have the select show the right item as selected using:
<select id="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
With jquery would be:
$('#state').val('AK').change();
I recommend you to read more about the this keyword.
You cannot expect "this" to select the "select" tag in this case.
What you want to do in this case is use obj.id
to get the id of select tag.
Try this:
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)
it is API Level 1, check the link.
I know this is not typical alert box, but I hope it may help someone.
There is this expansion that enables you to show notifications inside HTML page using bootstrap.
It is very easy to implement and it works fine. Here is a github page for the project including some demo images.
This works for me. It will get you both dist-packages and site-packages folders. If the folder is not on Python's path, it won't be doing you much good anyway.
import sys;
print [f for f in sys.path if f.endswith('packages')]
Output (Ubuntu installation):
['/home/username/.local/lib/python2.7/site-packages',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages']
It's all about the linkage.
The previous answers provided good explainations about extern
.
But I want to add an important point.
You ask about extern
in C++ not in C and I don't know why there is no answer mentioning about the case when extern
comes with const
in C++.
In C++, a const
variable has internal linkage by default (not like C).
So this scenario will lead to linking error:
Source 1 :
const int global = 255; //wrong way to make a definition of global const variable in C++
Source 2 :
extern const int global; //declaration
It need to be like this:
Source 1 :
extern const int global = 255; //a definition of global const variable in C++
Source 2 :
extern const int global; //declaration
//slightly improved code without using collection framework
package com.test;
public class TestClass {
private static Link last;
private static Link first;
public static void main(String[] args) {
//Inserting
for(int i=0;i<5;i++){
Link.insert(i+5);
}
Link.printList();
//Deleting
Link.deletefromFirst();
Link.printList();
}
protected static class Link {
private int data;
private Link nextlink;
public Link(int d1) {
this.data = d1;
}
public static void insert(int d1) {
Link a = new Link(d1);
a.nextlink = null;
if (first != null) {
last.nextlink = a;
last = a;
} else {
first = a;
last = a;
}
System.out.println("Inserted -:"+d1);
}
public static void deletefromFirst() {
if(null!=first)
{
System.out.println("Deleting -:"+first.data);
first = first.nextlink;
}
else{
System.out.println("No elements in Linked List");
}
}
public static void printList() {
System.out.println("Elements in the list are");
System.out.println("-------------------------");
Link temp = first;
while (temp != null) {
System.out.println(temp.data);
temp = temp.nextlink;
}
}
}
}
function isNotANumber(n) {_x000D_
if (typeof n !== 'number') {_x000D_
return true;_x000D_
} _x000D_
return n !== n;_x000D_
}
_x000D_
Clearly there are lots of different ways of getting the same results, your question seems to be what is an efficient way of getting the last results in each group in MySQL. If you are working with huge amounts of data and assuming you are using InnoDB with even the latest versions of MySQL (such as 5.7.21 and 8.0.4-rc) then there might not be an efficient way of doing this.
We sometimes need to do this with tables with even more than 60 million rows.
For these examples I will use data with only about 1.5 million rows where the queries would need to find results for all groups in the data. In our actual cases we would often need to return back data from about 2,000 groups (which hypothetically would not require examining very much of the data).
I will use the following tables:
CREATE TABLE temperature(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
groupID INT UNSIGNED NOT NULL,
recordedTimestamp TIMESTAMP NOT NULL,
recordedValue INT NOT NULL,
INDEX groupIndex(groupID, recordedTimestamp),
PRIMARY KEY (id)
);
CREATE TEMPORARY TABLE selected_group(id INT UNSIGNED NOT NULL, PRIMARY KEY(id));
The temperature table is populated with about 1.5 million random records, and with 100 different groups. The selected_group is populated with those 100 groups (in our cases this would normally be less than 20% for all of the groups).
As this data is random it means that multiple rows can have the same recordedTimestamps. What we want is to get a list of all of the selected groups in order of groupID with the last recordedTimestamp for each group, and if the same group has more than one matching row like that then the last matching id of those rows.
If hypothetically MySQL had a last() function which returned values from the last row in a special ORDER BY clause then we could simply do:
SELECT
last(t1.id) AS id,
t1.groupID,
last(t1.recordedTimestamp) AS recordedTimestamp,
last(t1.recordedValue) AS recordedValue
FROM selected_group g
INNER JOIN temperature t1 ON t1.groupID = g.id
ORDER BY t1.recordedTimestamp, t1.id
GROUP BY t1.groupID;
which would only need to examine a few 100 rows in this case as it doesn't use any of the normal GROUP BY functions. This would execute in 0 seconds and hence be highly efficient. Note that normally in MySQL we would see an ORDER BY clause following the GROUP BY clause however this ORDER BY clause is used to determine the ORDER for the last() function, if it was after the GROUP BY then it would be ordering the GROUPS. If no GROUP BY clause is present then the last values will be the same in all of the returned rows.
However MySQL does not have this so let's look at different ideas of what it does have and prove that none of these are efficient.
Example 1
SELECT t1.id, t1.groupID, t1.recordedTimestamp, t1.recordedValue
FROM selected_group g
INNER JOIN temperature t1 ON t1.id = (
SELECT t2.id
FROM temperature t2
WHERE t2.groupID = g.id
ORDER BY t2.recordedTimestamp DESC, t2.id DESC
LIMIT 1
);
This examined 3,009,254 rows and took ~0.859 seconds on 5.7.21 and slightly longer on 8.0.4-rc
Example 2
SELECT t1.id, t1.groupID, t1.recordedTimestamp, t1.recordedValue
FROM temperature t1
INNER JOIN (
SELECT max(t2.id) AS id
FROM temperature t2
INNER JOIN (
SELECT t3.groupID, max(t3.recordedTimestamp) AS recordedTimestamp
FROM selected_group g
INNER JOIN temperature t3 ON t3.groupID = g.id
GROUP BY t3.groupID
) t4 ON t4.groupID = t2.groupID AND t4.recordedTimestamp = t2.recordedTimestamp
GROUP BY t2.groupID
) t5 ON t5.id = t1.id;
This examined 1,505,331 rows and took ~1.25 seconds on 5.7.21 and slightly longer on 8.0.4-rc
Example 3
SELECT t1.id, t1.groupID, t1.recordedTimestamp, t1.recordedValue
FROM temperature t1
WHERE t1.id IN (
SELECT max(t2.id) AS id
FROM temperature t2
INNER JOIN (
SELECT t3.groupID, max(t3.recordedTimestamp) AS recordedTimestamp
FROM selected_group g
INNER JOIN temperature t3 ON t3.groupID = g.id
GROUP BY t3.groupID
) t4 ON t4.groupID = t2.groupID AND t4.recordedTimestamp = t2.recordedTimestamp
GROUP BY t2.groupID
)
ORDER BY t1.groupID;
This examined 3,009,685 rows and took ~1.95 seconds on 5.7.21 and slightly longer on 8.0.4-rc
Example 4
SELECT t1.id, t1.groupID, t1.recordedTimestamp, t1.recordedValue
FROM selected_group g
INNER JOIN temperature t1 ON t1.id = (
SELECT max(t2.id)
FROM temperature t2
WHERE t2.groupID = g.id AND t2.recordedTimestamp = (
SELECT max(t3.recordedTimestamp)
FROM temperature t3
WHERE t3.groupID = g.id
)
);
This examined 6,137,810 rows and took ~2.2 seconds on 5.7.21 and slightly longer on 8.0.4-rc
Example 5
SELECT t1.id, t1.groupID, t1.recordedTimestamp, t1.recordedValue
FROM (
SELECT
t2.id,
t2.groupID,
t2.recordedTimestamp,
t2.recordedValue,
row_number() OVER (
PARTITION BY t2.groupID ORDER BY t2.recordedTimestamp DESC, t2.id DESC
) AS rowNumber
FROM selected_group g
INNER JOIN temperature t2 ON t2.groupID = g.id
) t1 WHERE t1.rowNumber = 1;
This examined 6,017,808 rows and took ~4.2 seconds on 8.0.4-rc
Example 6
SELECT t1.id, t1.groupID, t1.recordedTimestamp, t1.recordedValue
FROM (
SELECT
last_value(t2.id) OVER w AS id,
t2.groupID,
last_value(t2.recordedTimestamp) OVER w AS recordedTimestamp,
last_value(t2.recordedValue) OVER w AS recordedValue
FROM selected_group g
INNER JOIN temperature t2 ON t2.groupID = g.id
WINDOW w AS (
PARTITION BY t2.groupID
ORDER BY t2.recordedTimestamp, t2.id
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
)
) t1
GROUP BY t1.groupID;
This examined 6,017,908 rows and took ~17.5 seconds on 8.0.4-rc
Example 7
SELECT t1.id, t1.groupID, t1.recordedTimestamp, t1.recordedValue
FROM selected_group g
INNER JOIN temperature t1 ON t1.groupID = g.id
LEFT JOIN temperature t2
ON t2.groupID = g.id
AND (
t2.recordedTimestamp > t1.recordedTimestamp
OR (t2.recordedTimestamp = t1.recordedTimestamp AND t2.id > t1.id)
)
WHERE t2.id IS NULL
ORDER BY t1.groupID;
This one was taking forever so I had to kill it.
I use Remote login with vnc-ltsp-config with GNOME Desktop Environment on CentOS 5.9. From experimenting today, I managed to get cut and paste working for the session and the login prompt (because I'm lazy and would rather copy and paste difficult passwords).
I created a file vncconfig.desktop in the /etc/xdg/autostart directory which enabled cut and paste during the session after login. The vncconfig process is run as the logged in user.
[Desktop Entry]
Name=No name
Encoding=UTF-8
Version=1.0
Exec=vncconfig -nowin
X-GNOME-Autostart-enabled=true
Added vncconfig -nowin & to the bottom of the file /etc/gdm/Init/Desktop which enabled cut and paste in the session during login but terminates after login. The vncconfig process is run as root.
Adding vncconfig -nowin & to the bottom of the file /etc/gdm/PostLogin/Desktop also enabled cut and paste during the session after login. The vncconfig process is run as root however.
If you have access to the device console (adb shell), then change permissions of following:
/data/local/
in which case, make sure the set the right permissions to the apk also. I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.
IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.
check out the documentation and the demo.
This may be sufficient in many cases
stream.findAny().isPresent()
Another reason of the above error is corrupted jar file. I got the same error but for Junit when running unit tests. Removing jar and downloading it again fixed the issue.
In Python 2.6 and above you can use 'itertools.product`. In older versions of Python you can use the following (almost -- see documentation) equivalent code from the documentation, at least as a starting point:
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
The result of both is an iterator, so if you really need a list for furthert processing, use list(result)
.
That's the distinction between declaration and definition. Header files typically include just the declaration, and the source file contains the definition.
In order to use something you only need to know it's declaration not it's definition. Only the linker needs to know the definition.
So this is why you will include a header file inside one or more source files but you won't include a source file inside another.
Also you mean #include
and not import.
DECLARE @MyDate datetime
-- ... set your datetime's initial value ...'
DATEADD(d, 1, @MyDate)
Others have recommended BeautifulSoup, but it's much better to use lxml. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.
There's no reason to use BeautifulSoup anymore, unless you're on Google App Engine or something where anything not purely Python isn't allowed.
lxml.html also supports CSS3 selectors so this sort of thing is trivial.
An example with lxml and xpath would look like this:
import urllib
import lxml.html
connection = urllib.urlopen('http://www.nytimes.com')
dom = lxml.html.fromstring(connection.read())
for link in dom.xpath('//a/@href'): # select the url in href for all a tags(links)
print link
I had a similar problem. I created a new repository, NOT IN THE DIRECTORY THAT I WANTED TO MAKE A REPOSITORY. I then copied the files created to the directory I wanted to make a repository. Then open an existing repository using the directory I just copied the files to.
NOTE: I did use github desktop to make and open exiting repository.
If "debugging information" means the values present when exception was raised, then logging.exception(...)
won't help. So you'll need a tool that logs all variable values along with the traceback lines automatically.
Out of the box you'll get log like
2020-03-30 18:24:31 main ERROR File "./temp.py", line 13, in get_ratio
2020-03-30 18:24:31 main ERROR return height / width
2020-03-30 18:24:31 main ERROR height = 300
2020-03-30 18:24:31 main ERROR width = 0
2020-03-30 18:24:31 main ERROR builtins.ZeroDivisionError: division by zero
Have a look at some pypi tools, I'd name:
Some of them give you pretty crash messages:
But you might find some more on pypi
if (!Directory.Exists(Path.GetDirectoryName(fileName)))
{
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
}
Updating Mrchief's answer with Linq, we will have:
public static IPAddress GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
var ipAddress= host.AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
return ipAddress;
}
One additional thing I would like to mention that some of the answers may have missed is the downside to having both ETags
and Expires/Cache-control
in your headers.
Depending on your needs it may just add extra bytes in your headers which may increase packets which means more TCP overhead. Again, you should see if the overhead of having both things in your headers is necessary or will it just add extra weight in your requests which reduces performance.
You can read more about it on this excellent blog post by Kyle Simpson: http://calendar.perfplanet.com/2010/bloated-request-response-headers/
This old chestnut...
In short, you should be using require and letting node handle the parsing as part of the require call, not outsourcing it to a 3rd party module. You should also be taking care that your configs are bulletproof, which means you should check the returned data carefully.
But for brevity's sake, consider the following example:
For Example, let's say I have a config file 'admins.json' in the root of my app containing the following:
admins.json[{
"userName": "tech1337",
"passSalted": "xxxxxxxxxxxx"
}]
Note the quoted keys, "userName"
, "passSalted"
!
I can do the following and get the data out of the file with ease.
let admins = require('~/app/admins.json');
console.log(admins[0].userName);
Now the data is in and can be used as a regular (or array of) object.
Try to embed a table element.
<div>_x000D_
<table style='width:200px; height:100px;'>_x000D_
<td style='vertical-align:middle;'>_x000D_
copenhagen_x000D_
</td>_x000D_
</table>_x000D_
</div>
_x000D_
You should use new
when you wish an object to remain in existence until you delete
it. If you do not use new
then the object will be destroyed when it goes out of scope. Some examples of this are:
void foo()
{
Point p = Point(0,0);
} // p is now destroyed.
for (...)
{
Point p = Point(0,0);
} // p is destroyed after each loop
Some people will say that the use of new
decides whether your object is on the heap or the stack, but that is only true of variables declared within functions.
In the example below the location of 'p' will be where its containing object, Foo, is allocated. I prefer to call this 'in-place' allocation.
class Foo
{
Point p;
}; // p will be automatically destroyed when foo is.
Allocating (and freeing) objects with the use of new
is far more expensive than if they are allocated in-place so its use should be restricted to where necessary.
A second example of when to allocate via new
is for arrays. You cannot* change the size of an in-place or stack array at run-time so where you need an array of undetermined size it must be allocated via new.
E.g.
void foo(int size)
{
Point* pointArray = new Point[size];
...
delete [] pointArray;
}
(*pre-emptive nitpicking - yes, there are extensions that allow variable sized stack allocations).
Why not using: SELECT home, MAX(datetime) AS MaxDateTime,player,resource FROM topten GROUP BY home Did I miss something?
By default, Sublime Text set 'UTF8 without BOM'
, but that wasn't specified.
The only specicified things is 'UTF8 with BOM'
.
Hope this help :)
Try data.table's :=
operator :
DT = as.data.table(df)
DT[b==0, est := (a-5)/2.533]
It's fast and short. See these linked questions for more information on :=
:
When should I use the :=
operator in data.table
With Mac OS X v10.10 (Yosemite), use Option + Command + K to clear the scrollback in Terminal.app.
There can be more than one main method in a single program. Others are Overloaded method. This overloaded method works fine under a single main method
public class MainMultiple{
public static void main(String args[]){
main(122);
main('f');
main("hello java");
}
public static void main(int i){
System.out.println("Overloaded main()"+i);
}
public static void main(char i){
System.out.println("Overloaded main()"+i);
}
public static void main(String str){
System.out.println("Overloaded main()"+str);
}
}
You can use the Clone
method if you want to iterate through strings along with the string builder... It returns an object so you can convert to a string using the ToString method...:)
So this is one of the top hits in Google for styling Leaflet Icon, but it didn't have a solution that worked without third parties, and I was having this problem in React as we needed dynamic colours for our routes and icons.
The solution I came up with was to use Leaflet.DivIcon html
attribute, it allows you to pass a string which is evaluated into a DOM element.
So for example I created a marker style follows:
const myCustomColour = '#583470'
const markerHtmlStyles = `
background-color: ${myCustomColour};
width: 3rem;
height: 3rem;
display: block;
left: -1.5rem;
top: -1.5rem;
position: relative;
border-radius: 3rem 3rem 0;
transform: rotate(45deg);
border: 1px solid #FFFFFF`
const icon = Leaflet.divIcon({
className: "my-custom-pin",
iconAnchor: [0, 24],
labelAnchor: [-6, 0],
popupAnchor: [0, -36],
html: `<span style="${markerHtmlStyles}" />`
})
Change background-color
in markerHtmlStyles
to your custom colour and you're good to go.
Scala class same as Java Class but scala not gives you any entry method in class, like main method in java. The main method associated with object keyword. You can think of the object keyword as creating a singleton object of a class that is defined implicitly.
more information check this article class and object keyword in scala programming
This trick supposed to prevent v = null
kind of typos.
But Java allows only boolean expressions as if()
conditions so that trick does not make much sense, compiler will find those typos anyway.
It is still valuable trick for C/C++ code though.
There are already many answers provided for deleting the .svn-directory. But I want to add, that you can avoid these directories from the beginning, if you do an export instead of a checkout:
svn export <url>
There is no specific option to disable caching only for JavaScript, you will have to disable caching entirely.
FireBug has an option to disable the browser cache on the Network tab's drop down menu.
The other solutions are good. If these are your goals:
These two lines are useful ...
df.persist
df.show(df.count, false) // in Scala or 'False' in Python
By persisting, the 2 executor actions, count and show, are faster & more efficient when using persist
or cache
to maintain the interim underlying dataframe structure within the executors. See more about persist and cache.
assuming certain column names...
INSERT one
newToner = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
dbsession.add(newToner)
dbsession.commit()
INSERT multiple
newToner1 = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
newToner2 = Toner(toner_id = 2,
toner_color = 'red',
toner_hex = '#F01731')
dbsession.add_all([newToner1, newToner2])
dbsession.commit()
UPDATE
q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'
dbsession.commit()
or using a fancy one-liner using MERGE
record = dbsession.merge(Toner( **kwargs))
Someone had gave good answers. I made another instruction clue step by step. First, open your studio and search. You can find the decompier is Fernflower.
Second, we can find it in the plugins directory.
/Applications/Android Studio.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar
Third, run it, you will get the usage
java -cp "/Applications/Android Studio.app/Contents/plugins/java-decompiler/lib/java-decompiler.jar" org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler
Usage: java -jar fernflower.jar [-<option>=<value>]* [<source>]+ <destination>
Example: java -jar fernflower.jar -dgs=true c:\my\source\ c:\my.jar d:\decompiled\
Finally, The studio's nest options for decompiler list as follows according IdeaDecompiler.kt
-hdc=0 -dgs=1 -rsy=1 -rbr=1 -lit=1 -nls=1 -mpm=60 -lac=1
IFernflowerPreferences.HIDE_DEFAULT_CONSTRUCTOR to "0",
IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES to "1",
IFernflowerPreferences.REMOVE_SYNTHETIC to "1",
IFernflowerPreferences.REMOVE_BRIDGE to "1",
IFernflowerPreferences.LITERALS_AS_IS to "1",
IFernflowerPreferences.NEW_LINE_SEPARATOR to "1",
**IFernflowerPreferences.BANNER to BANNER,**
IFernflowerPreferences.MAX_PROCESSING_METHOD to 60,
**IFernflowerPreferences.INDENT_STRING to indent,**
**IFernflowerPreferences.IGNORE_INVALID_BYTECODE to "1",**
IFernflowerPreferences.VERIFY_ANONYMOUS_CLASSES to "1",
**IFernflowerPreferences.UNIT_TEST_MODE to if (ApplicationManager.getApplication().isUnitTestMode) "1" else "0")**
I cant find the sutialbe option for the asterisk items.
Hope these steps will make the question clear.
New location for mysql config file is
/etc/mysql/mysql.conf.d/mysqld.cnf
1.1) First-level cache
First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.
1.2) Second-level cache
Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also.
Quoted from: http://javabeat.net/introduction-to-hibernate-caching/
I think u want to change the default settings of android studio. Whenever a layout or Activity in created u want to create "RelativeLayout" by default. In that case, flow the step below
you are done
After the C# 6.0 (including) you can use nameof expression:
using Stuff = Some.Cool.Functionality
class C {
static int Method1 (string x, int y) {}
static int Method1 (string x, string y) {}
int Method2 (int z) {}
string f<T>() => nameof(T);
}
var c = new C()
nameof(C) -> "C"
nameof(C.Method1) -> "Method1"
nameof(C.Method2) -> "Method2"
nameof(c.Method1) -> "Method1"
nameof(c.Method2) -> "Method2"
nameof(z) -> "z" // inside of Method2 ok, inside Method1 is a compiler error
nameof(Stuff) = "Stuff"
nameof(T) -> "T" // works inside of method but not in attributes on the method
nameof(f) -> “f”
nameof(f<T>) -> syntax error
nameof(f<>) -> syntax error
nameof(Method2()) -> error “This expression does not have a name”
Note! nameof
not get the underlying object's runtime Type, it is just the compile-time argument. If a method accepts an IEnumerable then nameof simply returns "IEnumerable", whereas the actual object could be "List".
Extending the contains function you linked to:
containsRegex(a, regex){
for(var i = 0; i < a.length; i++) {
if(a[i].search(regex) > -1){
return i;
}
}
return -1;
}
Then you call the function with an array of strings and a regex, in your case to look for height:
containsRegex([ '<param name=\"bgcolor\" value=\"#FFFFFF\" />', 'sdafkdf' ], /height/)
You could additionally also return the index where height was found:
containsRegex(a, regex){
for(var i = 0; i < a.length; i++) {
int pos = a[i].search(regex);
if(pos > -1){
return [i, pos];
}
}
return null;
}
You should be able to continue the sequences directly in your existing -f
specification.
To skip both 5 and 7, try:
cut -d, -f-4,6-6,8-
As you're skipping a single sequential column, this can also be written as:
cut -d, -f-4,6,8-
To keep it going, if you wanted to skip 5, 7, and 11, you would use:
cut -d, -f-4,6-6,8-10,12-
To put it into a more-clear perspective, it is easier to visualize when you use starting/ending columns which go on the beginning/end of the sequence list, respectively. For instance, the following will print columns 2 through 20, skipping columns 5 and 11:
cut -d, -f2-4,6-10,12-20
So, this will print "2 through 4", skip 5, "6 through 10", skip 11, and then "12 through 20".
Use preg_grep
$array = preg_grep(
'/(my\n+string\n+)/i',
array( 'file' , 'my string => name', 'this')
);
string
is synonym for System.String
type, They are identical.
Values are also identical: string.Empty == String.Empty == ""
I would not use character constant "" in code, rather string.Empty
or String.Empty
- easier to see what programmer meant.
Between string
and String
I like lower case string
more just because I used to work with Delphi for lot of years and Delphi style is lowercase string
.
So, if I was your boss, you would be writing string.Empty
If you are using VB, you need to drop the semicolon:
<% Response.Redirect("new.aspx", true) %>
You don't want regular expressions here.
s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"
print s.split(',')
Gives you:
['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']
https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/app-icon/
Keep icon corners square. The system applies a mask that rounds icon corners automatically.
Keep the background simple and avoid transparency. Make sure your icon is opaque, and don’t clutter the background. Give it a simple background so it doesn’t overpower other app icons nearby. You don’t need to fill the entire icon with content.
I just got another case to display backslash \
with Razor and Java Script.
My @Model.AreaName
looks like Name1\Name2\Name3 so when I display it all backslashes are gone and I see Name1Name2Name3
I found solution to fix it:
var areafullName = JSON.parse("@Html.Raw(HttpUtility.JavaScriptStringEncode(JsonConvert.SerializeObject(Model.AreaName)))");
Don't forget to add @using Newtonsoft.Json
on top of chtml
page.
You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.
Public Sub SaveToDesktop()
ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
I'm not sure whether this would be a requirement, but may help!
please try this
echo $VAR | grep ClNonZ | awk '{print $3}';
or
echo cat filename | grep ClNonZ | awk '{print $3}';
Better solution is to introduce another interface for async operations. New interface must inherit from original interface.
Example:
interface IIO
{
void DoOperation();
}
interface IIOAsync : IIO
{
Task DoOperationAsync();
}
class ClsAsync : IIOAsync
{
public void DoOperation()
{
DoOperationAsync().GetAwaiter().GetResult();
}
public async Task DoOperationAsync()
{
//just an async code demo
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
IIOAsync asAsync = new ClsAsync();
IIO asSync = asAsync;
Console.WriteLine(DateTime.Now.Second);
asAsync.DoOperation();
Console.WriteLine("After call to sync func using Async iface: {0}",
DateTime.Now.Second);
asAsync.DoOperationAsync().GetAwaiter().GetResult();
Console.WriteLine("After call to async func using Async iface: {0}",
DateTime.Now.Second);
asSync.DoOperation();
Console.WriteLine("After call to sync func using Sync iface: {0}",
DateTime.Now.Second);
Console.ReadKey(true);
}
}
P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.
A list comprehension is your best bet for the most Pythonic (and fastest) way to do this:
[int(i.days) for i in (df.B - df.A)]
If your columns aren't in datetime format. The shorter syntax would be: df.A = pd.to_datetime(df.A)
Simple ASP.NET MVC subscription form with email textbox would be implemented like that:
The data from the form is mapped to this model
public class SubscribeModel
{
[Required]
public string Email { get; set; }
}
View name should match controller method name.
@model App.Models.SubscribeModel
@using (Html.BeginForm("Subscribe", "Home", FormMethod.Post))
{
@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
<button type="submit">Subscribe</button>
}
Controller is responsible for request processing and returning proper response view.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Subscribe(SubscribeModel model)
{
if (ModelState.IsValid)
{
//TODO: SubscribeUser(model.Email);
}
return View("Index", model);
}
}
Here is my project structure. Please notice, "Home" views folder matches HomeController name.
In my pretty standard setup I've been seeing the following work well when passed in as VM Option (commandline before class in Java, or VM Option in an IDE):
-Droot.log.level=TRACE
I had an issue with node.exe
programs like test output with mocha
.
In my case, I solved it by removing some default "node.exe" alias.
I'm using Git Bash for Windows(2.29.2) and some default aliases are set from /etc/profile.d/aliases.sh
,
# show me alias related to 'node'
$ alias|grep node
alias node='winpty node.exe'`
To remove the alias, update aliases.sh
or simply do
unalias node
I don't know why winpty
has this side effect on console.info
buffered output but with a direct node.exe
use, I've no more stdout issue.
Also realized this problem comes up when trying to combine reactive form and template form approaches. I had #name="ngModel"
and [formControl]="name"
on the same element. Removing either one fixed the issue. Also not that if you use #name=ngModel
you should also have a property such as this [(ngModel)]="name"
, otherwise, You will still get the errors. This applies to angular 6, 7 and 8 too.
They are the same concepts, apart from the NULL value returned.
See below:
declare @table1 table( col1 int, col2 int );
insert into @table1 select 1, 11 union all select 2, 22;
declare @table2 table ( col1 int, col2 int );
insert into @table2 select 10, 101 union all select 2, 202;
select
t1.*,
t2.*
from @table1 t1
full outer join @table2 t2 on t1.col1 = t2.col1
order by t1.col1, t2.col1;
/* full outer join
col1 col2 col1 col2
----------- ----------- ----------- -----------
NULL NULL 10 101
1 11 NULL NULL
2 22 2 202
*/
select
t1.*,
t2.*
from @table1 t1
cross join @table2 t2
order by t1.col1, t2.col1;
/* cross join
col1 col2 col1 col2
----------- ----------- ----------- -----------
1 11 2 202
1 11 10 101
2 22 2 202
2 22 10 101
*/
http://jsbin.com/ubalax/1/edit .You can see the results here
body {
position: relative;
float: left;
height: 3000px;
width: 100%;
}
body div {
position: absolute;
height: 100%;
width: 100%;
top:0;
left:0;
background-color: yellow;
}
You can use "system.properties.os", for example:
public class GetOs {
public static void main (String[] args) {
String s =
"name: " + System.getProperty ("os.name");
s += ", version: " + System.getProperty ("os.version");
s += ", arch: " + System.getProperty ("os.arch");
System.out.println ("OS=" + s);
}
}
// EXAMPLE OUTPUT: OS=name: Windows 7, version: 6.1, arch: amd64
Here are more details:
If you want your script to return values, just do return [1,2,3]
from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:
(again, this would have to be run by a separate Python script and be imported in order to even do any good):
import ...
def main():
# calculate stuff
return [1,2,3]
(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)
import sys
# calculate and stuff
sys.exit(100)
And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.
(os._exit(100)
also works, and is a bit more forceful)
If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.
import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)
Are you running your script in a controlled scheduling environment then exit codes are the best way to go.
There's also the option to simply write information to a file, and store the result there.
# calculate
with open('finish.txt', 'wb') as fh:
fh.write(str(5)+'\n')
And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.
If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.
DO
$do$
BEGIN
IF EXISTS (SELECT FROM orders) THEN
DELETE FROM orders;
ELSE
INSERT INTO orders VALUES (1,2,3);
END IF;
END
$do$
There are no procedural elements in standard SQL. The IF
statement is part of the default procedural language PL/pgSQL. You need to create a function or execute an ad-hoc statement with the DO
command.
You need a semicolon (;
) at the end of each statement in plpgsql (except for the final END
).
You need END IF;
at the end of the IF
statement.
A sub-select must be surrounded by parentheses:
IF (SELECT count(*) FROM orders) > 0 ...
Or:
IF (SELECT count(*) > 0 FROM orders) ...
This is equivalent and much faster, though:
IF EXISTS (SELECT FROM orders) ...
The additional SELECT
is not needed. This does the same, faster:
DO
$do$
BEGIN
DELETE FROM orders;
IF NOT FOUND THEN
INSERT INTO orders VALUES (1,2,3);
END IF;
END
$do$
Though unlikely, concurrent transactions writing to the same table may interfere. To be absolutely sure, write-lock the table in the same transaction before proceeding as demonstrated.
Equals comparison:
((f1 IS NULL AND f2 IS NULL) OR (f1 IS NOT NULL AND f2 IS NOT NULL AND f1 = f2))
Not Equal To comparison: Just negate the Equals comparison above.
NOT ((f1 IS NULL AND f2 IS NULL) OR (f1 IS NOT NULL AND f2 IS NOT NULL AND f1 = f2))
Is it verbose? Yes, it is. However it's efficient since it doesn't call any function. The idea is to use short circuit in predicates to make sure the equal operator (=) is used only with non-null values, otherwise null would propagate up in the expression tree.
full binary tree is full if every node has 0 or 2 children. in full binary number of leaf nodes is number of internal nodes plus 1 L=l+1
You need to add CSS to .active
instead of .active a
.
Fiddle: http://jsfiddle.net/T5X6h/2/
Something like this:
.navbar-default .navbar-nav > .active{
color: #000;
background: #d65c14;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #000;
background: #d65c14;
}
Use one of keyup / keydown / beforeinput events instead.
based on this reference, keypress is deprecated and no longer recommended.
The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.
if you use "beforeinput" be careful about it's Browser compatibility. the difference between "beforeinput" and the other two is that "beforeinput" is fired when input value is about to changed, so with characters that can't change the input value, it is not fired (e.g shift, ctr ,alt).
I had the same problem and by using keyup it was solved.
Wrote my own test. tested the code on stackoverflow, works fine tells me that chrome/FF can do 6
var change = 0;
var simultanius = 0;
var que = 20; // number of tests
Array(que).join(0).split(0).forEach(function(a,i){
var xhr = new XMLHttpRequest;
xhr.open("GET", "/?"+i); // cacheBust
xhr.onreadystatechange = function() {
if(xhr.readyState == 2){
change++;
simultanius = Math.max(simultanius, change);
}
if(xhr.readyState == 4){
change--;
que--;
if(!que){
console.log(simultanius);
}
}
};
xhr.send();
});
it works for most websites that can trigger readystate change event at different times. (aka: flushing)
I notice on my node.js server that i had to output at least 1025 bytes to trigger the event/flush. otherwise the events would just trigger all three state at once when the request is complete so here is my backend:
var app = require('express')();
app.get("/", function(req,res) {
res.write(Array(1025).join("a"));
setTimeout(function() {
res.end("a");
},500);
});
app.listen(80);
I notice that You can now have up to 2x request if you are using both xhr and fetch api at the same time
var change = 0;_x000D_
var simultanius = 0;_x000D_
var que = 30; // number of tests_x000D_
_x000D_
Array(que).join(0).split(0).forEach(function(a,i){_x000D_
fetch("/?b"+i).then(r => {_x000D_
change++;_x000D_
simultanius = Math.max(simultanius, change);_x000D_
return r.text()_x000D_
}).then(r => {_x000D_
change--;_x000D_
que--;_x000D_
if(!que){_x000D_
console.log(simultanius);_x000D_
}_x000D_
});_x000D_
});_x000D_
_x000D_
Array(que).join(0).split(0).forEach(function(a,i){_x000D_
var xhr = new XMLHttpRequest;_x000D_
xhr.open("GET", "/?a"+i); // cacheBust_x000D_
xhr.onreadystatechange = function() {_x000D_
if(xhr.readyState == 2){_x000D_
change++;_x000D_
simultanius = Math.max(simultanius, change);_x000D_
}_x000D_
if(xhr.readyState == 4){_x000D_
change--;_x000D_
que--;_x000D_
if(!que){_x000D_
document.body.innerHTML = simultanius;_x000D_
}_x000D_
}_x000D_
};_x000D_
xhr.send();_x000D_
});
_x000D_
After searching a bit about the method to open the existing sheet in xlxs, i discovered
existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')
You can now append/write any data to the open worksheet. I hope it helps. Thanks
In your app.module.ts file
import { RouterModule, Routes } from '@angular/router';
const appRoutes: Routes = [
{
path: '',
redirectTo: '/dashboard',
pathMatch: 'full',
component: DashboardComponent
},
{
path: 'dashboard',
component: DashboardComponent
}
];
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes),
FormsModule
],
declarations: [
AppComponent,
DashboardComponent
],
bootstrap: [AppComponent]
})
export class AppModule {
}
Add this code. Happy Coding.
If you need simplify code then live is better in the most cases. If you need to get the best performance then delegate will always better than live. bind (click) vs delegate isn't so simple question (if you have a lot of similar items then delegate will be better).
I faced same issue. After some Googling with the right search terms, I came across this nice article on DigitalOcean.
I am merely quoting the relevant part from the article here.
Based on the HAVEGE principle, and previously based on its associated library, haveged allows generating randomness based on variations in code execution time on a processor. Since it's nearly impossible for one piece of code to take the same exact time to execute, even in the same environment on the same hardware, the timing of running a single or multiple programs should be suitable to seed a random source. The haveged implementation seeds your system's random source (usually /dev/random) using differences in your processor's time stamp counter (TSC) after executing a loop repeatedly
Follow the steps in this article. https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged
I have posted it here
Like said Gumbo,
<?php
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
?>
I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.
Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.
Here is an attempt at this with your data:
import matplotlib.pyplot as plt
# ... define 2D array hist as you did
plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case
From the manual: The SELECT ... INTO OUTFILE
statement is intended primarily to let you very quickly dump a table to a text file on the server machine. If you want to create the resulting file on some client host other than the server host, you cannot use SELECT ... INTO OUTFILE
. In that case, you should instead use a command such as mysql -e "SELECT ..." > file_name
to generate the file on the client host."
http://dev.mysql.com/doc/refman/5.0/en/select.html
An example:
mysql -h my.db.com -u usrname--password=pass db_name -e 'SELECT foo FROM bar' > /tmp/myfile.txt
Another alternative:
# Is there anything in this row non-zero?
# df != 0 --> which entries are non-zero? T/F
# (df != 0).any(axis=1) --> are there 'any' entries non-zero row-wise? T/F of rows that return true to this statement.
# df.loc[all_zero_mask,:] --> mask your rows to only show the rows which contained a non-zero entry.
# df.shape to confirm a subset.
all_zero_mask=(df != 0).any(axis=1) # Is there anything in this row non-zero?
df.loc[all_zero_mask,:].shape
INSERT INTO Data ( Col1 ) VALUES ('Hello'), ('World')
In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]:
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
You can add new user jQuery function 'getDate'
JSFiddle: getDate jQuery
Or you can run code snippet. Just press "Run code snippet" button below this post.
// Create user jQuery function 'getDate'_x000D_
(function( $ ){_x000D_
$.fn.getDate = function(format) {_x000D_
_x000D_
var gDate = new Date();_x000D_
var mDate = {_x000D_
'S': gDate.getSeconds(),_x000D_
'M': gDate.getMinutes(),_x000D_
'H': gDate.getHours(),_x000D_
'd': gDate.getDate(),_x000D_
'm': gDate.getMonth() + 1,_x000D_
'y': gDate.getFullYear(),_x000D_
}_x000D_
_x000D_
// Apply format and add leading zeroes_x000D_
return format.replace(/([SMHdmy])/g, function(key){return (mDate[key] < 10 ? '0' : '') + mDate[key];});_x000D_
_x000D_
return getDate(str);_x000D_
}; _x000D_
})( jQuery );_x000D_
_x000D_
_x000D_
// Usage: example #1. Write to '#date' div_x000D_
$('#date').html($().getDate("y-m-d H:M:S"));_x000D_
_x000D_
// Usage: ex2. Simple clock. Write to '#clock' div_x000D_
function clock(){_x000D_
$('#clock').html($().getDate("H:M:S, m/d/y"))_x000D_
}_x000D_
clock();_x000D_
setInterval(clock, 1000); // One second_x000D_
_x000D_
// Usage: ex3. Simple clock 2. Write to '#clock2' div_x000D_
function clock2(){_x000D_
_x000D_
var format = 'H:M:S'; // Date format_x000D_
var updateInterval = 1000; // 1 second_x000D_
var clock2Div = $('#clock2'); // Get div_x000D_
var currentTime = $().getDate(format); // Get time_x000D_
_x000D_
clock2Div.html(currentTime); // Write to div_x000D_
setTimeout(clock2, updateInterval); // Set timer 1 second_x000D_
_x000D_
}_x000D_
// Run clock2_x000D_
clock2();_x000D_
_x000D_
// Just for fun_x000D_
// Usage: ex4. Simple clock 3. Write to '#clock3' span_x000D_
_x000D_
function clock3(){_x000D_
_x000D_
var formatHM = 'H:M:'; // Hours, minutes_x000D_
var formatS = 'S'; // Seconds_x000D_
var updateInterval = 1000; // 1 second_x000D_
var clock3SpanHM = $('#clock3HM'); // Get span HM_x000D_
var clock3SpanS = $('#clock3S'); // Get span S_x000D_
var currentHM = $().getDate(formatHM); // Get time H:M_x000D_
var currentS = $().getDate(formatS); // Get seconds_x000D_
_x000D_
clock3SpanHM.html(currentHM); // Write to div_x000D_
clock3SpanS.fadeOut(1000).html(currentS).fadeIn(1); // Write to span_x000D_
setTimeout(clock3, updateInterval); // Set timer 1 second_x000D_
_x000D_
}_x000D_
// Run clock2_x000D_
clock3();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
_x000D_
<div id="date"></div><br>_x000D_
<div id="clock"></div><br>_x000D_
<span id="clock3HM"></span><span id="clock3S"></span>
_x000D_
Enjoy!
You can do this with a single image using something like this:
//get the image view
ImageView imageView = (ImageView)findViewById(R.id.ImageView);
//set the ontouch listener
imageView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
ImageView view = (ImageView) v;
//overlay is black with transparency of 0x77 (119)
view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
view.invalidate();
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
ImageView view = (ImageView) v;
//clear the overlay
view.getDrawable().clearColorFilter();
view.invalidate();
break;
}
}
return false;
}
});
I will probably be making this into a subclass of ImageView (or ImageButton as it is also a subclass of ImageView) for easier re-usability, but this should allow you to apply a "selected" look to an imageview.
This error is mainly caused by empty returned ajax calls, when trying to parse an empty JSON.
To solve this test if the returned data is empty
$.ajax({
url: url,
type: "get",
dataType: "json",
success: function (response) {
if(response.data.length == 0){
// EMPTY
}else{
var obj =jQuery.parseJSON(response.data);
console.log(obj);
}
}
});
Just an improved version to nkron responce.
const httpGet = url => {
return new Promise((resolve, reject) => {
http.get(url, res => {
res.setEncoding('utf8');
const body = [];
res.on('data', chunk => body.push(chunk));
res.on('end', () => resolve(body.join('')));
}).on('error', reject);
});
};
Appending chunks in an string[] is better for memory usage, the join(''), will allocate new memory only once.
It is actually called file:///android_asset/index.html
file:///android_assets/index.html
will give you a build error.
You need to stringify the json, not calling toString
var buf = Buffer.from(JSON.stringify(obj));
And for converting string to json obj :
var temp = JSON.parse(buf.toString());
std::vector always makes a copy of whatever is being stored in the vector.
If you are keeping a vector of pointers, then it will make a copy of the pointer, but not the instance being to which the pointer is pointing. If you are dealing with large objects, you can (and probably should) always use a vector of pointers. Often, using a vector of smart pointers of an appropriate type is good for safety purposes, since handling object lifetime and memory management can be tricky otherwise.
A bit late, but maybe someone finds it useful.
For me, ISNULL was out of question due to the table scan. UNION ALL would need me to repeat a complex query, and due to me selecting only the TOP X it would not have been very efficient.
If you are able to change the table design, you can:
Add another field, just for sorting, such as Next_Contact_Date_Sort.
Create a trigger that fills that field with a large (or small) value, depending on what you need:
CREATE TRIGGER FILL_SORTABLE_DATE ON YOUR_TABLE AFTER INSERT,UPDATE AS
BEGIN
SET NOCOUNT ON;
IF (update(Next_Contact_Date)) BEGIN
UPDATE YOUR_TABLE SET Next_Contact_Date_Sort=IIF(YOUR_TABLE.Next_Contact_Date IS NULL, 99/99/9999, YOUR_TABLE.Next_Contact_Date_Sort) FROM inserted i WHERE YOUR_TABLE.key1=i.key1 AND YOUR_TABLE.key2=i.key2
END
END
Unlike the other answers, return false
is only part of the answer. Consider the scenario in which a JS error occurs prior to the return statement...
html
<form onsubmit="return mySubmitFunction(event)">
...
</form>
script
function mySubmitFunction()
{
someBug()
return false;
}
returning false
here won't be executed and the form will be submitted either way. You should also call preventDefault
to prevent the default form action for Ajax form submissions.
function mySubmitFunction(e) {
e.preventDefault();
someBug();
return false;
}
In this case, even with the bug the form won't submit!
Alternatively, a try...catch
block could be used.
function mySubmit(e) {
e.preventDefault();
try {
someBug();
} catch (e) {
throw new Error(e.message);
}
return false;
}
The syntax is token-level, so the meaning of the dollar sign depends on the token it's in. The expression $(command)
is a modern synonym for `command`
which stands for command substitution; it means run command
and put its output here. So
echo "Today is $(date). A fine day."
will run the date
command and include its output in the argument to echo
. The parentheses are unrelated to the syntax for running a command in a subshell, although they have something in common (the command substitution also runs in a separate subshell).
By contrast, ${variable}
is just a disambiguation mechanism, so you can say ${var}text
when you mean the contents of the variable var
, followed by text
(as opposed to $vartext
which means the contents of the variable vartext
).
The while
loop expects a single argument which should evaluate to true or false (or actually multiple, where the last one's truth value is examined -- thanks Jonathan Leffler for pointing this out); when it's false, the loop is no longer executed. The for
loop iterates over a list of items and binds each to a loop variable in turn; the syntax you refer to is one (rather generalized) way to express a loop over a range of arithmetic values.
A for
loop like that can be rephrased as a while
loop. The expression
for ((init; check; step)); do
body
done
is equivalent to
init
while check; do
body
step
done
It makes sense to keep all the loop control in one place for legibility; but as you can see when it's expressed like this, the for
loop does quite a bit more than the while
loop.
Of course, this syntax is Bash-specific; classic Bourne shell only has
for variable in token1 token2 ...; do
(Somewhat more elegantly, you could avoid the echo
in the first example as long as you are sure that your argument string doesn't contain any %
format codes:
date +'Today is %c. A fine day.'
Avoiding a process where you can is an important consideration, even though it doesn't make a lot of difference in this isolated example.)
Based on Charles Clayton's response, I included some JSDoc, ES6 tweaks, and incorporated suggestions from the comments in the original response.
/**_x000D_
* Returns a scaled number within its source bounds to the desired target bounds._x000D_
* @param {number} n - Unscaled number_x000D_
* @param {number} tMin - Minimum (target) bound to scale to_x000D_
* @param {number} tMax - Maximum (target) bound to scale to_x000D_
* @param {number} sMin - Minimum (source) bound to scale from_x000D_
* @param {number} sMax - Maximum (source) bound to scale from_x000D_
* @returns {number} The scaled number within the target bounds._x000D_
*/_x000D_
const scaleBetween = (n, tMin, tMax, sMin, sMax) => {_x000D_
return (tMax - tMin) * (n - sMin) / (sMax - sMin) + tMin;_x000D_
}_x000D_
_x000D_
if (Array.prototype.scaleBetween === undefined) {_x000D_
/**_x000D_
* Returns a scaled array of numbers fit to the desired target bounds._x000D_
* @param {number} tMin - Minimum (target) bound to scale to_x000D_
* @param {number} tMax - Maximum (target) bound to scale to_x000D_
* @returns {number} The scaled array._x000D_
*/_x000D_
Array.prototype.scaleBetween = function(tMin, tMax) {_x000D_
if (arguments.length === 1 || tMax === undefined) {_x000D_
tMax = tMin; tMin = 0;_x000D_
}_x000D_
let sMax = Math.max(...this), sMin = Math.min(...this);_x000D_
if (sMax - sMin == 0) return this.map(num => (tMin + tMax) / 2);_x000D_
return this.map(num => (tMax - tMin) * (num - sMin) / (sMax - sMin) + tMin);_x000D_
}_x000D_
}_x000D_
_x000D_
// ================================================================_x000D_
// Usage_x000D_
// ================================================================_x000D_
_x000D_
let nums = [10, 13, 25, 28, 43, 50], tMin = 0, tMax = 100,_x000D_
sMin = Math.min(...nums), sMax = Math.max(...nums);_x000D_
_x000D_
// Result: [ 0.0, 7.50, 37.50, 45.00, 82.50, 100.00 ]_x000D_
console.log(nums.map(n => scaleBetween(n, tMin, tMax, sMin, sMax).toFixed(2)).join(', '));_x000D_
_x000D_
// Result: [ 0, 30.769, 69.231, 76.923, 100 ]_x000D_
console.log([-4, 0, 5, 6, 9].scaleBetween(0, 100).join(', '));_x000D_
_x000D_
// Result: [ 50, 50, 50 ]_x000D_
console.log([1, 1, 1].scaleBetween(0, 100).join(', '));
_x000D_
.as-console-wrapper { top: 0; max-height: 100% !important; }
_x000D_
You should pass length into fwrite instead of sizeof(buffer).
Under HTML5 you are be able to do this:
document.getElementById('test').selectedOptions[0].text
MDN's documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions indicates full cross-browser support (as of at least December 2017), including Chrome, Firefox, Edge and mobile browsers, but excluding Internet Explorer.
Use the onsubmit
event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault
method to disable the form submission.
For example:
<script>
function doSomething() {
alert('Form submitted!');
return false;
}
</script>
<form onsubmit="return doSomething();" class="my-form">
<input type="submit" value="Submit">
</form>
This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:
<script>
$('.my-form').on('submit', function () {
alert('Form submitted!');
return false;
});
</script>
<form class="my-form">
<input type="submit" value="Submit">
</form>
I figured out how to do this in Powershell that someone asked about:
$keyname=(((gci cert:\LocalMachine\my | ? {$_.thumbprint -like $thumbprint}).PrivateKey).CspKeyContainerInfo).UniqueKeyContainerName
$keypath = $env:ProgramData + “\Microsoft\Crypto\RSA\MachineKeys\”
$fullpath=$keypath+$keyname
$Acl = Get-Acl $fullpath
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("IIS AppPool\$iisAppPoolName", "Read", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $fullpath $Acl
According to the spec
Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unncessarily complicated approach.
So what you are trying to do is apparently not supposed to work.
You have to pass instance of MainActivity into another class, then you can call everything public (in MainActivity) from everywhere.
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Instance of AnotherClass for future use
private AnotherClass anotherClass;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Create new instance of AnotherClass and
// pass instance of MainActivity by "this"
anotherClass = new AnotherClass(this);
}
// Method you want to call from another class
public void startChronometer(){
...
}
}
AnotherClass.java
public class AnotherClass {
// Main class instance
private MainActivity mainActivity;
// Constructor
public AnotherClass(MainActivity activity) {
// Save instance of main class for future use
mainActivity = activity;
// Call method in MainActivity
mainActivity.startChronometer();
}
}
For LinearLayout
with horizontal orientation, give layout_weight
to other child view except for the view that you want to align right. This works perfectly.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Specialization"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Right"
android:textColor="#ff0000" />
</LinearLayout>
if you use general java script and you need to assign string to text area value then
document.getElementById("textareaid").value='texthere\\\ntexttext'.
you need to replace \n
or < br >
to \\\n
otherwise it gives Uncaught SyntaxError: Unexpected token ILLEGAL
on all browsers.
I prefer not to check session variable in code instead use FormAuthentication. They have inbuilt functionlity to redirect to given LoginPage specified in web.config.
However if you want to explicitly check the session you can check for NULL value for any of the variable you created in session earlier as Pranay answered.
You can create Login.aspx page and write your message there , when session expires FormAuthentication automatically redirect to loginUrl given in FormAuthentication section
<authentication mode="Forms">
<forms loginUrl="Login.aspx" protection="All" timeout="30">
</forms>
</authentication>
The thing is that you can't give seperate page for Login and SessionExpire , so you have to show/hide some section on Login.aspx to act it both ways.
There is another way to redirect to sessionexpire page after timeout without changing formauthentication->loginurl , see the below link for this : http://www.schnieds.com/2009/07/aspnet-session-expiration-redirect.html
Hope this helps:
// Export (file name: my-functions.js)
export const MyFunction1 = () => {}
export const MyFunction2 = () => {}
export const MyFunction3 = () => {}
// if using `eslint` (airbnb) then you will see warning, so do this:
const MyFunction1 = () => {}
const MyFunction2 = () => {}
const MyFunction3 = () => {}
export {MyFunction1, MyFunction2, MyFunction3};
// Import
import * as myFns from "./my-functions";
myFns.MyFunction1();
myFns.MyFunction2();
myFns.MyFunction3();
// OR Import it as Destructured
import { MyFunction1, MyFunction2, MyFunction3 } from "./my-functions";
// AND you can use it like below with brackets (Parentheses) if it's a function
// AND without brackets if it's not function (eg. variables, Objects or Arrays)
MyFunction1();
MyFunction2();
Just use Javascript's built-in join(separator)
function for arrays:
<li ng-repeat="friend in friends">
<b>{{friend.email.join(', ')}}</b>...
</li>
On iOS there is the switch UI component instead of a checkbox, look into the UISwitch
class.
The property on
(boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.
Just simple modification of @silgon answer:
while true; do
inotifywait -r -e modify,create,delete /directory
rsync -avz /directory /target
done
(@silgon version sometimes crashes on Ubuntu 16 if you run it in cron)
I had this problem after enabling a new service API on the Google console and trying to use the previously made credentials.
To fix the problem, I had to go back to the credential page, clicking on the credential name, and clicking "Save" again. After that, I could authenticate just fine.
Assuming you have GNU find:
find . -size +10000k -printf '%s %f\n'
If you want a constant width for the size field, you can do something like:
find . -size +10000k -printf '%10s %f\n'
Note that -size +1000k
selects files of at least 10,240,000 bytes (k
is 1024, not 1000). You said in a comment that you want files bigger than 1M; if that's 1024*1024 bytes, then this:
find . -size +1M ...
will do the trick -- except that it will also print the size and name of files that are exactly 1024*1024 bytes. If that matters, you could use:
find . -size +1048575c ...
You need to decide just what criterion you want.
Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function on_event()
and data pointers to a framework function watch_events()
(for example). When an event happens, your function is called with your data and some event-specific data.
Callbacks are also used in GUI programming. The GTK+ tutorial has a nice section on the theory of signals and callbacks.
You can use sklearn.feature_extraction.text.CountVectorizer:
import sklearn.feature_extraction.text # FYI http://scikit-learn.org/stable/install.html
ngram_size = 4
string = ["I really like python, it's pretty awesome."]
vect = sklearn.feature_extraction.text.CountVectorizer(ngram_range=(ngram_size,ngram_size))
vect.fit(string)
print('{1}-grams: {0}'.format(vect.get_feature_names(), ngram_size))
outputs:
4-grams: [u'like python it pretty', u'python it pretty awesome', u'really like python it']
You can set to ngram_size
to any positive integer. I.e. you can split a text in four-grams, five-grams or even hundred-grams.
For a long time, DOM3 mutation events were the best available solution, but they have been deprecated for performance reasons. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver
(or as the vendor-prefixed WebKitMutationObserver
in old versions of Chrome):
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
console.log(mutations, observer);
// ...
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});
This example listens for DOM changes on document
and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:
childList
- Set to
true
if mutations to target's children are to be observed.attributes
- Set to
true
if mutations to target's attributes are to be observed.characterData
- Set to
true
if mutations to target's data are to be observed.subtree
- Set to
true
if mutations to not just target, but also target's descendants are to be observed.attributeOldValue
- Set to
true
ifattributes
is set to true and target's attribute value before the mutation needs to be recorded.characterDataOldValue
- Set to
true
ifcharacterData
is set to true and target's data before the mutation needs to be recorded.attributeFilter
- Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.
(This list is current as of April 2014; you may check the specification for any changes.)
@bogatron has it right, you can use where
, it's worth noting that you can do this natively in pandas:
df1 = df.where(pd.notnull(df), None)
Note: this changes the dtype of all columns to object
.
Example:
In [1]: df = pd.DataFrame([1, np.nan])
In [2]: df
Out[2]:
0
0 1
1 NaN
In [3]: df1 = df.where(pd.notnull(df), None)
In [4]: df1
Out[4]:
0
0 1
1 None
Note: what you cannot do recast the DataFrames dtype
to allow all datatypes types, using astype
, and then the DataFrame fillna
method:
df1 = df.astype(object).replace(np.nan, 'None')
Unfortunately neither this, nor using replace
, works with None
see this (closed) issue.
As an aside, it's worth noting that for most use cases you don't need to replace NaN with None, see this question about the difference between NaN and None in pandas.
However, in this specific case it seems you do (at least at the time of this answer).
You might want to use TRUNC function on your column when comparing with string format, so it compares only till seconds, not milliseconds.
SELECT * FROM <table_name> WHERE id = 1
AND TRUNC(usagetime, 'SS') = '2012-09-03 08:03:06';
If you wanted to truncate upto minutes, hours, etc. that is also possible, just use appropriate notation instead of 'SS':
hour ('HH'), minute('MI'), year('YEAR' or 'YYYY'), month('MONTH' or 'MM'), Day ('DD')
You need a root node
<?xml version="1.0" encoding="ISO-8859-1"?>
<documents>
<document>
<name>Sample Document</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&wordcount3=0</url>
</document>
<document>
<name>Sample</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&</url>
</document>
</documents>