Truncate can also be Rollbacked here the exapmle
begin Tran
delete from Employee
select * from Employee
Rollback
select * from Employee
my suggestion: Choose a different version. I had the same problem you have deinstalled v5.6.11, downloaded and installed v5.6.3, works fine for me.
cheers!
g++ hw.cpp -o hw
./hw
Add this for pages not currently on your site...
ErrorDocument 404 http://example.com/
Along with your Redirect 301 / http://www.thenewdomain.com/ that should cover all the bases...
Good luck!
You should set layout first by syntax pnlButton.setLayout()
, and then choose the most suitable layout which u want. Ex: pnlButton.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
. And then, take that JButton into JPanel.
If you want to "encode" a full URL without having to think about manually splitting it into its different parts, I found the following worked in the same way that I used to use URI.encode
:
URI.parse(my_url).to_s
The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature
Use this:
SELECT
Pieces, Price,
Pieces * Price as 'Total'
FROM myTable
value = value.setScale(2, RoundingMode.CEILING)
I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT
function on the nvarchar field.
Example: Left(Field,4)
Basically, the query will look like:
Select convert(float,left(Field,4)) from TABLE
Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.
One liner here
document.querySelector("meta[property='og:image']").getAttribute("content");
<?php
header("Content-Type: $type");
readfile($file);
That's the short version. There's a few extra little things you can do to make things nicer, but that'll work for you.
for switch to another page, try with this code:
viewPager.postDelayed(new Runnable()
{
@Override
public void run()
{
viewPager.setCurrentItem(num, true);
}
}, 100);
For Redmi users,
Settings -> Password & security -> Privacy -> Special app access -> Device admin apps
Click the deactivate the apps
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
You can use deparse
and substitute
to get the name of a function argument:
myfunc <- function(v1) {
deparse(substitute(v1))
}
myfunc(foo)
[1] "foo"
Simply remove the .value
from your code.
Set envFrmwrkPath = ActiveSheet.Range("D6").Value
instead of this, use:
Set envFrmwrkPath = ActiveSheet.Range("D6")
If you google for sort order windows explorer you will find out that Windows Explorer (since Windows XP) obviously uses the function StrCmpLogicalW in the sort order "by name". I did not find information about the treatment of the underscore character. I was amused by the following note in the documentation:
Behavior of this function, and therefore the results it returns, can change from release to release. ...
select Id, Count, @total := @total + Count as cumulative_sum
from YourTable, (Select @total := 0) as total ;
Try this code
<input type="TextBox" ID="yearBox" border="0" disabled>
$('#yearSelected li').on('click', function(){
$('#yearBox').val($(this).text());
});
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fas fa-calendar-alt"></i> <span>Academic Years</span> <i class="fas fa-chevron-down"></i> </a>
<ul class="dropdown-menu">
<li>
<ul class="menu" id="yearSelected">
<li><a href="#">2014-2015</a></li>
<li><a href="#">2015-2016</a></li>
<li><a href="#">2016-2017</a></li>
<li><a href="#">2017-2018</a></li>
</ul>
</li>
</ul>
its work for me
IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:
the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])
Edit: Note that join wants an iterable (e.g. a list) as its single argument.
I had the same problem due to ghost processes that didn't show up when using top in bash. This prevented the JVM to spawn more threads.
For me, it resolved when listing all java processes with jps (just execute jps
in your shell) and killed them separately using the kill -9 pid
bash command for each ghost process.
This might help in some scenarios.
You can also get the path on GNU/Linux with (not thoroughly tested):
char file[32];
char buf[64];
pid_t pid = getpid();
sprintf(file, "/proc/%i/cmdline", pid);
FILE *f = fopen(file, "r");
fgets(buf, 64, f);
fclose(f);
If you want the directory of the executable for perhaps changing the working directory to the process's directory (for media/data/etc), you need to drop everything after the last /:
*strrchr(buf, '/') = '\0';
/*chdir(buf);*/
Is there a way to unmarshal the nested bar property and assign it directly to a struct property without creating a nested struct?
No, encoding/json cannot do the trick with ">some>deep>childnode" like encoding/xml can do. Nested structs is the way to go.
Try this:
yAxis: {min: 0, max: 100}
See this jsfiddle example
You need to be using AJAX. Submitting the form usually results in the browser loading a new page.
// works also after bind operation for WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);
As per Oracle Glossary :
SID is a unique name for an Oracle database instance. ---> To switch between Oracle databases, users must specify the desired SID <---. The SID is included in the CONNECT DATA parts of the connect descriptors in a TNSNAMES.ORA file, and in the definition of the network listener in the LISTENER.ORA file. Also known as System ID. Oracle Service Name may be anything descriptive like "MyOracleServiceORCL". In Windows, You can your Service Name running as a service under Windows Services.
You should use SID in TNSNAMES.ORA as a better approach.
I prefer this way so I don't need to remember any rare parameters.
git merge branch_name
It will then say your branch is ahead by "#
" commits, you can now pop these commits off and put them into the working changes with the following:
git reset @~#
For example if after the merge it is 1 commit ahead, use:
git reset @~1
Note: On Windows, quotes are needed. (As Josh noted in comments) eg:
git reset "@~1"
I believe that this question deserves an updated. Just compare with other approaches.
Here's how you do redirection (3xx) from one url to another in Flask (0.12.2):
#!/usr/bin/env python
from flask import Flask, redirect
app = Flask(__name__)
@app.route("/")
def index():
return redirect('/you_were_redirected')
@app.route("/you_were_redirected")
def redirected():
return "You were redirected. Congrats :)!"
if __name__ == "__main__":
app.run(host="0.0.0.0",port=8000,debug=True)
For other official references, here.
/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);
private void SumOFEPFWages(GridView grd)
{
Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
/*Sum of the total Amount of the day*/
foreach (GridViewRow gvr in grd.Rows)
{
Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
}
}
You can use Jackson API as well for this :
final String json = "....your json...";
final ObjectMapper mapper = new ObjectMapper();
final MapType type = mapper.getTypeFactory().constructMapType(
Map.class, String.class, Object.class);
final Map<String, Object> data = mapper.readValue(json, type);
Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.
You can download from (https://npmjs.org/package/underscore)
$ npm install underscore
Here is small snippet to demonstrate how you can do it.
var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
newArray = [];
_.each(calendars, function (item, index) {
newArray.push(item);
});
console.log(newArray);
Just two more things I found helpful to know, even if they are not part of the question, really.
You can use the relayEvents
method to tell a component to listen for certain events of another component and then fire them again as if they originate from the first component. The API docs give the example of a grid relaying the store load
event. It is quite handy when writing custom components that encapsulate several sub-components.
The other way around, i.e. passing on events received by an encapsulating component mycmp
to one of its sub-components subcmp
, can be done like this
mycmp.on('show' function (mycmp, eOpts)
{
mycmp.subcmp.fireEvent('show', mycmp.subcmp, eOpts);
});
Other bash alternatives that do not involve a subshell:
read str <<END # here-doc
hello
END
read str <<< "hello" # here-string
read str < <(echo hello) # process substitution
Maybe something like this:
import matplotlib.pyplot
import pylab
x = [1,2,3,4]
y = [3,4,8,6]
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
EDIT:
Let me see if I understand you correctly now:
You have:
test1 | test2 | test3
test3 | 1 | 0 | 1
test4 | 0 | 1 | 0
test5 | 1 | 1 | 0
Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.
Let's say you results are stored in a 2-D list:
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
We want to transform them into two variables so we are able to plot them.
And I believe this code will give you what you are looking for:
import matplotlib
import pylab
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
x = []
y = []
for ind_1, sublist in enumerate(results):
for ind_2, ele in enumerate(sublist):
if ele == 1:
x.append(ind_1)
y.append(ind_2)
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
Notice that I do need to import pylab
, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.
Swift 3
let vc0 : ViewController1 = ViewController1()
let vc2: NavigationController1 = NavigationController1(rootViewController: vc0)
self.present(vc2, animated: true, completion: nil)
Expanding on cd1's answer: You might use append() instead of copy(). append() makes ever bigger advance provisions, costing a little more memory, but saving time. I added two more benchmarks at the top of yours. Run locally with
go test -bench=. -benchtime=100ms
On my thinkpad T400s it yields:
BenchmarkAppendEmpty 50000000 5.0 ns/op
BenchmarkAppendPrealloc 50000000 3.5 ns/op
BenchmarkCopy 20000000 10.2 ns/op
select true from tablename where condition limit 1;
I believe that this is the query that postgres uses for checking foreign keys.
In your case, you could do this in one go too:
insert into yourtable select $userid, $rightid, $count where not (select true from yourtable where userid = $userid limit 1);
Try this:
DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
.AddSeconds(-DateTime.Now.Second);
Output will be like:
07/29/2015 00:00:00
Here is how to do dump the database (with just the schema):
mysqldump -u root -p"passwd" --no-data --add-drop-database --databases my_db_name | sed 's#/[*]!40000 DROP DATABASE IF EXISTS my_db_name;#' >my_db_name.sql
If you also want the data, remove the --no-data
option.
You only have to add group = 1
into the ggplot or geom_line aes().
For line graphs, the data points must be grouped so that it knows which points to connect. In this case, it is simple -- all points should be connected, so group=1. When more variables are used and multiple lines are drawn, the grouping for lines is usually done by variable.
Reference: Cookbook for R, Chapter: Graphs Bar_and_line_graphs_(ggplot2), Line graphs.
Try this:
plot5 <- ggplot(df, aes(year, pollution, group = 1)) +
geom_point() +
geom_line() +
labs(x = "Year", y = "Particulate matter emissions (tons)",
title = "Motor vehicle emissions in Baltimore")
For Apache HttpClient 4.5 or newer version:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://targethost/login");
String JSON_STRING="";
HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
CloseableHttpResponse response2 = httpclient.execute(httpPost);
Note:
1 in order to make the code compile, both httpclient
package and httpcore
package should be imported.
2 try-catch block has been ommitted.
Reference: appache official guide
the Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules
For Bootstrap 3
The workflow I had to deal with was loading content with a url context that could change. So by default setup your modal with javascript or the href for the default context you want to show :
$('#myModal').modal({
show: false,
remote: 'some/context'
});
Destroying the modal wouldn't work for me because I wasn't loading from the same remote, thus I had to :
$(".some-action-class").on('click', function () {
$('#myModal').removeData('bs.modal');
$('#myModal').modal({remote: 'some/new/context?p=' + $(this).attr('buttonAttr') });
$('#myModal').modal('show');
});
This of course was easily refactored into a js library and gives you a lot of flexibility with loading modals
I hope this saves someone 15 minutes of tinkering.
Do not send email to 5,000 people using standard PHP tools. You'll get banned by most ISPs in seconds and never even know it. You should either use some mailing lists software or an Email Service Provider do to this.
Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:
var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
assert = require('assert');
var user = 'user';
var password = 'password';
MongoClient.connect('mongodb://'+user+':'+password+'@localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
if(err){
console.log("Auth Failed");
return;
}
console.log("Connected");
db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc['_id']);
}
});
});
db.close();
});
If the value is a file url like file://C:/whatever, use the Uri class to translate to a regular filename:
var localPath = (new Uri(urlStylePath)).AbsolutePath
In general, using the provided API is best practice.
Read up some on css, it's fun: http://www.w3.org/Style/Examples/007/units.en.html
<style>
.bottom-three {
margin-bottom: 3cm;
}
</style>
<p class="bottom-three">
This is the first question?
</p>
<p class="bottom-three">
This is the second question?
</p>
When a type is used in a file (i.e. func.c file), it must be visible. The very worst way to do it is copy paste it in each source file needed it.
The right way is putting it in an header file, and include this header file whenever needed.
This is the solution I like more, because it makes the code highly modular. I would code your struct as:
#ifndef SOME_HEADER_GUARD_WITH_UNIQUE_NAME
#define SOME_HEADER_GUARD_WITH_UNIQUE_NAME
struct a
{
int i;
struct b
{
int j;
}
};
#endif
I would put functions using this structure in the same header (the function that are "semantically" part of its "interface").
And usually, I could name the file after the structure name, and use that name again to choose the header guards defines.
If you need to declare a function using a pointer to the struct, you won't need the full struct definition. A simple forward declaration like:
struct a ;
Will be enough, and it decreases coupling.
This is another way, easier somewhat, but less modular: Some code needing only your structure to work would still have to include all types.
In C++, this could lead to interesting complication, but this is out of topic (no C++ tag), so I won't elaborate.
I fail to see the point, perhaps, but Greg Hewgill has a very good answer in his post How to declare a structure in a header that is to be used by multiple files in c?.
The reason being that C struct managing can be a pain: You have to declare the struct keyword everywhere it is used:
struct MyStruct ; /* Forward declaration */
struct MyStruct
{
/* etc. */
} ;
void doSomething(struct MyStruct * p) /* parameter */
{
struct MyStruct a ; /* variable */
/* etc */
}
While a typedef will enable you to write it without the struct keyword.
struct MyStructTag ; /* Forward declaration */
typedef struct MyStructTag
{
/* etc. */
} MyStruct ;
void doSomething(MyStruct * p) /* parameter */
{
MyStruct a ; /* variable */
/* etc */
}
It is important you still keep a name for the struct. Writing:
typedef struct
{
/* etc. */
} MyStruct ;
will just create an anonymous struct with a typedef-ed name, and you won't be able to forward-declare it. So keep to the following format:
typedef struct MyStructTag
{
/* etc. */
} MyStruct ;
Thus, you'll be able to use MyStruct everywhere you want to avoid adding the struct keyword, and still use MyStructTag when a typedef won't work (i.e. forward declaration)
Corrected wrong assumption about C99 struct declaration, as rightfully remarked by Jonathan Leffler.
Craig Barnes reminds us in his comment that you don't need to keep separate names for the struct "tag" name and its "typedef" name, like I did above for the sake of clarity.
Indeed, the code above could well be written as:
typedef struct MyStruct
{
/* etc. */
} MyStruct ;
IIRC, this is actually what C++ does with its simpler struct declaration, behind the scenes, to keep it compatible with C:
// C++ explicit declaration by the user
struct MyStruct
{
/* etc. */
} ;
// C++ standard then implicitly adds the following line
typedef MyStruct MyStruct;
Back to C, I've seen both usages (separate names and same names), and none has drawbacks I know of, so using the same name makes reading simpler if you don't use C separate "namespaces" for structs and other symbols.
I had a similar problem - authenticate device and user at device. I used a Cookie
header alongside an Authorization: Bearer...
header. One header authenticated the device, the other authenticated the user. I used a Cookie
header because these are commonly used for authentication.
There is a page documenting Advanced User Interactions; which has a lot of great examples on how to generate a sequence of actions, you can find it here
// Configure the action
Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL)
.click(someElement)
.click(someOtherElement)
.keyUp(Keys.CONTROL);
// Then get the action:
Action selectMultiple = builder.build();
// And execute it:
selectMultiple.perform();
or
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement)
.moveToElement(otherElement)
.release(otherElement)
.build();
dragAndDrop.perform();
I rely heavily on commands like this.
python -c 'import sys; print(sys.maxsize)'
Max int returned: 9223372036854775807
For more references for 'sys' you should access
Using Windows Authentication
To connect to the database server is recommended to use Windows Authentication, commonly known as integrated security. To specify the Windows authentication, you can use any of the following two key-value pairs with the data provider. NET Framework for SQL Server:
Integrated Security = true;
Integrated Security = SSPI;
However, only the second works with the data provider .NET Framework OleDb. If you set Integrated Security = true
for ConnectionString an exception is thrown.
To specify the Windows authentication in the data provider. NET Framework for ODBC, you should use the following key-value pair.
Trusted_Connection = yes;
Use logging module to debug and follow your app
Here is how I managed to log to file and to console / stdout
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
filename='logs_file',
filemode='w')
# Until here logs only to file: 'logs_file'
# define a new Handler to log to console as well
console = logging.StreamHandler()
# optional, set the logging level
console.setLevel(logging.INFO)
# set a format which is the same for console use
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
# Now, we can log to both ti file and console
logging.info('Jackdaws love my big sphinx of quartz.')
logging.info('Hello world')
read it from source: https://docs.python.org/2/howto/logging-cookbook.html
Please follow the way like below:
.selectParent {_x000D_
width:120px;_x000D_
overflow:hidden; _x000D_
}_x000D_
.selectParent select { _x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 2px 25px 2px 2px; _x000D_
border: none; _x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
appearance: none; _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
direction: rtl;_x000D_
padding: 2px 2px 2px 25px;_x000D_
background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>
_x000D_
Error is straight forward and its because of wrong placeholders you have used in function call. Inside init
you are not passing any parameters to your function. It should be this way
destination = Node("some key", neighbors: [edge1 , edge2], visited: true, lat: 23.45, long: 45.67) // fill up with your dummy values
Or you can just initialise with default method
destination = Node()
UPDATE
Add empty initialiser in your Node class
init() {
}
In case you have smaller data set, a way to achieve it by GUI is:
Reference: http://www.youtube.com/watch?v=tnhJa_zYNVY
Edit: I had first said:
What's inelegant about the dictionary solution. It seems perfectly elegant to me, esp since you only need to set the comparator in creation of the dictionary.
Of course though, it is inelegant to use something as a key when it's also the value.
Therefore I would use a HashSet. If later operations required indexing, I'd create a list from it when the Adding was done, otherwise, just use the hashset.
Use below command to change computer hostname remotely , Require system reboot after change..
psexec.exe -h -e \\\IPADDRESS -u USERNAME -p PASSWORD netdom renamecomputer CurrentComputerName /newname:NewComputerName /force
I think that the usage of @Html.LabelForModel()
should be explained in more detail.
The LabelForModel Method returns an HTML label element and the property name of the property that is represented by the model.
You could refer to the following code:
Code in model:
using System.ComponentModel;
[DisplayName("MyModel")]
public class MyModel
{
[DisplayName("A property")]
public string Test { get; set; }
}
Code in view:
@Html.LabelForModel()
<div class="form-group">
@Html.LabelFor(model => model.Test, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Test)
@Html.ValidationMessageFor(model => model.Test)
</div>
</div>
The output screenshot:
Chrome will never implement support RTSP streaming.
At least, in the words of a Chromium developer here:
we're never going to add support for this
I've got another idea. What if you create this table-based function:
CREATE FUNCTION tbfSelectFromView
(
-- Add the parameters for the function here
@SessionGUID UNIQUEIDENTIFIER
)
RETURNS TABLE
AS
RETURN
(
SELECT *
FROM Report_Opener
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
)
GO
And then selected from it using the following statement (even putting this in your SP):
SELECT *
FROM tbfSelectFromView(@SessionGUID)
It looks like what's happening (which everybody has already commented on) is that SQL Server just makes an assumption somewhere that's wrong, and maybe this will force it to correct the assumption. I hate to add the extra step, but I'm not sure what else might be causing it.
You should create a ModelForm
(docs), which has a field that uses the PasswordInput
widget from the forms library.
It would look like this:
from django import models
class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=50)
from django import forms
class UserForm(forms.ModelForm):
class Meta:
model = User
widgets = {
'password': forms.PasswordInput(),
}
For more about using forms in a view, see this section of the docs.
This should work:
// Gets linearlayout
LinearLayout layout = findViewById(R.id.numberPadLayout);
// Gets the layout params that will allow you to resize the layout
LayoutParams params = layout.getLayoutParams();
// Changes the height and width to the specified *pixels*
params.height = 100;
params.width = 100;
layout.setLayoutParams(params);
If you want to convert dip to pixels, use this:
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, <HEIGHT>, getResources().getDisplayMetrics());
Like Davide Lorigliola, I fixed it by cranking up the z-index:
.modal-backdrop { z-index: -999999; }
Doh.. If I get you right, it should be as simple as:
$('.test').click(function() {_x000D_
console.log(this.id);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<a href="#" class="test" id="test_1">Some text</a>_x000D_
<a href="#" class="test" id="test_2">Some text</a>_x000D_
<a href="#" class="test" id="test_3">Some text</a>
_x000D_
You can just access the id property over the underlaying dom node, within the event handler.
You could use a Filter and do the following test:
HttpSession session = request.getSession(false);// don't create if it doesn't exist
if(session != null && !session.isNew()) {
chain.doFilter(request, response);
} else {
response.sendRedirect("/login.jsp");
}
The above code is untested.
This isn't the most extensive solution however. You should also test that some domain-specific object or flag is available in the session before assuming that because a session isn't new the user must've logged in. Be paranoid!
Put your code in a method.
Try this:
public class MyClass {
public static void main(String[] args) {
UserInput input = new UserInput();
input.name();
}
}
Then "run" the class from your IDE
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Where str
is your XML string. See the MSDN article for more info.
You must use $rootScope to send and capture events between controllers in same app. Inject $rootScope dependency to your controllers. Here is a working example.
app.controller('firstCtrl', function($scope, $rootScope) {
function firstCtrl($scope) {
{
$rootScope.$emit('someEvent', [1,2,3]);
}
}
app.controller('secondCtrl', function($scope, $rootScope) {
function secondCtrl($scope)
{
$rootScope.$on('someEvent', function(event, data) { console.log(data); });
}
}
Events linked into $scope object just work in the owner controller. Communication between controllers is done via $rootScope or Services.
I think your question boils down to what proper selector to use when setting up your tooltips, and the answer to that is almost whatever you want. If you want to use a class to trigger your tooltips you can do that, take the following for example:
<a href="#" class="link" data-original-title="first tooltip">Hover me for a tooltip</a>
Then you can trigger all links with the .link
class attached as tooltips like so:
$('.link').tooltip()
Now, to answer your question as to why the bootstrap developers did not use a class to trigger tooltips that is because it is not needed exactly, you can pretty much use any selectors you want to target your tooltips, such as (my personal favorite) the rel
attribute. With this attribute you can target all links or elements with the rel
property set to tooltip
, like so:
$('[rel=tooltip]').tooltip()
And your links would look like something like this:
<a href="#" rel="tooltip" data-original-title="first tooltip">Hover me for a tooltip</a>
Of course, you can also use a container class or id to target your tooltips inside an specific container that you want to single out with an specific option or to separate from the rest of your content and you can use it like so:
$('#example').tooltip({
selector: "a[rel=tooltip]"
})
This selector will target all of your tooltips with the rel
attribute "within" your #example
div, this way you can add special styles or options to that section alone. In short, you can pretty much use any valid selector to target your tooltips and there is no need to dirty your markup with an extra class to target them.
try this in your command prompt: python -m pip intsall pygame
Take a Look at this Plugin
Makes your code as easy as -> $('SelectorToPrint').printElement();
The SELECT ... INTO
needs to be in the select from the CTE.
;WITH Calendar
AS (SELECT /*... Rest of CTE definition removed for clarity*/)
SELECT EventID,
EventStartDate,
EventEndDate,
PlannedDate AS [EventDates],
Cast(PlannedDate AS DATETIME) AS DT,
Cast(EventStartTime AS TIME) AS ST,
Cast(EventEndTime AS TIME) AS ET,
EventTitle,
EventType
INTO TEMPBLOCKEDDATES /* <---- INTO goes here*/
FROM Calendar
WHERE ( PlannedDate >= Getdate() )
AND ',' + EventEnumDays + ',' LIKE '%,' + Cast(Datepart(dw, PlannedDate) AS CHAR(1)) + ',%'
OR EventEnumDays IS NULL
ORDER BY EventID,
PlannedDate
OPTION (maxrecursion 0)
I just wanted to bring a small contribution, because I have been able to debug on my Nexus 5 device on Windows 8, without doing all of this.
When I plugged it, there wasn't any yellow exclamation mark within Device Manager. So for me, the drivers were OK. But the device was not listed within my Eclipse DDMS. After a little bit of searching, it was just an option to change in the device settings. By default, the Nexus 5 USB computer connection is in MTP mode (Media Device).
What you have to do is:
I hope this will help!
Yes, the syntax is accurate and it should be fine.
Here is the SQL Fiddle Demo I created for your particular case
create table sample2
(
id int primary key,
created_date date,
data varchar(10)
)
insert into sample2 values (1,'2012-01-01','testing');
And here is how to select the data
SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())
Given the huge amount of replies I was not gonna post. However, this method may help someone, as it did help me.
It's worth to mention, I avoid floats like Ebola. There are many reasons and I am not alone; Read Rikudo answer about what is a clearfix and you'll see what I mean. In his own words: ...the use of floated elements for layout is getting more and more discouraged with the use of better alternatives...
There are other good (and sometimes better) options out there other than floats. As technology advances and improves, flexbox (and other methods) are going to be widely adopted and floats will become just a bad memory. Maybe a CSS4?
First off, sometimes, you may think that you are safe from floats until your lifesaver is punctured and your html flow starts to sink:
In the codepen http://codepen.io/omarjuvera/pen/jEXBya below, the practice of clearing a float with <div classs="clear"></div>
(or other element) is common but frown upon and anti-semantic.
<div class="floated">1st</div>
<div class="floated">2nd</div>
<div class="floated">3nd</div>
<div classs="clear"></div> <!-- Acts as a wall -->
<section>Below</section>
CSS
div {
border: 1px solid #f00;
width: 200px;
height: 100px;
}
div.floated {
float: left;
}
.clear {
clear: both;
}
section {
border: 1px solid #f0f;
}
However, just when you thought your float is sail worthy...boom! As the screen size becomes smaller and smaller you see weird behaviors in like the graphic below (Same http://codepen.io/omarjuvera/pen/jEXBya):
Why should you care? Roughly, about 80% (or more) of the devices used are mobile devices with small screens. Desktop computers/laptops are no longer king.
This is not the only problem with floats. There are many, but in this example, some may say all you have to do is to place your floats in a container
. But as you can see in the codepen and graphic, that is not the case. It apparently made things worst:
HTML
<div id="container" class="">
<div class="floated">1st</div>
<div class="floated">2nd</div>
<div class="floated">3nd</div>
</div> <!-- /#conteiner -->
<div classs="clear"></div> <!-- Acts as a wall -->
<section>Below</section>
CSS
#container {
min-height: 100px; /* To prevent it from collapsing */
border: 1px solid #0f0;
}
.floated {
float: left;
border: 1px solid #f00;
width: 200px;
height: 100px;
}
.clear {
clear: both;
}
section {
border: 1px solid #f0f;
}
As for the result?
It's the *** same!
Least you know, you'll start a CSS party, inviting all kinds of selectors and properties to the party; making a bigger mess of your CSS than what you started with. Just to fix your float.
This simple and very adaptable piece of CSS is a beauty and a "savior":
.clearfix:before, .clearfix:after {
content: "";
display: table;
clear: both;
zoom: 1; /* ie 6/7 */
}
That's it! It really works without breaking semantics and did I mention it works?:
From the same sample...HTML
<div class="clearfix">
<div class="floated">1st</div>
<div class="floated">2nd</div>
<div class="floated">3nd</div>
</div>
<section>Below</section>
CSS
div.floated {
float: left;
border: 1px solid #f00;
width: 200px;
height: 100px;
}
section {
border: 4px solid #00f;
}
.clearfix:before, .clearfix:after {
content: "";
display: table;
clear: both;
zoom: 1; /* ie 6/7 */
}
Now we no longer need <div classs="clear"></div> <!-- Acts as a wall -->
and keep the semantic police happy. This is not the only benefit. This clearfix is responsive to any screen size without the use of @media
in it's simplest form. In other words, it will keep your float container in check and preventing floodings. Lastly, it provides support for old browsers all in one small karate chop =)
.clearfix:before, .clearfix:after {
content: "";
display: table;
clear: both;
zoom: 1; /* ie 6/7 */
}
You'd need to be careful as onBlur
has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).
There is, however, no way to use onFocusOut
in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.
I'll add that if you want to read the dimensions, you can do this:
int[][][] a = new int[4][3][2];
System.out.println(a.length); // 4
System.out.println(a[0].length); // 3
System.out.println(a[0][0].length); //2
You can also have jagged arrays, where different rows have different lengths, so a[0].length != a[1].length
.
I find this to be concise and self-documenting:
[true, false].include? foo
If using Rails or ActiveSupport, you can even do a direct query using in?
foo.in? [true, false]
Checking against all possible values isn't something I'd recommend for floats, but feasible when there are only two possible values!
You could create a table somewhere on a calculation spreadsheet which performs this operation for each pair of cells, and use auto-fill to fill it up.
Aggregate the results from that table into a results cell.
The 200 so cells which reference the results could then reference the cell that holds the aggregation results. In the newest versions of excel you can name the result cell and reference it that way, for ease of reading.
Both Query is used for round down the nearest integer in MySQL
Between those two syntaxes, you should really choose the one you prefer :-)
Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.
The result will be the same; and even if there are performance implications, those won't matter 1.
As a sidenote, so my answer is a bit more complete: the day you'll want to do something like this:
echo "Welcome $names!";
PHP will interpret your code as if you were trying to use the $names
variable -- which doesn't exist.
- note that it will only work if you use "" not '' for your string.
That day, you'll need to use {}
:
echo "Welcome {$name}s!"
No need to fallback to concatenations.
Also note that your first syntax:
echo "Welcome ".$name."!";
Could probably be optimized, avoiding concatenations, using:
echo "Welcome ", $name, "!";
(But, as I said earlier, this doesn't matter much...)
1 - Unless you are doing hundreds of thousands of concatenations vs interpolations -- and it's probably not quite the case.
To refresh menu from Fragment simply call:
getActivity().invalidateOptionsMenu();
I had this issue when exporting CSV data from C# code, and resolved this by prepending the leading zero data with the tab character \t, so the data was interpreted as text rather than numeric in Excel (yet unlike prepending other characters, it wouldn't be seen).
I did like the ="001" approach, but this wouldn't allow exported CSV data to be re-imported again to my C# application without removing all this formatting from the import CSV file (instead I'll just trim the import data).
I have a Mac, but luckily this should work the same way:
pip
is a command-line thing. You don't run it in python.
For example, on my Mac, I just say:
$pip install somelib
pretty easy!
Use the span
tag
<style>
.redText
{
color:red;
}
.blackText
{
color:black;
font-weight:bold;
}
</style>
<span class="redText">My Name is:</span> <span class="blackText">Tintincute</span>
It's also a good idea to avoid inline styling. Use a custom CSS class instead.
Try this:
select
contract,
max (activity)
from
mytable
group by
contract
having
count (activity) = 1
Because @User and @BiXiC asked for help with UTF-8 here a variation of the solution by @Matthew. (I'm not allowed to comment, so I'm answering.)
import unicodecsv as csv
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(toCSV)
This has a more elegant explanation and more than one possible solutions. http://kasunh.wordpress.com/2011/10/11/preserving-remote-iphost-while-proxying/
The post describes how to use one popular and one lesser known Apache modules to preserve host/ip while in a setup involving proxying.
Use mod_rpaf module, install and enable it in the backend server and add following directives in the module’s configuration. RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1
(2017 edit) Current location of mod_rpaf: https://github.com/gnif/mod_rpaf
With credits to previous answer https://stackoverflow.com/a/36549068/7149454
Boostrap compatible, adust your container width (300px in this example) and you're good to go:
<div class="embed-responsive embed-responsive-16by9" style="height: 100 %; width: 300px; ">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/LbLB0K-mXMU?start=1841" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0"></iframe>
</div>
In Ruby, any variable whose name starts with a capital letter is a constant and you can only assign to it once. Choose one of these alternatives:
class MyClass
MYCONSTANT = "blah"
def mymethod
MYCONSTANT
end
end
class MyClass
def mymethod
my_constant = "blah"
end
end
I have an answer that might be a bit less confusing for newbies like myself. You can just use map
within the components render method.
render () {
return (
<div>
{stations.map(station => <div key={station}> {station} </div>)}
</div>
);
}
The first and stable debugger for MySQL is in dbForge Studio for MySQL
One of the alternatives is to write the mutliprocessing logging to a known file and register an atexit
handler to join on those processes read it back on stderr; however, you won't get a real-time flow to the output messages on stderr that way.
unset($a->new_property);
This works for array elements, variables, and object attributes.
Example:
$a = new stdClass();
$a->new_property = 'foo';
var_export($a); // -> stdClass::__set_state(array('new_property' => 'foo'))
unset($a->new_property);
var_export($a); // -> stdClass::__set_state(array())
Actually these only work when the window isn't scrolled at all from the top left position.
You have to subtract the window scroll values to get an offset that's useful for repositioning elements so they stay on the page:
var offset = $('#whatever').offset();
offset.right = ($(window).width() + $(window).scrollLeft()) - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = ($(window).height() + $(window).scrollTop()) - (offset.top + $('#whatever').outerHeight(true));
You can also do it using reredirect
(https://github.com/jerome-pouiller/reredirect/).
The command bellow redirects the outputs (standard and error) of the process PID
to FILE
:
reredirect -m FILE PID
The README
of reredirect
also explains other interesting features: how to restore the original state of the process, how to redirect to another command or to redirect only stdout or stderr.
The tool also provides relink
, a script allowing to redirect the outputs to the current terminal:
relink PID
relink PID | grep usefull_content
(reredirect
seems to have same features than Dupx described in another answer but, it does not depend on Gdb).
Shorter version:
dependencies {
implementation fileTree('lib')
}
formatDate(date) {
const d = new Date(date)
const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
return `${da}-${mo}-${ye}`;
}
console.log("Formatated Date : ", formatDate("09/25/2020") )
// Output :: Formatated Date : 25-Sep-2020
It can be done using CSS alone. It works perfect on my machine in Firefox, Chrome and Opera browser under Ubuntu 12.04.
CSS :
.hover_img a { position:relative; }
.hover_img a span { position:absolute; display:none; z-index:99; }
.hover_img a:hover span { display:block; }
HTML :
<div class="hover_img">
<a href="#">Show Image<span><img src="images/01.png" alt="image" height="100" /></span></a>
</div>
Go to design for that table. Now, on the right, set the ID column as the column in question. It will now auto populate without specification.
Use $elemMatch to find the array of particular object
db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})
None of the other answers worked for me. Note that SQL Server will give different results if you pass in a hard-coded string versus feed it from a column in your result set. Below is the magic that worked for me to give a perfect match between SQL Server and MySql
select LOWER(CONVERT(VARCHAR(32), HashBytes('MD5', CONVERT(varchar, EmailAddress)), 2)) from ...
I realise this is an old question but for anyone who does come across it this can be done using contenteditable
as shown in this JSFiddle.
Kudos to Alex who mentioned this in the comments (I didn't see that until now!)
I documented and tested 10 different ways to read a file in Java and then ran them against each other by making them read in test files from 1KB to 1GB. Here are the fastest 3 file reading methods for reading a 1GB test file.
Note that when running the performance tests I didn't output anything to the console since that would really slow down the test. I just wanted to test the raw reading speed.
1) java.nio.file.Files.readAllBytes()
Tested in Java 7, 8, 9. This was overall the fastest method. Reading a 1GB file was consistently just under 1 second.
import java.io..File;
import java.io.IOException;
import java.nio.file.Files;
public class ReadFile_Files_ReadAllBytes {
public static void main(String [] pArgs) throws IOException {
String fileName = "c:\\temp\\sample-1GB.txt";
File file = new File(fileName);
byte [] fileBytes = Files.readAllBytes(file.toPath());
char singleChar;
for(byte b : fileBytes) {
singleChar = (char) b;
System.out.print(singleChar);
}
}
}
2) java.nio.file.Files.lines()
This was tested successfully in Java 8 and 9 but it won't work in Java 7 because of the lack of support for lambda expressions. It took about 3.5 seconds to read in a 1GB file which put it in second place as far as reading larger files.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.stream.Stream;
public class ReadFile_Files_Lines {
public static void main(String[] pArgs) throws IOException {
String fileName = "c:\\temp\\sample-1GB.txt";
File file = new File(fileName);
try (Stream linesStream = Files.lines(file.toPath())) {
linesStream.forEach(line -> {
System.out.println(line);
});
}
}
}
3) BufferedReader
Tested to work in Java 7, 8, 9. This took about 4.5 seconds to read in a 1GB test file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile_BufferedReader_ReadLine {
public static void main(String [] args) throws IOException {
String fileName = "c:\\temp\\sample-1GB.txt";
FileReader fileReader = new FileReader(fileName);
try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
}
}
You can find the complete rankings for all 10 file reading methods here.
For windows 10 you need to path C:\Program Files\Java\jre1.8.0_161\bin
restart command and open
Alternative to raising exception or attempting to recreate a now empty table - while still enabling migration rollback, redo etc -
def change
drop_table(:users, force: true) if ActiveRecord::Base.connection.tables.include?('users')
end
Provided my_command
is canonically designed, ie returns 0 when succeeds, then &&
is exactly the opposite of what you want. You want ||
.
Also note that (
does not seem right to me in bash, but I cannot try from where I am. Tell me.
my_command || {
echo 'my_command failed' ;
exit 1;
}
If you'd like to add text at the end of each line in-place (in the same file), you can use -i
parameter, for example:
sed -i'.bak' 's/$/:80/' foo.txt
However -i
option is non-standard Unix extension and may not be available on all operating systems.
So you can consider using ex
(which is equivalent to vi -e
/vim -e
):
ex +"%s/$/:80/g" -cwq foo.txt
which will add :80
to each line, but sometimes it can append it to blank lines.
So better method is to check if the line actually contain any number, and then append it, for example:
ex +"g/[0-9]/s/$/:80/g" -cwq foo.txt
If the file has more complex format, consider using proper regex, instead of [0-9]
.
I met such problem. Visual Studio 2008 clearly said: problem was caused by libtiff.dll. It cannot be loaded for some reasom, caused by its manifest (as a matter of fact, this dll has no manifest at all). I fixed it, when I had removed libtiff.dll from my project (but simultaneously I lost ability to open compressed TIFFs!). I recompiled aforementioned dll, but problem still remains. Interesting, that at my own machine I have no such error. Three others comps refused to load my prog. Attention!!! Here http://www.error-repair-tools.com/ppc/error.php?t=0xc0150002 one wise boy wrote, that this error was caused by problem with registry and offers repair tool. I have a solid guess, that this "repair tool" will install some malicious soft at your comp.
Do not use any white space. I had the same issue. Then I removed white space like:
header("location:index.php"); or header('location:index.php');
Then it worked.
After spending hours on this issue found solution here
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule,
ReactiveFormsModule
]
})
If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:
PARAMETERS SomeParam Text(10);
SELECT Field FROM Table
WHERE OtherField=SomeParam
You can also say:
CREATE PROCEDURE ProcedureName
(Parameter1 datatype, Parameter2 datatype) AS
SQLStatement
From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs
Note that the procedure contains only one statement.
Once a DataTable
has been filled, you can't change the type of a column.
Your best option in this scenario is to add an Int32
column to the DataTable
before filling it:
dataTable = new DataTable("Contact");
dataColumn = new DataColumn("Id");
dataColumn.DataType = typeof(Int32);
dataTable.Columns.Add(dataColumn);
Then you can clone the data from your original table to the new table:
DataTable dataTableClone = dataTable.Clone();
Here's a post with more details.
Instead of Windows PowerShell
, find the item in the Start Menu called SharePoint 2013 Management Shell
:
for direct access a object property by position... generally usefull for property [0]... so it holds info about the further... or in node.js 'require.cache[0]' for the first loaded external module, etc. etc.
Object.keys( myObject )[ 0 ]
Object.keys( myObject )[ 1 ]
...
Object.keys( myObject )[ n ]
The answer I was looking for is at https://unix.stackexchange.com/a/9557/114862.
Using the
-c
flag when the local file is of greater or equal size to the server version will avoid re-downloading.
You can implement UINavigationControllerDelegate
like this:
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
let item = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil)
viewController.navigationItem.backBarButtonItem = item
}
class MyNavigationController: UINavigationController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
let item = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
viewController.navigationItem.backBarButtonItem = item
}
}
backBarButtonItem
is nil
by default and it affects next pushed controller, so you just set it for all controllers
HTML: Use names as
<input name="levels[level][]">
<input name="levels[build_time][]">
PHP:
$array = filter_input_array(INPUT_POST);
$newArray = array();
foreach (array_keys($array) as $fieldKey) {
foreach ($array[$fieldKey] as $key=>$value) {
$newArray[$key][$fieldKey] = $value;
}
}
$newArray will hold data as you want
Array (
[0] => Array ( [level] => 1 [build_time] => 123 )
[1] => Array ( [level] => 2 [build_time] => 456 )
)
No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.
First, create your queue:
Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();
Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):
YourProducer producer = new YourProducer(queue);
and:
YourConsumer consumer = new YourConsumer(queue);
and add stuff to it in your producer:
queue.offer(myObject);
and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):
YourObject myObject = queue.poll();
For more info see the Javadoc
If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.
If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:
Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());
A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.
Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:
BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();
queue.put(myObject); // Blocks until queue isn't full.
YourObject myObject = queue.take(); // Blocks until queue isn't empty.
Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.
Just in case you are able to utilize a scripting language to prepare your SQL queries, you could reuse field=value pairs by using SET
instead of (a,b,c) VALUES(a,b,c)
.
An example with PHP:
$pairs = "a=$a,b=$b,c=$c";
$query = "INSERT INTO $table SET $pairs ON DUPLICATE KEY UPDATE $pairs";
Example table:
CREATE TABLE IF NOT EXISTS `tester` (
`a` int(11) NOT NULL,
`b` varchar(50) NOT NULL,
`c` text NOT NULL,
UNIQUE KEY `a` (`a`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
alternatively
In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
cursor:pointer
doesn't work when you're using Chrome's mobile emulator.
A different approach that I found ugly compared to the classic dict+append, but that works:
df = df.T
df[0] = ['1/1/2013', 'Smith','test',123]
df = df.T
df
Out[6]:
Date Name Action ID
0 1/1/2013 Smith test 123
For those who don't want elegant solutions, just a quick and dirty way to stop those messages, here is a solution that worked for me (I use Hibernate 4.3.6 and Eclipse and no answers provided above (or found on the internet) worked; neither log4j config files nor setting the logging level programatically)
public static void main(String[] args) {
//magical - do not touch
@SuppressWarnings("unused")
org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger("org.hibernate");
java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.WARNING); //or whatever level you need
...
}
I used it in a tutorial program downloaded from this site
The server at x3.chatforyoursite.com
needs to output the following header:
Access-Control-Allow-Origin: http://www.example.com
Where http://www.example.com
is your website address. You should check your settings on chatforyoursite.com
to see if you can enable this - if not their technical support would probably be the best way to resolve this. However to answer your question, you need the remote site to allow your site to access AJAX responses client side.
If you have cleanup you need to do on exit, you can also use 'trap' with the pseudo-signal ERR. This works the same way as trapping INT or any other signal; bash throws ERR if any command exits with a nonzero value:
# Create the trap with
# trap COMMAND SIGNAME [SIGNAME2 SIGNAME3...]
trap "rm -f /tmp/$MYTMPFILE; exit 1" ERR INT TERM
command1
command2
command3
# Partially turn off the trap.
trap - ERR
# Now a control-C will still cause cleanup, but
# a nonzero exit code won't:
ps aux | grep blahblahblah
Or, especially if you're using "set -e", you could trap EXIT; your trap will then be executed when the script exits for any reason, including a normal end, interrupts, an exit caused by the -e option, etc.
Because of the way the function is called (i.e. as a simple call to a function variable), this
is the global object (for which window
is an alias in browsers). Use the obj
parameter instead.
Also, creating a jQuery object and the using its attr()
method for obtaining an element ID is inefficient and unnecessary. Just use the element's id
property, which works in all browsers.
function showHideOther(obj){
var sel = obj.options[obj.selectedIndex].value;
var ID = obj.id;
if (sel == 'other') {
$(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(obj).css({'display' : 'none'});
}
}
Server side put this on top of .php:
header('Access-Control-Allow-Origin: *');
You can set specific domain restriction access:
header('Access-Control-Allow-Origin: https://www.example.com')
Just put following lines in global.asax:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
Import
using System.Data.Entity;
UICollectionView is same as UITableView but it gives us the additional functionality of simply creating a grid view, which is a bit problematic in UITableView. It will be a very long post I mention a link from where you will get everything in simple steps.
For viewers who got this error after upgrading React Native to 0.40+, you may need to run react-native upgrade
on the command line.
This is how I did a similar thing. I have tiles that are thumbnails to YouTube videos. When I click the tile, it redirects me to a 'player' page that uses the 'video_id' to render the correct video to the page.
<GridTile
key={video_id}
title={video_title}
containerElement={<Link to={`/player/${video_id}`}/>}
>
ETA: Sorry, just noticed that you didn't want to use the LINK or REDIRECT components for some reason. Maybe my answer will still help in some way. ; )
This is how I did it without scripting:
@using (Html.BeginForm("Action", "Controller", FormMethod.Get))
{
<button type="submit"
class="btn btn-default"
title="Action description">Button Label</button>
}
Same, but with parameter and confirmation dialog:
@using (Html.BeginForm("Action", "Controller",
new { paramName = paramValue },
FormMethod.Get,
new { onsubmit = "return confirm('Are you sure?');" }))
{
<button type="submit"
class="btn btn-default"
title="Action description">Button Label</button>
}
Add validation groups for your validator elements. This allows you distinguish between different groups which to include in validation. Add validation group also to your submit button
N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):
N[i]/2
will be a float64
but range()
expects an integer. Just cast the call to
for j in range(int(N[i]/2)):
No, you can't. JavaScript is executed on the client side (browser), while the session data is stored on the server.
However, you can expose session variables for JavaScript in several ways:
In JSP you'd have something like:
<input type="hidden" name="pONumb" value="${sessionScope.pONumb} />
or:
<div id="product" data-prodnumber="${sessionScope.pONumb}" />
Then in JS:
// you can find a more efficient way to select the input you want
var inputs = document.getElementsByTagName("input"), len = inputs.length, i, pONumb;
for (i = 0; i < len; i++) {
if (inputs[i].name == "pONumb") {
pONumb = inputs[i].value;
break;
}
}
or:
var product = document.getElementById("product"), pONumb;
pONumb = product.getAttribute("data-prodnumber");
The inline example is the most straightforward, but if you then want to store your JavaScript code as an external resource (the recommended way) it won't be feasible.
<script>
var pONumb = ${sessionScope.pONumb};
[...]
</script>
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
Try:
System.Environment.GetEnvironmentVariable("USERPROFILE");
Edit:
If the version of .NET you are using is 4 or above, you can use the Environment.SpecialFolder
enumeration:
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
I found the syslog module to make it quite easy to get the basic logging behavior you describe:
import syslog
syslog.syslog("This is a test message")
syslog.syslog(syslog.LOG_INFO, "Test message at INFO priority")
There are other things you could do, too, but even just the first two lines of that will get you what you've asked for as I understand it.
If you want to select the last child and need to be specific on the element type you can use the selector last-of-type
Here is an example:
$("div p:last-of-type").css("border", "3px solid red");
$("div span:last-of-type").css("border", "3px solid red");
<div id="example">
<p>This is paragraph 1</p>
<p>This is paragraph 2</p>
<span>This is paragraph 3</span>
<span>This is paragraph 4</span>
<p>This is paragraph 5</p>
</div>
In the example above both Paragraph 4 and Paragraph 5 will have a red border since Paragraph 5 is the last element of "p" type in the div and Paragraph 4 is the last "span" in the div.
Converting the input string into a number rather than keeping it as a string, limits the solution to the maximum allowed float / integer value on that machine/browser. My script below handles currency up to 1 Trillion dollars - 1 cent :-). I can be extended to handle up to 999 Trillions by adding 3 or 4 lines of code.
var ones = ["","One","Two","Three","Four","Five","Six","Seven","Eight",
"Nine","Ten","Eleven","Twelve","Thirteen","Fourteen",
"Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"];
var tens = ["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy",
"Eighty","Ninety"];
function words999(n999) { // n999 is an integer less than or equal to 999.
//
// Accept any 3 digit int incl 000 & 999 and return words.
//
var words = ''; var Hn = 0; var n99 = 0;
Hn = Math.floor(n999 / 100); // # of hundreds in it
if (Hn > 0) { // if at least one 100
words = words99(Hn) + " Hundred"; // one call for hundreds
}
n99 = n999 - (Hn * 100); // subtract the hundreds.
words += ((words == '')?'':' ') + words99(n99); // combine the hundreds with tens & ones.
return words;
} // function words999( n999 )
function words99(n99) { // n99 is an integer less than or equal to 99.
//
// Accept any 2 digit int incl 00 & 99 and return words.
//
var words = ''; var Dn = 0; var Un = 0;
Dn = Math.floor(n99 / 10); // # of tens
Un = n99 % 10; // units
if (Dn > 0 || Un > 0) {
if (Dn < 2) {
words += ones[Dn * 10 + Un]; // words for a # < 20
} else {
words += tens[Dn];
if (Un > 0) words += "-" + ones[Un];
}
} // if ( Dn > 0 || Un > 0 )
return words;
} // function words99( n99 )
function getAmtInWords(id1, id2) { // use numeric value of id1 to populate text in id2
//
// Read numeric amount field and convert into word amount
//
var t1 = document.getElementById(id1).value;
var t2 = t1.trim();
amtStr = t2.replace(/,/g,''); // $123,456,789.12 = 123456789.12
dotPos = amtStr.indexOf('.'); // position of dot before cents, -ve if it doesn't exist.
if (dotPos > 0) {
dollars = amtStr.slice(0,dotPos); // 1234.56 = 1234
cents = amtStr.slice(dotPos+1); // 1234.56 = .56
} else if (dotPos == 0) {
dollars = '0';
cents = amtStr.slice(dotPos+1); // 1234.56 = .56
} else {
dollars = amtStr.slice(0); // 1234 = 1234
cents = '0';
}
t1 = '000000000000' + dollars; // to extend to trillion, use 15 zeros
dollars = t1.slice(-12); // and -15 here.
billions = Number(dollars.substr(0,3));
millions = Number(dollars.substr(3,3));
thousands = Number(dollars.substr(6,3));
hundreds = Number(dollars.substr(9,3));
t1 = words999(billions); bW = t1.trim(); // Billions in words
t1 = words999(millions); mW = t1.trim(); // Millions in words
t1 = words999(thousands); tW = t1.trim(); // Thousands in words
t1 = words999(hundreds); hW = t1.trim(); // Hundreds in words
t1 = words99(cents); cW = t1.trim(); // Cents in words
var totAmt = '';
if (bW != '') totAmt += ((totAmt != '') ? ' ' : '') + bW + ' Billion';
if (mW != '') totAmt += ((totAmt != '') ? ' ' : '') + mW + ' Million';
if (tW != '') totAmt += ((totAmt != '') ? ' ' : '') + tW + ' Thousand';
if (hW != '') totAmt += ((totAmt != '') ? ' ' : '') + hW + ' Dollars';
if (cW != '') totAmt += ((totAmt != '') ? ' and ' : '') + cW + ' Cents';
// alert('totAmt = ' + totAmt); // display words in a alert
t1 = document.getElementById(id2).value;
t2 = t1.trim();
if (t2 == '') document.getElementById(id2).value = totAmt;
return false;
} // function getAmtInWords( id1, id2 )
// ======================== [ End Code ] ====================================
Other alternative:
JAXBElement<String> element = new JAXBElement<>(new QName("Your localPart"),
String.class, "Your message");
Then:
System.out.println(element.getValue()); // Result: Your message
Make sure you have your Spring bean definitions correct. Sometimes, the application works fine, it just displays an error in the IDE, check your project ‘iml’ file if you have a Spring facet defined.
For cleaning the pasted text and replacing the currently selected text with the pasted text the matter is pretty trivial:
<div id='div' contenteditable='true' onpaste='handlepaste(this, event)'>Paste</div>
JS:
function handlepaste(el, e) {
document.execCommand('insertText', false, e.clipboardData.getData('text/plain'));
e.preventDefault();
}
The problem is that Elements
only takes the direct child elements of whatever you call it on. If you want all descendants, use the Descendants
method:
var query = from c in xmlFile.Descendants("Band")
You may also have a look on Runtyper - a tool that performs type checking of operands in ===
(and other operations).
For your example, if you have strict comparison x === y
and x = 123, y = "123"
, it will automatically check typeof x, typeof y
and show warning in console:
Strict compare of different types: 123 (number) === "123" (string)
A jar file is a zip archive. You can extract it using 7zip (a great simple tool to open archives). You can also change its extension to zip and use whatever to unzip the file.
Now you have your class file. There is no easy way to edit class file, because class files are binaries (you won't find source code in there. maybe some strings, but not java code). To edit your class file you can use a tool like classeditor.
You have all the strings your class is using hard-coded in the class file. So if the only thing you would like to change is some strings you can do it without using classeditor.
I figured everyone looking for this answer was probably just trying to avoid writing out the whole if/else statements, so I wrote it out for you so you can copy/paste. The only caveat with this function is that it goes on the actual number of the month, not a 0-indexed number, so January = 1, not 0.
function getMonthString($m){
if($m==1){
return "January";
}else if($m==2){
return "February";
}else if($m==3){
return "March";
}else if($m==4){
return "April";
}else if($m==5){
return "May";
}else if($m==6){
return "June";
}else if($m==7){
return "July";
}else if($m==8){
return "August";
}else if($m==9){
return "September";
}else if($m==10){
return "October";
}else if($m==11){
return "November";
}else if($m==12){
return "December";
}
}
The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).
For this example, let's draw a RED pixel at position 100x50.
Mat foo;
int x=100, y=50;
Solution 1:
Create a macro function that obtains the pixel from the array.
#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0; // B
p[1] = 0; // G
p[2] = 255; // R
Solution 2:
Get's the pixel using the method ptr.
unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0; // B
p[1] = 0; // G
p[2] = 255; // R
As this is only tagged sql
(which does not indicate any specific DBMS), here is a solution for Postgres:
select d::date
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);
If you need that a lot, it's more efficient to store that in an table (which can e.g. be indexed):
create table calendar
as
select d::date as the_date
from generate_series(date '1990-01-01', date '1990-01-01' + interval '100' year, interval '1' day) as t(d);
The following line doesn't work?
rm -rf ~/anaconda3
You should know where your anaconda3(or anaconda1, anaconda2) is installed. So write
which anaconda
output
output: somewhere
Now use that somewhere and run:
rm -rf somewhere
Similar to what Mark E has proposed, you have to come up with your own. Just to help you a bit, there is a neat article http://gleichmann.wordpress.com/2008/01/15/building-your-own-literals-in-java-tuples-and-maps/ which gives you a really neat way of creating tuples and maps that might be something you might want to consider.
You could try Conditional Formatting available in the tool menu "Format -> Conditional Formatting".
Using a #t=10,20
fragment worked for me.
Here's a more readable example of an in-place Insertion sort algorithm.
a = [3, 1, 5, 2, 4]
for i in a[1:]:
j = a.index(i)
while j > 0 and a[j-1] > a[j]:
a[j], a[j-1] = a[j-1], a[j]
j = j - 1
If that is the entire line, it very well might be because you are missing a ;
at the end of the line.
I was trying to verify the installation of TensorFlow as specified here on a newly created virtual environment on Python 3.6. On running:
pip3 install --ignore-installed --upgrade "/Users/Salman/Downloads/tensorflow-1.12.0-cp37-cp37m-macosx_10_13_x86_64.whl"
I get the error and/or warning:
tensorflow-1.12.0-cp37-cp37m-macosx_10_13_x86_64.whl is not a supported wheel on this platform.
Since I had previously upgraded from pip to pip3, I simply replaced pip with pip3 as in:
pip3 install --ignore-installed --upgrade "/Users/Salman/Downloads/tensorflow-1.12.0-cp37-cp37m-macosx_10_13_x86_64.whl"
and it worked like a charm!
Another approach which allows you to specify how many numbers you want with size
and the min
and max
values of the returned numbers
public static int getRandomInt(int min, int max) {
Random random = new Random();
return random.nextInt((max - min) + 1) + min;
}
public static ArrayList<Integer> getRandomNonRepeatingIntegers(int size, int min,
int max) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (numbers.size() < size) {
int random = getRandomInt(min, max);
if (!numbers.contains(random)) {
numbers.add(random);
}
}
return numbers;
}
To use it returning 7 numbers between 0 and 25.
ArrayList<Integer> list = getRandomNonRepeatingIntegers(7, 0, 25);
for (int i = 0; i < list.size(); i++) {
System.out.println("" + list.get(i));
}
I had something similar when passing a script to a function with invoke-command. I ran the command in single quotes instead of double quotes, because it then becomes a string literal. 'Set-Mailbox $sourceUser -LitigationHoldEnabled $false -ElcProcessingDisabled $true';
I think I found why there are a few varying answers for this question. When the window has been resized such that it has a horizontal scroll bar (because the buffer is larger than the window) Console.CursorTop seems to return the wrong line. The following code works for me, regardless of window size or cursor position.
public static void ClearLine()
{
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - (Console.WindowWidth >= Console.BufferWidth ? 1 : 0));
}
Without the (Console.WindowWidth >= Console.BufferWidth ? 1 : 0), the code may either move the cursor up or down, depending on which version you use from this page, and the state of the window.
If you use this:
contentType: "application/json"
AJAX won't sent GET or POST params to the server.... dont know why.
It took me hours to lear it today.
Just Use:
$.ajax(
{ url : 'http://blabla.com/wsGetReport.php',
data : myFormData, type : 'POST', dataType : 'json',
// contentType: "application/json",
success : function(wsQuery) { }
}
)
One way would be using slice
, like follow:
var id="ctl03_Tabs1";
var temp=id.slice(-5);
so the value of temp
would be "Tabs1"
.
Simplest is use list[i:i]
a = [1,2, 3, 4]
a[2:2] = [10]
Print a to check insertion
print a
[1, 2, 10, 3, 4]
In fact in the last answer String strAsciiTab = Character.toString((char) iAsciiValue); the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)
Meaning the first answer was correct actually char ch = (char) yourInt;
if in yourint=49 (or 0x31), ch will be '1'
<?php
$link = mysqli_connect('localhost','root','');
if (!$link) {
die('Could not connect to MySQL: ' . mysqli_error());
}
echo 'Connection OK'; mysqli_close($link);
?>
This will solve your problem.
Using the ironRuby interperter you have the full .net platform, meaning you can code Winforms and WPF(I have only tried Winforms). It is potentially cross platform since the mono platform exist
Since you're on an embedded platform, it's quite possible that you don't have the full range of capabilities from the printf()
-style functions.
Assuming you have floats at all (still not necessarily a given for embedded stuff), you can emulate it with something like:
char str[100];
float adc_read = 678.0123;
char *tmpSign = (adc_read < 0) ? "-" : "";
float tmpVal = (adc_read < 0) ? -adc_read : adc_read;
int tmpInt1 = tmpVal; // Get the integer (678).
float tmpFrac = tmpVal - tmpInt1; // Get fraction (0.0123).
int tmpInt2 = trunc(tmpFrac * 10000); // Turn into integer (123).
// Print as parts, note that you need 0-padding for fractional bit.
sprintf (str, "adc_read = %s%d.%04d\n", tmpSign, tmpInt1, tmpInt2);
You'll need to restrict how many characters come after the decimal based on the sizes of your integers. For example, with a 16-bit signed integer, you're limited to four digits (9,999 is the largest power-of-ten-minus-one that can be represented).
However, there are ways to handle this by further processing the fractional part, shifting it by four decimal digits each time (and using/subtracting the integer part) until you have the precision you desire.
Update:
One final point you mentioned that you were using avr-gcc
in a response to one of the other answers. I found the following web page that seems to describe what you need to do to use %f
in your printf()
statements here.
As I originally suspected, you need to do some extra legwork to get floating point support. This is because embedded stuff rarely needs floating point (at least none of the stuff I've ever done). It involves setting extra parameters in your makefile and linking with extra libraries.
However, that's likely to increase your code size quite a bit due to the need to handle general output formats. If you can restrict your float outputs to 4 decimal places or less, I'd suggest turning my code into a function and just using that - it's likely to take up far less room.
In case that link ever disappears, what you have to do is ensure that your gcc command has "-Wl,-u,vfprintf -lprintf_flt -lm
". This translates to:
printf()
library for searching.Yet another answer:
-1
... requires import
+1
... is very readable
import operator
a = [1,2,3,4]
b = [10,11,12,13]
list(map(operator.mul, a, b))
outputs [10, 22, 36, 52]
If you are redirecting with PHP, then you would simply use the sleep() command to sleep for however many seconds before redirecting.
But, I think what you are referring to is the meta refresh tag:
http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm
/**
* Check if a number is even or not using modulus operator.
*
* @param number the number to be checked.
* @return {@code true} if the given number is even, otherwise {@code false}.
*/
public static boolean isEven(int number) {
return number % 2 == 0;
}
/**
* Check if a number is even or not using & operator.
*
* @param number the number to be checked.
* @return {@code true} if the given number is even, otherwise {@code false}.
*/
public static boolean isEvenFaster(int number) {
return (number & 1) == 0;
}
The Doc of the npm defines that only tag/version can be specified after repo_url.
Here is the Doc: https://docs.npmjs.com/cli/install
Just to add another unexpected case, here is query that wasn't returning expected results:
*:* AND ( ( field_a:foo AND field_b:bar ) OR !field_b:bar )
field_b
in my case is something I perform faceting on, and needed to target the query term "foo" only on that type (bar)
I had to insert another *:*
after the or condition to get this to work, like so:
*:* AND ( ( field_a:foo AND field_b:bar ) OR ( *:* AND !field_b:bar ) )
edit: this is in solr 6.6.3
You can go from String (hex)
to byte array
to String as UTF-8(?)
. Make sure your hex string does not have leading spaces and stuff.
public static byte[] hexStringToByteArray(String hex) {
int l = hex.length();
byte[] data = new byte[l / 2];
for (int i = 0; i < l; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
return data;
}
Usage:
String b = "0xfd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = hexStringToByteArray(b);
String st = new String(bytes, StandardCharsets.UTF_8);
System.out.println(st);
I encountered this problem when working with COM objects. Under certain circumstances (my fault), I destroyed an external .EXE process, in a parallel thread, a variable tried to access the com interface app.method and a COM-level crash occurred. Task Scheduler noticed this and shut down the app. But if you run the app in the console and don't handle the exception, the app will continue to work ...
Please note that if you use unmanaged code or external objects (AD, Socket, COM ...), you need to monitor them!
Working solution for Windows:
Control Panel > User Accounts > Credential Manager > Generic Credentials
<form id="yourFormName" >
<input type="text" value="" id="val1">
<input type="text" value="" id="val2">
<input type="text" value="" id="val3">
<button type="button" onclick="yourFunction()"> Check </button>
</form>
<script type="text/javascript">
function yourFunction()
{
var elements = document.querySelectorAll("#yourFormName input[type=text]")
console.log(elements);
for (var i = 0; i<elements.length; i++ )
{
var check = document.getElementById(elements[i].id).value);
console.log(check);
// write your logic here
}
}
</script>
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
allScreenBounds.width += screenBounds.width;
allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);
allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);
}
Robot robot = new Robot();
BufferedImage bufferedImage = robot.createScreenCapture(allScreenBounds);
File file = new File("C:\\Users\\Joe\\Desktop\\scr.png");
if(!file.exists())
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
ImageIO.write( bufferedImage, "png", fos );
bufferedImage will contain a full screenshot, this was tested with three monitors
First zip or gzip the folders:
Use the following command:
zip -r NameYouWantForZipFile.zip foldertozip/
or
tar -pvczf BackUpDirectory.tar.gz /path/to/directory
for gzip compression use SCP:
scp [email protected]:~/serverpath/public_html ~/Desktop
I'm a fan of:
chooseCRANmirror()
Which will print the list of mirrors in the output (no worrying a popup window since you are running it from the terminal) and then you enter the number you want.
With .Net Framework 4.5 (using ZipArchive):
using (ZipArchive zip = ZipFile.Open(zipfile, ZipArchiveMode.Read))
foreach (ZipArchiveEntry entry in zip.Entries)
if(entry.Name == "myfile")
entry.ExtractToFile("myfile");
Find "myfile" in zipfile and extract it.
I really like the YUI3 library for this sort of thing.
<div id="mydiv"> ... </div>
<script>
YUI().use('node-base', function(Y) {
Y.on("available", someFunction, '#mydiv')
})
Dummy data (you should supply this for us)
visual1 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
visual2 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
combine:
visuals = rbind(visual1,visual2)
visuals$vis=c(rep("visual1",100),rep("visual2",100)) # 100 points of each flavour
Now do:
ggplot(visuals, aes(ISSUE_DATE,COUNTED,group=vis,col=vis)) +
geom_point() + geom_smooth()
and adjust colours etc to taste.
Whoa there!
There's a potentially serious problem with this code, because it ignores the character encoding specified in the String
(which is UTF-8 by default). When you call String.getBytes()
the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something… not pretty!
Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:
import java.io.StringReader;
import org.xml.sax.InputSource;
…
return builder.parse(new InputSource(new StringReader(xml)));
It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.
Mount a volume, copy the artifacts, adjust owner id and group id:
mkdir artifacts
docker run -i --rm -v ${PWD}/artifacts:/mnt/artifacts centos:6 /bin/bash << COMMANDS
ls -la > /mnt/artifacts/ls.txt
echo Changing owner from \$(id -u):\$(id -g) to $(id -u):$(id -g)
chown -R $(id -u):$(id -g) /mnt/artifacts
COMMANDS
EDIT: Note that some of the commands like $(id -u)
are backslashed and will therefore be processed within the container, while the ones that are not backslashed will be processed by the shell being run in the host machine BEFORE the commands are sent to the container.
It is, in theory, possible using data:
scheme URIs and frames, but that is rather a long way from practical.
You can fake it by hiding some content with JS and then revealing it when something is clicked (in the style of tabtastic).
You don't have to do a replace, you can get the length of the children text and subtract that from the overall length, and slice into the original text. That should be substantially faster.
Use this to force IE to hide that annoying browser compatibility button in the address bar:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
HERE=$(cd $(dirname $BASH_SOURCE) && pwd)
where you get the full path with new_path=$(dirname ${BASH_SOURCE[0]})
. You change current directory with cd
new_path and then run pwd
to get the full path to the current directory.
FPM is a process manager to manage the FastCGI SAPI (Server API) in PHP.
Basically, it replaces the need for something like SpawnFCGI. It spawns the FastCGI children adaptively (meaning launching more if the current load requires it).
Otherwise, there's not much operating difference between it and FastCGI (The request pipeline from start of request to end is the same). It's just there to make implementing it easier.
ES6 one liner. Clean and simple.
Object.fromEntries(new URLSearchParams(location.search));
For your specific case, it would be:
console.log(_x000D_
Object.fromEntries(new URLSearchParams('abc=foo&def=%5Basf%5D&xyz=5'))_x000D_
);
_x000D_
import UIKit
class ItemViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var nameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.nameTextField.delegate = self
}
// Called when 'return' key pressed. return NO to ignore.
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// Called when the user click on the view (outside the UITextField).
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
}
As dasblinkenlight already answered, the numbers come from the way that floating point numbers are represented in IEEE-754, and Andreas has a nice breakdown of the maths.
However - be careful that the precision of floating point numbers isn't exactly 6 or 15 significant decimal digits as the table suggests, since the precision of IEEE-754 numbers depends on the number of significant binary digits.
float
has 24 significant binary digits - which depending on the number represented translates to 6-8 decimal digits of precision.
double
has 53 significant binary digits, which is approximately 15 decimal digits.
Another answer of mine has further explanation if you're interested.
I like to concat a counter, then save the final value of the counter;
int counter = 0;
HashMap<String, String> m = new HashMap<String, String>();
for(int i = 0;i<items.length;i++)
{
m.put("firstname"+i, items.get(i).getFirstName());
counter = i;
}
m.put("recordCount",String.valueOf(counter));
Then when you want to retrieve:
int recordCount = Integer.parseInf(m.get("recordCount"));
for(int i =0 ;i<recordCount;i++)
{
System.out.println("First Name :" + m.get("firstname"+i));
}
This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array()
then pass the variable into your function, VBA will be happy.
Sub test()
Dim fString As String
Dim arr() As Variant
arr = Array("foo", "bar")
fString = processArr(arr)
End Sub
Also your function processArr()
could be written as:
Function processArr(arr() As Variant) As String
processArr = Replace(Join(arr()), " ", "")
End Function
If you are into the whole brevity thing.
Just write
System.Diagnostics.Process.Start(@"file path");
example
System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...
And shell will run associated program reading it from the registry, like usual double click does.
The way i do it is:
var obj = new Object();
obj.name = "Raj";
obj.age = 32;
obj.married = false;
var jsonString= JSON.stringify(obj);
I guess this way can reduce chances for errors.