Using ex
/vi
editor and globstar option (syntax similar to awk
and sed
):
ex +"/string1/,/string3/p" -R -scq! file.txt
where aaa
is your starting point, and bbb
is your ending text.
To search recursively, try:
ex +"/aaa/,/bbb/p" -scq! **/*.py
Note: To enable **
syntax, run shopt -s globstar
(Bash 4 or zsh).
All answers are correct, but you need to convert a long big fat number into a timer first:
public String toTimer(long milliseconds){
String finalTimerString = "";
String secondsString;
// Convert total duration into time
int hours = (int)( milliseconds / (1000*60*60));
int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
// Add hours if there
if(hours > 0){
finalTimerString = hours + ":";
}
// Prepending 0 to seconds if it is one digit
if(seconds < 10){
secondsString = "0" + seconds;
}else{
secondsString = "" + seconds;}
finalTimerString = finalTimerString + minutes + ":" + secondsString;
// return timer string
return finalTimerString;
}
And this is how you use it:
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.format("%s", toTimer(progress)));
}
I would suggest to kill the port number. It worked for me
netstat -ano | findstr :yourPortNumber taskkill /PID typeyourPIDhere /F
Your function would work like this:
CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;
END
$$ LANGUAGE plpgsql;
Call:
SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.
The aggregate function count()
returns bigint
, but you had rowcount
defined as integer
, so you need an explicit cast ::int
to make this work
I use dollar quoting to avoid quoting hell.
However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.
Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)
The query itself seems rather odd, btw. But that's beside the point here.
render
will be called every time you setState
to re-render the component if there are changes. If you move your call to drawGrid
there rather than calling it in your update*
methods, you shouldn't have a problem.
If that doesn't work for you, there is also an overload of setState
that takes a callback as a second parameter. You should be able to take advantage of that as a last resort.
If you want to find the rows
that have any of the values in a vector, one option is to loop the vector (lapply(v1,..)
), create a logical index of (TRUE/FALSE) with (==
). Use Reduce
and OR (|
) to reduce the list to a single logical matrix by checking the corresponding elements. Sum the rows (rowSums
), double negate (!!
) to get the rows with any matches.
indx1 <- !!rowSums(Reduce(`|`, lapply(v1, `==`, df)), na.rm=TRUE)
Or vectorise and get the row indices with which
with arr.ind=TRUE
indx2 <- unique(which(Vectorize(function(x) x %in% v1)(df),
arr.ind=TRUE)[,1])
I didn't use @kristang's solution as it is giving me errors. Based on a 1000x500
matrix, @konvas's solution is the most efficient (so far). But, this may vary if the number of rows are increased
val <- paste0('M0', 1:1000)
set.seed(24)
df1 <- as.data.frame(matrix(sample(c(val, NA), 1000*500,
replace=TRUE), ncol=500), stringsAsFactors=FALSE)
set.seed(356)
v1 <- sample(val, 200, replace=FALSE)
konvas <- function() {apply(df1, 1, function(r) any(r %in% v1))}
akrun1 <- function() {!!rowSums(Reduce(`|`, lapply(v1, `==`, df1)),
na.rm=TRUE)}
akrun2 <- function() {unique(which(Vectorize(function(x) x %in%
v1)(df1),arr.ind=TRUE)[,1])}
library(microbenchmark)
microbenchmark(konvas(), akrun1(), akrun2(), unit='relative', times=20L)
#Unit: relative
# expr min lq mean median uq max neval
# konvas() 1.00000 1.000000 1.000000 1.000000 1.000000 1.00000 20
# akrun1() 160.08749 147.642721 125.085200 134.491722 151.454441 52.22737 20
# akrun2() 5.85611 5.641451 4.676836 5.330067 5.269937 2.22255 20
# cld
# a
# b
# a
For ncol = 10
, the results are slighjtly different:
expr min lq mean median uq max neval
konvas() 3.116722 3.081584 2.90660 2.983618 2.998343 2.394908 20
akrun1() 27.587827 26.554422 22.91664 23.628950 21.892466 18.305376 20
akrun2() 1.000000 1.000000 1.00000 1.000000 1.000000 1.000000 20
v1 <- c('M017', 'M018')
df <- structure(list(datetime = c("04.10.2009 01:24:51",
"04.10.2009 01:24:53",
"04.10.2009 01:24:54", "04.10.2009 01:25:06", "04.10.2009 01:25:07",
"04.10.2009 01:26:07", "04.10.2009 01:26:27", "04.10.2009 01:27:23",
"04.10.2009 01:27:30", "04.10.2009 01:27:32", "04.10.2009 01:27:34"
), col1 = c("M017", "M018", "M051", "<NA>", "<NA>", "<NA>", "<NA>",
"<NA>", "<NA>", "M017", "M051"), col2 = c("<NA>", "<NA>", "<NA>",
"M016", "M015", "M017", "M017", "M017", "M017", "<NA>", "<NA>"
), col3 = c("<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>",
"<NA>", "<NA>", "<NA>", "<NA>"), col4 = c(NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA)), .Names = c("datetime", "col1", "col2",
"col3", "col4"), class = "data.frame", row.names = c("1", "2",
"3", "4", "5", "6", "7", "8", "9", "10", "11"))
This might help:
select * from tbl where col like '[ABC-XYZ-PQR]%'
I've used this in SQL Server 2005 and it worked.
Until very recent years, PHP has defined its AST and PHP interpreter has isolated the parser from the evaluation part. During the time when the closure is introduced, PHP's parser is highly coupled with the evaluation.
Therefore when the closure was firstly introduced to PHP, the interpreter has no method to know which which variables will be used in the closure, because it is not parsed yet. So user has to pleased the zend engine by explicit import, doing the homework that zend should do.
This is the so-called simple way in PHP.
Try the below Code:
$("#textbox").on('change keypress paste', function() {
console.log("Handler for .keypress() called.");
});
If you see this warning:
warning: receiver 'MyCoolClass' is a forward class and corresponding @interface may not exist
you need to #import
the file, but you can do that in your implementation file (.m), and use the @class
declaration in your header file.
@class
does not (usually) remove the need to #import
files, it just moves the requirement down closer to where the information is useful.
For Example
If you say @class MyCoolClass
, the compiler knows that it may see something like:
MyCoolClass *myObject;
It doesn't have to worry about anything other than MyCoolClass
is a valid class, and it should reserve room for a pointer to it (really, just a pointer). Thus, in your header, @class
suffices 90% of the time.
However, if you ever need to create or access myObject
's members, you'll need to let the compiler know what those methods are. At this point (presumably in your implementation file), you'll need to #import "MyCoolClass.h"
, to tell the compiler additional information beyond just "this is a class".
You need a semicolon after font-family: Arial, Helvetica, sans-serif
. This will make your updated code the following:
<!DOCTYPE>
<html>
<head>
<title>DIV Font</title>
<style>
.my_text
{
font-family: Arial, Helvetica, sans-serif;
font-size: 40px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="my_text">some text</div>
</body>
</html>
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/
Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)
See this question for additional information.
The preferred way is to always use the literal syntax with square brackets; its behaviour is predictable for any number of items, unlike Array
's. What's more, Array
is not a keyword, and although it is not a realistic situation, someone could easily overwrite it:
function Array() { return []; }
alert(Array(1, 2, 3)); // An empty alert box
However, the larger issue is that of consistency. Someone refactoring code could come across this function:
function fetchValue(n) {
var arr = new Array(1, 2, 3);
return arr[n];
}
As it turns out, only fetchValue(0)
is ever needed, so the programmer drops the other elements and breaks the code, because it now returns undefined
:
var arr = new Array(1);
I found this solution amazing.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
ArrayList list = new ArrayList();
list.add("one");
list.add("two");
list.add("three");
%>
<c:set var="list" value="<%=list%>" />
<html>
<body>
My list is ${list}<br/>
<c:if test='${fn:contains(list, "two")}'>
My list contains two <br/>
</c:if>
<c:if test='${fn:contains(list, ",")}'>
My list contains ,
</c:if>
</body>
</html>
The output for the code above is
My list is [one, two, three]
My list contains two
My list contains ,
I hope it helps someone.
I try GET 'http://example.com/?var=value'
Important use '
add >/dev/null 2>&1
for not send email when this activate
Sorry for my English
This is my function -
public function is_assoc_array($array){
if(is_array($array) !== true){
return false;
}else{
$check = json_decode(json_encode($array));
if(is_object($check) === true){
return true;
}else{
return false;
}
}
}
Some examples
print_r((is_assoc_array(['one','two','three']))===true?'Yes':'No'); \\No
print_r(is_assoc_array(['one'=>'one','two'=>'two','three'=>'three'])?'Yes':'No'); \\Yes
print_r(is_assoc_array(['1'=>'one','2'=>'two','3'=>'three'])?'Yes':'No'); \\Yes
print_r(is_assoc_array(['0'=>'one','1'=>'two','2'=>'three'])?'Yes':'No'); \\No
There was a similar solution by @devios1 in one of the answers but this was just another way using the inbuilt json related functions of PHP. I haven't checked how this solution fairs in terms of performance compared to other solutions that have been posted here. But it certainly has helped me solve this problem. Hope this helps.
It is worth noting that @Marius's second answer could be used as pure Javascript solution.
document.getElementById('elementId').tagName
Your command line should have a -d/--data inserted before the string you want to send in the PUT, and you want to set the Content-Type and not Accept.
curl -H 'Content-Type: application/json' -X PUT -d '[JSON]' \
http://example.com/service
Using the exact JSON data from the question, the full command line would become:
curl -H 'Content-Type: application/json' -X PUT \
-d '{"tags":["tag1","tag2"],
"question":"Which band?",
"answers":[{"id":"a0","answer":"Answer1"},
{"id":"a1","answer":"answer2"}]}' \
http://example.com/service
Note: JSON data wrapped only for readability, not valid for curl
request.
As mentioned by Klap "android.R.layout.simple_list_item_1 is a reference to an built-in XML layout document that is part of the Android OS"
All the layouts are located in: sdk\platforms\android-xx\data\res\layout
To view the XML of layout :
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select "Open declaration in layout/simple_list_item_1.xml". It'll direct you to the contents of the XML.
Android Studio: Project Window -> External Libraries -> Android X Platform -> res -> layout, and here you will see a list of available layouts.
The utf8mb4
character set is useful because nowadays we need support for storing not only language characters but also symbols, newly introduced emojis, and so on.
A nice read on How to support full Unicode in MySQL databases by Mathias Bynens can also shed some light on this.
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.
xDoc.LoadXML("<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer>
</body></head>");
You don't need ng-checked
when you use ng-model
. If you're performing CRUD on your HTML Form, just create a model for CREATE
mode that is consistent with your EDIT
mode during the data-binding:
$scope.dataModel = {
isItemSelected: true,
isApproved: true,
somethingElse: "Your default value"
}
$scope.dataModel = getFromDatabaseWithSameStructure()
Then whether EDIT
or CREATE
mode, you can consistently make use of your ng-model
to sync with your database.
Check the XML. It is not a valid xml.
Prolog is the first line with xml version info. It ok not to include it in your xml.
This error is thrown when the parser reads an invalid tag at the start of the document. Normally where the prolog resides.
e.g.
\rule{1.2ex}{1.2ex}
will give you a filled box.
\fbox{\phantom{\rule{.7ex}{.7ex}}}
will give you an empty box. The \phantom
command will typeset with invisible ink.
The advantage of this approach is that no package is needed. Also the size is up to your control. Less is more.
My application is using Mura CMS and I faced this issue. However the solution was the password mismatch between my mysql local server and the password in the config files. As soon as I synched them it worked.
Yes, you can input multiple items from cin
, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T)
(where T
is some arbitrary type) returns a reference to its first argument. So cin >> a
returns cin
, which can be used as (cin>>a)>>b
and so forth.
Note that each call to operator>>(istream&, T)
first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.
You forgot the C: after the file:///
This works for me
<!DOCTYPE html>
<html>
<head>
<title>Experiment</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
html,body { width: 100%; height: 100%; }
</style>
</head>
<body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
</body>
</html>
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):
Mark Miller said... June 28, 2010 12:13 PM
Thanks for the post. "Interference issues" was intentionally vague. At the time of writing, the issues were still being investigated, but it was clear there were several broken scenarios.
For instance, some applications use Assemby.LoadWithPartialName to load the highest version of an assembly. If the highest version was compiled with v4, then a v2 (3.0 or 3.5) app could not load it, and the app would crash, even if there were a version that would have worked. Originally, we partitioned the GAC under it's original location, but that caused some problems with windows upgrade scenarios. Both of these involved code that had already shipped, so we moved our (version-partitioned GAC to another place.
This shouldn't have any impact to most applications, and doesn't add any maintenance burden. Both locations should only be accessed or modified using the native GAC APIs, which deal with the partitioning as expected. The places where this does surface are through APIs that expose the paths of the GAC such as GetCachePath, or examining the path of mscorlib loaded into managed code.
It's worth noting that we modified GAC locations when we released v2 as well when we introduced architecture as part of the assembly identity. Those added GAC_MSIL, GAC_32, and GAC_64, although all still under %windir%\assembly. Unfortunately, that wasn't an option for this release.
Hope it helps future readers.
Try the following code:
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Add("YourKey", "YourValue");
config.Save(ConfigurationSaveMode.Minimal);
It worked for me :-)
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
Googling gives me this:
Command A & Command B
Execute Command A, then execute Command B (no evaluation of anything)
Command A | Command B
Execute Command A, and redirect all its output into the input of Command B
Command A && Command B
Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B
Command A || Command B
Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B
You need to get 2 folders back from your css file.
Try:
background-image: url("../../images/image.png");
I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .
It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .
... and a lot of other examples as well ...
You first need to check if directory exists file_exists('path_to_directory')
Then use mkdir(path_to_directory)
to create a directory
mkdir( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] ) : bool
More about mkdir() here
Full code here:
$structure = './depth1/depth2/depth3/';
if (!file_exists($structure)) {
mkdir($structure);
}
Once you have localized the dropdown element
dropdownElement = $("#dropdownElement");
Find the <option>
element using the JQuery attribute selector
dropdownElement.find('option[value=foo]').remove();
I did it this way. Firstly, don't push your changes or you are out of luck. Grab and install the collapse extension. Commit another dummy changeset. Then use collapse to combine the previous two changesets into one. It will prompt you for a new commit message, giving you the messages that you already have as a starting point. You have effectively changed your original commit message.
For multicolumn listbox extract data from any column of selected row by
listboxControl.List(listboxControl.ListIndex,col_num)
where col_num is required column ( 0 for first column)
SELECT
table_name,
column_name,
CONCAT('ALTER TABLE `',
TABLE_SCHEMA,
'`.`',
table_name,
'` CHANGE `',
column_name,
'` `',
column_name,
'` ',
column_type,
' ',
IF(is_nullable = 'YES', '' , 'NOT NULL '),
IF(column_default IS NOT NULL, concat('DEFAULT ', IF(column_default IN ('CURRENT_TIMESTAMP', 'CURRENT_TIMESTAMP()', 'NULL', 'b\'0\'', 'b\'1\''), column_default, CONCAT('\'',column_default,'\'') ), ' '), ''),
IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '' AND column_type = 'timestamp','NULL ', ''),
IF(column_default IS NULL AND is_nullable = 'YES' AND column_key = '','DEFAULT NULL ', ''),
extra,
' COMMENT \'',
column_comment,
'\' ;') as script
FROM
information_schema.columns
WHERE
table_schema = 'my_database_name'
ORDER BY table_name , column_name
Note: You can improve to only one table if you prefer
The solution given by @Rufinus is great but if you have auto increments it will break it.
I put together a little test here:
\documentclass[10pt,twocolumn]{article}
\title{Article Title}
\author{
First Author\\
Department\\
school\\
email@edu
\and
Second Author\\
Department\\
school\\
email@edu
\and
Third Author\\
Department\\
school\\
email@edu
\and
Fourth Author\\
Department\\
school\\
email@edu
}
\date{\today}
\begin{document}
\maketitle
\begin{abstract}
\ldots
\end{abstract}
\section{Introduction}
\ldots
\end{document}
Things to note, the title, author and date fields are declared before \begin{document}
. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn
in the document class.
This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}
. Here's a more detailed article on \LaTeX
font sizes:
https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont
To italicize you can use {\it First Name}
or \textit{First Name}
.
Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.
Do not try doing that using a map function. Map function should be used to map values from one thing to other. When the number of input and output match.
In this case use filter function which is also available on the array. Filter function is used when you want to selectively take values maching certain criteria. Then you can write your code like
var items = list
.filter((i, index) => (index < 3))
.map((i, index) => {
return (
<myview item={i} key={i.id} />
);
});
Using Woodstox, configure the StAX parser to validate against your schema and parse the XML.
If exceptions are caught the XML is not valid, otherwise it is valid:
// create the XSD schema from your schema file
XMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);
XMLValidationSchema validationSchema = schemaFactory.createSchema(schemaInputStream);
// create the XML reader for your XML file
WstxInputFactory inputFactory = new WstxInputFactory();
XMLStreamReader2 xmlReader = (XMLStreamReader2) inputFactory.createXMLStreamReader(xmlInputStream);
try {
// configure the reader to validate against the schema
xmlReader.validateAgainst(validationSchema);
// parse the XML
while (xmlReader.hasNext()) {
xmlReader.next();
}
// no exceptions, the XML is valid
} catch (XMLStreamException e) {
// exceptions, the XML is not valid
} finally {
xmlReader.close();
}
Note: If you need to validate multiple files, you should try to reuse your XMLInputFactory
and XMLValidationSchema
in order to maximize the performance.
The original code is a bit cumbersome and you might want to use the collections.deque instead if you want to use BFS to find if a path exists between 2 points on the graph. Here is a quick solution I hacked up:
Note: this method might continue infinitely if there exists no path between the two nodes. I haven't tested all cases, YMMV.
from collections import deque
# a sample graph
graph = {'A': ['B', 'C','E'],
'B': ['A','C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F','D'],
'F': ['C']}
def BFS(start, end):
""" Method to determine if a pair of vertices are connected using BFS
Args:
start, end: vertices for the traversal.
Returns:
[start, v1, v2, ... end]
"""
path = []
q = deque()
q.append(start)
while len(q):
tmp_vertex = q.popleft()
if tmp_vertex not in path:
path.append(tmp_vertex)
if tmp_vertex == end:
return path
for vertex in graph[tmp_vertex]:
if vertex not in path:
q.append(vertex)
I usually write in such style :
<a class="btn" ng-click="remove($index)">Delete</a>
$scope.remove = function(index){
$scope.[yourArray].splice(index, 1)
};
Hope this will help You have to use a dot(.) between $scope and [yourArray]
Today there are four font container formats in use on the web: EOT, TTF, WOFF,
andWOFF2.
Unfortunately, despite the wide range of choices, there isn't a single universal format that works across all old and new browsers:
If you want your web app to have the same font across all browsers then you might want to provide all 4 font type in CSS
@font-face {
font-family: 'besom'; !important
src: url('fonts/besom/besom.eot');
src: url('fonts/besom/besom.eot?#iefix') format('embedded-opentype'),
url('fonts/besom/besom.woff2') format('woff2'),
url('fonts/besom/besom.woff') format('woff'),
url('fonts/besom/besom.ttf') format('truetype'),
url('fonts/besom/besom.svg#besom_2regular') format('svg');
font-weight: normal;
font-style: normal;
}
In this piece of code the height of left panel will gets adjusted to the height of right panel dynamically...
function resizeDiv() {
var rh=$('.pright').height()+'px'.toString();
$('.pleft').css('height',rh);
}
You can try this here http://jsfiddle.net/SriharshaCR/7q585k1x/9/embedded/result/
Include this code somewhere when you slide to your 'section' called blog.
$("#myLink").click(function() {
setTimeout(function() {
window.navigate("the url of the page you want to navigate back to");
}, 2000);
});
Where myLink
is the id of your href.
When building a GET
request, there is no body to the request, but rather everything goes on the URL. To build a URL (and properly percent escaping it), you can also use URLComponents
.
var url = URLComponents(string: "https://www.google.com/search/")!
url.queryItems = [
URLQueryItem(name: "q", value: "War & Peace")
]
The only trick is that most web services need +
character percent escaped (because they'll interpret that as a space character as dictated by the application/x-www-form-urlencoded
specification). But URLComponents
will not percent escape it. Apple contends that +
is a valid character in a query and therefore shouldn't be escaped. Technically, they are correct, that it is allowed in a query of a URI, but it has a special meaning in application/x-www-form-urlencoded
requests and really should not be passed unescaped.
Apple acknowledges that we have to percent escaping the +
characters, but advises that we do it manually:
var url = URLComponents(string: "https://www.wolframalpha.com/input/")!
url.queryItems = [
URLQueryItem(name: "i", value: "1+2")
]
url.percentEncodedQuery = url.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
This is an inelegant work-around, but it works, and is what Apple advises if your queries may include a +
character and you have a server that interprets them as spaces.
So, combining that with your sendRequest
routine, you end up with something like:
func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
var components = URLComponents(string: url)!
components.queryItems = parameters.map { (key, value) in
URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let request = URLRequest(url: components.url!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, // is there data
let response = response as? HTTPURLResponse, // is there HTTP response
(200 ..< 300) ~= response.statusCode, // is statusCode 2XX
error == nil else { // was there no error, otherwise ...
completion(nil, error)
return
}
let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
completion(responseObject, nil)
}
task.resume()
}
And you'd call it like:
sendRequest("someurl", parameters: ["foo": "bar"]) { responseObject, error in
guard let responseObject = responseObject, error == nil else {
print(error ?? "Unknown error")
return
}
// use `responseObject` here
}
Personally, I'd use JSONDecoder
nowadays and return a custom struct
rather than a dictionary, but that's not really relevant here. Hopefully this illustrates the basic idea of how to percent encode the parameters into the URL of a GET request.
See previous revision of this answer for Swift 2 and manual percent escaping renditions.
You can browse package folder below method.
Preferences\Browse Packages
C:\Users\%username%\AppData\Roaming\Sublime Text 2\Packages
(equals %appdata%\Sublime Text 2\Packages
)Or Simply change the @Style/AppTheme
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
This works for me!
This is for Ubunutu 14.04:
In file /etc/apache2/apache2.conf
it should be as below without the directory name:
<Directory /home/username>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
And in file /etc/apache2/sites-available/000-default.conf
you should include the custom directory name, i.e., www:
DocumentRoot /home/username/www
If it is not as above, it will give you an error when loading the server:
Forbidden You don't have permission to access / on this server
This was my stupidity, but a stupidity that was not easy to identify :).
Problem:
If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war.
If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!
You have uniqid function for unique id
You can add prefix to make it more unique
Source : http://pk1.php.net/uniqid
Try this
TextWatcher changeText = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
tv3.setText(et.getText().toString());
tv3.post(new Runnable() {
@Override
public void run() {
while(tv3.getLineCount() >= 3){
tv3.setTextSize((tv3.getTextSize())-1);
}
}
});
}
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void afterTextChanged(Editable s) { }
};
The MultiCell
is used for print text with multiple lines. It has the same atributes of Cell
except for ln
and link
.
$pdf->MultiCell( 200, 40, $reportSubtitle, 1);
What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).
MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
You can read the full documentation here.
To expand on runeh's answer:
>>> def foo(a):
... x = 2
... return x + a
>>> import inspect
>>> inspect.getsource(foo)
u'def foo(a):\n x = 2\n return x + a\n'
print inspect.getsource(foo)
def foo(a):
x = 2
return x + a
EDIT: As pointed out by @0sh this example works using ipython
but not plain python
. It should be fine in both, however, when importing code from source files.
Maybe it is the case that you have your path in couple of lines, you used enter to make it? If so, then part of you paths might look like that "/\nData/" instead of "/Data/", which causes the problem. Just set it to be in one line and issue is solved!
I needed to get the form data as some sort of object. I used this:
$('#preview_form').serializeArray().reduce((function(acc, val) {
acc[val.name.replace('[', '_').replace(']', '')] = val.value;
return acc;
}), {});
For symfony 2.6 and above we can use
{{ app.user.getFirstname() }}
as app.security global variable for Twig template has been deprecated and will be removed from 3.0
more info:
http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
and see the global variables in
http://symfony.com/doc/current/reference/twig_reference.html
It may not work for you if you use localhost/info.php
.
You may be able to found the clue from the error. Find the port number in the error message. To me it was 80. I changed address as http://localhost:80/info.php, and then it worked to me.
Use it in conjunction with pipefail
.
set -e
set -o pipefail
-e (errexit): Abort the script at the first error, when a command exits with non-zero status (except in until or while loops, if-tests, and list constructs)
-o pipefail: Causes a pipeline to return the exit status of the last command in the pipe that returned a non-zero return value.
If your code is ES7 based (or upper versions):
channelArray.includes('three'); //will return true or false
If not, for example you are using IE with no babel transpile:
channelArray.indexOf('three') !== -1; //will return true or false
the indexOf
method will return the position the element has into the array, because of that we use !==
different from -1 if the needle is found at the first position.
Im my browser, this doesn't work at all. The tooltip field doesn't show a link, but <a href='#' onClick='alert('Hello World!')>The Link</a>
.
I'm using FF 3.6.12.
You'll have to do this by hand with JS and CSS. Begin here
Your problem is most likely with the video file, not the code. Your video is most likely not "safe for streaming". See where to place videos to stream android for more.
From http://docs.python-requests.org/en/latest/user/quickstart/
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get
or .post
method.
So more specific to your question:
headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)
Only for using as a value:
x = 3 if a==2 else 0
or
return 3 if a==2 else 0
Note: if you're using(importing) org.json.simple.JSONArray
, you have to use JSONArray.size()
to get the data you want. But use JSONArray.length()
if you're using org.json.JSONArray
.
What would you expect it to return when it's supposed to format a number ? If you have a number you can't pretty much do anything with it because e.g.2 == 2.0 == 2.00
etc. so it has to be a string.
You can use a modulus to get the remainder. Though @cnicutar's answer seems cleaner/more direct.
It is possible without any Javascript :)
The HTML:
<div class='box'>
<div class='content'>Aspect ratio of 1:1</div>
</div>
The CSS:
.box {
position: relative;
width: 50%; /* desired width */
}
.box:before {
content: "";
display: block;
padding-top: 100%; /* initial ratio of 1:1*/
}
.content {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
/* Other ratios - just apply the desired class to the "box" element */
.ratio2_1:before{
padding-top: 50%;
}
.ratio1_2:before{
padding-top: 200%;
}
.ratio4_3:before{
padding-top: 75%;
}
.ratio16_9:before{
padding-top: 56.25%;
}
IMHO JSmooth seems to do a pretty good job.
Would you be happy with your Python command running another program to get the info?
If so, I'd suggest you have a look at PsList and all its options. For example, The following would tell you about any running iTunes process
PsList itunes
If you can work out how to interpret the results, this should hopefully get you going.
Edit:
When I'm not running iTunes, I get the following:
pslist v1.29 - Sysinternals PsList
Copyright (C) 2000-2009 Mark Russinovich
Sysinternals
Process information for CLARESPC:
Name Pid Pri Thd Hnd Priv CPU Time Elapsed Time
iTunesHelper 3784 8 10 229 3164 0:00:00.046 3:41:05.053
With itunes running, I get this one extra line:
iTunes 928 8 24 813 106168 0:00:08.734 0:02:08.672
However, the following command prints out info only about the iTunes program itself, i.e. with the -e
argument:
pslist -e itunes
I think the best answer is actually explained on the vim wikia:
http://vim.wikia.com/wiki/Indenting_source_code
Note that it advises against using "set autoindent." The best feature of all I find in this explanation is being able to set per-file settings, which is especially useful if you program in python and C++, for example, as you'd want 4 spaces for tabs in the former and 2 for spaces in the latter.
It will work perfectly with 50px. Which will act as a static and thus as min-width.
font-size: calc(50px + 5vw);
Use this code:
internal void SomeFunction() {
Dictionary<string, string> formField = new Dictionary<string, string>();
formField.Add("Name", "Henry");
formField.Add("Age", "21");
string body = GetBodyStringFromDictionary(formField);
// output : Name=Henry&Age=21
}
internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
string body = string.Empty;
foreach (var pair in formField)
{
body += $"{pair.Key}={pair.Value}&";
}
// delete last "&"
body = body.Substring(0, body.Length - 1);
return body;
}
If the question taught me anything, it's this: don't change something that already works :)
I'm providing an (almost) verbatim copy of how this was handled on http://www.jakpsatweb.cz/css/css-vertical-center-solution.html - it's heavily hacked for IE but provides a pure CSS way of answering the question:
.container {display:table; height:100%; position:absolute; overflow:hidden; width:100%;}
.helper {#position:absolute; #top:50%;
display:table-cell; vertical-align:middle;}
.content {#position:relative; #top:-50%;
margin:0 auto; width:200px; border:1px solid orange;}
Fiddle: http://jsfiddle.net/S9upd/4/
I've run this through browsershots and it seems fine; if for nothing else, I'll keep the original below so that margin percentage handling as dictated by CSS spec sees the light of day.
Looks like I'm late to the party!
There are some comments above that suggest this is a CSS question - separation of concerns and all. Let me preface this by saying that CSS really shot itself in the foot on this one. I mean, how easy would it be to do this:
.container {
position:absolute;
left: 50%;
top: 50%;
overflow:visible;
}
.content {
position:relative;
margin:-50% 50% 50% -50%;
}
Right? Container's top left corner would be in the center of the screen, and with negative margins the content will magically reappear in the absolute center of the page! http://jsfiddle.net/rJPPc/
Wrong! Horizontal positioning is OK, but vertically... Oh, I see. Apparently in css, when setting top margins in %, the value is calculated as a percentage always relative to the width of the containing block. Like apples and oranges! If you don't trust me or Mozilla doco, have a play with the fiddle above by adjusting content width and be amazed.
Now, with CSS being my bread and butter, I was not about to give up. At the same time, I prefer things easy, so I've borrowed the findings of a Czech CSS guru and made it into a working fiddle. Long story short, we create a table in which vertical-align is set to middle:
<table class="super-centered"><tr><td>
<div class="content">
<p>I am centered like a boss!</p>
</div>
</td></tr></table>
And than the content's position is fine-tuned with good old margin:0 auto;:
.super-centered {position:absolute; width:100%;height:100%;vertical-align:middle;}
.content {margin:0 auto;width:200px;}?
Working fiddle as promised: http://jsfiddle.net/teDQ2/
Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.
public class Hello {
static {
System.out.println("Hello, World!");
}
}
Of course, you can run the program as java Hello
and you will see the message; however, the command will also fail with a message stating:
Exception in thread "main" java.lang.NoSuchMethodError: main
[Edit] as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0)
immediately after printing the message.
As of JDK6 onward, you no longer see the message from the static
initializer block; details here.
The easier way to accept all accents is this:
[A-zÀ-ú] // accepts lowercase and uppercase characters
[A-zÀ-ÿ] // as above but including letters with an umlaut (includes [ ] ^ \ × ÷)
[A-Za-zÀ-ÿ] // as above but not including [ ] ^ \
[A-Za-zÀ-ÖØ-öø-ÿ] // as above but not including [ ] ^ \ × ÷
See https://unicode-table.com/en/ for characters listed in numeric order.
Google thrives on scraping websites of the world...so if it was "so illegal" then even Google won't survive ..of course other answers mention ways of mitigating IP blocks by Google. One more way to explore avoiding captcha could be scraping at random times (dint try) ..Moreover, I have a feeling, that if we provide novelty or some significant processing of data then it sounds fine at least to me...if we are simply copying a website.. or hampering its business/brand in some way...then it is bad and should be avoided..on top of it all...if you are a startup then no one will fight you as there is no benefit.. but if your entire premise is on scraping even when you are funded then you should think of more sophisticated ways...alternative APIs..eventually..Also Google keeps releasing (or depricating) fields for its API so what you want to scrap now may be in roadmap of new Google API releases..
Thanks for the Answer I have modified the statements to look like below
SELECT
AlarmEventTransactionTable.TxnID,
CASE
WHEN DeviceID IN('7', '10', '62', '58', '60',
'46', '48', '50', '137', '139',
'141', '145', '164') THEN '01'
WHEN DeviceID IN('8', '9', '63', '59', '61',
'47', '49', '51', '138', '140',
'142', '146', '165') THEN '02'
ELSE 'NA' END AS clocking,
AlarmEventTransactionTable.DateTimeOfTxn
FROM
multiMAXTxn.dbo.AlarmEventTransactionTable
Edited Java 8 Solution:
final Drawable drawable =
Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
.orElseGet(() -> getRandomDrawable());
You can declare drawable
final
in this case.
As Chasmo pointed out, Android doesn't support Java 8 at the moment. So this solution is only possible in other contexts.
One more thing, triggering GC Collect explicitly may NOT improve your program's performance. It is quite possible to make it worse.
The .NET GC is well designed and tuned to be adaptive, which means it can adjust GC0/1/2 threshold according to the "habit" of your program memory usage. So, it will be adapted to your program after some time running. Once you invoke GC.Collect explicitly, the thresholds will be reset! And the .NET has to spent time to adapt to your program's "habit" again.
My suggestion is always trust .NET GC. Any memory problem surfaces, check ".NET Memory" performance counter and diagnose my own code.
Thanks for the replies.
What I did was,
1. I install meinberg ntp software application on windows 7 pc. (softros ntp server is also possible.)
2. change raspberry pi ntp.conf file (for auto update date and time)
server xxx.xxx.xxx.xxx iburst
server 1.debian.pool.ntp.org iburst
server 2.debian.pool.ntp.org iburst
server 3.debian.pool.ntp.org iburst
3. If you want to make sure that date and time update at startup run this python script in rpi,
import os
try:
client = ntplib.NTPClient()
response = client.request('xxx.xxx.xxx.xxx', version=4)
print "===================================="
print "Offset : "+str(response.offset)
print "Version : "+str(response.version)
print "Date Time : "+str(ctime(response.tx_time))
print "Leap : "+str(ntplib.leap_to_text(response.leap))
print "Root Delay : "+str(response.root_delay)
print "Ref Id : "+str(ntplib.ref_id_to_text(response.ref_id))
os.system("sudo date -s '"+str(ctime(response.tx_time))+"'")
print "===================================="
except:
os.system("sudo date")
print "NTP Server Down Date Time NOT Set At The Startup"
pass
I found more info in raspberry pi forum.
This tutorial:
http://techdroid.kbeanie.com/2010/02/sign-your-android-applications-for.html
was very helpful for me the first time I had to create a keystore. It is simple but the instructions on developer.android.com are a little too brief.
The part I was unsure about was where to save and what name to give the keystore file.
I seems it doesn't matter where you put it just be sure to keep it safe and keep a number of backups. I just put it in my app directory
Name the file "something.keystore" where something can be whatever you want. I used app_name.keystore, where app_name was the name of my app.
The next part was what to name the alias. Again it doesn't seem to matter so again I just used the app_name again. Keep the passwords the same as you used before. Fill out the rest of the fields and you are done.
Recently I used an AS3 engine: PushButton (now is dead, but it's still functional and you could use something else) to do this job. To make it works with Android and iOS, the project was compiled in AIR for both platforms and everything worked with no performance damage. Since Flash Builder is kinda expensive ($249), you could use FlashDevelop (there is some tutorials to compile in AIR with it).
Flash could be an option since is very easy to learn.
There is a class, Class
, that can do this:
Class c = Class.forName("MyClass"); // if you want to specify a class
Class c = this.getClass(); // if you want to use the current class
System.out.println("Package: "+c.getPackage()+"\nClass: "+c.getSimpleName()+"\nFull Identifier: "+c.getName());
If c
represented the class MyClass
in the package mypackage
, the above code would print:
Package: mypackage
Class: MyClass
Full Identifier: mypackage.MyClass
You can take this information and modify it for whatever you need, or go check the API for more information.
This is just to help somebody in future. When we initiate InternetExplorerDriver() instance in a java project it uses IEDriver.exe (downloaded by individuals) which tries to extract temporary files in user's TEMP folder when it's not in path then ur busted.
Safest way is to provide your own extract path as shown below
System.setProperty("webdriver.ie.driver.extractpath", "F:\\Study\\");
System.setProperty("webdriver.ie.driver", "F:\\Study\\IEDriverServer.exe");
System.setProperty("webdriver.ie.logfile", "F:\\Study\\IEDriverServer.log");
InternetExplorerDriver d = new InternetExplorerDriver();
d.get("http://www.google.com");
d.quit();
If your newline character is CRLF
, that means it's a CHR(13)
followed by CHR(10)
. If you REPLACE(input, CHR(10), '_')
, that turns into CHR(13)
followed by an underscore. Since CR
on its own can be just as well rendered as a newline character, it'll appear to you as if an underscore has ben inserted after your newline, but actually only half of your newline has been replaced.
Use REPLACE(REPLACE(input, CHR(13)), CHR(10))
to replace all CR
's and LF
's.
Core Java:
It’s a general term used by Sun Microsystems to describe the standard version of Java (JSE). It’s the most basic version of Java which sets the foundation for all other editions of Java plus a set of related technologies such as CORBA, Java VM, etc. Core Java refers to a collection of libraries rather than just the programming language.
Java :
Java is hypothetically everywhere, thanks to its readability and simplicity. From mobile applications to websites, game consoles to datacenters, from mobile phones to the Internet, Java is everywhere. Millions of devices throughout the world use Java as a core programming language. Even all native Android apps come built-in with Java and several companies use Java as server-side scripting language for backend development.
Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;
function get(k) {
return map[k];
}
//map[myKey1] == get(myKey1);
It seems that in general, this happens when Wordpress doesn't find the site information in the expected places (tables) in the database. It thinks no site has been created yet, so it starts going through the installation process.
This situation means that:
AND
Just to be clear, both 1) and 2) are happening when you see this symptom.
Possible causes:
Wrong database. You're working on several projects and you copied and pasted wrong database name, database host, or table prefix to the wp-config file. So now, you're unwittingly destroying ANOTHER client's website while agonizing over why isn't THIS website working at all.
Wrong database prefix. You can put several Wordpress sites in one database by using different prefixes for each. Make sure the tables in the database have the same prefixes as you entered in your wp-config. So, if wp-config says: $table_prefix = 'wp_'; Check that the tables in your database are called "wp_options", etc. and not "WP_options", "mysite_options" or something like that.
The data in the database is corrupted. Maybe you messed up while importing the sql dump, you imported a truncated file, a file belonging to some other project, or whatever.
Java 8 Comparator
interface has a reversed
method : https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#reversed--
The simple approach (gcc -dM -E - < /dev/null
) works fine for gcc but fails for g++. Recently I required a test for a C++11/C++14 feature. Recommendations for their corresponding macro names are published at https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations. But:
g++ -dM -E - < /dev/null | fgrep __cpp_alias_templates
always fails, because it silently invokes the C-drivers (as if invoked by gcc
). You can see this by comparing its output against that of gcc or by adding a g++-specific command line option like (-std=c++11) which emits the error message cc1: warning: command line option ‘-std=c++11’ is valid for C++/ObjC++ but not for C
.
Because (the non C++) gcc will never support "Templates Aliases" (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2258.pdf) you must add the -x c++
option to force the invocation of the C++ compiler (Credits for using the -x c++
options instead of an empty dummy file go to yuyichao, see below):
g++ -dM -E -x c++ /dev/null | fgrep __cpp_alias_templates
There will be no output because g++ (revision 4.9.1, defaults to -std=gnu++98) does not enable C++11-features by default. To do so, use
g++ -dM -E -x c++ -std=c++11 /dev/null | fgrep __cpp_alias_templates
which finally yields
#define __cpp_alias_templates 200704
noting that g++ 4.9.1 does support "Templates Aliases" when invoked with -std=c++11
.
Emacs expects one of db, sqlite, sqlite2 or sqlite3 in the default configuration for sql-sqlite mode.
Check-it Out:
HTML:
<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server" SelectionMode="Multiple" Width="100px">
<asp:ListItem Text="Raj" Value="1"></asp:ListItem>
<asp:ListItem Text="Karan" Value="2"></asp:ListItem>
<asp:ListItem Text="Riya" Value="3"></asp:ListItem>
<asp:ListItem Text="Aman" Value="4"></asp:ListItem>
<asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>
JQUERY:
$("#aSelect").click(function(){
var selectedValues = [];
$("#lstSelect :selected").each(function(){
selectedValues.push($(this).val());
});
alert(selectedValues);
return false;
});
This is how I do it
public void B_ODOC_OnClick(Object sender, EventArgs e)
{
string script="<script>__doPostBack(\'fileView$ctl01$OTHDOC\',\'{\"EventArgument\":\"OpenModal\",\"EncryptedData\":null}\');</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(),"JsOtherDocuments",script);
}
A simple solution is – just to ignore user interactions :-)
video {
pointer-events: none;
}
So, I checked Windows Features to make sure I didn't have this thing called WebDAV installed, and it said I didn't. Anyways, I went ahead and placed the following in my web.config (both front end and WebAPI, just to be sure), and it works now. I placed this inside <system.webServer>
.
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/> <!-- add this -->
</modules>
Additionally, it is often required to add the following to web.config
in the handlers. Thanks to Babak
<handlers>
<remove name="WebDAV" />
...
</handlers>
In addition to Amra's answer, you can find other snippets by typing
Ctrl + K, Ctrl + X
Which is mapped to Edit.InsertSnippet in my Visual Studio and shows you the full list of snippets available.
Also remember that you can configure your own snippets by using the Snippets Manager, which is available in the Tools
menu, Code Snippets Manager...
.
Basically you create a file *.snippet
and use the Import button in the Code Snippets Manager to add it to Visual Studio.
For a full tutorial you can go to the docs; Walkthrough: Create a code snippet.
In Visual Studio Code snippets are handled slightly different than in Visual Studio. You can access all snippets by typing Ctrl + Shift + P and type in snippet
. Two options should be available, Insert Snippet
and Preferences: Configure User Snippets
.
The former inserts a snippet from your list of snippets (using the Language Mode which you can see in the status bar), and with the latter you can create your own snippets for any Language Mode.
If you know the shortname you can just type that and use Tab to expand the snippet. For inserting a C# property you have three snippets available, prop
, propfull
, and propg
, for different purposes.
The default dbpath for mongodb is /data/db
.
There is no default config file, so you will either need to specify this when starting mongod
with:
mongod --config /etc/mongodb.conf
.. or use a packaged install of MongoDB (such as for Redhat or Debian/Ubuntu) which will include a config file path in the service definition.
Note: to check the dbpath and command-line options for a running mongod
, connect via the mongo
shell and run:
db.serverCmdLineOpts()
In particular, if a custom dbpath
is set it will be the value of:
db.serverCmdLineOpts().parsed.dbpath // MongoDB 2.4 and older
db.serverCmdLineOpts().parsed.storage.dbPath // MongoDB 2.6+
Try the following:
<script>
//Functions to open database and to create, insert data into tables
getSelectedRow = function(val)
{
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM Employ where number = ?;',[parseInt(val)], selectedRowValues, errorHandler);
});
};
selectedRowValues = function(transaction,results)
{
for(var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
alert(row['number']);
alert(row['name']);
}
};
</script>
You don't have access to javascript variable names in SQL, you must pass the values to the Database.
Some responses focus on refactoring, rather than naming conventions, as the way to improve readability. I don't feel that one can replace the other.
I've known programmers who are uncomfortable with using local declarations; they prefer to place all the declarations at the top of a block (as in C), so they know where to find them. I've found that, where scoping allows for it, declaring variables where they're first used decreases the time that I spend glancing backwards to find the declarations. (This is true for me even for small functions.) That makes it easier for me to understand the code I'm looking at.
I hope it's clear enough how this relates to member naming conventions: When members are uniformly prefixed, I never have to look back at all; I know the declaration won't even be found in the source file.
I'm sure that I didn't start out preferring these styles. Yet over time, working in environments where they were used consistently, I optimized my thinking to take advantage of them. I think it's possible that many folks who currently feel uncomfortable with them would also come to prefer them, given consistent usage.
There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:
appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5
Appcmd is located in %windir%\System32\inetsrv
. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.
Check your capitalization!
Your host system (Windows or Mac) is case insensitive by default, and Homestead inherits this behavior. Your production server on the other hand is case sensitive.
Whenever you get a ClassNotFound Exception check the following:
From the documentation:
With one argument, return the natural logarithm of x (to base e).
With two arguments, return the logarithm of x to the given base, calculated as
log(x)/log(base)
.
But the log10 is made available as math.log10()
, which does not resort to log division if possible.
An unwind segue (sometimes called exit segue) can be used to navigate back through push, modal or popover segues (as if you popped the navigation item from the navigation bar, closed the popover or dismissed the modally presented view controller). On top of that you can actually unwind through not only one but a series of push/modal/popover segues, e.g. "go back" multiple steps in your navigation hierarchy with a single unwind action.
When you perform an unwind segue, you need to specify an action, which is an action method of the view controller you want to unwind to.
Objective-C:
- (IBAction)unwindToThisViewController:(UIStoryboardSegue *)unwindSegue
{
}
Swift:
@IBAction func unwindToThisViewController(segue: UIStoryboardSegue) {
}
The name of this action method is used when you create the unwind segue in the storyboard. Furthermore, this method is called just before the unwind segue is performed. You can get the source view controller from the passed UIStoryboardSegue
parameter to interact with the view controller that initiated the segue (e.g. to get the property values of a modal view controller). In this respect, the method has a similar function as the prepareForSegue:
method of UIViewController
.
iOS 8 update: Unwind segues also work with iOS 8's adaptive segues, such as Show and Show Detail.
Let us have a storyboard with a navigation controller and three child view controllers:
From Green View Controller you can unwind (navigate back) to Red View Controller. From Blue you can unwind to Green or to Red via Green. To enable unwinding you must add the special action methods to Red and Green, e.g. here is the action method in Red:
Objective-C:
@implementation RedViewController
- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
}
@end
Swift:
@IBAction func unwindToRed(segue: UIStoryboardSegue) {
}
After the action method has been added, you can define the unwind segue in the storyboard by control-dragging to the Exit icon. Here we want to unwind to Red from Green when the button is pressed:
You must select the action which is defined in the view controller you want to unwind to:
You can also unwind to Red from Blue (which is "two steps away" in the navigation stack). The key is selecting the correct unwind action.
Before the the unwind segue is performed, the action method is called. In the example I defined an unwind segue to Red from both Green and Blue. We can access the source of the unwind in the action method via the UIStoryboardSegue parameter:
Objective-C:
- (IBAction)unwindToRed:(UIStoryboardSegue *)unwindSegue
{
UIViewController* sourceViewController = unwindSegue.sourceViewController;
if ([sourceViewController isKindOfClass:[BlueViewController class]])
{
NSLog(@"Coming from BLUE!");
}
else if ([sourceViewController isKindOfClass:[GreenViewController class]])
{
NSLog(@"Coming from GREEN!");
}
}
Swift:
@IBAction func unwindToRed(unwindSegue: UIStoryboardSegue) {
if let blueViewController = unwindSegue.sourceViewController as? BlueViewController {
println("Coming from BLUE")
}
else if let redViewController = unwindSegue.sourceViewController as? RedViewController {
println("Coming from RED")
}
}
Unwinding also works through a combination of push/modal segues. E.g. if I added another Yellow view controller with a modal segue, we could unwind from Yellow all the way back to Red in a single step:
When you define an unwind segue by control-dragging something to the Exit symbol of a view controller, a new segue appears in the Document Outline:
Selecting the segue and going to the Attributes Inspector reveals the "Identifier" property. Use this to give a unique identifier to your segue:
After this, the unwind segue can be performed from code just like any other segue:
Objective-C:
[self performSegueWithIdentifier:@"UnwindToRedSegueID" sender:self];
Swift:
performSegueWithIdentifier("UnwindToRedSegueID", sender: self)
You don't really want to be reallocing memory every time you remove something. If you know the rough size of your deck then choose an appropriate size for your array and keep a pointer to the current end of the list. This is a stack.
If you don't know the size of your deck, and think it could get really big as well as keeps changing size, then you will have to do something a little more complex and implement a linked-list.
In C, you have two simple ways to declare an array.
On the stack, as a static array
int myArray[16]; // Static array of 16 integers
On the heap, as a dynamically allocated array
// Dynamically allocated array of 16 integers
int* myArray = calloc(16, sizeof(int));
Standard C does not allow arrays of either of these types to be resized. You can either create a new array of a specific size, then copy the contents of the old array to the new one, or you can follow one of the suggestions above for a different abstract data type (ie: linked list, stack, queue, etc).
If you are looking to create an instant messenger for Android, this code should get you started somewhere.
Excerpt from the source :
This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.
EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.
There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!
*UPDATE : * Scringo services will be closed down on 15 February, 2015.
Using:
apt HelloImpl.java -classpath /sac/tools/thirdparty/jaxws-ri/jaxws-ri-2.1.4/lib/jsr181-api.jar:.
works but it gives me another error, see new question
This is one of the other method to solve the Error: "Cannot get a text value from a numeric cell “Poi”"
Go to the Excel Sheet. Drag and Select the Numerics which you are importing Data from the Excel sheet. Go to Format > Number > Then Select "Plain Text" Then Export as .xlsx. Now Try to Run the Script
Hope works Fine...!
I dont know why all these complicated answers are on here but this is what I would do
where pdate >= CURRENT_TIMESTAMP -30
OR WHERE CAST(PDATE AS DATE) >= GETDATE() -30
Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.
So if you are manipulating DOM directly and inserting content it, you need to sanitize it otherwise Angular will through errors.
I have created the pipe SanitizeUrlPipe for this
import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Pipe({
name: "sanitizeUrl"
})
export class SanitizeUrlPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) { }
transform(v: string): SafeHtml {
return this._sanitizer.bypassSecurityTrustResourceUrl(v);
}
}
and this is how you can use
<iframe [src]="url | sanitizeUrl" width="100%" height="500px"></iframe>
If you want to add HTML, then SanitizeHtmlPipe can help
import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";
@Pipe({
name: "sanitizeHtml"
})
export class SanitizeHtmlPipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) { }
transform(v: string): SafeHtml {
return this._sanitizer.bypassSecurityTrustHtml(v);
}
}
Read more about angular security here.
In c# Option("truncate", false)
does not truncate data in the output.
StreamingQuery query = spark
.Sql("SELECT * FROM Messages")
.WriteStream()
.OutputMode("append")
.Format("console")
.Option("truncate", false)
.Start();
The quick answer: switch off AutoSize.
The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic.
Basically what you need to do in OnPaint is:
You will also need to set the ResizeRedraw style flag in the constructor.
The angular2 way is to use listen
or listenGlobal
from Renderer
For example, if you want to add a click event to a Component, you have to use Renderer and ElementRef (this gives you as well the option to use ViewChild, or anything that retrieves the nativeElement
)
constructor(elementRef: ElementRef, renderer: Renderer) {
// Listen to click events in the component
renderer.listen(elementRef.nativeElement, 'click', (event) => {
// Do something with 'event'
})
);
You can use listenGlobal
that will give you access to document
, body
, etc.
renderer.listenGlobal('document', 'click', (event) => {
// Do something with 'event'
});
Note that since beta.2 both listen
and listenGlobal
return a function to remove the listener (see breaking changes section from changelog for beta.2). This is to avoid memory leaks in big applications (see #6686).
So to remove the listener we added dynamically we must assign listen
or listenGlobal
to a variable that will hold the function returned, and then we execute it.
// listenFunc will hold the function returned by "renderer.listen"
listenFunc: Function;
// globalListenFunc will hold the function returned by "renderer.listenGlobal"
globalListenFunc: Function;
constructor(elementRef: ElementRef, renderer: Renderer) {
// We cache the function "listen" returns
this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
// Do something with 'event'
});
// We cache the function "listenGlobal" returns
this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
// Do something with 'event'
});
}
ngOnDestroy() {
// We execute both functions to remove the respectives listeners
// Removes "listen" listener
this.listenFunc();
// Removs "listenGlobal" listener
this.globalListenFunc();
}
Here's a plnkr with an example working. The example contains the usage of listen
and listenGlobal
.
25/02/2017: Renderer
has been deprecated, now we should use (see line below). See the commit.RendererV2
10/03/2017: RendererV2
was renamed to Renderer2
. See the breaking changes.
RendererV2
has no more listenGlobal
function for global events (document, body, window). It only has a listen
function which achieves both functionalities.
For reference, I'm copy & pasting the source code of the DOM Renderer implementation since it may change (yes, it's angular!).
listen(target: 'window'|'document'|'body'|any, event: string, callback: (event: any) => boolean):
() => void {
if (typeof target === 'string') {
return <() => void>this.eventManager.addGlobalEventListener(
target, event, decoratePreventDefault(callback));
}
return <() => void>this.eventManager.addEventListener(
target, event, decoratePreventDefault(callback)) as() => void;
}
As you can see, now it verifies if we're passing a string (document, body or window), in which case it will use an internal addGlobalEventListener
function. In any other case, when we pass an element (nativeElement) it will use a simple addEventListener
To remove the listener it's the same as it was with Renderer
in angular 2.x. listen
returns a function, then call that function.
// Add listeners
let global = this.renderer.listen('document', 'click', (evt) => {
console.log('Clicking the document', evt);
})
let simple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
console.log('Clicking the button', evt);
});
// Remove listeners
global();
simple();
plnkr with Angular 4.0.0-rc.1 using RendererV2
plnkr with Angular 4.0.0-rc.3 using Renderer2
The @jfriend00's answer helps me to understand the technique to animate only remove class (not add).
A "base" class should have transition
property (like transition: 2s linear all;
). This enables animations when any other class is added or removed on this element. But to disable animation when other class is added (and only animate class removing) we need to add transition: none;
to the second class.
Example
CSS:
.issue {
background-color: lightblue;
transition: 2s linear all;
}
.recently-updated {
background-color: yellow;
transition: none;
}
HTML:
<div class="issue" onclick="addClass()">click me</div>
JS (only needed to add class):
var timeout = null;
function addClass() {
$('.issue').addClass('recently-updated');
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(function () {
$('.issue').removeClass('recently-updated');
}, 1000);
}
plunker of this example.
With this code only removing of recently-updated
class will be animated.
I had the same problem. The only solution that worked for me was adding <property = "defaultEncoding" value = "UTF-8"> to multipartResoler in spring configurations file.
ssh -t 'command; bash -l'
will execute the command and then start up a login shell when it completes. For example:
ssh -t [email protected] 'cd /some/path; bash -l'
'lines' term from your snippet consists of set of strings.
lines = f.readlines()
match = re.findall('[A-Z]+', lines)
You cannot send entire lines into the re.findall('pattern',<string>)
You can try to send line by line
for i in lines:
match = re.findall('[A-Z]+', i)
print match
or to convert the entire lines collection into single line (each line seperated by space)
NEW_LIST=' '.join(lines)
match=re.findall('[A-Z]+' ,NEW_LIST)
print match
This might help you
Or, you can use the Newtownsoft.Json library as follows:
using Newtonsoft.Json;
...
var result = JsonConvert.DeserializeObject<T>(json);
Where T
is your object type that matches your JSON string.
Add this at the top of your file:
#!/usr/bin/python
This is a shebang. You can read more about it on Wikipedia.
After that, you must make the file executable via
chmod +x your_script.py
This can be simplified by completely skipping the where object and the $users declaration. All you need is:
Code
get-content c:\scripts\users.txt | get-aduser -properties * | select displayname, office | export-csv c:\path\to\your.csv
Here if you are referring to my previous answers Here is an Update. 1. Compile would be removed from the dependencies after 2018.
a new version build Gradle is available.
Use the above-noted stuff it will help you to resolve the errors. It is needed for the developers who are working after March 2018. Also, maven update might be needed. All above answers will not work on the Android Studio 3.1. Hence Above code block is needed to be changed if you are using 3.1. See also I replaced compile by implementation.
In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.
I would change to this, though. You don't need "ans" at all.
return String.format("%d:%d", mins, secs);
Gist with log rotation: https://gist.github.com/barsv/85c93b599a763206f47aec150fb41ca0
Usage:
. .\logger.ps1
Write-Log "debug message"
Write-Log "info message" "INFO"
Adding this to the Vagrantfile
worked for me. These lines are the equivalent of you entering sudo su -
every time you login. Please notice that this requires reprovisioning the VM.
config.vm.provision "shell", inline: <<-SHELL
echo "sudo su -" >> .bashrc
SHELL
Use GETDATE()
Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.
UPDATE table SET date = GETDATE()
I have tried to do aspnet_regiis in command prompt but I got answer that I don't have admin rights. Then, after some more googling and looking for a solution I tried to right click cmd and run it as an admin. Confirmed yes when dialog appeared, ran aspnet_iis again ant worked like a charm. In short: 1. check .NET framework in app_pool 2. run cmd as an admin 3. run aspnet_regiis -i
Simple stuff here:
Incase you don't need a ScrollView for this approach you can go with the below code to achieve Something like this :
<View style={{flex: 1, backgroundColor:'grey'}}>
<View style={{flex: 1, backgroundColor: 'red'}} />
<View style={{height: 100, backgroundColor: 'green'}} />
</View>
As Sai said, the shell is the child, so signals are intercepted by it -- best way I've found is to use shell=False and use shlex to split the command line:
if isinstance(command, unicode):
cmd = command.encode('utf8')
args = shlex.split(cmd)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Then p.kill() and p.terminate() should work how you expect.
You can also not draw the header or footer at all by setting sDom
: http://datatables.net/usage/options#sDom
'sDom': 't'
will display JUST the table, no headers or footers or anything.
It's discussed some here: http://www.datatables.net/forums/discussion/2722/how-to-hide-empty-header-and-footer/p1
Simple Answer: NO. You cannot help ad hoc queries on a 238 column table with a 50% Fill Factor on the Clustered Index.
Detailed Answer:
As I have stated in other answers on this topic, Index design is both Art and Science and there are so many factors to consider that there are few, if any, hard and fast rules. You need to consider: the volume of DML operations vs SELECTs, disk subsystem, other indexes / triggers on the table, distribution of data within the table, are queries using SARGable WHERE conditions, and several other things that I can't even remember right now.
I can say that no help can be given for questions on this topic without an understanding of the Table itself, its indexes, triggers, etc. Now that you have posted the table definition (still waiting on the Indexes but the Table definition alone points to 99% of the issue) I can offer some suggestions.
First, if the table definition is accurate (238 columns, 50% Fill Factor) then you can pretty much ignore the rest of the answers / advice here ;-). Sorry to be less-than-political here, but seriously, it's a wild goose chase without knowing the specifics. And now that we see the table definition it becomes quite a bit clearer as to why a simple query would take so long, even when the test queries (Update #1) ran so quickly.
The main problem here (and in many poor-performance situations) is bad data modeling. 238 columns is not prohibited just like having 999 indexes is not prohibited, but it is also generally not very wise.
Recommendations:
ANSI_PADDING OFF
is disturbing, not to mention inconsistent within the table due to the various column additions over time. Not sure if you can fix that now, but ideally you would always have ANSI_PADDING ON
, or at the very least have the same setting across all ALTER TABLE
statements.PRIMARY
as that is where SQL SERVER stores all of its data and meta-data about your objects. You create your Table and Clustered Index (as that is the data for the table) on [Tables]
and all Non-Clustered indexes on [Indexes]
WHERE
condition, then consider moving that to the leading column of the clustered index. Assuming that it is used more often than "ER101_ORD_NBR". If "ER101_ORD_NBR" is used more often then keep it. It just seems, assuming that the field names mean "OrganizationCode" and "OrderNumber", that "OrgCode" is a better grouping that might have multiple "OrderNumbers" within it.CHAR(2)
instead of VARCHAR(2)
as it will save a byte in the row header which tracks variable width sizes and adds up over millions of rows.SELECT *
will hurt performance. Not only due to it requiring SQL Server to return all columns and hence be more likely to do a Clustered Index Scan regardless of your other indexes, but it also takes SQL Server time to go to the table definition and translate *
into all of the column names. It should be slightly faster to specify all 238 column names in the SELECT
list though that won't help the Scan issue. But do you ever really need all 238 columns at the same time anyway?Good luck!
UPDATE
For the sake of completeness to the question "how to improve performance on a large table for ad-hoc queries", it should be noted that while it will not help for this specific case, IF someone is using SQL Server 2012 (or newer when that time comes) and IF the table is not being updated, then using Columnstore Indexes is an option. For more details on that new feature, look here:
http://msdn.microsoft.com/en-us/library/gg492088.aspx (I believe these were made to be updateable starting in SQL Server 2014).
UPDATE 2
Additional considerations are:
INT
, BIGINT
, TINYINT
, SMALLINT
, CHAR
, NCHAR
, BINARY
, DATETIME
, SMALLDATETIME
, MONEY
, etc) and well over 50% of the rows are NULL
, then consider enabling the SPARSE
option which became available in SQL Server 2008. Please see the MSDN page for Use Sparse Columns for details.I got it
Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"
Basically, I need to set the cell format, instead of setting the date.
It is possible, if you're using a browser which supports the CSS :valid
pseudo-class and the pattern
validation attribute on inputs -- which includes most modern browsers except IE9.
For instance, to change the text of an input from black to green when the correct answer is entered:
input {_x000D_
color: black;_x000D_
}_x000D_
input:valid {_x000D_
color: green;_x000D_
}
_x000D_
<p>Which country has fifty states?</p>_x000D_
_x000D_
<input type="text" pattern="^United States$">
_x000D_
Yes, there is a way to show a single command output on the console (screen) and in a file. Using your example, use...
@ECHO OFF
FOR /F "tokens=*" %%I IN ('DIR') DO ECHO %%I & ECHO %%I>>windows-dir.txt
Detailed explanation:
The FOR
command parses the output of a command or text into a variable, which can be referenced multiple times.
For a command, such as DIR /B
, enclose in single quotes as shown in example below. Replace the DIR /B
text with your desired command.
FOR /F "tokens=*" %%I IN ('DIR /B') DO ECHO %%I & ECHO %%I>>FILE.TXT
For displaying text, enclose text in double quotes as shown in example below.
FOR /F "tokens=*" %%I IN ("Find this text on console (screen) and in file") DO ECHO %%I & ECHO %%I>>FILE.TXT
... And with line wrapping...
FOR /F "tokens=*" %%I IN ("Find this text on console (screen) and in file") DO (
ECHO %%I & ECHO %%I>>FILE.TXT
)
If you have times when you want the output only on console (screen), and other times sent only to file, and other times sent to both, specify the "DO" clause of the FOR loop using a variable, as shown below with %TOECHOWHERE%
.
@ECHO OFF
FOR %%I IN (TRUE FALSE) DO (
FOR %%J IN (TRUE FALSE) DO (
SET TOSCREEN=%%I & SET TOFILE=%%J & CALL :Runit)
)
GOTO :Finish
:Runit
REM Both TOSCREEN and TOFILE get assigned a trailing space in the FOR loops
REM above when the FOR loops are evaluating the first item in the list,
REM "TRUE". So, the first value of TOSCREEN is "TRUE " (with a trailing
REM space), the second value is "FALSE" (no trailing or leading space).
REM Adding the ": =" text after "TOSCREEN" tells the command processor to
REM remove all spaces from the value in the "TOSCREEN" variable.
IF "%TOSCREEN: =%"=="TRUE" (
IF "%TOFILE: =%"=="TRUE" (
SET TEXT=On screen, and in "FILE.TXT"
SET TOECHOWHERE="ECHO %%I & ECHO %%I>>FILE.TXT"
) ELSE (
SET TEXT=On screen, not in "FILE.TXT"
SET TOECHOWHERE="ECHO %%I"
)
) ELSE (
IF "%TOFILE: =%"=="TRUE" (
SET TEXT=Not on screen, but in "FILE.TXT"
SET TOECHOWHERE="ECHO %%I>>FILE.txt"
) ELSE (
SET TEXT=Not on screen, nor in "FILE.TXT"
SET TOECHOWHERE="ECHO %%I>NUL"
)
)
FOR /F "tokens=*" %%I IN ("%TEXT%") DO %TOECHOWHERE:~1,-1%
GOTO :eof
:Finish
ECHO Finished [this text to console (screen) only].
PAUSE
Xcode 11+, Swift 5
If you are wondering why all of the answers does not work anymore, make sure that you have pinned the content view (the one you've put inside the scroll view) to Content Layout Guide of the scroll view and NOT to Frame Layout Guide.
Content view edges (leading, trailing, top, bottom) should not be pinned like leading on the image - to Frame Layout Guide
but like this - to Content Layout Guide.
And then the most of the answers will work for you.
The most simple approach now is going like this:
Overall your structure in the simplest implementation will look like this
Still using empty strings you can use:
document.getElementById("name").value = '';
document.getElementById("review").value = '';
It's really interesting case. Actually in your setup the following statement is true:
binary_crossentropy = len(class_id_index) * categorical_crossentropy
This means that up to a constant multiplication factor your losses are equivalent. The weird behaviour that you are observing during a training phase might be an example of a following phenomenon:
adam
- the learning rate has a much smaller value than it had at the beginning of training (it's because of the nature of this optimizer). It makes training slower and prevents your network from e.g. leaving a poor local minimum less possible.That's why this constant factor might help in case of binary_crossentropy
. After many epochs - the learning rate value is greater than in categorical_crossentropy
case. I usually restart training (and learning phase) a few times when I notice such behaviour or/and adjusting a class weights using the following pattern:
class_weight = 1 / class_frequency
This makes loss from a less frequent classes balancing the influence of a dominant class loss at the beginning of a training and in a further part of an optimization process.
EDIT:
Actually - I checked that even though in case of maths:
binary_crossentropy = len(class_id_index) * categorical_crossentropy
should hold - in case of keras
it's not true, because keras
is automatically normalizing all outputs to sum up to 1
. This is the actual reason behind this weird behaviour as in case of multiclassification such normalization harms a training.
// GET DATE & TIME IN ANY FORMAT
import java.util.Calendar;
import java.text.SimpleDateFormat;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
Taken from here
Here is the simplest solution w/o Service
nor Observer
:
Put the global variables in a file an export them.
//
// ===== File globals.ts
//
'use strict';
export const sep='/';
export const version: string="22.2.2";
To use globals in another file use an import
statement:
import * as myGlobals from 'globals';
Example:
//
// ===== File heroes.component.ts
//
import {Component, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';
import {HeroService} from './hero.service';
import {HeroDetailComponent} from './hero-detail.component';
import {Hero} from './hero';
import * as myGlobals from 'globals'; //<==== this one (**Updated**)
export class HeroesComponent implements OnInit {
public heroes: Hero[];
public selectedHero: Hero;
//
//
// Here we access the global var reference.
//
public helloString: string="hello " + myGlobals.sep + " there";
...
}
}
Thanks @eric-martinez
Here are different method of doing this. And i found your code is even working fine.
Your code: http://jsfiddle.net/NKC2j/
Jquery toggle class demo: http://jsfiddle.net/NKC2j/2/
Jquery fade toggle: http://jsfiddle.net/NKC2j/3/
Jquery slide toggle: http://jsfiddle.net/NKC2j/4/
And you can do this with CSS as answered by Sandeep
If you need to get all the files in the folder named 'Data', just code it as below
string[] Documents = System.IO.Directory.GetFiles("../../Data/");
Now the 'Documents' consists of array of complete object name of two text files in the 'Data' folder 'Data'.
When Card I always use RoundedRectangleBorder.
Card(
color: Colors.grey[900],
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.white70, width: 1),
borderRadius: BorderRadius.circular(10),
),
margin: EdgeInsets.all(20.0),
child: Container(
child: Column(
children: <Widget>[
ListTile(
title: Text(
'example',
style: TextStyle(fontSize: 18, color: Colors.white),
),
),
],
),
),
),
Try this to move your table (tbl1) to tablespace (tblspc2).
alter table tb11 move tablespace tblspc2;
Here is the answer from @mvanle, converted to Scala:
scala> val Array(javaVerPrefix, javaVerMajor, javaVerMinor, _, _) = System.getProperty("java.runtime.version").split("\\.|_|-b")
javaVerPrefix: String = 1
javaVerMajor: String = 8
javaVerMinor: String = 0
I used to declare the configuration in application.properties
like this (you can use you own property file)
server.host = localhost
server.port = 8081
and in application you can get it easily by @Value("${server.host}")
and @Value("${server.port}")
as field level annotation.
or if in your case it is dynamic than you can get from system properties
Here is the example
@Value("#{systemproperties['server.host']}")
@Value("#{systemproperties['server.port']}")
For a better understanding of this annotation , see this example Multiple uses of @Value annotation
Using Rational ClearCase the answer is no. Only the .sln & .*proj should be registered in source code control.
I can't answer for other vendors. If I recall correctly, these files are "user" specific options, your environment.
We can use another way to edit files inside working containers (this won't work if container is stoped).
Logic is to:
-)copy file from container to host
-)edit file on host using its host editor
-)copy file back to container
We can do all this steps manualy, but i have written simple bash script to make this easy by one call.
/bin/dmcedit:
#!/bin/sh
set -e
CONTAINER=$1
FILEPATH=$2
BASE=$(basename $FILEPATH)
DIR=$(dirname $FILEPATH)
TMPDIR=/tmp/m_docker_$(date +%s)/
mkdir $TMPDIR
cd $TMPDIR
docker cp $CONTAINER:$FILEPATH ./$DIR
mcedit ./$FILEPATH
docker cp ./$FILEPATH $CONTAINER:$FILEPATH
rm -rf $TMPDIR
echo 'END'
exit 1;
Usage example:
dmcedit CONTAINERNAME /path/to/file/in/container
The script is very easy, but it's working fine for me.
Any suggestions are appreciated.
Pretty sure you can't do that, as it violates the purpose of uniques.
However, this person seems to have a decent work around: http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html
I was using AngularJS and AngularStrap 2.3.7 and trying to catch the 'change'
event by listening to a <form>
element (not the input itself) and none of the answers here worked for me. I tried to do:
$(form).on('change change.dp dp.change changeDate' function () {...})
And nothing would fire. I ended up listening to the focus
and blur
events and setting a custom property before/after on the element itself:
// special hack to make bs-datepickers fire change events
// use timeout to make sure they all exist first
$timeout(function () {
$('input[bs-datepicker]').on('focus', function (e){
e.currentTarget.focusValue = e.currentTarget.value;
});
$('input[bs-datepicker]').on('blur', function (e){
if (e.currentTarget.focusValue !== e.currentTarget.value) {
var event = new Event('change', { bubbles: true });
e.currentTarget.dispatchEvent(event);
}
});
})
This basically manually checks the value before and after the focus
and blur
and dispatches a new 'change'
event. The { bubbles: true }
bit is what got the form to detect the change. If you have any datepicker elements inside of an ng-if
you'll need to wrap the listeners in a $timeout
to make sure the digest happens first so all of your datepicker elements exist.
Hope this helps someone!
This one deserves an update - nowadays we have the wheel
event :
$(function() {_x000D_
_x000D_
$(window).on('wheel', function(e) {_x000D_
_x000D_
var delta = e.originalEvent.deltaY;_x000D_
_x000D_
if (delta > 0) $('body').text('down');_x000D_
else $('body').text('up');_x000D_
_x000D_
return false; // this line is only added so the whole page won't scroll in the demo_x000D_
});_x000D_
});
_x000D_
body {_x000D_
font-size: 22px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Support has been pretty good on modern browsers for quite a while already :
https://developer.mozilla.org/en-US/docs/Web/Events/wheel
If deeper browser support is required, probably best to use mousewheel.js instead of messing about :
https://plugins.jquery.com/mousewheel/
$(function() {_x000D_
_x000D_
$(window).mousewheel(function(turn, delta) {_x000D_
_x000D_
if (delta > 0) $('body').text('up');_x000D_
else $('body').text('down');_x000D_
_x000D_
return false; // this line is only added so the whole page won't scroll in the demo_x000D_
});_x000D_
});
_x000D_
body {_x000D_
font-size: 22px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
_x000D_
I'm using the following configuration:
#site.yml:
- name: Example play
hosts: all
remote_user: ansible
become: yes
become_method: sudo
vars:
ansible_ssh_private_key_file: "/home/ansible/.ssh/id_rsa"
I think this working CodePen example that I created will show you exactly how to do what you want.
The template:
<section ng-app="app" ng-controller="MainCtrl">
<span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br>
<table class="table table-bordered">
<thead>
<tr>
<th>
<a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort">
First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
<th>
<a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort">
Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
<th>
<a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort">
Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort">
<td>{{emp.firstName}}</td>
<td>{{emp.lastName}}</td>
<td>{{emp.age}}</td>
</tr>
</tbody>
</table>
</section>
The JavaScript code:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.orderByField = 'firstName';
$scope.reverseSort = false;
$scope.data = {
employees: [{
firstName: 'John',
lastName: 'Doe',
age: 30
},{
firstName: 'Frank',
lastName: 'Burns',
age: 54
},{
firstName: 'Sue',
lastName: 'Banter',
age: 21
}]
};
});
Found the code that I referred to in my comment above. To test it, do this:
Sheet1
change the cell height and width of say A1
as shown in the snapshot below. Start Timer
button on the sheet and click on Assign Macros
. Select StartTimer
macro.End Timer
button on the sheet and click on Assign Macros
. Select EndTimer
macro.Now click on Start Timer button and you will see the time getting updated in cell A1
. To stop time updates, Click on End Timer button.
Code (TRIED AND TESTED)
Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long
Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long
Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long
'~~> Start Timer
Sub StartTimer()
'~~ Set the timer for 1 second
TimerSeconds = 1
TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub
'~~> End Timer
Sub EndTimer()
On Error Resume Next
KillTimer 0&, TimerID
End Sub
Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
'~~> Update value in Sheet 1
Sheet1.Range("A1").Value = Time
End Sub
SNAPSHOT
There is no way.
This question is basically a duplicate of Is there a way to hide the new HTML5 spinbox controls shown in Google Chrome & Opera? but maybe not a full duplicate, since the motivation is given.
If the purpose is “browser's awareness of the content being purely numeric”, then you need to consider what that would really mean. The arrows, or spinners, are part of making numeric input more comfortable in some cases. Another part is checking that the content is a valid number, and on browsers that support HTML5 input enhancements, you might be able to do that using the pattern
attribute. That attribute may also affect a third input feature, namely the type of virtual keyboard that may appear.
For example, if the input should be exactly five digits (like postal numbers might be, in some countries), then <input type="text" pattern="[0-9]{5}">
could be adequate. It is of course implementation-dependent how it will be handled.
One tested solution for Bootstrap 4 beta:
.popover {
min-width: 30em !important;
}
Together with the jQuery statement:
$('[data-toggle="popover"]').popover({
container: 'body',
trigger: 'focus',
html: true,
placement: 'top'
})
Side-note, data-container="body"
or container: "body"
in either HTML or as an option
to the popover({})
object didn't really do the trick [maybe the do work but only together with the CSS statement];
Also, remember that Bootstrap 4 beta relies on popper.js for its popover and tooltip positioning (prior to that it was tether.js)
this is what it worked for me:
select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
AND STR_TO_DATE('07/10/15', '%d/%m/%Y')
Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load
The accepted answer does not correctly dispose the WebResponse
or decode the text. Also, there's a new way to do this in .NET 4.5.
To perform an HTTP GET and read the response text, do the following.
public static string GetResponseText(string address)
{
var request = (HttpWebRequest)WebRequest.Create(address);
using (var response = (HttpWebResponse)request.GetResponse())
{
var encoding = Encoding.GetEncoding(response.CharacterSet);
using (var responseStream = response.GetResponseStream())
using (var reader = new StreamReader(responseStream, encoding))
return reader.ReadToEnd();
}
}
private static readonly HttpClient httpClient = new HttpClient();
public static async Task<string> GetResponseText(string address)
{
return await httpClient.GetStringAsync(address);
}
HTML5 introduces a number of APIs that help in creating Web applications. These can be used together with the new elements introduced for applications:
contenteditable
attribute.draggable
attribute.Jackson provides an annotation that can be used on class level (JsonIgnoreProperties).
Add the following to the top of your class (not to individual methods):
@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {
...
}
Depending on the jackson version you are using you would have to use a different import in the current version it is:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
in older versions it has been:
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.
In 'Path Variables' create a variable for example ANALYTICS_VERSION
.
In a 'Run Configuration' under 'Environment Variables' add for example the following:
ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin
To answer the original question you would need to add an APP_HOME
environment variable to your run configuration which references the path variable:
APP_HOME=$APP_HOME$
I solved this issue by removing the password for the ssh key in PuTTY.
For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.
Your question is pretty hard to decode, but I'll try taking a stab at it.
You say:
I want to create a json object having two fields
uniqueIDofSelect
andoptionValue
in javascript.
And then you say:
I need output like
[{"selectID":2,"optionValue":"2"}, {"selectID":4,"optionvalue":"1"}]
Well, this example output doesn't have the field named uniqueIDofSelect
, it only has optionValue
.
Anyway, you are asking for array of objects...
Then in the comment to michaels answer you say:
It creates json object array. but I need only one json object.
So you don't want an array of objects?
What do you want then?
Please make up your mind.
Here is a bash script that combines the ideas and idioms of several previous comments to provide, with examples, inline comments having the general form ${__+ <comment text>}
.
In particular
<comment text>
can be multi-line <comment text>
is not parameter-expandedThere is one restriction on the <comment text>
, namely, unbalanced braces '}'
and parentheses ')'
must be protected (i.e., '\}'
and '\)'
).
There is one requirement on the local bash environment:
__
must be unsetAny other syntactically valid bash parameter-name will serve in place of __
, provided that the name has no set value.
An example script follows
# provide bash inline comments having the form
# <code> ${__+ <comment>} <code>
# <code> ${__+ <multiline
# comment>} <code>
# utility routines that obviate "useless use of cat"
function bashcat { printf '%s\n' "$(</dev/stdin)"; }
function scat { 1>&2 bashcat; exit 1; }
# ensure that '__' is unset && remains unset
[[ -z ${__+x} ]] && # if '__' is unset
declare -r __ || # then ensure that '__' remains unset
scat <<EOF # else exit with an error
Error: the parameter __='${__}' is set, hence the
comment-idiom '\${__+ <comment text>}' will fail
EOF
${__+ (example of inline comments)
------------------------------------------------
the following inline comment-idiom is supported
<code> ${__+ <comment>} <code>
<code> ${__+ <multiline
comment>} <code>
(advisory) the parameter '__' must NOT be set;
even the null declaration __='' will fail
(advisory) protect unbalanced delimiters \} and \)
(advisory) NO parameter-expansion of <comment>
(advisory) NO subprocesses are spawned
(advisory) a functionally equivalent idiom is
<code> `# <comment>` <code>
<code> `# <multiline
comment>` <code>
however each comment spawns a bash subprocess
that inelegantly requires ~1ms of computation
------------------------------------------------}
Just for your information,after add the "PATH",for my win7 i need to reboot it to get it work.
I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.
After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.
In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:
var startTimeout = function(timeout, i){
setTimeout(function() {
myAsyncFunc(i).then(function(data){
console.log(data);
})
}, timeout);
}
var myFunc = function(){
timeout = 0;
i = 0;
while(i < 10){
// By calling a function, the i-value is going to be 1.. 10 and not always 10
startTimeout(timeout, i);
// Increase timeout by 1 sec after each call
timeout += 1000;
i++;
}
}
This examples waits 1 second after each request before sending the next one.
This rules are compatible whit all browser:
body {overflow: hidden; }
body::-webkit-scrollbar { width: 0 !important; }
body { overflow: -moz-scrollbars-none; }
body { -ms-overflow-style: none; }
HTML:
<div class="form">
<form name="Form1" action="mypage.asp" method="get">
...
</form>
</div>
CSS:
div.form
{
display: block;
text-align: center;
}
form
{
display: inline-block;
margin-left: auto;
margin-right: auto;
text-align: left;
}
I just read this on RubyInRails classes http://api.rubyonrails.org/classes/Object.html#method-i-blank-3F
you can use blank?
method which is equivalent to params[:one].nil? || params[:one].empty?
(e.g)
if params[:one].blank?
# do something if not exist
else
# do something if exist
end
AFAIK, there's no clean way to implement a "logout" function when using htaccess (i.e. HTTP-based) authentication.
This is because such authentication uses the HTTP error code '401' to tell the browser that credentials are required, at which point the browser prompts the user for the details. From then on, until the browser is closed, it will always send the credentials without further prompting.
SOLUTION: @Before building your component (using mvn clean install). Build the entire project once and build your component again
WHY SO :
I get this error many times.
Most of the times I will try to build my component alone (As I have not made changes elsewhere).
Right, But that extra jar which has been downloaded recently might have affected by changes done by a third party(inside their component). Making a full mvn clean install on entire project saved me many times
for n in range(6,0,-1):
print n
# prints [6, 5, 4, 3, 2, 1]
There are various methods to get an input textbox value directly (without wrapping the input element inside a form element):
Method 1:
document.getElementById('textbox_id').value
to get the value of desired boxFor example,
document.getElementById("searchTxt").value;
Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0], for the second one use 1, and so on...
Method 2:
Use
document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollectionFor example,
document.getElementsByClassName("searchField")[0].value;
if this is the first textbox in your page.
Method 3:
Use
document.getElementsByTagName('tag_name')[whole_number].value
which also returns a live HTMLCollectionFor example,
document.getElementsByTagName("input")[0].value;
, if this is the first textbox in your page.
Method 4:
document.getElementsByName('name')[whole_number].value
which also >returns a live NodeListFor example,
document.getElementsByName("searchTxt")[0].value;
if this is the first textbox with name 'searchtext' in your page.
Method 5:
Use the powerful
document.querySelector('selector').value
which uses a CSS selector to select the elementFor example,
document.querySelector('#searchTxt').value;
selected by id
document.querySelector('.searchField').value;
selected by class
document.querySelector('input').value;
selected by tagname
document.querySelector('[name="searchTxt"]').value;
selected by name
Method 6:
document.querySelectorAll('selector')[whole_number].value
which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.For example,
document.querySelectorAll('#searchTxt')[0].value;
selected by id
document.querySelectorAll('.searchField')[0].value;
selected by class
document.querySelectorAll('input')[0].value;
selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value;
selected by name
Support
Browser Method1 Method2 Method3 Method4 Method5/6
IE6 Y(Buggy) N Y Y(Buggy) N
IE7 Y(Buggy) N Y Y(Buggy) N
IE8 Y N Y Y(Buggy) Y
IE9 Y Y Y Y(Buggy) Y
IE10 Y Y Y Y Y
FF3.0 Y Y Y Y N IE=Internet Explorer
FF3.5/FF3.6 Y Y Y Y Y FF=Mozilla Firefox
FF4b1 Y Y Y Y Y GC=Google Chrome
GC4/GC5 Y Y Y Y Y Y=YES,N=NO
Safari4/Safari5 Y Y Y Y Y
Opera10.10/
Opera10.53/ Y Y Y Y(Buggy) Y
Opera10.60
Opera 12 Y Y Y Y Y
Useful links
Another alternative (other than binary operators suggested by @jm-) is to use ng-switch:
<span ng-switch on="interface">
<img ng-switch-when="UP" src='green-checkmark.png'>
<img ng-switch-default src='big-black-X.png'>
</span>
ng-switch will likely be better/easier if you have more than two images.
I'm not familiar with paramiko, but this may work:
ssh_stdin.write('input value')
ssh_stdin.flush()
For information on stdin:
http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin
I don't think you understand how \n works. The resulting string still just contains a byte with value 10. This is represented in javascript source code with \n.
The code snippet you posted doesn't actually work, but if it did, the newline would be equivalent to \n, unless it's a windows-style newline, in which case it would be \r\n. (but even that the replace would still work).
I had the opposite problem and finally had to create my own bash shell script for the company to migrate the hundred of repos from Github to Gitlab due to a change in the company policy.
The script use the Gitlab API to remotely create a repo, and push the Github repo into it.
There is no README.md file yet, but the sh is well documented.
The same thing can be done opposite way I imagine. Hope this could help.
https://github.com/mahmalsami/migrate-github-gitlab/blob/master/migrate.sh
CodeGear Delphi
Its really not the language I disliked, but the IDE: CodeGear RAD Studio for Delphi. This is easily the worst, most buggy, crash-happy IDE I've ever used. Me and the other Delphi programmers would routinely lose hours of development time everyday because the IDE would crash or freeze.
After we installed CodeRush, the application became virtually unsuable. It crashed in regular 5-15 minute intervals, even without user input. Even worse, mysterious errors were triggered by basic debugging, such as hitting a breakpoint (routinely, the debugger would hit a breakpoint and simply freeze in its tracks on a trivial line, like a variable assignment. Nothing you could do would make it proceed any further). If you left the program alone, it would sit stable for up to a half hours before throwing some kind of memory exception.
So, after we'd spent thousands of dollars on licenses CodeGear RAD Studio, no one wanted to use it. By the time I left the company, all of our Delphi projects were coded with VIM instead.
I recently discovered an interesting trick that allows to "Split String With String As Delimiter", so I couldn't resist the temptation to post it here as a new answer. Note that "obviously the question wasn't accurate. Firstly, both string1 and string2 can contain spaces. Secondly, both string1 and string2 can contain ampersands ('&')". This method correctly works with the new specifications (posted as a comment below Stephan's answer).
@echo off
setlocal
set "str=string1&with spaces by string2&with spaces.txt"
set "string1=%str: by =" & set "string2=%"
set "string2=%string2:.txt=%"
echo "%string1%"
echo "%string2%"
For further details on the split method, see this post.
Many of us develop in Eclipse via a Maven project. If so,
you can include Tomcat dependencies in Maven via the tomcat-servlet-api
and tomcat-jsp-api
jars. One exists for each version of Tomcat. Usually adding these with scope provided
to your POM is sufficient. This will keep your build more portable.
If you upgrade Tomcat in the future, you simply update the version of these jars as well.
You can use this, it works fine:
<input type="date" class="form1"
value="{{date | date:MM/dd/yyyy}}"
ng-model="date"
name="id"
validatedateformat
data-date-format="mm/dd/yyyy"
maxlength="10"
id="id"
calendar
maxdate="todays"
ng-click="openCalendar('id')">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar" ng-click="openCalendar('id')"></span>
</span>
</input>
Oracle
stores only the fractions up to second in a DATE
field.
Use TIMESTAMP
instead:
SELECT TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM dual
, possibly casting it to a DATE
then:
SELECT CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM dual
I think the classic answer is to create a more decoupled application, which has no knowledge of which implementation will be used during runtime.
For example, we're a central payment provider, working with many payment providers around the world. However, when a request is made, I have no idea which payment processor I'm going to call. I could program one class with a ton of switch cases, such as:
class PaymentProcessor{
private String type;
public PaymentProcessor(String type){
this.type = type;
}
public void authorize(){
if (type.equals(Consts.PAYPAL)){
// Do this;
}
else if(type.equals(Consts.OTHER_PROCESSOR)){
// Do that;
}
}
}
Now imagine that now you'll need to maintain all this code in a single class because it's not decoupled properly, you can imagine that for every new processor you'll support, you'll need to create a new if // switch case for every method, this only gets more complicated, however, by using Dependency Injection (or Inversion of Control - as it's sometimes called, meaning that whoever controls the running of the program is known only at runtime, and not complication), you could achieve something very neat and maintainable.
class PaypalProcessor implements PaymentProcessor{
public void authorize(){
// Do PayPal authorization
}
}
class OtherProcessor implements PaymentProcessor{
public void authorize(){
// Do other processor authorization
}
}
class PaymentFactory{
public static PaymentProcessor create(String type){
switch(type){
case Consts.PAYPAL;
return new PaypalProcessor();
case Consts.OTHER_PROCESSOR;
return new OtherProcessor();
}
}
}
interface PaymentProcessor{
void authorize();
}
** The code won't compile, I know :)
For Python3 I needed to do this:
python3 -m pip install MySQL
There's no way of getting around issue #2. That's just the way the C compiler (and hence the Objective-C compiler) work. If you use the XCode editor, the function popup should make it easy to navigate the @interface
and @implementation
blocks in the file.
You can't create a new branch with this command
git checkout --track origin/branch
if you have changes that are not staged.
Here is example:
$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: src/App.js
no changes added to commit (use "git add" and/or "git commit -a")
// TRY TO CREATE:
$ git checkout --track origin/new-branch
fatal: 'origin/new-branch' is not a commit and a branch 'new-branch' cannot be created from it
However you can easily create a new branch with un-staged changes with git checkout -b
command:
$ git checkout -b new-branch
Switched to a new branch 'new-branch'
M src/App.js
In the future one would use left: unset;
for unsetting the value of left.
As of today 4 nov 2014 unset
is only supported in Firefox.
My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.
Create an Event
object and pass it to the dispatchEvent
method of the element:
var element = document.getElementById('just_an_example');
var event = new Event('change');
element.dispatchEvent(event);
This will trigger event listeners regardless of whether they were registered by calling the addEventListener
method or by setting the onchange
property of the element.
If you want the event to bubble, you need to pass a second argument to the Event
constructor:
var event = new Event('change', { bubbles: true });
Information about browser compability:
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
Here's another way to do it in VBA.
Function ConvertToArray(ByVal value As String)
value = StrConv(value, vbUnicode)
ConvertToArray = Split(Left(value, Len(value) - 1), vbNullChar)
End Function
Sub example()
Dim originalString As String
originalString = "hi there"
Dim myArray() As String
myArray = ConvertToArray(originalString)
End Sub
This is an excellent article : http://www.daniweb.com/software-development/computer-science/threads/13488/time-complexity-of-algorithm
The below answer is copied from above (in case the excellent link goes bust)
The most common metric for calculating time complexity is Big O notation. This removes all constant factors so that the running time can be estimated in relation to N as N approaches infinity. In general you can think of it like this:
statement;
Is constant. The running time of the statement will not change in relation to N.
for ( i = 0; i < N; i++ )
statement;
Is linear. The running time of the loop is directly proportional to N. When N doubles, so does the running time.
for ( i = 0; i < N; i++ ) {
for ( j = 0; j < N; j++ )
statement;
}
Is quadratic. The running time of the two loops is proportional to the square of N. When N doubles, the running time increases by N * N.
while ( low <= high ) {
mid = ( low + high ) / 2;
if ( target < list[mid] )
high = mid - 1;
else if ( target > list[mid] )
low = mid + 1;
else break;
}
Is logarithmic. The running time of the algorithm is proportional to the number of times N can be divided by 2. This is because the algorithm divides the working area in half with each iteration.
void quicksort ( int list[], int left, int right )
{
int pivot = partition ( list, left, right );
quicksort ( list, left, pivot - 1 );
quicksort ( list, pivot + 1, right );
}
Is N * log ( N ). The running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm is a combination of linear and logarithmic.
In general, doing something with every item in one dimension is linear, doing something with every item in two dimensions is quadratic, and dividing the working area in half is logarithmic. There are other Big O measures such as cubic, exponential, and square root, but they're not nearly as common. Big O notation is described as O ( <type> )
where <type>
is the measure. The quicksort algorithm would be described as O ( N * log ( N ) )
.
Note that none of this has taken into account best, average, and worst case measures. Each would have its own Big O notation. Also note that this is a VERY simplistic explanation. Big O is the most common, but it's also more complex that I've shown. There are also other notations such as big omega, little o, and big theta. You probably won't encounter them outside of an algorithm analysis course. ;)
This is the result of ifconfig:
pi@raspberrypi:~ $ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.2.24 netmask 255.255.255.0 broadcast 192.168.2.255
inet6 fe80::88e9:4d2:c057:2d5f prefixlen 64 scopeid 0x20<link>
ether b8:27:eb:d0:9a:f3 txqueuelen 1000 (Ethernet)
RX packets 261861 bytes 250818555 (239.1 MiB)
RX errors 0 dropped 6 overruns 0 frame 0
TX packets 299436 bytes 280053853 (267.0 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 74 bytes 16073 (15.6 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 74 bytes 16073 (15.6 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
wlan0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
ether b8:27:eb:85:cf:a6 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
pi@raspberrypi:~ $
Cutting a bit the output, we have:
pi@raspberrypi:~ $
pi@raspberrypi:~ $ ifconfig eth0 | grep "inet 192" | cut -c 14-25
192.168.2.24
pi@raspberrypi:~ $
pi@raspberrypi:~ $
Now, we can go to python and do:
import os
mine = os.popen('ifconfig eth0 | grep "inet 192" | cut -c 14-25')
myip = mine.read()
print (myip)
Careful with rewriting URLs, though. I'm using this, so it keeps URLs rewritten.
Response.Redirect(Request.RawUrl);
The answer's here are talking about the reflection of the change on the docker-compose.yml file.
But what if I want to incorporate the changes I have done in my code, and I believe that will be only possible by rebuilding the image and that I do with following commands
1. docker container stop
docker stop container-id
2. docker container removal
docker rm container-id
3. docker image removal
docker rmi image-id
4. compose the container again
docker-compose up container-name