Edited and fixed (thanks to Shredder)
If you mean you want to open a new tab, try the below:
protected void Page_Load(object sender, EventArgs e)
{
this.Form.Target = "_blank";
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Otherpage.aspx");
}
This will keep the original page to stay open and cause the redirects on the current page to affect the new tab only.
-J
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
You can use window.location
window.location="/newpage.php";
Or you can just make the form that the search button is in have a action of the page you want.
You can achieve this by using cssSelector
// Use of List web elements:
String cssSelectorOfLoginButton="input[type='button'][id='login']";
//****Add cssSelector of your 1st webelement
//List<WebElement> button
=driver.findElements(By.cssSelector(cssSelectorOfLoginButton));
button.get(0).click();
I hope this work for you
Use SQL Profiler and use a filter on it to get the most expensive queries.
myHash.each{|item|..}
is returning you array object for item
iterative variable like the following :--
[:company_name, "MyCompany"]
[:street, "Mainstreet"]
[:postcode, "1234"]
[:city, "MyCity"]
[:free_seats, "3"]
You should do this:--
def format
output = Hash.new
myHash.each do |k, v|
output[k] = cleanup(v)
end
output
end
If we load script in partial view then this issue coming
This solution working fine for me
Sample: Number of requests sent.
The Throughput: is the number of requests per unit of time (seconds, minutes, hours) that are sent to your server during the test.
The Response time: is the elapsed time from the moment when a given request is sent to the server until the moment when the last bit of information has returned to the client.
The throughput is the real load processed by your server during a run but it does not tell you anything about the performance of your server during this same run. This is the reason why you need both measures in order to get a real idea about your server’s performance during a run. The response time tells you how fast your server is handling a given load.
Average: This is the Average (Arithmetic mean µ = 1/n * Si=1…n xi) Response time of your total samples.
Min and Max are the minimum and maximum response time.
An important thing to understand is that the mean value can be very misleading as it does not show you how close (or far) your values are from the average.For this purpose, we need the Deviation value since Average value can be the Same for different response time of the samples!!
Deviation: The standard deviation (s) measures the mean distance of the values to their average (µ).It gives you a good idea of the dispersion or variability of the measures to their mean value.
The following equation show how the standard deviation (s) is calculated:
s = 1/n * v Si=1…n (xi-µ)2
For Details, see here!!
So, if the deviation value is low compared to the mean value, it will indicate you that your measures are not dispersed (or mostly close to the mean value) and that the mean value is significant.
Kb/sec: The throughput measured in Kilobytes per second.
Error % : Percent of requests with errors.
An example is always better to understand!!! I think, this article will help you.
If you want to call these methods without including module in another class then you need to define them as module methods:
module UsefulThings
def self.get_file; ...
def self.delete_file; ...
def self.format_text(x); ...
end
and then you can call them with
UsefulThings.format_text("xxx")
or
UsefulThings::format_text("xxx")
But anyway I would recommend that you put just related methods in one module or in one class. If you have problem that you want to include just one method from module then it sounds like a bad code smell and it is not good Ruby style to put unrelated methods together.
I noticed the same thing about BOTHER not being defined. Like Jamey Sharp said, you can find it in <asm/termios.h>
. Just a forewarning, I think I ran into problems including both it and the regular <termios.h>
file at the same time.
Aside from that, I found with the glibc I have, it still didn't work because glibc's tcsetattr was doing the ioctl for the old-style version of struct termios which doesn't pay attention to the speed setting. I was able to set a custom speed by manually doing an ioctl with the new style termios2 struct, which should also be available by including <asm/termios.h>
:
struct termios2 tio;
ioctl(fd, TCGETS2, &tio);
tio.c_cflag &= ~CBAUD;
tio.c_cflag |= BOTHER;
tio.c_ispeed = 12345;
tio.c_ospeed = 12345;
ioctl(fd, TCSETS2, &tio);
I simply had to add -h localhost
Can use CSS to show error message only on error.
.form-group.has-error .help-block {
display: block;
}
.form-group .help-block {
display: none;
}
<div class="form-group has-error">
<label class="control-label" for="inputError">Input with error</label>
<input type="text" class="form-control" id="inputError">
<span class="help-block">Please correct the error</span>
</div>
You can call view.setVisibility(View.GONE)
if you want to remove it from the layout.
Or view.setVisibility(View.INVISIBLE)
if you just want to hide it.
From Android Docs:
INVISIBLE
This view is invisible, but it still takes up space for layout purposes. Use with
setVisibility(int)
andandroid:visibility
.GONE
This view is invisible, and it doesn't take any space for layout purposes. Use with
setVisibility(int)
andandroid:visibility
.
Here's what I use:
function isArray(input) {
if (input instanceof Array || Object.prototype.toString.call(input) === '[object Array]') {
return true;
} else return false;
}
Try setting the parameters' "default value" to use the same query as the "available values". In effect it provides every single "available value" as a "default value" and the "Select All" option is automatically checked.
You could also get the error if your Billing is not set up correctly.
Google hands out credit worth $300 or 12 months of free usage whichever runs out faster. After that you would need to enable billing.
vector.size()
returns the size of a vector. You didn't put any string in the vector before the loop , so the size of the vector is 0. It will never enter the loop. First put some data in the vector and then try to add them. You can take input from the user for the number of string user wants to enter.
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
int main(int a, char* b [])
{
vector<string> userString;
string word;
string sentence = "";
int SIZE;
cin>>SIZE; //what will be the size of the vector
for (int i = 0; i < SIZE; i++)
{
cin >> word;
userString.push_back(word);
sentence += userString[i] + " ";
}
cout << sentence;
system("PAUSE");
return 0;
}
another thing, actually you don't have to use a vector to do this.Two strings can do the job for you.
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
int main(int a, char* b [])
{
// vector<string> userString;
string word;
string sentence = "";
int SIZE;
cin>>SIZE; //what will be the size of the vector
for (int i = 0; i < SIZE; i++)
{
cin >> word;
sentence += word+ " ";
}
cout << sentence;
system("PAUSE");
return 0;
}
and if you want to enter string until the user wish , code will be like this:
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
int main(int a, char* b [])
{
// vector<string> userString;
string word;
string sentence = "";
//int SIZE;
//cin>>SIZE; //what will be the size of the vector
while(cin>>word)
{
//cin >> word;
sentence += word+ " ";
}
cout << sentence;
// system("PAUSE");
return 0;
}
Try dropping the \
in front of the >
.
Edit: I just tested your regex and it works fine. This is what I used:
<?
$content = "this is something with an <img src=\"test.png\"/> in it.";
$content = preg_replace("/<img[^>]+\>/i", "(image) ", $content);
echo $content;
?>
The result is:
this is something with an (image) in it.
To solve this issue you need below three steps:
Set page encoding to UTF-8 like below:
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8" %>
Set filter in web.xml file as below:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Set resource encoding to UTF-8, in case if you are writing any UTF-8 characters in Java code or JSP directly.
Let me give you a working example to understand the hashable objects in python. I am taking 2 Tuples for this example.Each value in a tuple has a unique Hash Value which never changes during its lifetime. So based on this has value, the comparison between two tuples is done. We can get the hash value of a tuple element using the Id().
You can see in pg_log folder if the log configuration is enabled in postgresql.conf with this log directory name.
The previous code was
<p class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></p>
So I have to changed it to
<div class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></div>
It was the easy fix. And the CSS for the above code is
.item {
position: relative;
border: 1px solid green;
height: 30px;
}
.item .name {
position: absolute;
top: 0px;
left: 0px;
}
.item .price {
position: absolute;
right: 0px;
bottom: 0px;
}
So div tag can contain other elements. P should not be forced to do that.
This worked for me:
String dat="02/08/2017";
long date=new SimpleDateFormat("dd/MM/yyyy").parse(dat,newParsePosition(0)).getTime();
java.sql.Date dbDate=new java.sql.Date(date);
System.out.println(dbDate);
I was getting this error on Vue 3. It was because defineComponent
must be imported like this:
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
name: "HelloWorld",
props: {
msg: String,
},
created() {
this.testF();
},
methods: {
testF() {
console.log("testF");
},
},
});
</script>
Here is an example which you could use:
<html>
<body>
<form action="btnclick.php" method="get">
<input type="submit" name="on" value="on">
<input type="submit" name="off" value="off">
</form>
</body>
</html>
<?php
if(isset($_GET['on'])) {
onFunc();
}
if(isset($_GET['off'])) {
offFunc();
}
function onFunc(){
echo "Button on Clicked";
}
function offFunc(){
echo "Button off clicked";
}
?>
Be aware that external-path is not pointing to your secondary storage, aka "removable storage" (despite the name "external"). If you're getting "Failed to find configured root" you may add this line to your XML file.
<root-path name="root" path="." />
See more details here FileProvider and secondary external storage
Use:
if (start-process filename1.exe) {} else {start-process filename2.exe}
It's a little longer than "&&", but it accomplishes the same thing without scripting and is not too hard to remember.
Use os.walk
with next
item function:
next(os.walk('.'))[1]
For Python <=2.5 use:
os.walk('.').next()[1]
os.walk
is a generator and calling next
will get the first result in the form of a 3-tuple (dirpath, dirnames, filenames). Thus the [1]
index returns only the dirnames
from that tuple.
First, attempt to pull from the same refspec that you are trying to push to.
If this does not work, you can force a git push
by using git push -f <repo> <refspec>
, but use caution: this method can cause references to be deleted on the remote repository.
To change even less on your original query, you can turn your join into a RIGHT
join
SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM appointment
RIGHT JOIN person ON person.person_id = appointment.person_id
GROUP BY person.person_id;
This just builds on the selected answer, but as the outer join is in the RIGHT
direction, only one word needs to be added and less changes. - Just remember that it's there and can sometimes make queries more readable and require less rebuilding.
Here's where they're stored on Windows XP through Windows Server 2012 R2:
HKEY_CURRENT_USER\Environment
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
To compare with an int do this:
<?php
$date = date("m");
$dateToCompareTo = 05;
if (strval($date) == strval($dateToCompareTo)) {
echo "They are the same";
}
?>
Ok, maybe I'm missing something here, but this is the way I do it:
public static Byte[] ToByteArray(this Stream stream) {
Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);
Byte[] buffer = new Byte[length];
stream.Read(buffer, 0, length);
return buffer;
}
No. EOF is not a character, but a state of the filehandle.
While there are there are control characters in the ASCII charset that represents the end of the data, these are not used to signal the end of files in general. For example EOT (^D) which in some cases almost signals the same.
When the standard C library uses signed integer to return characters and uses -1 for end of file, this is actually just the signal to indicate than an error happened. I don't have the C standard available, but to quote SUSv3:
If the end-of-file indicator for the stream is set, or if the stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgetc() shall return EOF. If a read error occurs, the error indicator for the stream shall be set, fgetc() shall return EOF, and shall set errno to indicate the error.
You can write like this:
img{
width:100%;
max-width:600px;
}
Check this http://jsfiddle.net/ErNeT/
For a GNU style changelog, I've cooked the function
gnuc() {
{
printf "$(date "+%Y-%m-%d") John Doe <[email protected]>\n\n"
git diff-tree --no-commit-id --name-only -r HEAD | sed 's/^/\t* /'
} | tee /dev/tty | xsel -b
}
With this:
gnuc
and now my clipboard contains something like:
2015-07-24 John Doe <[email protected]>
* gdb/python/py-linetable.c (): .
* gdb/python/py-symtab.c (): .
Then I use the clipboard as a starting point to update the ChangeLog.
It is not perfect (e.g. files should be relative to their ChangeLog path, so python/py-symtab.c
without gdb/
since I will edit the gdb/ChangeLog
), but is a good starting point.
More advanced scripts:
I have to agree with Tromey though: duplicating git commit data in the ChangeLog is useless.
If you are going to make a changelog, make it a good summary of what is going on, possibly as specified at http://keepachangelog.com/
I don't know whether a direct way of doing this is available or not, but you surely there is a workaround via code: listen for onFocus event of EditText
, and as soon it gains focus, set the hint to be nothing with something like editText.setHint("")
:
This may not be exactly what you have to do, but it may be something like this-
myEditText.setOnFocusListener(new OnFocusListener(){
public void onFocus(){
myEditText.setHint("");
}
});
Have you considered simply using Local/Session Storage? -or- Depending on the complexity of what you're building; you could even use indexDB.
note:
Local storage
and indexDB
are not secure - so you want to avoid storing any sensitive / personal data (i.e names, addresses, emails addresses, DOB etc) in either of these.
Session Storage
is a more secure option for anything sensitive, it's only accessible to the origin that set the items and also clears as soon as the browser / tab is closed.
IndexDB
is a little more [but not much more] complicated and is a 30MB noSQL database
built into every browser (but can be basically unlimited if the user opts in) -> next time you're using Google docs, open you DevTools -> application -> IndexDB and take a peak. [spoiler alert: it's encrypted].
Focusing on Local
and Session Storage
; these are both dead simple to use:
// To Set
sessionStorage.setItem( 'key' , 'value' );
// e.g.
sessionStorage.setItem( 'formData' , { name: "Mr Manager", company: "Bluth's Frozen Bananas", ... } );
// Get The Data
const fromData = sessionStorage.getItem( 'key' );
// e.g. (after navigating to next location)
const fromData = sessionStorage.getItem( 'formData' );
// Remove
sessionStorage.removeItem( 'key' );
// Remove _all_ saved data sessionStorage
sessionStorage.clear( );
If simple is not your thing -or- maybe you want to go off road and try a different approach all together -> you can probably use a shared web worker
... y'know, just for kicks.
With this query you can execute any stored procedure(With or Without output parameter):
DECLARE @temp varchar(100)
EXEC my_sp
@parameter1 = 1,
@parameter2 = 2,
@parameter3 = @temp output,
@parameter4 = 3,
@parameter5 = 4
PRINT @temp
Here datatype of @temp should be same as @parameter3 within SP.
Hope this helps..
Solution for IE8 and newer...
Issues worth noting:
Using background-color
to mask a border might not be the best solution. If you have a complex (or unknown) background color (or image), masking will ultimately fail. Also, if you resize the text, you'll notice that white background color (or whatever you set) will start covering up the text on the line above (or below).
You also don't want to "guesstimate" how wide the the sections are either, because it makes the styles very inflexible and almost impossible to implement on a responsive site where the width of the content is changing.
Solution:
(View JSFiddle)
Instead of "masking" a border with a background-color
, use your display
property.
HTML
<div class="group">
<div class="item line"></div>
<div class="item text">This is a test</div>
<div class="item line"></div>
</div>
CSS
.group { display: table; width: 100%; }
.item { display: table-cell; }
.text { white-space: nowrap; width: 1%; padding: 0 10px; }
.line { border-bottom: 1px solid #000; position: relative; top: -.5em; }
Resize your text by placing your font-size
property on the .group
element.
Limitations:
top
property on .line
element needs to be half of line-height
. So, if you have a line-height
of 1.5em
, then the top
should be -.75em
. This is a limitation because it's not automated, and if you are applying these styles on elements with different line-heights, then you might need to reapply your line-height
style.For me, these limitations outweigh the "issues" I noted at the beginning of my answer for most implementations.
Same issue, but for me problem was that Android Studio couldn't find my Default Activity. When I specified the intent filter to catch the MAIN action intent, I didn't specify the LAUNCHER category, and that caused the 'Error Launching activity' issue.
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <-- forgot
</intent-filter>
I found it easier (and more usefull) to use ServerAlias when using multiple vhosts.
<VirtualHost x.x.x.x:80>
ServerName www.example.com
ServerAlias example.com
....
</VirtualHost>
This also works with https vhosts.
I was getting the 405 on my GET call, and the problem turned out that I named the parameter in the GET server-side method Get(int formId)
, and I needed to change the route, or rename it Get(int id)
.
When you are going back and forth between scripts it may only sometimes be necessary to unload a package. Here's a simple IF statement that will prevent warnings that would appear if you tried to unload a package that was not currently loaded.
if("package:vegan" %in% search()) detach("package:vegan", unload=TRUE)
Including this at the top of a script might be helpful.
I hope that makes your day!
There is an issue with scroll direction: rtl. It seems the plugin doesn't support it correctly. Here is the fiddle: fiddle
Note that it works correctly in Chrome, but in all other popular browsers the top scroll bar direction remains left.
This is just an explanation not addressed in other answers
At least in recent versions of Mysql, your first query is not committed.
If you query it under the same session you will see the changes, but if you query it from a different session, the changes are not there, they are not committed.
What's going on?
When you open a transaction, and a query inside it fails, the transaction keeps open, it does not commit nor rollback the changes.
So BE CAREFUL, any table/row that was locked with a previous query likeSELECT ... FOR SHARE/UPDATE
, UPDATE
, INSERT
or any other locking-query, keeps locked until that session is killed (and executes a rollback), or until a subsequent query commits it explicitly (COMMIT
) or implicitly, thus making the partial changes permanent (which might happen hours later, while the transaction was in a waiting state).
That's why the solution involves declaring handlers to immediately ROLLBACK
when an error happens.
Extra
Inside the handler you can also re-raise the error using RESIGNAL
, otherwise the stored procedure executes "Successfully"
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
#.. Query 1 ..
#.. Query 2 ..
#.. Query 3 ..
COMMIT;
END
Yes. See this article. Here's an example from there:
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("White on blue.");
You can try with below one:
<div style="width: 100%; height: 100%; overflow-x: visible; overflow-y: scroll;">Text</div>
Both JB Nizet and Jorge_B's answers are correct.
In its simplest form, creating an executable JAR with Gradle is just a matter of adding the appropriate entries to the manifest. However, it's much more common to have dependencies that need to be included on the classpath, making this approach tricky in practice.
The application plugin provides an alternate approach; instead of creating an executable JAR, it provides:
run
task to facilitate easily running the application directly from the buildinstallDist
task that generates a directory structure including the built JAR, all of the JARs that it depends on, and a startup script that pulls it all together into a program you can rundistZip
and distTar
tasks that create archives containing a complete application distribution (startup scripts and JARs)A third approach is to create a so-called "fat JAR" which is an executable JAR that includes not only your component's code, but also all of its dependencies. There are a few different plugins that use this approach. I've included links to a few that I'm aware of; I'm sure there are more.
convert a number into time as a string
func convertToHMS(number: Int) -> String {
let hour = number / 3600;
let minute = (number % 3600) / 60;
let second = (number % 3600) % 60 ;
var h = String(hour);
var m = String(minute);
var s = String(second);
if h.count == 1{
h = "0\(hour)";
}
if m.count == 1{
m = "0\(minute)";
}
if s.count == 1{
s = "0\(second)";
}
return "\(h):\(m):\(s)"
}
print(convertToHMS(number:3900))
It looks like derivedFactor
from the mosaic
package was designed for this. In this example, it would look something like:
library(mosaic)
myfile <- mutate(myfile, V5 = derivedFactor(
"1" = (V1==1 & V2!=4),
"2" = (V2==4 & V3!=1),
.method = "first",
.default = 0
))
(If you want the outcome to be numeric instead of a factor, wrap the derivedFactor
with an as.numeric
.)
Note that the .default
option combined with .method = "first"
sets the "else" condition -- this approach is described in the help file for derivedFactor
.
You could regex it:
"string".replace(/^\/?|\/?$/, "")
"/installers/services/".replace(/^\/?|\/?$/, "") // -> installers/services
The regex explained:
- Optional first slash: ^/?
, escaped -> ^\/?
(the ^
means beginning of string)
- The pipe ( | ) can be read as or
- Than the option slash at the end -> /?$
, escaped -> \/?$
( the $
means end of string)
Combined it would be ^/?|/$
without escaping. Optional first slash OR optional last slash
I have used a Wrapper to get around this problem. Create a wrapper object and pass your mocked method.
See Mocking Static Methods for Unit Testing by Paul Irwin, it has nice examples.
Let me quickly summarize this for reference:
error_reporting()
adapts the currently active setting for the default error handler.
Editing the error reporting ini options also changes the defaults.
Here it's imperative to edit the correct php.ini
version - it's typically /etc/php5/fpm/php.ini
on modern servers, /etc/php5/mod_php/php.ini
alternatively; while the CLI version has a distinct one.
Alternatively you can use depending on SAPI:
.htaccess
with php_flag
optionsphp.ini
.user.ini
Restarting the webserver as usual.
If your code is unwieldy and somehow resets these options elsewhere at runtime, then an alternative and quick way is to define a custom error handler that just slurps all notices/warnings/errors up:
set_error_handler(function(){});
Again, this is not advisable, just an alternative.
All the solutions are correct, but I found it easier just write a function to implement this. like this:
template <class T1, class T2>
void ContainerInsert(T1 t1, T2 t2)
{
t1->insert(t1->end(), t2->begin(), t2->end());
}
That way you can avoid the temporary placement like this:
ContainerInsert(vec, GetSomeVector());
Just for completion, in the case I want to find the extension in a file name in order to check it, I need to find the last '.', in this case use rfind:
path = 'toto.titi.tata..xls'
path.find('.')
4
path.rfind('.')
15
in my case, I use the following, which works whatever the complete file name is:
filename_without_extension = complete_name[:complete_name.rfind('.')]
Ok I've done it. I'm sharing this code in case someone else will need it:
super.draw(canvas, mapView, true);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStrokeWidth(2);
paint.setColor(android.graphics.Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);
Point point1_draw = new Point();
Point point2_draw = new Point();
Point point3_draw = new Point();
mapView.getProjection().toPixels(point1, point1_draw);
mapView.getProjection().toPixels(point2, point2_draw);
mapView.getProjection().toPixels(point3, point3_draw);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(point1_draw.x,point1_draw.y);
path.lineTo(point2_draw.x,point2_draw.y);
path.lineTo(point3_draw.x,point3_draw.y);
path.lineTo(point1_draw.x,point1_draw.y);
path.close();
canvas.drawPath(path, paint);
//canvas.drawLine(point1_draw.x,point1_draw.y,point2_draw.x,point2_draw.y, paint);
return true;
Thanks for the hint Nicolas!
I had this issue while adding some packages from nuget and forgot to do an update
So first do an update of all packages installed in the project
Update-Package
In the Global.asax.cs add the following
BundleTable.EnableOptimizations = true;
You can find the ObjectId
constructor on require('mongoose').Types
. Here is an example:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();
id
is a newly generated ObjectId
.
You can read more about the Types
object at Mongoose#Types documentation.
It happens because the *.res?
is excluded from migration.
Or something like this:
private static String myRemComa(String input) {
String[] exploded = input.split(",");
input="";
boolean start = true;
for(String str : exploded) {
str=str.trim();
if (str.length()>0) {
if (start) {
input = str;
start = false;
} else {
input = input + "," + str;
}
}
}
return input;
}
Interfaces are implemented through classes. They are purely abstract classes, if you will.
In PHP when a class implements from an interface, the methods defined in that interface are to be strictly followed. When a class inherits from a parent class, method parameters may be altered. That is not the case for interfaces:
interface ImplementMeStrictly {
public function foo($a, $b);
}
class Obedient implements ImplementMeStrictly {
public function foo($a, $b, $c)
{
}
}
will cause an error, because the interface wasn't implemented as defined. Whereas:
class InheritMeLoosely {
public function foo($a)
{
}
}
class IDoWhateverWithFoo extends InheritMeLoosely {
public function foo()
{
}
}
Is allowed.
i don't know if it's the answer to your question but you can try setting the background color in the xml layout like this. It is easy, it always works
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="0xfff00000"
>
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
You can also do more fancy things with backgrounds by creating an xml background file with gradients which are cool and semi transparent, and refer to it for other use see example below:
the background.xml layout
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="90"
android:startColor="#f0000000"
android:endColor="#ff444444"
android:type="linear" />
</shape>
</item>
</selector>
your layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@layout/background"
>
<TextView
android:id="@+id/text_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
Modified (now it accepts any non null string
and any positive chunkSize
) Konstantin Spirin's solution:
public static IEnumerable<String> Split(String value, int chunkSize) {
if (null == value)
throw new ArgumentNullException("value");
else if (chunkSize <= 0)
throw new ArgumentOutOfRangeException("chunkSize", "Chunk size should be positive");
return Enumerable
.Range(0, value.Length / chunkSize + ((value.Length % chunkSize) == 0 ? 0 : 1))
.Select(index => (index + 1) * chunkSize < value.Length
? value.Substring(index * chunkSize, chunkSize)
: value.Substring(index * chunkSize));
}
Tests:
String source = @"ABCDEF";
// "ABCD,EF"
String test1 = String.Join(",", Split(source, 4));
// "AB,CD,EF"
String test2 = String.Join(",", Split(source, 2));
// "ABCDEF"
String test3 = String.Join(",", Split(source, 123));
If @Region
is not a null
value (lets say @Region = 'South'
) it will not return rows where the Region field is null, regardless of the value of ANSI_NULLS.
ANSI_NULLS will only make a difference when the value of @Region
is null
, i.e. when your first query essentially becomes the second one.
In that case, ANSI_NULLS ON will not return any rows (because null = null
will yield an unknown boolean value (a.k.a. null
)) and ANSI_NULLS OFF will return any rows where the Region field is null (because null = null
will yield true
)
If you know the key which you unset then put directly by comma separated
unset($attr['placeholder'], $attr['autocomplete']);
If you are looking for a direct approach and using a local
File in that case.
Try
<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>
This is the case of JS
with inline styling where Image
is a local file that you must have imported with a path.
may be you can do by using AJAX or jquery...
just send that file url on one page and then open like normally open pdf file in that page and use ajax.
1)so as soon as user will click on the button. then u call that function in which u above tast. So by this way there will be only one page and by that you can show as many pdf without refreshing page.
2) if u don't have many pdf and if u don't know then just upload that file on google docs and then just put the share link file....and then just use ajax or jquery.
i prefer jquery if u don't have use AJAX.
Change in your html with adding the function on the button click
<input type="button" value="Clear" onclick="javascript:eraseText();">
<textarea id='output' rows=20 cols=90></textarea>
Try this in your js file:
function eraseText() {
document.getElementById("output").value = "";
}
Use the double-star (aka double-splat?) operator:
func(**{'type':'Event'})
is equivalent to
func(type='Event')
Use this command:
truncate -s 0 /home/SYSTEM_NAME/.ssh/known_hosts
The typeof
operator isn't an infix (so the LHS of your example doesn't make sense).
You need to use it like so...
if (typeof a_string == 'string') {
// This is a string.
}
Remember, typeof
is an operator, not a function. Despite this, you will see typeof(var)
being used a lot in the wild. This makes as much sense as var a = 4 + (1)
.
Also, you may as well use ==
(equality comparison operator) since both operands are String
s (typeof
always returns a String
), JavaScript is defined to perform the same steps had I used ===
(strict comparison operator).
As Box9 mentions, this won't detect a instantiated String
object.
You can detect for that with....
var isString = str instanceof String;
...or...
var isString = str.constructor == String;
But this won't work in a multi window
environment (think iframe
s).
You can get around this with...
var isString = Object.prototype.toString.call(str) == '[object String]';
But again, (as Box9 mentions), you are better off just using the literal String
format, e.g. var str = 'I am a string';
.
This work in both Python 2 and 3:
>>> bytearray(b'ABCD')
bytearray(b'ABCD')
Note string started with b
.
To get individual chars:
>>> print("DEC HEX ASC")
... for b in bytearray(b'ABCD'):
... print(b, hex(b), chr(b))
DEC HEX ASC
65 0x41 A
66 0x42 B
67 0x43 C
68 0x44 D
Hope this helps
If your intention is to get hold of already instantiated controller of another component and that if you are following component/directive based approach you can always require
a controller (instance of a component) from a another component that follows a certain hierarchy.
For example:
//some container component that provides a wizard and transcludes the page components displayed in a wizard
myModule.component('wizardContainer', {
...,
controller : function WizardController() {
this.disableNext = function() {
//disable next step... some implementation to disable the next button hosted by the wizard
}
},
...
});
//some child component
myModule.component('onboardingStep', {
...,
controller : function OnboadingStepController(){
this.$onInit = function() {
//.... you can access this.container.disableNext() function
}
this.onChange = function(val) {
//..say some value has been changed and it is not valid i do not want wizard to enable next button so i call container's disable method i.e
if(notIsValid(val)){
this.container.disableNext();
}
}
},
...,
require : {
container: '^^wizardContainer' //Require a wizard component's controller which exist in its parent hierarchy.
},
...
});
Now the usage of these above components might be something like this:
<wizard-container ....>
<!--some stuff-->
...
<!-- some where there is this page that displays initial step via child component -->
<on-boarding-step ...>
<!--- some stuff-->
</on-boarding-step>
...
<!--some stuff-->
</wizard-container>
There are many ways you can set up require.
(no prefix) - Locate the required controller on the current element. Throw an error if not found.
? - Attempt to locate the required controller or pass null to the link fn if not found.
^ - Locate the required controller by searching the element and its parents. Throw an error if not found.
^^ - Locate the required controller by searching the element's parents. Throw an error if not found.
?^ - Attempt to locate the required controller by searching the element and its parents or pass null to the link fn if not found.
?^^ - Attempt to locate the required controller by searching the element's parents, or pass null to the link fn if not found.
Old Answer:
You need to inject $controller
service to instantiate a controller inside another controller. But be aware that this might lead to some design issues. You could always create reusable services that follows Single Responsibility and inject them in the controllers as you need.
Example:
app.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
var testCtrl1ViewModel = $scope.$new(); //You need to supply a scope while instantiating.
//Provide the scope, you can also do $scope.$new(true) in order to create an isolated scope.
//In this case it is the child scope of this scope.
$controller('TestCtrl1',{$scope : testCtrl1ViewModel });
testCtrl1ViewModel.myMethod(); //And call the method on the newScope.
}]);
In any case you cannot call TestCtrl1.myMethod()
because you have attached the method on the $scope
and not on the controller instance.
If you are sharing the controller, then it would always be better to do:-
.controller('TestCtrl1', ['$log', function ($log) {
this.myMethod = function () {
$log.debug("TestCtrl1 - myMethod");
}
}]);
and while consuming do:
.controller('TestCtrl2', ['$scope', '$controller', function ($scope, $controller) {
var testCtrl1ViewModel = $controller('TestCtrl1');
testCtrl1ViewModel.myMethod();
}]);
In the first case really the $scope
is your view model, and in the second case it the controller instance itself.
In informix it works as Claude said:
INSERT INTO table (column1, column2)
VALUES (value1, value2);
A Subquery in the Select clause, as in your case, is also known as a Scalar Subquery, which means that it's a form of expression. Meaning that it can only return one value.
I'm afraid you can't return multiple columns from a single Scalar Subquery, no.
Here's more about Oracle Scalar Subqueries:
http://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions010.htm#i1033549
Generally the verions of programs are linked to the version of your operating system. So if you were running gutsy you would either have to upgrade to the new jaunty jackalope version which has ruby 1.9 or add the respoistories for jaunty to your /etc/apt/sources.list file. Once you have done that you can start up the synaptic package manager and you should see it in there.
I run MariaDB (MySQL compatible) on two machines locally. I'm not sure what prompted the error and nothing I tried worked. So I stopped the service, deleted everything in MariaDB's directory (except the data directory) and copied the files from my secondary machine and everything is working well enough as far as I can tell.
For a live server it'd be a bit different and a super-guru might be able to add an insight comment (e.g. something outside of the data directory might have something to do with preventing data corruption or indexes in example?). I would just stop the service and copy the entire directory once every month or so and then start the service again.
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
Use parseInt()
.
var num = 2.9
console.log(parseInt(num, 10)); // 2
You can also use |
.
var num = 2.9
console.log(num | 0); // 2
Swift 4 version of Leo Natan answer is
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = UIFont.boldSystemFont(ofSize: 28)
If you wanted to set a custom font you could use
if let font = UIFont(name: "font-name", size: 12) {
UILabel.appearance(whenContainedInInstancesOf: [UITableViewHeaderFooterView.self]).font = font
}
I would rather use the Date valueOf method instead of === or !==
Seems like === is comparing internal Object's references and nothing concerning date.
Try This Code. here we have two longitude and latitude values and selected_location.distanceTo(near_locations) function returns the distance between those places in meters.
Location selected_location = new Location("locationA");
selected_location.setLatitude(17.372102);
selected_location.setLongitude(78.484196);
Location near_locations = new Location("locationB");
near_locations.setLatitude(17.375775);
near_locations.setLongitude(78.469218);
double distance = selected_location.distanceTo(near_locations);
here "distance" is distance between locationA & locationB (in Meters
)
I think this is cool
SELECT value,
PARSENAME(REPLACE(String,',','.'),2) 'Name' ,
PARSENAME(REPLACE(String,',','.'),1) 'Sur Name'
FROM table WITH (NOLOCK)
I also face the same problem. do the simple steps
In windows all you have to do is to go to windows search Allow an app through Windows Firewall.click on Allow another app select Apache and mark public and private both . Open cmd by pressing windows button+r write cmd than in cmd write ipconfig find out your ip . than open up your browser write down your ip http://172.16..x and you will be on the xampp startup page.if you want to access your local site simply put / infront of your ip e.g http://192.168.1.x/yousite. Now you are able to access your website in private network computers .
i hope this will resolve your problem
I got this error for my Linux Jenkins slave. I fixed it by changing from the node from "Known hosts file Verification Strategy" to "Non verifying Verification Strategy".
You can place your tables in a div and add style to your table "float: left"
<div>
<table style="float: left">
<tr>
<td>..</td>
</tr>
</table>
<table style="float: left">
<tr>
<td>..</td>
</tr>
</table>
</div>
or simply use css:
div>table {
float: left
}
This one shows SQL that is currently "ACTIVE":-
select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text
from v$sqltext_with_newlines t,V$SESSION s
where t.address =s.sql_address
and t.hash_value = s.sql_hash_value
and s.status = 'ACTIVE'
and s.username <> 'SYSTEM'
order by s.sid,t.piece
/
This shows locks. Sometimes things are going slow, but it's because it is blocked waiting for a lock:
select
object_name,
object_type,
session_id,
type, -- Type or system/user lock
lmode, -- lock mode in which session holds lock
request,
block,
ctime -- Time since current mode was granted
from
v$locked_object, all_objects, v$lock
where
v$locked_object.object_id = all_objects.object_id AND
v$lock.id1 = all_objects.object_id AND
v$lock.sid = v$locked_object.session_id
order by
session_id, ctime desc, object_name
/
This is a good one for finding long operations (e.g. full table scans). If it is because of lots of short operations, nothing will show up.
COLUMN percent FORMAT 999.99
SELECT sid, to_char(start_time,'hh24:mi:ss') stime,
message,( sofar/totalwork)* 100 percent
FROM v$session_longops
WHERE sofar/totalwork < 1
/
$("#id") vs document.querySelectorAll("#id")
The deal is with the $() function it makes an array and then breaks it up for you but with document.querySelectorAll() it makes an array and you have to break it up.
This is an example of the use of this pattern that worked for me on empty datagrids.
<Style.Triggers>
<DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
<Setter Property="Background">
<Setter.Value>
<VisualBrush Stretch="None">
<VisualBrush.Visual>
<TextBlock Text="We did't find any matching records for your search..." FontSize="16" FontWeight="SemiBold" Foreground="LightCoral"/>
</VisualBrush.Visual>
</VisualBrush>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
Nothing worked for me until I finally found the answer here: http://ptspts.blogspot.co.il/2011/10/how-to-fix-adb-no-permissions-error-on.html
I'm copying the text here in case it disappears in the future.
Create a file named /tmp/android.rules with the following contents (hex vendor numbers were taken from the vendor list page):
SUBSYSTEM=="usb", ATTRS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0e79", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0502", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0b05", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="413c", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0489", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="091e", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="18d1", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="12d1", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="24e3", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2116", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0482", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="17ef", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1004", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="22b8", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0409", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2080", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0955", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2257", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="10a9", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1d4d", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0471", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04da", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="05c6", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1f53", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04e8", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04dd", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0fce", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0930", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="19d2", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1bbb", MODE="0666"
Run the following commands:
sudo cp /tmp/android.rules /etc/udev/rules.d/51-android.rules
sudo chmod 644 /etc/udev/rules.d/51-android.rules
sudo chown root. /etc/udev/rules.d/51-android.rules
sudo service udev restart
sudo killall adb
Disconnect the USB cable between the phone and the computer.
Reconnect the phone.
Run adb devices
to confirm that now it has permission to access the phone.
Please note that it's possible to use , USER="$LOGINNAME"
instead of , MODE="0666"
in the .rules
file, substituting $LOGINNAME
for your login name, i.e. what id -nu
prints.
In some cases it can be necessary to give the udev rules file a name that sorts close to the end, such as z51-android.rules
.
I understand the OPs frustration, this usage of virtual is not for the templated abstraction that the defacto virtual modifier is effective for.
If any are still struggling with this, I would offer my view point, as I try to keep the solutions simple and the jargon to a minimum:
Entity Framework in a simple piece does utilize lazy loading, which is the equivalent of prepping something for future execution. That fits the 'virtual' modifier, but there is more to this.
In Entity Framework, using a virtual navigation property allows you to denote it as the equivalent of a nullable Foreign Key in SQL. You do not HAVE to eagerly join every keyed table when performing a query, but when you need the information -- it becomes demand-driven.
I also mentioned nullable because many navigation properties are not relevant at first. i.e. In a customer / Orders scenario, you do not have to wait until the moment an order is processed to create a customer. You can, but if you had a multi-stage process to achieve this, you might find the need to persist the customer data for later completion or for deployment to future orders. If all nav properties were implemented, you'd have to establish every Foreign Key and relational field on the save. That really just sets the data back into memory, which defeats the role of persistence.
So while it may seem cryptic in the actual execution at run time, I have found the best rule of thumb to use would be: if you are outputting data (reading into a View Model or Serializable Model) and need values before references, do not use virtual; If your scope is collecting data that may be incomplete or a need to search and not require every search parameter completed for a search, the code will make good use of reference, similar to using nullable value properties int? long?. Also, abstracting your business logic from your data collection until the need to inject it has many performance benefits, similar to instantiating an object and starting it at null. Entity Framework uses a lot of reflection and dynamics, which can degrade performance, and the need to have a flexible model that can scale to demand is critical to managing performance.
To me, that always made more sense than using overloaded tech jargon like proxies, delegates, handlers and such. Once you hit your third or fourth programming lang, it can get messy with these.
use return Observable.of(HEROES);
Check in your.angular-cli.json under app -> assets:[] if you have included assets folder.
Or perhaps something here: https://github.com/angular/angular-cli/issues/2231, can help.
You can't do what you ask (and the linked site does not do exactly that either).
You can, however, modify the part of the url after the #
sign, which is called the fragment, like this:
window.location.hash = 'something';
Fragments do not get sent to the server (so, for example, Google itself cannot tell the difference between http://www.google.com/
and http://www.google.com/#something
), but they can be read by Javascript on your page. In turn, this Javascript can decide to perform a different AJAX request based on the value of the fragment, which is how the site you linked to probably does it.
To get selected item, you have to use SELECTEDITEM property of comboBox. And since this is an Object, if you wanna assign it to a string, you have to convert it to string, by using ToString() method:
string myItem = comboBox1.SelectedItem.ToString(); //this does the trick
For API < 11 for textView color I did the following:
int textViewColor = textView.getTextColors().getDefaultColor();
textView.setTextColor(Color.argb(128, Color.red(textViewColor), Color.green(textViewColor), Color.blue(textViewColor))); //50% transparent
A little cumbersome, but hey, it works :-)
Okay. So this is a very old question and has great answers from that time. But a lot has changed since then.
Now, in 2020, if you are working with Kotlin and want to change the fragment then you can do the following.
In your app level build.gradle
file add the following,
dependencies {
def fragment_version = "1.2.5"
// Kotlin
implementation "androidx.fragment:fragment-ktx:$fragment_version"
// Testing Fragments in Isolation
debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
In your activity
supportFragmentManager.commit {
replace(R.id.frame_layout, YourFragment.newInstance(), "Your_TAG")
addToBackStack(null)
}
References
As other answers said, if you can see it you can copy/download it.
To add up to the other answers, just for your information, you can add invisible or tricky watermarks to your images: http://www.cgrats.com/create-an-invisible-watermark-in-photoshop.html (just an example, there are more techniques, just google for invisible watermarks)
Anyway if you want to prove the ownership of your image a good way is to have a bigger resolution copy for yourself, and always publish a lower resolution / size one. Or publish it also on a "public" media like ... deviantart or flickr or something where people can't change the upload date. This way you can prove you had that image before anybody else
Your example code is wrong. This works:
import datetime
datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.
You can easily access it in ConfigureServices, just persist it to a property during Startup method which is called first and gets it passed in, then you can access the property from ConfigureServices.
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
...your code here...
CurrentEnvironment = env;
}
private IHostingEnvironment CurrentEnvironment{ get; set; }
public void ConfigureServices(IServiceCollection services)
{
string envName = CurrentEnvironment.EnvironmentName;
... your code here...
}
<span class="txt">Some Text</span>
.txt:hover {
text-decoration: underline;
}
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#notice_div').load('response.php');
}, 3000); // the "3000"
});
If you can depend on the Google libraries being there for you target market, then you may want to piggy back on GTalk functionality (registering a resource on the existing username - the intercepting it the messages as they come in with a BroadcastReceiver).
If not, and I expect you can't, then you're into bundling your own versions of XMPP. This is a pain, but may be made easier if XMPP is bundled separately as a standalone library.
You may also consider PubSubHubub, but I have no idea the network usage of it. I believe it is built atop of XMPP.
You could use assign
, but using assign
(or get
) is often a symptom of a programming structure that is not very R like. Typically, lists or matrices allow cleaner solutions.
with a list:
A <- lapply (1 : 10, function (x) d + rnorm (3))
with a matrix:
A <- matrix (rep (d, each = 10) + rnorm (30), nrow = 10)
You can do something like
$(this).unbind('click').click();
Now it is possible to install openjdk-11 this way:
sudo apt-get install openjdk-11-jdk
(Previously it installed openjdk-10, but not anymore)
You are almost there :)
All that is left is to
git checkout featurex
git merge our-team
This will merge our-team into featurex.
The above assumes you have already committed/stashed your changes in featurex, if that is not the case you will need to do this first.
Another approach to this issue could be to create a self extracting executable (.exe) using something like winzip and use this as the install vector rather than the zip file. Similarly, you could use NSIS to create an executable installer and use that instead of the zip.
To write text to (or read text from) the Windows clipboard use this VBA function:
Function Clipboard$(Optional s$)
Dim v: v = s 'Cast to variant for 64-bit VBA support
With CreateObject("htmlfile")
With .parentWindow.clipboardData
Select Case True
Case Len(s): .setData "text", v
Case Else: Clipboard = .getData("text")
End Select
End With
End With
End Function
'Three examples of copying text to the clipboard:
Clipboard "Excel Hero was here."
Clipboard var1 & vbLF & var2
Clipboard 123
'To read text from the clipboard:
MsgBox Clipboard
This is a solution that does NOT use MS Forms nor the Win32 API. Instead it uses the Microsoft HTML Object Library which is fast and ubiquitous and NOT deprecated by Microsoft like MS Forms. And this solution respects line feeds. This solution also works from 64-bit Office. Finally, this solution allows both writing to and reading from the Windows clipboard. No other solution on this page has these benefits.
<br>
worked for me.
_.unescape
does what you're looking for
If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.
=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))
or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.
=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")
in earlier versions you need to repeat the VLOOKUP, e.g.
=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))
// this piece of code in the WebApiConfig.cs file or your custom bootstrap application class
// define two types of routes 1. DefaultActionApi and 2. DefaultApi as below
config.Routes.MapHttpRoute("DefaultActionApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { action = "Default", id = RouteParameter.Optional });
// decorate the controller action method with [ActionName("Default")] which need to invoked with below url
// http://localhost:XXXXX/api/Demo/ -- will invoke the Get method of Demo controller
// http://localhost:XXXXX/api/Demo/GetAll -- will invoke the GetAll method of Demo controller
// http://localhost:XXXXX/api/Demo/GetById -- will invoke the GetById method of Demo controller
// http://localhost:57870/api/Demo/CustomGetDetails -- will invoke the CustomGetDetails method of Demo controller
// http://localhost:57870/api/Demo/DemoGet -- will invoke the DemoGet method of Demo controller
public class DemoController : ApiController
{
// Mark the method with ActionName attribute (defined in MapRoutes)
[ActionName("Default")]
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, "Get Method");
}
public HttpResponseMessage GetAll()
{
return Request.CreateResponse(HttpStatusCode.OK, "GetAll Method");
}
public HttpResponseMessage GetById()
{
return Request.CreateResponse(HttpStatusCode.OK, "Getby Id Method");
}
//Custom Method name
[HttpGet]
public HttpResponseMessage DemoGet()
{
return Request.CreateResponse(HttpStatusCode.OK, "DemoGet Method");
}
//Custom Method name
[HttpGet]
public HttpResponseMessage CustomGetDetails()
{
return Request.CreateResponse(HttpStatusCode.OK, "CustomGetDetails Method");
}
}
You can find more debugging info just simply adding the option -loglevel debug, full command will be
ffmpeg -i INPUT OUTPUT -loglevel debug -v verbose
If you`re not using jQuery then please make sure:
var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);
And for the php receiving end:
$_POST['json_name']
If you are trying to bind is a Model class, you can add a new readonly property to it like:
public string FormattedPercentage
{
get
{
If(this.Percentage < 50)
return "0 %";
else
return string.Format("{0} %", this.Percentage)
}
}
Otherwise you can use Andrei's or kostas ch. suggestions if you cannot modify the class itself
Try this, when you see runtimeException due to Looper not prepared before handler.
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Run your task here
}
}, 1000 );
app.component.ts
behaviourService.setName("behaviour");
behaviour.service.ts
private name = new BehaviorSubject("");
getName = this.name.asObservable();`
constructor() {}
setName(data) {
this.name.next(data);
}
custom.component.ts
behaviourService.subscribe(response=>{
console.log(response); //output: behaviour
});
I had the same problem recently and this helped me:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="FILENAME"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize("PATH/TO/FILE"));
ob_clean();
flush();
readfile(PATH/TO/FILE);
exit();
I found this answer here
Sub DeleteEmptyRows()
Worksheets("YourSheetName").Activate
On Error Resume Next
Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
The following code will delete all rows on a sheet(YourSheetName) where the content of Column A is blank.
EDIT: User Defined Type Not Defined is caused by "oTable As Table" and "oRow As Row". Replace Table and Row with Object to resolve the error and make it compile.
The best way is set this two events to all of windows of your app:
GotKeyboardFocus
LostKeyboardFocus
in this way:
WiondowOfMyApp_GotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
windowThatShouldBeTopMost.TopMost = true;
}
WiondowOfMyApp_LostKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
{
windowThatShouldBeTopMost.TopMost = false;
}
This worked for me:
string string_test = "80123456";
unsigned long x;
signed long val;
std::stringstream ss;
ss << std::hex << string_test;
ss >> x;
// ss >> val; // if I try this val = 0
val = (signed long)x; // However, if I cast the unsigned result I get val = 0x80123456
Hate to be the one to bump an old subject, but I found this post extremely useful. After running performance tests on the snippets by stej and it's refinement by Graham Gold, plus the BITS suggestion by Nacht, I have decuded that:
Faced with the decision between the two... I found that Start-BitsTransfer supported Asynchronous mode. So here is the result of my merging the two.
function Copy-File {
# ref: https://stackoverflow.com/a/55527732/3626361
param([string]$From, [string]$To)
try {
$job = Start-BitsTransfer -Source $From -Destination $To `
-Description "Moving: $From => $To" `
-DisplayName "Backup" -Asynchronous
# Start stopwatch
$sw = [System.Diagnostics.Stopwatch]::StartNew()
Write-Progress -Activity "Connecting..."
while ($job.JobState.ToString() -ne "Transferred") {
switch ($job.JobState.ToString()) {
"Connecting" {
break
}
"Transferring" {
$pctcomp = ($job.BytesTransferred / $job.BytesTotal) * 100
$elapsed = ($sw.elapsedmilliseconds.ToString()) / 1000
if ($elapsed -eq 0) {
$xferrate = 0.0
}
else {
$xferrate = (($job.BytesTransferred / $elapsed) / 1mb);
}
if ($job.BytesTransferred % 1mb -eq 0) {
if ($pctcomp -gt 0) {
$secsleft = ((($elapsed / $pctcomp) * 100) - $elapsed)
}
else {
$secsleft = 0
}
Write-Progress -Activity ("Copying file '" + ($From.Split("\") | Select-Object -last 1) + "' @ " + "{0:n2}" -f $xferrate + "MB/s") `
-PercentComplete $pctcomp `
-SecondsRemaining $secsleft
}
break
}
"Transferred" {
break
}
Default {
throw $job.JobState.ToString() + " unexpected BITS state."
}
}
}
$sw.Stop()
$sw.Reset()
}
finally {
Complete-BitsTransfer -BitsJob $job
Write-Progress -Activity "Completed" -Completed
}
}
Also, from ojdbc14 to ojdbc6, several types (e.g., OracleResultSet
, OracleStatement
) moved from package oracle.jdbc.driver
to oracle.jdbc
.
This will hide your console. Implement these lines in your code first to start hiding your console at first.
import win32gui, win32con
the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)
Update May 2020 :
If you've got trouble on pip install win32con
on Command Prompt, you can simply pip install pywin32
.Then on your python script, execute import win32.lib.win32con as win32con
instead of import win32con
.
To show back your program again win32con.SW_SHOW
works fine:
win32gui.ShowWindow(the_program_to_hide , win32con.SW_SHOW)
If the value type is already double, then update the value with $set command can not change the value type double to int when using NumberInt() or NumberLong() function. So, to Change the value type, it must update the whole record.
var re = db.data.find({"name": "zero"})
re['value']=NumberInt(0)
db.data.update({"name": "zero"}, re)
This means the version of android of your avd is older than the version being used to compile the code
You need to access the underlying buffer:
printf("%s\n", someString.c_str());
Or better use cout << someString << endl;
(you need to #include <iostream>
to use cout
)
Additionally you might want to import the std
namespace using using namespace std;
or prefix both string
and cout
with std::
.
Just put the following code for jQuery :
jQuery("input:radio").removeAttr("checked");
And for javascript :
$("input:radio").removeAttr("checked");
There is no need to put any foreach loop , .each() fubction or any thing
For your literal example you'd want to use the adjacent selector (+).
h4 + p {color:red}//any <p> that is immediately preceded by an <h4>
<h4>Some text</h4>
<p>I'm red</p>
<p>I'm not</p>
However, if you wanted to select all successive paragraphs, you'd need to use the general sibling selector (~).
h4 ~ p {color:red}//any <p> that has the same parent as, and comes after an <h4>
<h4>Some text</h4>
<p>I'm red</p>
<p>I am too</p>
Here is an alternative method using ls
:
(ls x.txt && echo yes) || echo no
If you want to hide any output from ls
so you only see yes or no, redirect stdout
and stderr
to /dev/null
:
(ls x.txt >> /dev/null 2>&1 && echo yes) || echo no
You need to use a constant.
CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies
or if you want to use a variable you have to do it this way:
Dim NumberOfZombies As Integer
NumberOfZombies = 20000
Dim Zombies() As Zombies
ReDim Zombies(NumberOfZombies)
TOAD for MS SQL looks pretty good. I've never used it personally but I have used Quest's other products and they're solid.
Not complicated.
<div ng-app="Application" ng-controller="TreeController">
<table>
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
<th>col 3</th>
</tr>
</thead>
<tbody ng-repeat="item in tree">
<tr>
<td>{{item.id}}</td>
<td>{{item.fname}}</td>
<td>{{item.lname}}</td>
</tr>
<tr ng-repeat="children in item.child">
<td style="padding-left:15px;">{{children.id}}</td>
<td>{{children.fname}}</td>
</tr>
</tbody>
</table>
</div>
controller code:
angular.module("myApp", []).
controller("TreeController", ['$scope', function ($scope) {
$scope.tree = [{
id: 1,
fname: "tree",
child: [{
id: 1,
fname: "example"
}],
lname: "grid"
}];
}]);
The key error generally comes if the key doesn't match any of the dataframe column name 'exactly':
You could also try:
import csv
import pandas as pd
import re
with open (filename, "r") as file:
df = pd.read_csv(file, delimiter = ",")
df.columns = ((df.columns.str).replace("^ ","")).str.replace(" $","")
print(df.columns)
Strictly stated you must check all of the following: defined, not empty AND not None.
For "normal" variables it makes a difference if defined and set or not set. See foo
and bar
in the example below. Both are defined but only foo
is set.
On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz
and xyz.msg
in the example below:
cat > test.yml <<EOF
- hosts: 127.0.0.1
vars:
foo: "" # foo is defined and foo == '' and foo != None
bar: # bar is defined and bar != '' and bar == None
tasks:
- debug:
msg : ""
register: xyz # xyz is defined and xyz != '' and xyz != None
# xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "foo is defined and foo == '' and foo != None"
when: foo is defined and foo == '' and foo != None
- debug:
msg: "bar is defined and bar != '' and bar == None"
when: bar is defined and bar != '' and bar == None
- debug:
msg: "xyz is defined and xyz != '' and xyz != None"
when: xyz is defined and xyz != '' and xyz != None
- debug:
msg: "{{ xyz }}"
- debug:
msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
- debug:
msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml
Yeah, you can call other method before of the call base or this!
public class MyException : Exception
{
public MyException(int number) : base(ConvertToString(number))
{
}
private static string ConvertToString(int number)
{
return number.toString()
}
}
use the function norm in scipy.linalg (or numpy.linalg)
>>> from scipy import linalg as LA
>>> a = 10*NP.random.randn(6)
>>> a
array([ 9.62141594, 1.29279592, 4.80091404, -2.93714318,
17.06608678, -11.34617065])
>>> LA.norm(a)
23.36461979210312
>>> # compare with OP's function:
>>> import math
>>> mag = lambda x : math.sqrt(sum(i**2 for i in x))
>>> mag(a)
23.36461979210312
module Enumerable
def map_with_index(&block)
i = 0
self.map { |val|
val = block.call(val, i)
i += 1
val
}
end
end
["foo", "bar"].map_with_index {|item, index| [item, index] } => [["foo", 0], ["bar", 1]]
int keyIndex = Array.FindIndex(words, w => w.IsKey);
That actually gets you the integer index and not the object, regardless of what custom class you have created
Going by this article http://en.wikipedia.org/wiki/Criticism_of_Java#Large_arrays:
Java has been criticized for not supporting arrays of more than 231-1 (about 2.1 billion) elements. This is a limitation of the language; the Java Language Specification, Section 10.4, states that:
Arrays must be indexed by int values... An attempt to access an array component with a long index value results in a compile-time error.
Supporting large arrays would also require changes to the JVM. This limitation manifests itself in areas such as collections being limited to 2 billion elements and the inability to memory map files larger than 2 GiB. Java also lacks true multidimensional arrays (contiguously allocated single blocks of memory accessed by a single indirection), which limits performance for scientific and technical computing.
You can also install simplejson.
If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:
pip install simplejson
This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".
Another way
@Html.TextAreaFor(model => model.Comments[0].Comment)
And in your css do this
textarea
{
font-family: inherit;
width: 650px;
height: 65px;
}
That DataType dealie allows carriage returns in the data, not everybody likes those.
You want to use regex lookahead and lookbehind. This will give you only what is inside the curly braces:
(?<=\{)(.*?)(?=\})
Think that JavaScriptDevelopmentTools might do it. Although, I have eclipse indigo, and I'm pretty sure it does that kind of thing automatically.
I found that the cleanest way to do this is to create a custom TwigExtension and override its getGlobals()
method. Rather than using $_SESSION
, it's also better to use Symfony's Session
class since it handles automatically starting/stopping the session.
I've got the following extension in /src/AppBundle/Twig/AppExtension.php:
<?php
namespace AppBundle\Twig;
use Symfony\Component\HttpFoundation\Session\Session;
class AppExtension extends \Twig_Extension {
public function getGlobals() {
$session = new Session();
return array(
'session' => $session->all(),
);
}
public function getName() {
return 'app_extension';
}
}
Then add this in /app/config/services.yml:
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension }
Then the session can be accessed from any view using:
{{ session.my_variable }}
you export the project from Eclipse and then import the project from Android Studio, this should solve your problem, open a eclipse project without importing it from Android Studio you can cause problems, look at: (Excuse my language, I speak Spanish.) http://developer.android.com/intl/es/sdk/installing/migrate.html
for ANDROID , IPHONE, IPAD, BLACKBERRY, PALM, WINDOWS CE, PALM
<script language="javascript"> <!--
var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
if (mobile) {
alert("MOBILE DEVICE DETECTED");
document.write("<b>------------------------------------------<br>")
document.write("<b>" + navigator.userAgent + "<br>")
document.write("<b>------------------------------------------<br>")
var userAgent = navigator.userAgent.toLowerCase();
if ((userAgent.search("android") > -1) && (userAgent.search("mobile") > -1))
document.write("<b> ANDROID MOBILE <br>")
else if ((userAgent.search("android") > -1) && !(userAgent.search("mobile") > -1))
document.write("<b> ANDROID TABLET <br>")
else if ((userAgent.search("blackberry") > -1))
document.write("<b> BLACKBERRY DEVICE <br>")
else if ((userAgent.search("iphone") > -1))
document.write("<b> IPHONE DEVICE <br>")
else if ((userAgent.search("ipod") > -1))
document.write("<b> IPOD DEVICE <br>")
else if ((userAgent.search("ipad") > -1))
document.write("<b> IPAD DEVICE <br>")
else
document.write("<b> UNKNOWN DEVICE <br>")
}
else
alert("NO MOBILE DEVICE DETECTED"); //--> </script>
%s is the representation of an array of char
char string[10] // here is a array of chars, they max length is 10;
char character; // just a char 1 letter/from the ascii map
character = 'a'; // assign 'a' to character
printf("character %c ",a); //we will display 'a' to stout
so string is an array of char we can assign multiple character per space of memory
string[0]='h';
string[1]='e';
string[2]='l';
string[3]='l';
string[4]='o';
string[5]=(char) 0;//asigning the last element of the 'word' a mark so the string ends
this assignation can be done at initialization like char word="this is a word" // the word array of chars got this string now and is statically defined
toy can also assign values to the array of chars assigning it with functions like strcpy;
strcpy(string,"hello" );
this do the same as the example and automatically add the (char) 0 at the end
so if you print it with %S printf("my string %s",string);
and how string is a array we can just display part of it
// the array one char
printf("first letter of wrd %s is :%c ",string,string[1] );
I got trouble to get it so I post pictures showing different options:
Very very similar UI since at least Chrome 38.0.2125.111 [11 December 2014]
In tab Sources
:
When button is activated, you can Pause On Caught Exceptions
with the checkbox below:
Chrome 27.0.1453.93 Stable
The way to retrieve all the args to a script is here:
@ECHO off
ECHO The %~nx0 script args are...
for %%I IN (%*) DO ECHO %%I
pause
The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer that hosts the exe you are launching. This can be configured on the local security policy of the computer that hosts the exe. You can change the policy (on the server hosting the exe) under
Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log On As Batch Job
Add your user to this list (you could also make the user account a local admin on the machine hosting the exe).
Finally, you could also simply copy your exe from the network location to your local computer and run it from there instead.
Note also that a domain policy could be restricting "Log on as a batch job" rights at your organization.
If all you want to do is display an iframe on a page, the simplest solution I was able to come up with doesn't require divs or flex stuff is:
html {
width: 100%;
height: 100%;
display: table;
}
body {
text-align: center;
vertical-align: middle;
display: table-cell;
}
And then the HTML is just:
<html>
<body>
<iframe ...></iframe>
</body>
</html>
If this is all you need you don't need wrapper divs to do it. This works for text content and stuff, too.
Also this looks even simpler.
Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:
// All code to find the files are here and is working perfectly...
It doesn't make sense to call a API Controller from another controller on the same website.
This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...
As @joris pointed out, iterrows
is much slower than itertuples
and itertuples
is approximately 100 times fater than iterrows
, and I tested speed of both methods in a DataFrame with 5027505 records the result is for iterrows
, it is 1200it/s, and itertuples
is 120000it/s.
If you use itertuples
, note that every element in the for loop is a namedtuple, so to get the value in each column, you can refer to the following example code
>>> df = pd.DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2]},
index=['a', 'b'])
>>> df
col1 col2
a 1 0.1
b 2 0.2
>>> for row in df.itertuples():
... print(row.col1, row.col2)
...
1, 0.1
2, 0.2
@Entity
@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames = "column1"),@UniqueConstraint(columnNames = "column2")})
-- Here both Column1 and Column2 acts as unique constraints separately. Ex : if any time either the value of column1 or column2 value matches then you will get UNIQUE_CONSTRAINT Error.
@Entity
@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames ={"column1","column2"})})
-- Here both column1 and column2 combined values acts as unique constraints
java.util.Date date = ...
DateTime dateTime = new DateTime(date);
Make sure date
isn't null
, though, otherwise it acts like new DateTime()
- I really don't like that.
Press Ctrl+Shift+T in the code editor. It will show you popup with suggestion to create a test.
Mac OS: ? Cmd+Shift+T
If you are using XAMPP on Mac, this worked for me:
Moving the CSV/TXT file to /Applications/XAMPP/xamppfiles/htdocs/ as following
LOAD DATA LOCAL INFILE '/Applications/XAMPP/xamppfiles/htdocs/file.csv' INTO TABLE `tablename` FIELDS TERMINATED BY ',' LINES TERMINATED BY ';'
(Get-ADComputer $(hostname)).DNSHostName
byte[] a = new byte[50];
char [] cArray= System.Text.Encoding.ASCII.GetString(a).ToCharArray();
From the URL thedixon posted
http://bytes.com/topic/c-sharp/answers/250261-byte-char
You cannot ToCharArray the byte without converting it to a string first.
To quote Jon Skeet there
There's no need for the copying here - just use Encoding.GetChars. However, there's no guarantee that ASCII is going to be the appropriate encoding to use.
What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles
By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.
You should try changing the value of -Xmx
and -Xms
.
=RIGHT(TRIM(A1),LEN(TRIM(A1))-FIND(CHAR(7),SUBSTITUTE(" "&TRIM(A1)," ",CHAR(7),
LEN(TRIM(A1))-LEN(SUBSTITUTE(" "&TRIM(A1)," ",""))+1))+1)
This is very robust--it works for sentences with no spaces, leading/trailing spaces, multiple spaces, multiple leading/trailing spaces... and I used char(7) for the delimiter rather than the vertical bar "|" just in case that is a desired text item.
This may have been asked before but:
"every link that specifies target="_new" looks for and finds that window by name, and opens in it.
If you use target="_blank," a brand new window will be created each time, on top of the current window."
from here: http://thedesignspace.net/MT2archives/000316.html
Another possibility is to use the textwrap module. This also avoids the problem of "string just sitting in the middle of nowhere" as mentioned in the question.
import textwrap
mystr = """\
Why, hello there
wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))
You can mount to google drive by running following
from google.colab import drive
drive.mount('/content/drive')
Afterwards For training copy data from gdrive to colab root folder.
!cp -r '/content/drive/My Drive/Project_data' '/content'
where first path is gdrive path and second is colab root folder.
This way training is faster for large data.
I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.
Try the following:
@MvcHtmlString.Create(Model.CommentText.Replace(Environment.NewLine, "<br />"))
According to marcind's
comment on this related question, the ASP.NET MVC team is looking to implement something similar to the <%:
and <%=
for the Razor view engine.
We can turn any question about HTML encoding into a discussion on harmful user inputs, but enough of that already exists.
Anyway, take care of potential harmful user input.
@MvcHtmlString.Create(Html.Encode(Model.CommentText).Replace(Environment.NewLine, "<br />"))
@Html.Raw(Html.Encode(Model.CommentText).Replace("\n", "<br />"))
There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:
const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;
You can check at runtime if the value is valid and if not throw an error, i.e.:
function isToDoDto(obj: any): obj is IToDoDto {
return typeof obj.description === "string" && typeof obj.status === "boolean";
}
@Post()
addToDo(@Response() res, @Request() req) {
if (!isToDoDto(req.body)) {
throw new Error("invalid request");
}
const toDo = req.body as IToDoDto;
this.toDoService.addToDo(toDo);
return res.status(HttpStatus.CREATED).end();
}
As @huyz pointed out, there's no need for the type assertion because isToDoDto
is a type guard, so this should be enough:
if (!isToDoDto(req.body)) {
throw new Error("invalid request");
}
this.toDoService.addToDo(req.body);
I think I may have a better solution for having a fully responsive iframe (a vimeo video in my case) embed on your site. Nest the iframe in a div. Give them the following styles:
div {
width: 100%;
height: 0;
padding-bottom: 56%; /* Change this till it fits the dimensions of your video */
position: relative;
}
div iframe {
width: 100%;
height: 100%;
position: absolute;
display: block;
top: 0;
left: 0;
}
Just did it now for a client, and it seems to be working: http://themilkrunsa.co.za/
You can also check whether div has specific children or not,
if($('#myDiv').has('select').length>0)
{
// Do something here.
console.log("you can log here");
}
Preventing XSS is a different issue from validating input.
Regarding XSS: You should not try to check input for XSS or related exploits. You should prevent XSS exploits, SQL injection and so on by escaping correctly when inserting strings into a different language where some characters are "magic", eg, when inserting strings in HTML or SQL. For example a name like O'Reilly is perfectly valid input, but could cause a crash or worse if inserted unescaped into SQL. You cannot prevent that kind of problems by validating input.
Validation of user input makes sense to prevent missing or malformed data, eg. a user writing "asdf" in the zip-code field and so on. Wrt. e-mail adresses, the syntax is so complex though, that it doesnt provide much benefit to validate it using a regex. Just check that it contains a "@".
re.pl from Devel::REPL
I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.
The SQL*Plus® User's Guide and Reference gives an example:
sqlplus hr@\"sales-server:1521/sales.us.acme.com\"
Pay attention to two important points:
I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:
SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'
<?php
$dt = new DateTime;
if(isset($_GET['year']) && isset($_GET['week'])) {
$dt->setISODate($_GET['year'], $_GET['week']);
} else {
$dt->setISODate($dt->format('o'), $dt->format('W'));
}
$year = $dt->format('o');
$week = $dt->format('W');
?>
<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a>
<a href="<?php echo $_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next Week</a>
<table width="100%" style="height: 75px; border: 1px solid #00A2FF;">
<tr>
<td style="display: table-cell;
vertical-align: middle;
cursor: pointer;
width: 75px;
height: 75px;
border: 4px solid #00A2FF;
border-radius: 50%;">Employee</td>
<?php
do {
echo "<td>" . $dt->format('M') . "<br>" . $dt->format('d M Y') . "</td>\n";
$dt->modify('+1 day');
} while ($week == $dt->format('W'));
?>
</tr>
</table>
O(n) is big O notation used for writing time complexity of an algorithm. When you add up the number of executions in an algoritm you'll get an expression in result like 2N+2, in this expression N is the dominating term(the term having largest effect on expression if its value increases or decreases). Now O(N) is the time comlexity while N is dominating term. Example
For i= 1 to n;
j= 0;
while(j<=n);
j=j+1;
here total number of executions for inner loop are n+1 and total number of executions for outer loop are n(n+1)/2, so total number of executions for whole algorithm are n+1+n(n+1/2) = (n^2+3n)/2. here n^2 is the dominating term so the time complexity for this algorithm is O(n^2)
You can just use the output of is.na
to replace directly with subsetting:
bothbeams.data[is.na(bothbeams.data)] <- 0
Or with a reproducible example:
dfr <- data.frame(x=c(1:3,NA),y=c(NA,4:6))
dfr[is.na(dfr)] <- 0
dfr
x y
1 1 0
2 2 4
3 3 5
4 0 6
However, be careful using this method on a data frame containing factors that also have missing values:
> d <- data.frame(x = c(NA,2,3),y = c("a",NA,"c"))
> d[is.na(d)] <- 0
Warning message:
In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
invalid factor level, NA generated
It "works":
> d
x y
1 0 a
2 2 <NA>
3 3 c
...but you likely will want to specifically alter only the numeric columns in this case, rather than the whole data frame. See, eg, the answer below using dplyr::mutate_if
.
I have solved this topic with the solution I have found here: http://www.blackwasp.co.uk/SwitchConfig.aspx
In short what they state there is: "by adding a post-build event.[...] We need to add the following:
if "Debug"=="$(ConfigurationName)" goto :nocopy
del "$(TargetPath).config"
copy "$(ProjectDir)\Release.config" "$(TargetPath).config"
:nocopy
You are binding the click
event to anchors with an href attribute with value sign_new
.
Either bind anchors with class sign_new
or bind anchors with href value #sign_up
. I would prefer the former.
I have published a proper plugin for the dropdown hover functionality, in which you can even define what happens when clicking on the dropdown-toggle
element:
https://github.com/istvan-ujjmeszaros/bootstrap-dropdown-hover
I had issues with all the previously existing solutions. The simple CSS ones are not using the .open
class on the .dropdown
, so there will be no feedback on the dropdown toggle element when the dropdown is visible.
The js ones are interfering with clicking on .dropdown-toggle
, so the dropdown shows up on hover, then hides it when clicking on an opened dropdown, and moving out the mouse will trigger the dropdown to show up again. Some of the js solutions are braking iOS compatibility, some plugins are not working on modern desktop browsers which are supporting the touch events.
That's why I made the Bootstrap Dropdown Hover plugin which prevents all these issues by using only the standard Bootstrap javascript API, without any hack.
please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like
AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1
hope it helps
I'll share my very simple code for sample purpose. Hope it will help someone like me searching for quick code reference. My goal was to receive rsa signature from backend, then validate against input string using public key and store locally for future periodic verifications. Here is main part used for signature verification:
...
var signature = Get(url); // base64_encoded signature received from server
var inputtext= "inputtext"; // this is main text signature was created for
bool result = VerifySignature(inputtext, signature);
...
private bool VerifySignature(string input, string signature)
{
var result = false;
using (var cps=new RSACryptoServiceProvider())
{
// converting input and signature to Bytes Arrays to pass to VerifyData rsa method to verify inputtext was signed using privatekey corresponding to public key we have below
byte[] inputtextBytes = Encoding.UTF8.GetBytes(input);
byte[] signatureBytes = Convert.FromBase64String(signature);
cps.FromXmlString("<RSAKeyValue><Modulus>....</Modulus><Exponent>....</Exponent></RSAKeyValue>"); // xml formatted publickey
result = cps.VerifyData(inputtextBytes , new SHA1CryptoServiceProvider(), signatureBytes );
}
return result;
}
tldr; jsFiddle Demo
This functionality is not possible with an alert. However, you could use a div
function tempAlert(msg,duration)
{
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:40%;left:20%;background-color:white;");
el.innerHTML = msg;
setTimeout(function(){
el.parentNode.removeChild(el);
},duration);
document.body.appendChild(el);
}
Use this like this:
tempAlert("close",5000);
If you are certain that you only need column A, then you can use an End function in VBA to get that result.
If all the cells A1:A100 are filled, then to select the next empty cell use:
Range("A1").End(xlDown).Offset(1, 0).Select
Here, End(xlDown) is the equivalent of selecting A1 and pressing Ctrl + Down Arrow.
If there are blank cells in A1:A100, then you need to start at the bottom and work your way up. You can do this by combining the use of Rows.Count and End(xlUp), like so:
Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
Going on even further, this can be generalized to selecting a range of cells, starting at a point of your choice (not just in column A). In the following code, assume you have values in cells C10:C100, with blank cells interspersed in between. You wish to select all the cells C10:C100, not knowing that the column ends at row 100, starting by manually selecting C10.
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlUp)).Select
The above line is perhaps one of the more important lines to know as a VBA programmer, as it allows you to dynamically select ranges based on very few criteria, and not be bothered with blank cells in the middle.
Use driver.save_screenshot('/path/to/file')
or driver.get_screenshot_as_file('/path/to/file')
:
import selenium.webdriver as webdriver
import contextlib
@contextlib.contextmanager
def quitting(thing):
yield thing
thing.quit()
with quitting(webdriver.Firefox()) as driver:
driver.implicitly_wait(10)
driver.get('http://www.google.com')
driver.get_screenshot_as_file('/tmp/google.png')
# driver.save_screenshot('/tmp/google.png')
You can also reset select2 value using
$(function() {
$('#d').select2('data', null)
})
alternately you can pass 'allowClear': true
when calling select2 and it will have an X button to reset its value.
Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..
import random
from decimal import Decimal
GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)
EDIT
If you need to use git from bash there is --porcelain
option to git status
:
--porcelain
Give the output in a stable, easy-to-parse format for scripts. Currently this is identical to --short output, but is guaranteed not to change in the future, making it safe for scripts.
Output looks like this:
> git status --porcelain
M starthudson.sh
?? bla
Or if you do only one file at a time:
> git status --porcelain bla
?? bla
ORIGINAL
do:
git status
You will see report stating which files were updated and which ones are untracked.
You can see bla.sh
is tracked and modified and newbla
is not tracked:
# On branch master
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
#
# modified: bla.sh
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# newbla
no changes added to commit (use "git add" and/or "git commit -a")
I had the same problem, what I did was add a new ComboBox
with just the value in the same index then the first one, and then when I change the principal combo the index in the second one change at same time, then I take the value of the second combo and use it.
This is the code:
public Form1()
{
eventos = cliente.GetEventsTypes(usuario);
foreach (EventNo no in eventos)
{
cboEventos.Items.Add(no.eventno.ToString() + "--" +no.description.ToString());
cboEventos2.Items.Add(no.eventno.ToString());
}
}
private void lista_SelectedIndexChanged(object sender, EventArgs e)
{
lista2.Items.Add(lista.SelectedItem.ToString());
}
private void cboEventos_SelectedIndexChanged(object sender, EventArgs e)
{
cboEventos2.SelectedIndex = cboEventos.SelectedIndex;
}
Similar to the above solutions I used @Input()
in a directive and able to pass multiple arrays of values in the directive.
selector: '[selectorHere]',
@Input() options: any = {};
Input.html
<input selectorHere [options]="selectorArray" />
Array from TS file
selectorArray= {
align: 'left',
prefix: '$',
thousands: ',',
decimal: '.',
precision: 2
};
Based on Nrzonline's answer: I fixed the problem of the multiple "." at the end of the input by adding a
let lastCharacterEntered
outside of the input and then onKeyPress
e => {
var allowedChars = "0123456789.";
function contains(stringValue, charValue) {
return stringValue.indexOf(charValue) > -1;
}
var invalidKey =
(e.key.length === 1 && !contains(allowedChars, e.key)) ||
(e.key === "." && contains(e.target.value, "."));
console.log(e.target.value);
invalidKey && e.preventDefault();
if (!invalidKey) {
if (lastCharacterEntered === "." && e.key === ".") {
e.preventDefault();
} else {
lastCharacterEntered = e.key;
}
}
}
First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php
) will display an identification form, asking for a login and password.
To get that form, you should not use :
$cfg['Servers'][$i]['auth_type'] = 'config';
But you should use :
$cfg['Servers'][$i]['auth_type'] = 'cookie';
(At least, that's what I have on a server which prompts for login/password, using a form)
For more informations, you can take a look at the documentation :
'config'
authentication ($auth_type = 'config'
) is the plain old way: username and password are stored in config.inc.php.'cookie'
authentication mode ($auth_type = 'cookie'
) as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.
It is better to include stdlib.h
. Since without stdlibg it takes long as long
I have used this one and it served the purpose:
if($date < date("Y-m-d") ) {
echo "Date is in the past";}
BR
you should try this
g++-4.4 -std=c++0x or g++-4.7 -std=c++0x
I use the following method in my JavaFX applications.
newWindowButton.setOnMouseClicked((event) -> {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("NewWindow.fxml"));
/*
* if "fx:controller" is not set in fxml
* fxmlLoader.setController(NewWindowController);
*/
Scene scene = new Scene(fxmlLoader.load(), 600, 400);
Stage stage = new Stage();
stage.setTitle("New Window");
stage.setScene(scene);
stage.show();
} catch (IOException e) {
Logger logger = Logger.getLogger(getClass().getName());
logger.log(Level.SEVERE, "Failed to create new Window.", e);
}
});
If you want to achieve the same programmatically :
(this is C# but easily transatable to Java)
Button button = new Button(new ContextThemeWrapper(Context, Resource.Style.Widget_AppCompat_Button_Borderless_Colored), null, Resource.Style.Widget_AppCompat_Button_Borderless_Colored);
Match
<Button
style="@style/Widget.AppCompat.Button.Borderless.Colored"
.../>
You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.
You can install "Extended Read Permission" plug-in. Then in either "Global Settings" or in individual job configuration, you can give the user "Extended Read" permission.
You are touching multiple issues here:
1) A stack trace should never be visibile to end users (for user experience and security purposes)
Yes, it should be accessible to diagnose problems of end-users, but end-user should not see them for two reasons:
2) Generating a stack trace is a relatively expensive process (though unlikely to be an issue in most 'exception'al circumstances)
Generating a stack trace happens when the exception is being created/thrown (that's why throwing an exception comes with a price), printing is not that expensive. In fact you can override Throwable#fillInStackTrace()
in your custom exception effectively making throwing an exception almost as cheap as a simple GOTO statement.
3) Many logging frameworks will print the stack trace for you (ours does not and no, we can't change it easily)
Very good point. The main issue here is: if the framework logs the exception for you, do nothing (but make sure it does!) If you want to log the exception yourself, use logging framework like Logback or Log4J, to not put them on the raw console because it is very hard to control it.
With logging framework you can easily redirect stack traces to file, console or even send them to a specified e-mail address. With hardcoded printStackTrace()
you have to live with the sysout
.
4) Printing the stack trace does not constitute error handling. It should be combined with other information logging and exception handling.
Again: log SQLException
correctly (with the full stack trace, using logging framework) and show nice: "Sorry, we are currently not able to process your request" message. Do you really think the user is interested in the reasons? Have you seen StackOverflow error screen? It's very humorous, but does not reveal any details. However it ensures the user that the problem will be investigated.
But he will call you immediately and you need to be able to diagnose the problem. So you need both: proper exception logging and user-friendly messages.
To wrap things up: always log exceptions (preferably using logging framework), but do not expose them to the end-user. Think carefully and about error-messages in your GUI, show stack traces only in development mode.
Dockerfiles are to build an image for example from a bare bone Ubuntu, you can add mysql
called mySQL
on one image and mywordpress
on a second image called mywordpress
.
Compose YAML files are to take these images and run them cohesively.
For example, if you have in your docker-compose.yml
file a service called db
:
services:
db:
image: mySQL --- image that you built.
and a service called wordpress such as:
wordpress:
image: mywordpress
then inside the mywordpress container you can use db
to connect to your mySQL container. This magic is possible because your docker host create a network bridge (network overlay).