It might be safer to directly pass environment variables to maven system properties. For example, say on Linux you want to access environment variable MY_VARIABLE. You can use a system property in your pom file.
<properties>
...
<!-- Default value for my.variable can be defined here -->
<my.variable>foo</my.variable>
...
</properties>
...
<!-- Use my.variable -->
... ${my.variable} ...
Set the property value on the maven command line:
mvn clean package -Dmy.variable=$MY_VARIABLE
That way older browser don't parse the Javascript code and the page doesn't break.
Backwards compatability. Gotta love it.
This might not be the answer you're looking for, but I don't have a better way for downloading DB from phone. What I will suggest is make sure you're using this mini-DDMS. It will be super hidden though if you don't click the very small camoflage box at the very bottom left of program. (tried to hover over it otherwise you might miss it.)
Also the drop down that says no filters (top right). It literally has a ton of different ways you can monitor different process/apps by PPID, name, and a lot more. I've always used this to monitor phone, but keep in mind I'm not doing the type of dev work that needs to be 120% positive the database isn't doing something out of the ordinary.
Hope it helps
use jQuery.noConflict()
var j = jQuery.noConflict();
j(document).ready(function(){
j('#datetimepicker').datepicker();
})
For the simple email like [email protected], below code is sufficient.
public static bool ValidateEmail(string email)
{
System.Text.RegularExpressions.Regex emailRegex = new System.Text.RegularExpressions.Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
System.Text.RegularExpressions.Match emailMatch = emailRegex.Match(email);
return emailMatch.Success;
}
I can confirm that my original code seems to work. I was casually sticking to an image with a wrong path.
Here's a test : http://paragraphe.org/slidetoggletest/test.html
<script>
var pic = new Image();
var pic2 = new Image();
var pic3 = new Image();
pic.src="images/inputs/input1.png";
pic2.src="images/inputs/input2.png";
pic3.src="images/inputs/input3.png";
</script>
remove the ios::binary
from your modes in your ofstream and use studentPassword.c_str()
instead of (char *)&studentPassword
in your write.write()
After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?
BUT there was an import that was screwing the rest of it up:
.vue
files<script>
var mylib = require('./mylib');
export default {
....
mylib
exports.myfunc = () => {....}
import
The actual issue in my case (which I didn't think was relevant!) was that mylib.js
was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack
but anyway I had:
import models from './model/models'
import axios from 'axios'
This works so long as I'm not using mylib
in a .vue
component. However as soon as I use mylib
there, the error described in this issue arises.
I changed to:
let models = require('./model/models');
let axios = require('axios');
And all works as expected.
To print nth line using sed with a variable as line number:
a=4
sed -e $a'q:d' file
Here the '-e' flag is for adding script to command to be executed.
For me
Adding this line
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
Before this line.
<script id="microloader" type="text/javascript" src=".sencha/app/microloader/development.js"></script>
worked
Write your <span>
in <h1>
or <h2>
:
<h1> <span class="glyphicon glyphicon-th-list"></span></h1>
Perhaps the error message is somewhat misleading, but the gist is that X_train
is a list, not a numpy array. You cannot use array indexing on it. Make it an array first:
out_images = np.array(X_train)[indices.astype(int)]
I have had good success using Spring WS for the client end of a web service app - see http://static.springsource.org/spring-ws/sites/1.5/reference/html/client.html
My project uses a combination of:
XMLBeans (generated from a simple Maven job using the xmlbeans-maven-plugin)
Spring WS - using marshalSendAndReceive() reduces the code down to one line for sending and receiving
some Dozer - mapping the complex XMLBeans to simple beans for the client GUI
public static string XmlEscape(string unescaped)
{
XmlDocument doc = new XmlDocument();
XmlNode node = doc.CreateElement("root");
node.InnerText = unescaped;
return node.InnerXml;
}
public static string XmlUnescape(string escaped)
{
XmlDocument doc = new XmlDocument();
XmlNode node = doc.CreateElement("root");
node.InnerXml = escaped;
return node.InnerText;
}
I would like to add one point in this question which I was facing for couple of days. I tried all the answers but those were not working for me. If you are using android version 5.1 please change these settings.
If you are using android version 5.1 then you have to dis-select (Restrict to launch) from app settings.
settings> app > your app > Restrict to launch (dis-select)
Javascript is not an object oriented language as typically considered, mainly due to lack of true inheritance, DUCK typing allows for a semi-true form of inheritance/polymorphism along with the Object.prototype allowing for complex function sharing. At its heart however the lack of inheritance leads to a weak polymorphism to take place since the DUCK typing will insist some object with the same attribute names are an instance of an Object which they were not intended to be used as. Thus adding attributes to random object transforms their type's base in a manner of speaking.
simply use
this.recreate();
this will trigger the onCreate method in the activity
Check that your index is really datetime
, not str
Can be helpful:
data.index = pd.to_datetime(data['Index']).values
A simple for loop which tests the checked
property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked
further if needed.
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i=0; i<checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
// Call as
var checkedBoxes = getCheckedBoxes("mycheckboxes");
SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group
That works to get the max date..join it back to your data to get the other columns:
Select group,max_date,checks
from table t
inner join
(SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group)a
on a.group = t.group and a.max_date = date
Inner join functions as the filter to get the max record only.
FYI, your column names are horrid, don't use reserved words for columns (group, date, table).
Short answer: No practical, performance, or storage, difference.
Long answer:
There is essentially no difference (in MySQL) between VARCHAR(3000)
(or any other large limit) and TEXT
. The former will truncate at 3000 characters; the latter will truncate at 65535 bytes. (I make a distinction between bytes and characters because a character can take multiple bytes.)
For smaller limits in VARCHAR
, there are some advantages over TEXT
.
CHARACTER SET
.INDEXes
are limited in how big a column can be indexed. (767 or 3072 bytes; this is version and settings dependent)SELECTs
are handled in two different ways -- MEMORY (faster) or MyISAM (slower). When 'large' columns are involved, the slower technique is automatically picked. (Significant changes coming in version 8.0; so this bullet item is subject to change.)TEXT
datatypes (as opposed to VARCHAR
) jump straight to MyISAM. That is, TINYTEXT
is automatically worse for generated temp tables than the equivalent VARCHAR
. (But this takes the discussion in a third direction!)VARBINARY
is like VARCHAR
; BLOB
is like TEXT
.Rebuttal to other answers
The original question asked one thing (which datatype to use); the accepted answer answered something else (off-record storage). That answer is now out of date.
When this thread was started and answered, there were only two "row formats" in InnoDB. Soon afterwards, two more formats (DYNAMIC
and COMPRESSED
) were introduced.
The storage location for TEXT
and VARCHAR()
is based on size, not on name of datatype. For an updated discussion of on/off-record storage of large text/blob columns, see this .
Try this to make sure you get your shell back:
enter adb shell (root). Then type below comamnd.
stop adbd && setprop service.adb.root 0 && start adbd &
This command will stop adbd
, then setprop service.adb.root 0
if adbd
has been successfully stop
ped, and finally restart adbd
should the .root
property have successfully been set to 0. And all this will be done in the background thanks to the last &
.
You can use sort() function. sort() exists in algorithm header file
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
string str = "sharlock";
sort(str.begin(), str.end());
cout<<str<<endl;
return 0;
}
Output:
achklors
The size of your image is not sufficient to see in a naked eye. So please try to use atleast 50x50
import cv2 as cv
import numpy as np
black_screen = np.zeros([50,50,3])
black_screen[:, :, 2] = np.ones([50,50])*64/255.0
cv.imshow("Simple_black", black_screen)
cv.waitKey(0)
cv.displayAllWindows()
The above solutions work if you are compressing all white space in the XML document. Other quick options are JDOM (using Format.getCompactFormat()) and dom4j (using OutputFormat.createCompactFormat()) when outputting the XML document.
However, I had a unique requirement to preserve the white space contained within the element's text value and these solutions did not work as I needed. All I needed was to remove the 'pretty-print' formatting added to the XML document.
The solution that I came up with can be explained in the following 3-step/regex process ... for the sake of understanding the algorithm for the solution.
String regex, updatedXml;
// 1. remove all white space preceding a begin element tag:
regex = "[\\n\\s]+(\\<[^/])";
updatedXml = originalXmlStr.replaceAll( regex, "$1" );
// 2. remove all white space following an end element tag:
regex = "(\\</[a-zA-Z0-9-_\\.:]+\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );
// 3. remove all white space following an empty element tag
// (<some-element xmlns:attr1="some-value".... />):
regex = "(/\\>)[\\s]+";
updatedXml = updatedXml.replaceAll( regex, "$1" );
NOTE: The pseudo-code is in Java ... the '$1' is the replacement string which is the 1st capture group.
This will simply remove the white space used when adding the 'pretty-print' format to an XML document, yet preserve all other white space when it is part of the element text value.
In Skype:
Go to Tools ? Options ? Advanced ? Connections
and uncheck the box use port 80 and 443 as alternative
. This should help.
As Salman Quader said: In the updated skype(8.x), there is no menu option to change the port. This means this answer is no longer valid.
const int WIDTH = 1024;
const int HEIGHT = 800;
Use This as the solution
This worked for me perfectly..
<div align="center">
<img src="">
</div>
Try the following
for ( const auto &p : table )
{
std::cout << p.first << '\t' << p.second << std::endl;
}
The same can be written using an ordinary for loop
for ( auto it = table.begin(); it != table.end(); ++it )
{
std::cout << it->first << '\t' << it->second << std::endl;
}
Take into account that value_type for std::map
is defined the following way
typedef pair<const Key, T> value_type
Thus in my example p is a const reference to the value_type where Key is std::string
and T is int
Also it would be better if the function would be declared as
void output( const map<string, int> &table );
When I modify your code to use a file accessed by an absolute path instead of a resource, I get a different result (for 1 run, 1 iteration, and a 100,000 byte file -- times for a 10 byte file are identical to 100,000 bytes)
LENGTH sum: 33, per Iteration: 33.0
CHANNEL sum: 3626, per Iteration: 3626.0
URL sum: 294, per Iteration: 294.0
I know it's been a while on this question, but I was just looking for the same answer and found this seems to be the simplest solution:
select * from sales where datediff(dd, salesDate, '20101111') = 0
I actually use it more to find things within the last day or two, so my version looks like this:
select * from sales where datediff(dd, salesDate, getdate()) = 0
And by changing the 0 for today to a 1 I get yesterday's transactions, 2 is the day before that, and so on. And if you want everything for the last week, just change the equals to a less-than-or-equal-to:
select * from sales where datediff(dd, salesDate, getdate()) <= 7
You first add css
html,body{
height:100%;
}
This will be the html:
<div style="position:relative;height:100%;max-width:500px;margin:auto">
<iframe src="xyz.pdf" frameborder="0" width="100%" height="100%">
<p>Your browser does not support iframes.</p>
</iframe>
</div>
Jenkins stores the console log on master. If you want programmatic access to the log, and you are running on master, you can access the log that Jenkins already has, without copying it to the artifacts or having to GET the http job URL.
From http://javadoc.jenkins.io/archive/jenkins-1.651/hudson/model/Run.html#getLogFile(), this returns the File object for the console output (in the jenkins file system, this is the "log" file in the build output directory).
In my case, we use a chained (child) job to do parsing and analysis on a parent job's build.
When using a groovy script run in Jenkins, you get an object named "build" for the run. We use this to get the http://javadoc.jenkins.io/archive/jenkins-1.651/hudson/model/Build.html for the upstream job, then call this job's .getLogFile().
Added bonus; since it's just a File object, we call .getParent() to get the folder where Jenkins stores build collateral (like test xmls, environment variables, and other things that may not be explicitly exposed through the artifacts) which we can also parse.
Double added bonus; we also use matrix jobs. This sometimes makes inferring the file path on the system a pain. .getLogFile().getParent() takes away all the pain.
The easiest way to do this is generate a KML file (see http://code.google.com/apis/kml/articles/csvtokml.html for a possible solution). You can then open that up in Google Maps by storing it online and linking to it from Google Maps as described at http://code.google.com/apis/kml/documentation/whatiskml.html
EDIT: http://www.gpsbabel.org/ may let you do it without coding.
A standard Java HashMap cannot store multiple values per key, any new entry you add will overwrite the previous one.
If sheet contains unused area on the top, UsedRange.Rows.Count
is not the maximum row.
This is the correct max row number.
maxrow = Sheets("..name..").UsedRange.Rows(Sheets("..name..").UsedRange.Rows.Count).Row
Try it, This will work more efficiently.. 1. For number ranging 00 - 99.99 (decimal inclusive)
^([0-9]{1,2}){1}(\.[0-9]{1,2})?$
Working fiddle link
https://regex101.com/r/d1Kdw5/1/
2.For number ranging 1-100(inclusive) with no preceding 0.
(?:\b|-)([1-9]{1,2}[0]?|100)\b
Working Fiddle link
I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.
(function() {
var lastText = '';
$('#MyTextBox'), {
source: MyData
})
.on('autocompleteselect autocompletefocus', function(ev, ui) {
lastText = ui.item.label;
jqTag.data('autocomplete-item', ui.item);
})
.keyup(function(ev) {
if (lastText != jqTag.val()) {
// Clear when they stop typing
jqTag.data('autocomplete-item', null);
// Pass the event on as autocompleteclear so callers can listen for select/clear
var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
return jqTag.trigger(clearEv);
});
})();
With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.
`realpath(dirname(__FILE__))`
it gives you current script(the script inside which you placed this code) directory without trailing slash. this is important if you want to include other files with the result
Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary
// fordictionary
var x = (from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() })
.ToDictionary( t => t.type, t => t.count);
//for stringbuilder not sure for this
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
StringBuilder MyStringBuilder = new StringBuilder();
foreach (var res in x)
{
//: is separator between to object
MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
}
Console.WriteLine(MyStringBuilder.ToString());
Here is another one liner:
[[ -d /tmp/test ]] && rm -r /tmp/test
The integrated debuggers where you can watch the values of variable change as you step through code are really cool. They do, however, require software setup on the server and a certain amount of configuration on the client. Both of which require periodic maintenance to keep in good working order.
A print_r is easy to write and is guaranteed to work in any setup.
For repeat a value in my projects i use repeat
For example:
var n = 6;
for (i = 0; i < n; i++) {
console.log("#".repeat(i+1))
}
but be careful because this method has been added to the ECMAScript 6 specification.
<ListView android:id="@+id/listView" ... />
<TextView android:id="@+id/empty" ... />
and in the linked Activity:
this.listView = (ListView) findViewById(R.id.listView);
this.listView.setEmptyView(findViewById(R.id.empty));
This works clearly with FragmentActivity if you are using the support library. Tested this by building for API 17 i.e. 4.2.2 image.
You can try loading the file into a firefox window then go to View - Character Encoding. There should be a check mark next to the file's encoding type.
use os.path.isdir(path)
more info here http://docs.python.org/library/os.path.html
Since you've already stashed your changes, all you need is this one-liner:
git stash branch <branchname> [<stash>]
From the docs (https://www.kernel.org/pub/software/scm/git/docs/git-stash.html):
Creates and checks out a new branch named <branchname> starting from the commit at which the <stash> was originally created, applies the changes recorded in <stash> to the new working tree and index. If that succeeds, and <stash> is a reference of the form stash@{<revision>}, it then drops the <stash>. When no <stash> is given, applies the latest one.
This is useful if the branch on which you ran git stash save has changed enough that git stash apply fails due to conflicts. Since the stash is applied on top of the commit that was HEAD at the time git stash was run, it restores the originally stashed state with no conflicts.
From the accepted answer, it looks like your desired behaviour is to turn
skip 0
skip 1
skip 2
skip 3
"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636
into
2012,06,23,03,09,13.23,4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,NAN,-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636
If that's right, then I think something like
import csv
with open("test.dat", "rb") as infile, open("test.csv", "wb") as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile, quoting=False)
for i, line in enumerate(reader):
if i < 4: continue
date = line[0].split()
day = date[0].split('-')
time = date[1].split(':')
newline = day + time + line[1:]
writer.writerow(newline)
would be a little simpler than the reps
stuff.
The first one is the correct one, and IMHO the more efficient one, since the second 'solution' instantiates a new string instance.
In addition to the previous answers, here is a way to calculate the distance inside a SELECT:
CREATE FUNCTION Get_Distance
(
@La1 float , @Lo1 float , @La2 float, @Lo2 float
)
RETURNS TABLE
AS
RETURN
-- Distance in Meters
SELECT GEOGRAPHY::Point(@La1, @Lo1, 4326).STDistance(GEOGRAPHY::Point(@La2, @Lo2, 4326))
AS Distance
GO
Usage:
select Distance
from Place P1,
Place P2,
outer apply dbo.Get_Distance(P1.latitude, P1.longitude, P2.latitude, P2.longitude)
Scalar functions also work but they are very inefficient when computing large amount of data.
I hope this might help someone.
React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover
in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter
and onMouseLeave
. You then attach them to handlers in your component like so:
<ReactComponent
onMouseEnter={() => this.someHandler}
onMouseLeave={() => this.someOtherHandler}
/>
You'll then use some combination of state/props to pass changed state or properties down to your child React components.
I usually curse MS word and then run the following Wscript.
// replace with path to a file that needs cleaning
PATH = "test.html"
var go=WScript.CreateObject("Scripting.FileSystemObject");
var content=go.GetFile(PATH).OpenAsTextStream().ReadAll();
var out=go.CreateTextFile("clean-"+PATH, true);
// symbols
content=content.replace(/“/g,'"');
content=content.replace(/”/g,'"');
content=content.replace(/’/g,"'");
content=content.replace(/–/g,"-");
content=content.replace(/©/g,"©");
content=content.replace(/®/g,"®");
content=content.replace(/°/g,"°");
content=content.replace(/¶/g,"<p>");
content=content.replace(/¿/g,"¿");
content=content.replace(/¡/g,'¡');
content=content.replace(/¢/g,'¢');
content=content.replace(/£/g,'£');
content=content.replace(/¥/g,'¥');
out.Write(content);
The most you can get is:
select#xyz {
border:0px;
outline:0px;
}
You cannot style it completely, but you can try something like
select#xyz {
-webkit-appearance: button;
-webkit-border-radius: 2px;
-webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.1);
-webkit-padding-end: 20px;
-webkit-padding-start: 2px;
-webkit-user-select: none;
background-image: url(../images/select-arrow.png),
-webkit-linear-gradient(#FAFAFA, #F4F4F4 40%, #E5E5E5);
background-position: center right;
background-repeat: no-repeat;
border: 1px solid #AAA;
color: #555;
font-size: inherit;
margin: 0;
overflow: hidden;
padding-top: 2px;
padding-bottom: 2px;
text-overflow: ellipsis;
white-space: nowrap;
}
You will need to make sure you have Options -MultiViews
as well.
None of the above worked for me on a standard cPanel host.
This worked:
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]
You can also "fix" this by replacing the image with its inline Base64 representation:
Useful, when you do not intend to publish the page on the web, but instead use it on local machines only. img.src= "data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
I propose this query:
SELECT DISTINCT s.*
FROM INFORMATION_SCHEMA.STATISTICS s
LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS t
ON t.TABLE_SCHEMA = s.TABLE_SCHEMA
AND t.TABLE_NAME = s.TABLE_NAME
AND s.INDEX_NAME = t.CONSTRAINT_NAME
WHERE 0 = 0
AND t.CONSTRAINT_NAME IS NULL
AND s.TABLE_SCHEMA = 'YOUR_SCHEMA_SAMPLE';
You found all Index only index.
Regard.
I believe the following pdf will give you the bigger picture. Domain Driven Design by Eric Evans
NOTE: Think of a project you can work on, apply the little things you understood and see best practices. It will help you to grow your ability to the micro service architecture design approach too.
Actually, a new technique came out recently. This article will answer your questions: http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement
.hide-text {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
}
It is accessible, an has better performance than -99999px.
Update: As @deathlock mentions in the comment area, the author of the fix above (Scott Kellum), has suggested using a transparent font: http://scottkellum.com/2013/10/25/the-new-kellum-method.html.
Unfortunately, none of the ten answers posted so far are quite right.
If you are measuring elapsed time, and you want it to be correct, you must use System.nanoTime()
. You cannot use System.currentTimeMillis()
, unless you don't mind your result being wrong.
The purpose of nanoTime
is to measure elapsed time, and the purpose of currentTimeMillis
is to measure wall-clock time. You can't use the one for the other purpose. The reason is that no computer's clock is perfect; it always drifts and occasionally needs to be corrected. This correction might either happen manually, or in the case of most machines, there's a process that runs and continually issues small corrections to the system clock ("wall clock"). These tend to happen often. Another such correction happens whenever there is a leap second.
Since nanoTime
's purpose is to measure elapsed time, it is unaffected by any of these small corrections. It is what you want to use. Any timings currently underway with currentTimeMillis
will be off -- possibly even negative.
You may say, "this doesn't sound like it would ever really matter that much," to which I say, maybe not, but overall, isn't correct code just better than incorrect code? Besides, nanoTime
is shorter to type anyway.
Previously posted disclaimers about nanoTime
usually having only microsecond precision are valid. Also it can take more than a whole microsecond to invoke, depending on circumstances (as can the other one), so don't expect to time very very small intervals correctly.
I would like to give one additional answer, while the other ones will suffice in most cases.
I wanted to write a string over multiple lines, but its contents needed to be single-line.
sql=" \
SELECT c1, c2 \
from Table1, ${TABLE2} \
where ... \
"
I am sorry if this if a bit off-topic (I did not need this for SQL). However, this post comes up among the first results when searching for multi-line shell variables and an additional answer seemed appropriate.
I have great news: this will be in Compose 1.3!
I'm using it in the current RC (RC1) like this:
rng:
build: rng
extra_hosts:
seed: 1.2.3.4
tree: 4.3.2.1
This is the fastest way to calculate prime numbers in C#.
void PrimeNumber(long number)
{
bool IsprimeNumber = true;
long value = Convert.ToInt32(Math.Sqrt(number));
if (number % 2 == 0)
{
IsprimeNumber = false;
}
for (long i = 3; i <= value; i=i+2)
{
if (number % i == 0)
{
// MessageBox.Show("It is divisible by" + i);
IsprimeNumber = false;
break;
}
}
if (IsprimeNumber)
{
MessageBox.Show("Yes Prime Number");
}
else
{
MessageBox.Show("No It is not a Prime NUmber");
}
}
A very direct way is to just use read.table
on your character vector:
> read.table(text = text, sep = ".", colClasses = "character")
V1 V2 V3 V4
1 F US CLE V13
2 F US CA6 U13
3 F US CA6 U13
4 F US CA6 U13
5 F US CA6 U13
6 F US CA6 U13
7 F US CA6 U13
8 F US CA6 U13
9 F US DL U13
10 F US DL U13
11 F US DL U13
12 F US DL Z13
13 F US DL Z13
colClasses
needs to be specified, otherwise F
gets converted to FALSE
(which is something I need to fix in "splitstackshape", otherwise I would have recommended that :) )
Alternatively, you can use my cSplit
function, like this:
cSplit(as.data.table(text), "text", ".")
# text_1 text_2 text_3 text_4
# 1: F US CLE V13
# 2: F US CA6 U13
# 3: F US CA6 U13
# 4: F US CA6 U13
# 5: F US CA6 U13
# 6: F US CA6 U13
# 7: F US CA6 U13
# 8: F US CA6 U13
# 9: F US DL U13
# 10: F US DL U13
# 11: F US DL U13
# 12: F US DL Z13
# 13: F US DL Z13
Or, separate
from "tidyr", like this:
library(dplyr)
library(tidyr)
as.data.frame(text) %>% separate(text, into = paste("V", 1:4, sep = "_"))
# V_1 V_2 V_3 V_4
# 1 F US CLE V13
# 2 F US CA6 U13
# 3 F US CA6 U13
# 4 F US CA6 U13
# 5 F US CA6 U13
# 6 F US CA6 U13
# 7 F US CA6 U13
# 8 F US CA6 U13
# 9 F US DL U13
# 10 F US DL U13
# 11 F US DL U13
# 12 F US DL Z13
# 13 F US DL Z13
Some times there are problems with funtion/features that do not interact with the DOM
try to change the value sharply and then assign the $scope
document.getElementById ("textWidget") value = "<NewVal>";
$scope.widget.title = "<NewVal>";
ok so I used this:
public partial class Form1 : Form
{
private void Button_Click(object sender, EventArgs e)
{
Form2 myForm = new Form2();
this.Hide();
myForm.ShowDialog();
this.Close();
}
}
This seems to be working fine but the first form is just hidden and it can still generate events. the "this.Close()" is needed to close the first form but if you still want your form to run (and not act like a launcher) you MUST replace it with
this.Show();
Best of luck!
In Postman, click Generate Code and then in Generate Code Snippets dialog you can select a different coding language, including C# (RestSharp).
Also, you should only need the access token URL. The form parameters are then:
grant_type=client_credentials
client_id=abc
client_secret=123
Code Snippet:
/* using RestSharp; // https://www.nuget.org/packages/RestSharp/ */
var client = new RestClient("https://service.endpoint.com/api/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=abc&client_secret=123", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
From the response body you can then obtain your access token. For instance for a Bearer token type you can then add the following header to subsequent authenticated requests:
request.AddHeader("authorization", "Bearer <access_token>");
Yes, because in your case they use the same representation.
The bit pattern 0xFFFFFFFF
happens to look like -1 when interpreted as a 32b signed integer and as 4294967295 when interpreted as a 32b unsigned integer.
It's the same as char c = 65
. If you interpret it as a signed integer, it's 65. If you interpret it as a character it's a
.
As R and pmg point out, technically it's undefined behavior to pass arguments that don't match the format specifiers. So the program could do anything (from printing random values to crashing, to printing the "right" thing, etc).
The standard points it out in 7.19.6.1-9
If a conversion speci?cation is invalid, the behavior is unde?ned. If any argument is not the correct type for the corresponding conversion speci?cation, the behavior is unde?ned.
That's the normal structure for ngClass
is:
[ngClass]="{'classname' : condition}"
So in your case, just use it like this...
<ol class="breadcrumb">
<li [ngClass]="{'active': step==='step1'}" (click)="step='step1'">Step1</li>
<li [ngClass]="{'active': step==='step2'}" (click)="step='step2'">Step2</li>
<li [ngClass]="{'active': step==='step3'}" (click)="step='step3'">Step3</li>
</ol>
So what will happen if two threads attack a volatile primitive variable at same time?
Usually each one can increment the value. However sometime, both will update the value at the same time and instead of incrementing by 2 total, both thread increment by 1 and only 1 is added.
Does this mean that whosoever takes lock on it, that will be setting its value first.
There is no lock. That is what synchronized
is for.
And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?
Yes,
What is the difference between Atomic and volatile keyword?
AtomicXxxx wraps a volatile so they are basically same, the difference is that it provides higher level operations such as CompareAndSwap which is used to implement increment.
AtomicXxxx also supports lazySet. This is like a volatile set, but doesn't stall the pipeline waiting for the write to complete. It can mean that if you read a value you just write you might see the old value, but you shouldn't be doing that anyway. The difference is that setting a volatile takes about 5 ns, bit lazySet takes about 0.5 ns.
As mentioned in multiple answers above you can import the cURL in POSTMAN directly. But if URL is authorized (or is not working for some reason) ill suggest you can manually add all the data points as JSON in your postman body. take the API URL from the cURL.
for the Authorization part- just add an Authorization key and base 64 encoded string as value.
example:
curl -u rzp_test_26ccbdbfe0e84b:69b2e24411e384f91213f22a \ https://api.razorpay.com/v1/orders -X POST \ --data "amount=50000" \ --data "currency=INR" \ --data "receipt=Receipt #20" \ --data "payment_capture=1" https://api.razorpay.com/v1/orders
{
"amount": "5000",
"currency": "INR",
"receipt": "Receipt #20",
"payment_capture": "1"
}
Headers:
Authorization:Basic cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS***U056V25J
where "cnpwX3Rlc3RfWEk5QW5TU0N3RlhjZ0Y6dURjVThLZ3JiQVVnZ3JNS***U056V25J" is the encoded form of "rzp_test_26ccbdbfe0e84b:69b2e24411e384f91213f22a"`
small tip: for encoding, you can easily go to your chrome console (right-click => inspect) and type :
btoa("string you want to encode")
( or use postman basic authorization)
My issue was also within the heredoc. I had it within an if/then statement and the closing bracket directly after the semicolon. So I moved the closing bracket to its own line and issue was fixed.
I changed:
... ;}
to:
... ;
}
First of all, this line
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()
You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click()
there.
If you read the JavaScript you've got there, document.getElementById('foo')
it's looking for an HTML element with an ID of foo
. You don't have one. Give your image that ID:
<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />
Alternatively, you could throw the JS in a function and put an onclick in your HTML:
<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />
I suggest you do some reading up on JavaScript and HTML though.
The others are right about needing to move the <img>
above the JS click binding too.
I think you should use the Rails debug options:
logger.debug "Person attributes hash: #{@person.attributes.inspect}"
logger.info "Processing the request..."
logger.fatal "Terminating application, raised unrecoverable error!!!"
https://guides.rubyonrails.org/debugging_rails_applications.html
I agree that versioning the resource representation better follows the REST approach...but, one big problem with custom MIME types (or MIME types that append a version parameter) is the poor support to write to Accept and Content-Type headers in HTML and JavaScript.
For example, it is not possible IMO to POST with the following headers in HTML5 forms, in order to create a resource:
Accept: application/vnd.company.myapp-v3+json
Content-Type: application/vnd.company.myapp-v3+json
This is because the HTML5 enctype
attribute is an enumeration, therefore anything other than the usual application/x-www-formurlencoded
, multipart/form-data
and text/plain
are invalid.
...nor am I sure it is supported across all browsers in HTML4 (which has a more lax encytpe attribute, but would be a browser implementation issue as to whether the MIME type was forwarded)
Because of this I now feel the most appropriate way to version is via the URI, but I accept that it is not the 'correct' way.
I would use this
(function ($) {
$(document);
}(jQuery));
Tabulator is a set of unix command line tools to work with csv files that have header lines. Here is an example to extract columns by name from a file test.csv:
name,sex,house_nr,height,shoe_size
arthur,m,42,181,11.5
berta,f,101,163,8.5
chris,m,1333,175,10
don,m,77,185,12.5
elisa,f,204,166,7
Then tblmap -k name,height test.csv
produces
name,height
arthur,181
berta,163
chris,175
don,185
elisa,166
add this to your pom.xml file:
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>sample.HelloWorldApplication</mainClass>
</transformer>
</transformers>
</configuration>
and add the class name of your project (full path) along with the package name like "com.packageName.className" which consists of the main method having "run" method in it. And instead of your "???" write ${mainClass} which will automatically get the className which you have mentioned above.
Then try command mvn clean install and mvn -jar "jar_file_name.jar" server "yaml_file_name.yml"
I hope it will work normally and server will start at the specified port.
In Oracle 11g, if you want to search any text in whole database or procedure below mentioned query can be used:
select * from user_source WHERE UPPER(text) LIKE '%YOUR SAGE%'
We can try a simpler one as follows:
docker image inspect image_id
This worked in Docker version:
DockerVersion": "18.05.0-ce"
I found so many solution but I never got correct solution. But i have created some code to find minutes please check it.
<?php
$time1 = "23:58";
$time2 = "01:00";
$time1 = explode(':',$time1);
$time2 = explode(':',$time2);
$hours1 = $time1[0];
$hours2 = $time2[0];
$mins1 = $time1[1];
$mins2 = $time2[1];
$hours = $hours2 - $hours1;
$mins = 0;
if($hours < 0)
{
$hours = 24 + $hours;
}
if($mins2 >= $mins1) {
$mins = $mins2 - $mins1;
}
else {
$mins = ($mins2 + 60) - $mins1;
$hours--;
}
if($mins < 9)
{
$mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
}
if($hours < 9)
{
$hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
}
echo $hours.':'.$mins;
?>
It gives output in hours and minutes for example 01 hour 02 minutes like 01:02
If you wrote
pip install --upgrade pip
and you got
Installing collected packages: pip
Attempting uninstall: pip
Found existing installation: pip 20.2.1
Uninstalling pip-20.2.1:
ERROR: Could not install packages due to an EnvironmentError...
then you have uninstalled pip instead install pip. This could be the reason of your problem.
The Gorodeckij Dimitrij's answer works for me.
python -m ensurepip
Set the "AutoSizeColumnsMode" property to "Fill".. By default it is set to 'NONE'. Now columns will be filled across the DatagridView. Then you can set the width of other columns accordingly.
DataGridView1.Columns[0].Width=100;// The id column
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining
//space
You can refer Windows command prompt help using following command : xcopy /?
From what I understand, Python lists are already quite similar to ArrayLists. But if you want to tweak those parameters I found this post on the Internet that may be interesting (basically, just create your own ScalableList
extension):
http://mail.python.org/pipermail/python-list/2000-May/035082.html
Pretty straight forward to do:
$(function() {
$('#toptitle').html('New word');
});
The html function accepts html as well, but its straight forward for replacing text.
Try
curl -G ...
instead of
curl -X GET ...
Normally you don't need this option. All sorts of GET, HEAD, POST and PUT requests are rather invoked by using dedicated command line options.
This option only changes the actual word used in the HTTP request, it does not alter the way curl behaves. So for example if you want to make a proper HEAD request, using -X HEAD will not suffice. You need to use the -I, --head option.
This will get all dll files and filter ones that match a regex of your directory structure.
Get-ChildItem C:\code -Recurse -filter "*.dll" | where { $_.directory -match 'C:\\code\\myproj.\\bin\\debug'}
If you just want the path, not the object you can add | select fullname
to the end like this:
Get-ChildItem C:\code -Recurse -filter "*.dll" | where { $_.directory -match 'C:\\code\\myproj.\\bin\\debug'} | select fullname
You can also put a Text tag inside of another Text tag. The second text tag will inherit the styling of the first, but you maintain the ability to style it independently from its parent.
<Text style={styles.bold}>Level:
<Text style={styles.normal}>Easy</Text>
</Text>
//in your stylesheet...
bold: {
fontSize: 25,
fontWeight: "bold",
color: "blue",
},
normal: {
// will inherit size and color attributes
fontWeight: "normal",
}
Encapsulate hides variables or some implementation that may be changed so often in a class to prevent outsiders access it directly. They must access it via getter and setter methods.
Abstraction is used to hiding something too but in a higher degree(class, interface). Clients use an abstract class(or interface) do not care about who or which it was, they just need to know what it can do.
Don't know of a framework method but you could write a quick helper to do it for you.
public static void Populate<T>(this T[] arr, T value ) {
for ( int i = 0; i < arr.Length;i++ ) {
arr[i] = value;
}
}
You could put the body of your script into a function and then you could return from that function.
def main():
done = True
if done:
return
# quit/stop/exit
else:
# do other stuff
if __name__ == "__main__":
#Run as main program
main()
Rotating the labels is certainly possible. Note though that doing so reduces the readability of the text. One alternative is to alternate label positions using a code like this:
import numpy as np
n=5
x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Long ticklabel %i' % i for i in range(n)]
fig, ax = plt.subplots()
ax.plot(x,y, 'o-')
ax.set_xticks(x)
labels = ax.set_xticklabels(xlabels)
for i, label in enumerate(labels):
label.set_y(label.get_position()[1] - (i % 2) * 0.075)
For more background and alternatives, see this post on my blog
For me, I mistakenly added a parameter to the test method which caused initialization error.
I originally saw this error after upgrading from 0.2.13 to 0.3. These instructions have been updated for the release of Android Studio 0.5.2. These are the steps I completed to resolve the issue.
1.In build.gradle make sure gradle is set to 0.9.0
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.9.0'
}
}
2.In gradle-wrapper.properties make sure to use gradle 1.11
#Wed Apr 10 15:27:10 PDT 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http\://services.gradle.org/distributions/gradle-1.11-all.zip
3.Sync project with gradle files by pressing the button to the left of the avd button
4.Try to build project again. If still having issues possibly try File > Invalidate Caches/Restart
NOTE: If you are using 0.9.+
and it gives Could not GET 'http://repo1.maven.org/maven2/com/android/tools/build/gradle/'. Received status code 401 from server: Unauthorized
(happens sporadically) then change to 0.9.0
. Also, you have to use build tools 19.0 or greater I believe so make sure you have those downloaded in sdk manager and use as buildToolsVersion
in whichever gradle file holds that info.
Exiting from Java running process is very easy, basically you need to do just two simple things:
System.exit(...)
at at application's quit point.
For example, if your application is frame based, you can add listener WindowAdapter
and and call System.exit(...)
inside its method windowClosing(WindowEvent e)
. Note: you must call System.exit(...)
otherwise your program is error involved.
System.exit(...)
at right point, but It does not mean that the method can be called always, because unexpected java exceptions may prevent the method from been called. This is strongly related to your programming skills.
** Following is a simplest sample (JFrame
based) which shows you how to call exit method
import java.awt.event.*;
import javax.swing.*;
public class ExitApp extends JFrame
{
public ExitApp()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0); //calling the method is a must
}
});
}
public static void main(String[] args)
{
ExitApp app=new ExitApp();
app.setBounds(133,100,532,400);
app.setVisible(true);
}
}
You can also fit a set of a data to whatever function you like using curve_fit
from scipy.optimize
. For example if you want to fit an exponential function (from the documentation):
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func(x, a, b, c):
return a * np.exp(-b * x) + c
x = np.linspace(0,4,50)
y = func(x, 2.5, 1.3, 0.5)
yn = y + 0.2*np.random.normal(size=len(x))
popt, pcov = curve_fit(func, x, yn)
And then if you want to plot, you could do:
plt.figure()
plt.plot(x, yn, 'ko', label="Original Noised Data")
plt.plot(x, func(x, *popt), 'r-', label="Fitted Curve")
plt.legend()
plt.show()
(Note: the *
in front of popt
when you plot will expand out the terms into the a
, b
, and c
that func
is expecting.)
Simply add []
to those names like
<input type="text" class="form-control" placeholder="Titel" name="levels[level][]">
<input type="text" class="form-control" placeholder="Titel" name="levels[build_time][]">
Take that template and then you can add those even using a loop.
Then you can add those dynamically as much as you want, without having to provide an index. PHP will pick them up just like your expected scenario example.
Edit
Sorry I had braces in the wrong place, which would make every new value as a new array element. Use the updated code now and this will give you the following array structure
levels > level (Array)
levels > build_time (Array)
Same index on both sub arrays will give you your pair. For example
echo $levels["level"][5];
echo $levels["build_time"][5];
The extend
method for example in jQuery or PrototypeJS, copies all properties from the source to the destination object.
Now about the prototype
property, it is a member of function objects, it is part of the language core.
Any function can be used as a constructor, to create new object instances. All functions have this prototype
property.
When you use the new
operator with on a function object, a new object will be created, and it will inherit from its constructor prototype
.
For example:
function Foo () {
}
Foo.prototype.bar = true;
var foo = new Foo();
foo.bar; // true
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true
One-liner using spread operator.
const updatedData = originalData.map(x => (x.id === id ? { ...x, updatedField: 1 } : x));
Check out these two subs that reverse each other and flip the scope (worksheet to workbook or reverse) of all named ranges that refer to a range on the active sheet.
Option Explicit
'---------------------------------------------------------------------------------------
' Procedure : RescopeNamedRangesToWorkbook
' Author : JS20'07'11
' Date : 11/18/2013
' Purpose : Rescopes the parent of worksheet scoped named ranges to the active workbook
' for each named range with a scope equal to the active sheet in the active workbook.
'---------------------------------------------------------------------------------------
Public Sub RescopeNamedRangesToWorkbook()
Dim wb As Workbook
Dim ws As Worksheet
Dim objName As Name
Dim sWsName As String
Dim sWbName As String
Dim sRefersTo As String
Dim sObjName As String
Set wb = ActiveWorkbook
Set ws = ActiveSheet
sWsName = ws.Name
sWbName = wb.Name
'Loop through names in worksheet.
For Each objName In ws.Names
'Check name is visble.
If objName.Visible = True Then
'Check name refers to a range on the active sheet.
If InStr(1, objName.RefersTo, sWsName, vbTextCompare) Then
sRefersTo = objName.RefersTo
sObjName = objName.Name
'Check name is scoped to the worksheet.
If objName.Parent.Name <> sWbName Then
'Delete the current name scoped to worksheet replacing with workbook scoped name.
sObjName = Mid(sObjName, InStr(1, sObjName, "!") + 1, Len(sObjName))
objName.Delete
wb.Names.Add Name:=sObjName, RefersTo:=sRefersTo
End If
End If
End If
Next objName
End Sub
'---------------------------------------------------------------------------------------
' Procedure : RescopeNamedRangesToWorksheet
' Author : JS20'07'11
' Date : 11/18/2013
' Purpose : Rescopes each workbook scoped named range to the specific worksheet to
' which the range refers for each named range that refers to the active worksheet.
'---------------------------------------------------------------------------------------
Public Sub RescopeNamedRangesToWorksheet()
Dim wb As Workbook
Dim ws As Worksheet
Dim objName As Name
Dim sWsName As String
Dim sWbName As String
Dim sRefersTo As String
Dim sObjName As String
Set wb = ActiveWorkbook
Set ws = ActiveSheet
sWsName = ws.Name
sWbName = wb.Name
'Loop through names in worksheet.
For Each objName In wb.Names
'Check name is visble.
If objName.Visible = True Then
'Check name refers to a range on the active sheet.
If InStr(1, objName.RefersTo, sWsName, vbTextCompare) Then
sRefersTo = objName.RefersTo
sObjName = objName.Name
'Check name is scoped to the workbook.
If objName.Parent.Name = sWbName Then
'Delete the current name scoped to workbook replacing with worksheet scoped name.
objName.Delete
ws.Names.Add Name:=sObjName, RefersTo:=sRefersTo
End If
End If
End If
Next objName
End Sub
When you set keys (primary or foreign) you are setting constraints on how they can be used, which in turn limits what you can do with them. If you really want to alter the column, you could re-create the table without the constraints, although I'd recommend against it. Generally speaking, if you have a situation in which you want to do something, but it is blocked by a constraint, it's best resolved by changing what you want to do rather than the constraint.
Sometimes Excel will hiccup and needs a kick-start to reapply an equation. This happens in some cases when you are using custom formulas.
Make sure that you have the following script
ActiveSheet.EnableCalculation = True
Reapply the equation of choice.
Cells(RowA,ColB).Formula = Cells(RowA,ColB).Formula
This can then be looped as needed.
Why not use an indexer with the property name as a string value passed to the indexer?
Update
Based on Manipulating the browser history, passing the empty string as second parameter of pushState
method (aka title) should be safe against future changes to the method, so it's better to use pushState
like this:
history.pushState(null, '', '/en/step2');
You can read more about that in mentioned article
Original Answer
Use history.pushState
like this:
history.pushState(null, null, '/en/step2');
Update 2 to answer Idan Dagan's comment:
Why not using
history.replaceState()
?
From MDN
history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one
That means if you use replaceState
, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState
doesn't add new entry to history) and it's not recommended and provide bad UX.
Update 3 to add window.onpopstate
So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState
, you can detect the back/forward button navigation by using window.onpopstate
like this:
window.onpopstate = function(e) {
// ...
};
As the first argument of pushState
is an object, if you passed an object
instead of null
, you can access that object in onpopstate
which is very handy, here is how:
window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};
Update 4 to add Reading the current state:
When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate
event using the history.state
property like this:
console.log(history.state);
Bonus: Use following to check history.pushState
support:
if (history.pushState) {
// \o/
}
Try this,
Using foreach
Loop:
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
// ...
}
}
Use it in OnRowCommand
event and get checked CheckBox value.
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];
Make sure to learn from the padding oracle asp.net vulnerability that just happened (you applied the patch, right? ...) and use protected sections to encrypt the machine key and any other sensitive configuration.
An alternative option is to set it in the machine level web.config, so its not even in the web site folder.
To generate it do it just like the linked article in David's answer.
In my case in react was necessary to select the gh-pages branch:
you could always create a new list which is a result of adding two lists.
>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]
Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.
$("#commentForm").validate({
rules: {
cname : { required : true, minlength: 2 }
}
});
Should be something like that, I've just typed this up in the editor here so might be a syntax error or two, but you should be able to follow the pattern and the documentation
The %
operator is for integers. You're looking for the fmod()
function.
#include <cmath>
int main()
{
double x = 6.3;
double y = 2.0;
double z = std::fmod(x,y);
}
Actually, the solutions is to open the php.ini file edit the include_path line and either completely change it to
include_path='.:/usr/share/php:/usr/share/pear'
or append the
'.:/usr/share/php:/usr/share/pear'
to the current value of include_path.
It is further explained in : http://pear.php.net/manual/en/installation.checking.php#installation.checking.cli.phpdir
We have two problems to cope with.
You cannot provide a sensible GetHashCode()
if any field in the
object can be changed. Also often a object will NEVER be used in a
collection that depends on GetHashCode()
. So the cost of
implementing GetHashCode()
is often not worth it, or it is not
possible.
If someone puts your object in a collection that calls
GetHashCode()
and you have overrided Equals()
without also making
GetHashCode()
behave in a correct way, that person may spend days
tracking down the problem.
Therefore by default I do.
public class Foo
{
public int FooId { get; set; }
public string FooName { get; set; }
public override bool Equals(object obj)
{
Foo fooItem = obj as Foo;
if (fooItem == null)
{
return false;
}
return fooItem.FooId == this.FooId;
}
public override int GetHashCode()
{
// Some comment to explain if there is a real problem with providing GetHashCode()
// or if I just don't see a need for it for the given class
throw new Exception("Sorry I don't know what GetHashCode should do for this class");
}
}
And what about it?:
ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);
Version: Windows 10
Step 1: Right click Docker instance and Go to Settings
Step 2: Basic to Advanced and setting the "experimental": true
Step 4: To install dockerfile is successful( ex: docker build -t williehao/cheers2019 . )
In the java project, open .settings folder. there locate the file named "org.eclipse.wst.common.component" . Change tag <wb-module deploy-name="NEW_NAME"> .
Also you may want to change context root in project properties
You should try HttpAutoindexModule.
Set autoindex option to on
. It is off by default.
Your example configuration should be ok
location /{
root /home/yozloy/html/;
index index.html;
autoindex on;
}
Without autoindex option you should be getting Error 403 for requests that end with /
on directories that do not have an index.html
file. With this option you should be getting a simple listing:
<html>
<head><title>Index of /</title></head>
<body bgcolor="white">
<h1>Index of /test/</h1><hr><pre><a href="../">../</a>
<a href="test.txt">test.txt</a> 19-May-2012 10:43 0
</pre><hr></body>
</html>
Edit: Updated the listing to delete any references to test
I extended @Ben Lesh's answer with an ability to specify whether the validation is case sensitive or not (default)
use:
<input type="text" name="fruitName" ng-model="data.fruitName" blacklist="Coconuts,Bananas,Pears" caseSensitive="true" required/>
code:
angular.module('crm.directives', []).
directive('blacklist', [
function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
'blacklist': '=',
},
link: function ($scope, $elem, $attrs, modelCtrl) {
var check = function (value) {
if (!$attrs.casesensitive) {
value = (value && value.toUpperCase) ? value.toUpperCase() : value;
$scope.blacklist = _.map($scope.blacklist, function (item) {
return (item.toUpperCase) ? item.toUpperCase() : item
})
}
return !_.isArray($scope.blacklist) || $scope.blacklist.indexOf(value) === -1;
}
//For DOM -> model validation
modelCtrl.$parsers.unshift(function (value) {
var valid = check(value);
modelCtrl.$setValidity('blacklist', valid);
return value;
});
//For model -> DOM validation
modelCtrl.$formatters.unshift(function (value) {
modelCtrl.$setValidity('blacklist', check(value));
return value;
});
}
};
}
]);
The RegEx of accepted answer returns the values including their sourrounding quotation marks: "Foo Bar"
and "Another Value"
as matches.
Here are RegEx which return only the values between quotation marks (as the questioner was asking for):
Double quotes only (use value of capture group #1):
"(.*?[^\\])"
Single quotes only (use value of capture group #1):
'(.*?[^\\])'
Both (use value of capture group #2):
(["'])(.*?[^\\])\1
-
All support escaped and nested quotes.
You should use a Calendar instead:
Calendar start = Calendar.getInstance();
start.setTimeInMillis( timeStampValue.getTime() );
As other answers point out, there are many and good reasons why this class
was made generic. However there are plenty of times that you don't have any way of knowing the generic type to use with Class<T>
. In these cases, you can simply ignore the yellow eclipse warnings or you can use Class<?>
... That's how I do it ;)
I have written a complete article at Spring Boot JPA Multiple Data Sources Example. In this article, we will learn how to configure multiple data sources and connect to multiple databases in a typical Spring Boot web application. We will use Spring Boot 2.0.5, JPA, Hibernate 5, Thymeleaf and H2 database to build a simple Spring Boot multiple data sources web application.
First of all, finish()
doesn't destroy your process and free up the memory. It just removes the activity from the activity stack. You'd need to kill the process, which is answered in a bunch of questions (since this is being asked several times).
But the proper answer is - Don't do it. the Android OS will automatically free up memory when it needs memory. By not freeing up memory, your app will start up faster if the user gets back to it.
Please see here for a great write-up on the topic.
It's not in standard C, so the behavior is undefined.
Some implementation uses it to clear stdin
buffer.
From C11 7.21.5.2 The fflush function, fflush
works only with output/update stream, not input stream.
If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
Here is a good example in Python3.
>>> a = input("What is your name?")
What is your name?Peter
>>> b = input("Where are you from?")
Where are you from?DE
>>> print("So you are %s of %s" % (a, b))
So you are Peter of DE
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
I just had the same issue and this helped me:
html {
height: auto;
min-height: 100%;
background-size:cover;
}
You can do it with only one call to sed
:
$ echo "\"html\\test\\\"" | sed 's/^"\(.*\)"$/\1/'
html\test\
Use This..... You will love it
<TextView
android:layout_width="fill_parent"
android:layout_height="1px"
android:text=" "
android:background="#anycolor"
android:id="@+id/textView"/>
NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];
Use break
.
Unrelated to your question, I see in your code the line:
Violated = !(name.firstname == null) ? false : true;
In this line, you take a boolean value (name.firstname == null)
. Then, you apply the !
operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null)
. Why not use that, as in:
Violated = (name.firstname == null);
EDIT: I noticed a few downvotes and took another look at this Q&A. Most people seem to miss that the OP asked for fields to be dynamically selected based on the caller-provided list of fields. You can't do this with the statically-defined json struct tag.
If what you want is to always skip a field to json-encode, then of course use json:"-"
to ignore the field (also note that this is not required if your field is unexported - those fields are always ignored by the json encoder). But that is not the OP's question.
To quote the comment on the json:"-"
answer:
This [the
json:"-"
answer] is the answer most people ending up here from searching would want, but it's not the answer to the question.
I'd use a map[string]interface{} instead of a struct in this case. You can easily remove fields by calling the delete
built-in on the map for the fields to remove.
That is, if you can't query only for the requested fields in the first place.
You could simply replace the separator characters by NULL characters, and store the address after the newly created NULL character in a new char* pointer:
char* input = "asdf|qwer"
char* parts[10];
int partcount = 0;
parts[partcount++] = input;
char* ptr = input;
while(*ptr) { //check if the string is over
if(*ptr == '|') {
*ptr = 0;
parts[partcount++] = ptr + 1;
}
ptr++;
}
Note that this code will of course not work if the input string contains more than 9 separator characters.
For me the accepted answer for adding export PATH=/usr/local/share/npm/bin:$PATH
to .zshrc
didn't work. I tried adding the NVM_DIR
as well which solved my issue.
vi .bashrc
You will find a line like the following. Copy it.
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
Paste the copied content to .zshrc
file
I hope this solves your issue.
ALTER TABLE [TableName] ADD CONSTRAINT [constraintName] UNIQUE ([columns])
The Mach-O object file format used by Mac OS X for executables and libraries distinguishes between shared libraries and dynamically loaded modules. Use otool -hv some_file
to see the filetype of some_file
.
Mach-O shared libraries have the file type MH_DYLIB
and carry the extension .dylib. They can be linked against with the usual static linker flags, e.g. -lfoo
for libfoo.dylib. They can be created by passing the -dynamiclib
flag to the compiler. (-fPIC
is the default and needn't be specified.)
Loadable modules are called "bundles" in Mach-O speak. They have the file type MH_BUNDLE
. They can carry any extension; the extension .bundle
is recommended by Apple, but most ported software uses .so
for the sake of compatibility. Typically, you'll use bundles for plug-ins that extend an application; in such situations, the bundle will link against the application binary to gain access to the application’s exported API. They can be created by passing the -bundle
flag to the compiler.
Both dylibs and bundles can be dynamically loaded using the dl
APIs (e.g. dlopen
, dlclose
). It is not possible to link against bundles as if they were shared libraries. However, it is possible that a bundle is linked against real shared libraries; those will be loaded automatically when the bundle is loaded.
Historically, the differences were more significant. In Mac OS X 10.0, there was no way to dynamically load libraries. A set of dyld APIs (e.g. NSCreateObjectFileImageFromFile
, NSLinkModule
) were introduced with 10.1 to load and unload bundles, but they didn't work for dylibs. A dlopen
compatibility library that worked with bundles was added in 10.3; in 10.4, dlopen
was rewritten to be a native part of dyld and added support for loading (but not unloading) dylibs. Finally, 10.5 added support for using dlclose
with dylibs and deprecated the dyld APIs.
On ELF systems like Linux, both use the same file format; any piece of shared code can be used as a library and for dynamic loading.
Finally, be aware that in Mac OS X, "bundle" can also refer to directories with a standardized structure that holds executable code and the resources used by that code. There is some conceptual overlap (particularly with "loadable bundles" like plugins, which generally contain executable code in the form of a Mach-O bundle), but they shouldn't be confused with Mach-O bundles discussed above.
Additional references:
Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.
You seem to be emphasizing the need for a positional association with your data, so wouldn't an associative array be more fitting?
Dictionary<int, string> foo = new Dictionary<int, string>();
foo[2] = "string";
The Java EE version of Eclipse is not installed, insted a standard SDK version is installed.
You can go to Help > Install New Software then select the Eclipse site from the dropdown (Helios, Kepler depending upon your revision). Then select the option that shows Java EE. Restart Eclipse and you should see the Server list, such as Apache, Oracle, IBM etc.
Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
});
The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.
Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/
Kudos to this answer for showing me the way.
Content types are included in HTTP responses because the same, byte for byte sequence of values in the content could be interpreted in more than one way.(*)
Remember that http can transport more than just HTML (js, css and images are obvious examples), and in some cases, the receiver will not know what type of object it's going to receive.
(*) the obvious one here is XHTML - which is XML. If it's served with a content type of application/xml
, the receiver ought to just treat it as XML. If it's served up as application/xhtml+xml
, then it ought to be treated as XHTML.
Yes its possible! and you can use as many colors and images as you desire, here is the right way:
body{_x000D_
/* Its, very important to set the background repeat to: no-repeat */_x000D_
background-repeat:no-repeat; _x000D_
_x000D_
background-image: _x000D_
/* 1) An image */ url(http://lorempixel.com/640/100/nature/John3-16/), _x000D_
/* 2) Gradient */ linear-gradient(to right, RGB(0, 0, 0), RGB(255, 255, 255)), _x000D_
/* 3) Color(using gradient) */ linear-gradient(to right, RGB(110, 175, 233), RGB(110, 175, 233));_x000D_
_x000D_
background-position:_x000D_
/* 1) Image position */ 0 0, _x000D_
/* 2) Gradient position */ 0 100px,_x000D_
/* 3) Color position */ 0 130px;_x000D_
_x000D_
background-size: _x000D_
/* 1) Image size */ 640px 100px,_x000D_
/* 2) Gradient size */ 100% 30px, _x000D_
/* 3) Color size */ 100% 30px;_x000D_
}
_x000D_
You can try this way also,
Html:
<form action="javascript:next()" method="post">
<input type="submit" value=Submit /></form>
Javascript:
function next(){
//Location where you want to forward your values
window.location.href = "http://localhost:8563/And/try1.jsp?dymanicValue=" + values;
}
In LinearLayout
, use: android:layout_gravity="center"
.
In RelativeLayout
, use: android:layout_centerInParent="true"
.
New CSS Specs contain an experimental :has
pseudo selector that might be able to do this thing.
li:has(a:active) {
/* ... */
}
The browser support on this is basically non-existent at this time, but it is in consideration on the official specs.
While it is true that CSS cannot ASCEND, it is incorrect that you cannot grab the parent element of another element. Let me reiterate:
Using your HTML example code, you are able to grab the li without specifying li
ul * a {
property:value;
}
In this example, the ul is the parent of some element and that element is the parent of anchor. The downside of using this method is that if there is a ul with any child element that contains an anchor, it inherits the styles specified.
You may also use the child selector as well since you'll have to specify the parent element anyway.
ul>li a {
property:value;
}
In this example, the anchor must be a descendant of an li that MUST be a child of ul, meaning it must be within the tree following the ul declaration. This is going to be a bit more specific and will only grab a list item that contains an anchor AND is a child of ul.
SO, to answer your question by code.
ul.menu > li a.active {
property:value;
}
This should grab the ul with the class of menu, and the child list item that contains only an anchor with the class of active.
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.
I find very useful to understand how to organize code in Golang this chapter http://www.golang-book.com/11 of the book written by Caleb Doxsey
Arrays in java are objects, and all objects are passed by reference. In order to really "copy" an array, instead of creating another name for an array, you have to go and create a new array and copy over all the values. Note that System.arrayCopy will copy 1-dimensional arrays fully, but NOT 2-dimensional arrays. The reason is that a 2D array is in fact a 1D array of 1D arrays, and arrayCopy copies over pointers to the same internal 1D arrays.
A note to this old question:
My reset.css had set border-spacing: 0
, causing the corners to get cut off. I had to set it to 3px
for my radius to work properly (value will depend on the radius in question).
A portable way of doing this is using a custom function (to handle browser differences) like this one.
Then setup a handler for the onload
at the end of your <body>
tag, as jessegavin wrote:
window.onload = function() {
document.getElementById("myinputbox").focus();
}
Attached is a Swift solution based in:
Define App registers for location updates
in the info.plist
Keep the locationManager running all the time
Switch kCLLocationAccuracy
between BestForNavigation
(for 5 secs to get the location) and ThreeKilometers
for the rest of the wait period to avoid battery drainage
This example updates location every 1 min in Foreground and every 15 mins in Background.
The example works fine with Xcode 6 Beta 6, running in a iOS 7 device.
In the App Delegate (mapView is an Optional pointing to the mapView Controller)
func applicationDidBecomeActive(application: UIApplication!) {
if appLaunched! == false { // Reference to mapView used to limit one location update per timer cycle
appLaunched = true
var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var window = appDelegate.window
var tabBar = window?.rootViewController as UITabBarController
var navCon = tabBar.viewControllers[0] as UINavigationController
mapView = navCon.topViewController as? MapViewController
}
self.startInitialPeriodWithTimeInterval(60.0)
}
func applicationDidEnterBackground(application: UIApplication!) {
self.startInitialPeriodWithTimeInterval(15 * 60.0)
}
func startInitialPeriodWithTimeInterval(timeInterval: NSTimeInterval) {
timer?.invalidate() // reset timer
locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation
timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("getFirstLocationUpdate:"), userInfo: timeInterval, repeats: false)
}
func getFirstLocationUpdate(sender: NSTimer) {
let timeInterval = sender.userInfo as Double
timer?.invalidate()
mapView?.canReportLocation = true
timer = NSTimer.scheduledTimerWithTimeInterval(timeInterval, target: self, selector: Selector("waitForTimer:"), userInfo: timeInterval, repeats: true)
}
func waitForTimer(sender: NSTimer) {
let time = sender.userInfo as Double
locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation
finalTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("getLocationUpdate"), userInfo: nil, repeats: false)
}
func getLocationUpdate() {
finalTimer?.invalidate()
mapView?.canReportLocation = true
}
In the mapView (locationManager points to the object in the AppDelegate)
override func viewDidLoad() {
super.viewDidLoad()
var appDelegate = UIApplication.sharedApplication().delegate! as AppDelegate
locationManager = appDelegate.locationManager!
locationManager.delegate = self
canReportLocation = true
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if canReportLocation! {
canReportLocation = false
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
} else {
//println("Ignore location update")
}
}
You can either use the readonly
or the disabled
attribute. Note that when disabled, the input's value will not be submitted when submitting the form.
<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">
Why not serialize the whole list at once?
FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList);
Assuming, of course, that MyClassList is an ArrayList
or LinkedList
, or another Serializable
collection.
In the case of reading it back, in your code you ready only one item, there is no loop to gather all the item written.
You could do something like this, a bit hacky though, forget position
if it's already absolute:
var previousCss = $("#myDiv").attr("style");
$("#myDiv").css({
position: 'absolute', // Optional if #myDiv is already absolute
visibility: 'hidden',
display: 'block'
});
optionHeight = $("#myDiv").height();
$("#myDiv").attr("style", previousCss ? previousCss : "");
Elasticsearch 1.1+ has the Cardinality Aggregation which will give you a unique count
Note that it is actually an approximation and accuracy may diminish with high-cardinality datasets, but it's generally pretty accurate in my testing.
You can also tune the accuracy with the precision_threshold
parameter. The trade-off, or course, is memory usage.
This graph from the docs shows how a higher precision_threshold
leads to much more accurate results.
Follow the steps that are described on this answer just instead of using the drop down, type the port (8787) in "port range" an then "Add rule".
Go to the "Network & Security" -> Security Group settings in the left hand navigation
Find the Security Group that your instance is apart of Click on Inbound Rules Use the drop down and add HTTP (port 80) Click Apply and enjoy
The filter
method should do the trick:
const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const toRemove = ['b', 'c', 'g'];
// ES5 syntax
const filteredArray = myArray.filter(function(x) {
return toRemove.indexOf(x) < 0;
});
If your toRemove
array is large, this sort of lookup pattern can be inefficient. It would be more performant to create a map so that lookups are O(1)
rather than O(n)
.
const toRemoveMap = toRemove.reduce(
function(memo, item) {
memo[item] = memo[item] || true;
return memo;
},
{} // initialize an empty object
);
const filteredArray = myArray.filter(function (x) {
return toRemoveMap[x];
});
// or, if you want to use ES6-style arrow syntax:
const toRemoveMap = toRemove.reduce((memo, item) => ({
...memo,
[item]: true
}), {});
const filteredArray = myArray.filter(x => toRemoveMap[x]);
for i in iterator:
try:
# Do something.
pass
except:
# Continue to next iteration.
continue
In addition to the accepted answer you can use this if you want to group by multiple columns:
<ul ng-repeat="(key, value) in players | groupBy: '[team,name]'">
Try jQuery.inArray()
Here is a jsfiddle link using the same code : http://jsfiddle.net/yrshaikh/SUKn2/
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0
Example Code :
<html>
<head>
<style>
div { color:blue; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div>"John" found at <span></span></div>
<div>4 found at <span></span></div>
<div>"Karl" not found, so <span></span></div>
<div>
"Pete" is in the array, but not at or after index 2, so <span></span>
</div>
<script>
var arr = [ 4, "Pete", 8, "John" ];
var $spans = $("span");
$spans.eq(0).text(jQuery.inArray("John", arr));
$spans.eq(1).text(jQuery.inArray(4, arr));
$spans.eq(2).text(jQuery.inArray("Karl", arr));
$spans.eq(3).text(jQuery.inArray("Pete", arr, 2));
</script>
</body>
</html>
Output:
"John" found at 3 4 found at 0 "Karl" not found, so -1 "Pete" is in the array, but not at or after index 2, so -1
You can bind the mouseenter
and mouseleave
events and jQuery will emulate those where they are not native.
$("div.system_box").on('mouseenter', function(){
//enter
})
.on('mouseleave', function(){
//leave
});
note: do not use hover as that is deprecated
The thread you linked to does answer the question for you. You need to target the a
elements themselves. E.g.
.nav.navbar-nav.navbar-right a {
color: blue;
}
If that doesn't work, it just needs to be more specific. E.g.
.nav.navbar-nav.navbar-right li a {
color: blue;
}
You can also connect via port 465, but due to some limitations of the System.Net.Mail namespace you may have to alter your code. This is because the namespace does not offer the ability to make implicit SSL connections. This is discussed at http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx.
It is possible to make implicit connections without having to use the now obsolete System.Web.Mail namespace, but you have to access the Microsoft CDO (Collaborative Data Object). I have supplied an example of how to use the CDO in another discussion (GMail SMTP via C# .Net errors on all ports).
Hope this helps!
easy with this
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:visibility="visible"
android:gravity="center"
android:orientation="vertical" >
<ProgressBar
android:id="@+id/pbEndTrip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Gettings" />
</LinearLayout>
The path to the nginx.conf
file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf
.
You may access and edit this file by typing this at the terminal
cd /etc/nginx
/etc/nginx$ sudo nano nginx.conf
Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.
I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf
file which is the primary Configuration file for Nginx.
Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d
. Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-
http{
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
Further to this you may comment out from the PRIMARY Config file , the line
http{
#include /etc/nginx/sites-available/some_file.conf; # Comment Out
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
and need not keep any Config Files in /etc/nginx/sites-available/
and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/
, kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .
EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/
, this was the older practice and is DEPRECIATED now .
Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf;
.
Quote from Nginx CookBook page - 5 .
"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."
Although I didn't use this exact function I got this same error.
In my case I just had to remove the protocol.
Instead of $uri = "http://api.hostip.info/?ip=$ip&position=true";
Use $uri = "api.hostip.info/?ip=$ip&position=true";
And it worked fine afterwards
The reason is that the compiler has to actually see the definition in order to be able to drop it in in place of the call.
Remember that C and C++ use a very simplistic compilation model, where the compiler always only sees one translation unit at a time. (This fails for export, which is the main reason only one vendor actually implemented it.)
You can select just the part of the string you want to check:
if [ "${HOST:0:4}" = user ]
For your follow-up question, you could use an OR:
if [[ "$HOST" == user1 || "$HOST" == node* ]]
i Did it, just follow this tutorial. helps a lot
Is a copy from javadb (because is down)
http://informatictips.blogspot.pt/2013/09/using-message-handler-to-alter-soap.html
or
http://www.javadb.com/using-a-message-handler-to-alter-the-soap-header-in-a-web-service-client
You cannot add AM / PM to a TimeSpan
. You'll anyway have to associate the TimaSpan
value with DateTime
if you want to display the time in 12-hour clock format.
TimeSpan
is not intended to use with a 12-hour clock format, because we are talking about a time interval here.
As it says in the documentation;
A
TimeSpan
object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. TheTimeSpan
structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, theDateTime
orDateTimeOffset
structure should be used instead.
Also Microsoft Docs describes as follows;
A
TimeSpan
value can be represented as[-]d.hh:mm:ss.ff
, where the optional minus sign indicates a negative time interval, thed
component is days,hh
is hours as measured on a 24-hour clock,mm
is minutes,ss
is seconds, andff
is fractions of a second.
So in this case, you can display using AM/PM as follows.
TimeSpan storedTime = new TimeSpan(03,00,00);
string displayValue = new DateTime().Add(storedTime).ToString("hh:mm tt");
Side note :
Also should note that the TimeOfDay property of DateTime
is a TimeSpan
, where it represents
a time interval that represents the fraction of the day that has elapsed since midnight.
Try
SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]')
FROM traptabclob;
Here is a sqlfiddle demo
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
You can use the below effect to animate, you can change the values as per your requirements
$("#myElem").fadeIn('slow').animate({opacity: 1.0}, 1500).effect("pulsate", { times: 2 }, 800).fadeOut('slow');
If the databases share server, have a login that has priveleges to both of the databases, and simply have a query run similiar to:
$query = $this->db->query("
SELECT t1.*, t2.id
FROM `database1`.`table1` AS t1, `database2`.`table2` AS t2
");
Otherwise I think you might have to run the 2 queries separately and fix the logic afterwards.
In Rails 5, the has_key? method checks if key exists in hash. The syntax to use it is:
YourHash.has_key? :yourkey
#include <iostream.h>
#include<typeinfo.h>
template<class T>
void fun(T a)
{
if(typeid(T) == typeid(int))
{
//Do something
cout<<"int";
}
else if(typeid(T) == typeid(float))
{
//Do Something else
cout<<"float";
}
}
void main()
{
fun(23);
fun(90.67f);
}
Just git commit
it.
Optionally git abort
it:
I ran into a merge conflict. How can I abort the merge?
To make life easier with on merges install kdiff3 and configure it as a mergetool. Instructions: http://doodkin.com/2016/05/29/git-merge-easy-github-this-branch-has-conflicts-that-must-be-resolved-use-the-command-line/
That page contains this video: https://www.youtube.com/watch?v=Cc4xPp7Iuzo
If you add the favicon into the root/images folder with the name favicon.ico browser will automatically understand and get it as favicon.I tested and worked. your link must be www.website.com/images/favicon.ico
For more information look this answer:
Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?
Without using a formula you can do this with 'Text to columns'.
The 'side-effect' is that Excel has removed all trailing spaces in the original column.
Unit test is usually done for a single functionality implemented in Software module. The scope of testing is entirely within this SW module. Unit test never fulfils the final functional requirements. It comes under whitebox testing methodology..
Whereas Integration test is done to ensure the different SW module implementations. Testing is usually carried out after module level integration is done in SW development.. This test will cover the functional requirements but not enough to ensure system validation.
A more subtle reason for this could be a Settings.xml file which has a space in the first line before the doctype
You can also set a Constraint on a Table with the KEY fields and set On Conflict "Ignore"
When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint violation and continues processing subsequent rows of the SQL statement as if nothing went wrong. Other rows before and after the row that contained the constraint violation are inserted or updated normally. No error is returned when the IGNORE conflict resolution algorithm is used.
...because the .NET environment is designed to support many languages.
System.Boolean (in mscorlib.dll) is designed to be used internally by languages to support a boolean datatype. C# uses all lowercase for its keywords, hence 'bool', 'true', and 'false'.
VB.NET however uses standard casing: hence 'Boolean', 'True', and 'False'.
Since the languages have to work together, you couldn't have true.ToString() (C#) giving a different result to True.ToString() (VB.NET). The CLR designers picked the standard CLR casing notation for the ToString() result.
The string representation of the boolean true is defined to be Boolean.TrueString.
(There's a similar case with System.String: C# presents it as the 'string' type).
Just because I was here looking for this solution but for updating from another identically-structured table (in my case website test DB to live DB):
INSERT live-db.table1
SELECT *
FROM test-db.table1 t
ON DUPLICATE KEY UPDATE
ColToUpdate1 = t.ColToUpdate1,
ColToUpdate2 = t.ColToUpdate2,
...
As mentioned elsewhere, only the columns you want to update need to be included after ON DUPLICATE KEY UPDATE
.
No need to list the columns in the INSERT
or SELECT
, though I agree it's probably better practice.
Also register your created service in the Manifest and uses-permission as
<application ...>
<service android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.MyBroadcastReciver"/>
</intent-filter>
</service>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
and then in braod cast Reciever call your service
public class MyBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Intent myIntent = new Intent(context, MyService.class);
context.startService(myIntent);
}
}
All the answers for the Run->Run menu option go with the "/K" switch of cmd, so the terminal stays open, or "-i" for python.exe so python forces interactive mode - both to preserve the output for you to observe.
Yet in cmd /k
you have to type exit
to close it, in the python -i
- quit()
. If that is too much typing for your liking (for me it sure is :), the Run command to use is
cmd /k C:\Python27\python.exe "$(FULL_CURRENT_PATH)" & pause & exit
C:\Python27\python.exe
- obviously the full path to your python install (or just python
if you want to go with the first executable in your user's path).
&
is unconditional execution of the next command in Windows - unconditional as it runs regardless of the RC of the previous command (&&
is "and" - run only if the previous completed successfully, ||
- is "or").
pause
- prints "Press any key to continue . . ." and waits for any key (that output can be suppressed if need).
exit
- well, types the exit for you :)
So at the end, cmd
runs python.exe
which executes the current file and keeps the window opened, pause
waits for you to press any key, and exit
finally close the window once you press that any key.
A possibility is to declare the variable at the index.html because it is really global. It can be done adding a javascript method to return the value of the variable, and it will be READ ONLY.
An example of this solution can be found at this answer: https://stackoverflow.com/a/62485644/1178478
In your app's theme/style, add the following lines:
<item name="android:buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
<item name="android:buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
<item name="android:buttonBarNeutralButtonStyle">@style/NeutralButtonStyle</item>
Then add the following styles:
<style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="android:textColor">@color/red</item>
</style>
<style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="android:textColor">@color/red</item>
</style>
<style name="NeutralButtonStyle"
parent="Widget.MaterialComponents.Button.TextButton.Dialog">
<item name="android:textColor">#00f</item>
</style>
Using this method makes it unneccessary to set the theme in the AlertDialog builder.
the bottom cell will grow as you enter more text ... setting the table width will help too
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>
An update if one is using Express 4.2 then the timeout middleware has been removed so need to manually add it with
npm install connect-timeout
and in the code it has to be (Edited as per comment, how to include it in the code)
var timeout = require('connect-timeout');
app.use(timeout('100s'));
Nothing. Just execute your query. If the connection has died, either your JDBC driver will reconnect (if it supports it, and you enabled it in your connection string--most don't support it) or else you'll get an exception.
If you check the connection is up, it might fall over before you actually execute your query, so you gain absolutely nothing by checking.
That said, a lot of connection pools validate a connection by doing something like SELECT 1
before handing connections out. But this is nothing more than just executing a query, so you might just as well execute your business query.
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
autoSize for column width set as bellow. It works for me.
$spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
Try with this:
SELECT to_char (2/3::float, 'FM999999990.00');
-- RESULT: 0.67
Or simply:
SELECT round (2/3::DECIMAL, 2)::TEXT
-- RESULT: 0.67
The real problem is that you are using dynamic return type in the FacebookClient Get method. And although you use a method for serializing, the JSON converter cannot deserialize this Object after that.
Use insted of:
dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
string jsonstring = JsonConvert.SerializeObject(result);
something like that:
string result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}).ToString();
Then you can use DeserializeObject method:
var datalist = JsonConvert.DeserializeObject<List<RootObject>>(result);
Hope this helps.
The official solution (and others) were incomplete when I first visited, so I came back, years later, to post this alternate approach in case any others wound up here intending to use a public/private key-pair:
Execute this from the target backup machine, which pulls from source to target backup
rsync -av --delete -e 'ssh -p 59333 -i /home/user/.ssh/id_rsa' [email protected]:/home/user/Server/ /home/keith/Server/
Execute this from the source machine, which sends from source to target backup
rsync -av --delete -e 'ssh -p 59333 -i /home/user/.ssh/id_rsa' /home/user/Server/ [email protected]:/home/user/Server/
And, if you are not using an alternate port for ssh, then consider the more elegant examples below:
Execute this from the target backup machine, which pulls from source to target backup:
sudo rsync -avi --delete [email protected]:/var/www/ /media/sdb1/backups/www/
Execute this from the source machine, which sends from source to target backup:
sudo rsync -avi --delete /media/sdb1/backups/www/ [email protected]:/var/www/
If you are still getting prompted for a password, then you need to check your ssh configuration in /etc/ssh/sshd_config
and verify that the users in source and target each have the others' respective public ssh key by sending each over with ssh-copy-id [email protected]
.
(Again, this is for using ssh key-pairs without a password, as an alternate approach, and not for passing the password over via a file.)
To change color of SVG element I have found out a way while inspecting Google search box search icon below:
.search_icon {
color: red;
fill: currentColor;
display: inline-block;
width: 100px;
height: 100px;
}
_x000D_
<span class="search_icon">
<svg focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path></svg>
</span>
_x000D_
I have used span element with "display:inline-block", height, width and setting a particular style "color: red; fill: currentColor;" to that span tag which is inherited by the child svg element.
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
Let's start with a simple example. Let's say you have an email list, that is going to send out the following RFC2822 content.
From: <[email protected]> To: <[email protected]> Subject: Super simple email Reply-To: <[email protected]> This is a very simple body.
Now, let's say you are going to send it from a mailing list, that implements VERP (or some other bounce tracking mechanism that uses a different return-path). Lets say it will have a return-path of [email protected]
. The SMTP session might look like:
{S}220 workstation1 Microsoft ESMTP MAIL Service {C}HELO workstation1 {S}250 workstation1 Hello [127.0.0.1] {C}MAIL FROM:<[email protected]> {S}250 2.1.0 [email protected] OK {C}RCPT TO:<[email protected]> {S}250 2.1.5 [email protected] {C}DATA {S}354 Start mail input; end with <CRLF>.<CRLF> {C}From: <[email protected]> To: <[email protected]> Subject: Super simple email Reply-To: <[email protected]> This is a very simple body. . {S}250 Queued mail for delivery {C}QUIT {S}221 Service closing transmission channel
Where {C} and {S} represent Client and Server commands, respectively.
The recipient's mail would look like:
Return-Path: [email protected] From: <[email protected]> To: <[email protected]> Subject: Super simple email Reply-To: <[email protected]> This is a very simple body.
Now, let's describe the different "FROM"s.
MAIL FROM
command. As you can see, this does not need to be the same value that is found in the message headers. Only the recipient's mail server is supposed to add a Return-Path header to the top of the email. This records the actual Return-Path sender during the SMTP session. If a Return-Path header already exists in the message, then that header is removed and replaced by the recipient's mail server.All bounces that occur during the SMTP session should go back to the Return-Path address. Some servers may accept all email, and then queue it locally, until it has a free thread to deliver it to the recipient's mailbox. If the recipient doesn't exist, it should bounce it back to the recorded Return-Path value.
Note, not all mail servers obey this rule; Some mail servers will bounce it back to the FROM address.
The FROM address is the value found in the FROM header. This is supposed to be who the message is FROM. This is what you see as the "FROM" in most mail clients. If an email does not have a Reply-To header, then all human (mail client) replies should go back to the FROM address.
The Reply-To header is added by the sender (or the sender's software). It is where all human replies should be addressed too. Basically, when the user clicks "reply", the Reply-To value should be the value used as the recipient of the newly composed email. The Reply-To value should not be used by any server. It is meant for client-side (MUA) use only.
However, as you can tell, not all mail servers obey the RFC standards or recommendations.
Hopefully this should help clear things up. However, if I missed anything, let me know, and I'll try to answer.