Second approach is object initializer in C#
Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.
The first approach
var albumData = new Album("Albumius", "Artistus", 2013);
explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:
var albumData = new Album
{
Name = "Albumius",
};
Object initializer would translate into something like:
var albumData;
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;
Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.
As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.
Just to expand on pcperini's answer. As he mentions you will need to add the following code to your application:didFinishLaunchingWithOptions:
method;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
You Also need to increment then decrement the badge in your application:didReceiveRemoteNotification:
method if you are trying to clear the message from the message centre so that when a user enters you app from pressing a notification the message centre will also clear, ie;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
This worked for me
Deactivate AdBlock.
Go to inspect -> settings gear -> Uncheck 'enable javascript source maps' and 'enable css source map'.
Refresh.
Including the header afxwin.h
signalizes use of MFC. The following instructions (based on those on CodeProject.com) could help to get MFC code compiling:
Download and install the Windows Driver Kit.
Select menu Tools > Options… > Projects and Solutions > VC++ Directories.
In the drop-down menu Show directories for select Include files.
Add the following paths (replace $(WDK_directory)
with the directory where you installed Windows Driver Kit in the first step):
$(WDK_directory)\inc\mfc42
$(WDK_directory)\inc\atl30
In the drop-down menu Show directories for select Library files and add (replace $(WDK_directory)
like before):
$(WDK_directory)\lib\mfc\i386
$(WDK_directory)\lib\atl\i386
In the $(WDK_directory)\inc\mfc42\afxwin.inl
file, edit the following lines (starting from 1033):
_AFXWIN_INLINE CMenu::operator==(const CMenu& menu) const
{ return ((HMENU) menu) == m_hMenu; }
_AFXWIN_INLINE CMenu::operator!=(const CMenu& menu) const
{ return ((HMENU) menu) != m_hMenu; }
to
_AFXWIN_INLINE BOOL CMenu::operator==(const CMenu& menu) const
{ return ((HMENU) menu) == m_hMenu; }
_AFXWIN_INLINE BOOL CMenu::operator!=(const CMenu& menu) const
{ return ((HMENU) menu) != m_hMenu; }
In other words, add BOOL
after _AFXWIN_INLINE
.
There are a number of ways of achieving your result. If you're just wanting a solution for your case, use string multiplication as @Ant mentions. This is only going to work if each of your print
statements prints the same string. Note that it works for multiplication of any length string (e.g. 'foo' * 20
works).
>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa
If you want to do this in general, build up a string and then print it once. This will consume a bit of memory for the string, but only make a single call to print
. Note that string concatenation using +=
is now linear in the size of the string you're concatenating so this will be fast.
>>> for i in xrange(20):
... s += 'a'
...
>>> print s
aaaaaaaaaaaaaaaaaaaa
Or you can do it more directly using sys.stdout.write(), which print
is a wrapper around. This will write only the raw string you give it, without any formatting. Note that no newline is printed even at the end of the 20 a
s.
>>> import sys
>>> for i in xrange(20):
... sys.stdout.write('a')
...
aaaaaaaaaaaaaaaaaaaa>>>
Python 3 changes the print
statement into a print() function, which allows you to set an end
parameter. You can use it in >=2.6 by importing from __future__
. I'd avoid this in any serious 2.x code though, as it will be a little confusing for those who have never used 3.x. However, it should give you a taste of some of the goodness 3.x brings.
>>> from __future__ import print_function
>>> for i in xrange(20):
... print('a', end='')
...
aaaaaaaaaaaaaaaaaaaa>>>
var len = $('#your_form_id input:radio:checked').length;
if (!len) {
alert("None checked");
};
alert("checked: "+ len);
Use the below function.
function utf8_converter($array)
{
array_walk_recursive($array, function (&$item, $key) {
if (!mb_detect_encoding($item, 'utf-8', true)) {
$item = utf8_encode($item);
}
});
return $array;
}
use arrayOf, arrayOfNulls, emptyArray
var colors_1: Array<String> = arrayOf("green", "red", "blue")
var colors_2: Array<String?> = arrayOfNulls(3)
var colors_3: Array<String> = emptyArray()
There's no need to use jQuery to change the title. Try:
document.title = "blarg";
See this question for more details.
To dynamically change on button click:
$(selectorForMyButton).click(function(){
document.title = "blarg";
});
To dynamically change in loop, try:
var counter = 0;
var titleTimerId = setInterval(function(){
document.title = document.title + '>';
counter++;
if(counter == 5){
clearInterval(titleTimerId);
}
}, 100);
To string the two together so that it dynamically changes on button click, in a loop:
var counter = 0;
$(selectorForMyButton).click(function(){
titleTimerId = setInterval(function(){
document.title = document.title + '>';
counter++;
if(counter == 5){
clearInterval(titleTimerId);
}
}, 100);
});
SELECT
*
FROM
(SELECT MAX(PriceDate) AS MaxP, Partid FROM MyPrices GROUP BY Partid) MaxP
JOIN
MyPrices MP On MaxP.Partid = MP.Partid AND MaxP.MaxP = MP.PriceDate
JOIN
MyParts P ON MP.Partid = P.Partid
You to get the latest pricedate for partid first (a standard aggregate), then join it back to get the prices (which can't be in the aggregate), followed by getting the part details.
You can try this:
Me.cbo1.Text = Me.Cbo1.Items(0).Tostring
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '@Url.Action("Action", "EventstController")', window.close();
</script>
A JTable normally forms the View part of an MVC implementation. You'll want to remove rows from your model. The JTable, which should be listening for these changes, will update to reflect this removal. Hence you won't find removeRow() or similar as a method on JTable.
For an array of strings (but not an array of objects), you can check if an item exists by calling .indexOf()
and if it doesn't then just push the item into the array:
var newItem = "NEW_ITEM_TO_ARRAY";_x000D_
var array = ["OLD_ITEM_1", "OLD_ITEM_2"];_x000D_
_x000D_
array.indexOf(newItem) === -1 ? array.push(newItem) : console.log("This item already exists");_x000D_
_x000D_
console.log(array)
_x000D_
The string objects themselves are immutable.
The variable, a
, which points to the string, is mutable.
Consider:
a = "Foo"
# a now points to "Foo"
b = a
# b points to the same "Foo" that a points to
a = a + a
# a points to the new string "FooFoo", but b still points to the old "Foo"
print a
print b
# Outputs:
# FooFoo
# Foo
# Observe that b hasn't changed, even though a has.
Composition is just as it sounds - you create an object by plugging in parts.
EDIT the rest of this answer is erroneously based on the following premise.
This is accomplished with Interfaces.
For example, using the Car
example above,
Car implements iDrivable, iUsesFuel, iProtectsOccupants
Motorbike implements iDrivable, iUsesFuel, iShortcutThroughTraffic
House implements iProtectsOccupants
Generator implements iUsesFuel
So with a few standard theoretical components you can build up your object. It's then your job to fill in how a House
protects its occupants, and how a Car
protects its occupants.
Inheritance is like the other way around. You start off with a complete (or semi-complete) object and you replace or Override the various bits you want to change.
For example, MotorVehicle
may come with a Fuelable
method and Drive
method. You may leave the Fuel method as it is because it's the same to fill up a motorbike and a car, but you may override the Drive
method because the Motorbike drives very differently to a Car
.
With inheritance, some classes are completely implemented already, and others have methods that you are forced to override. With Composition nothing's given to you. (but you can Implement the interfaces by calling methods in other classes if you happen to have something laying around).
Composition is seen as more flexible, because if you have a method such as iUsesFuel, you can have a method somewhere else (another class, another project) that just worries about dealing with objects that can be fueled, regardless of whether it's a car, boat, stove, barbecue, etc. Interfaces mandate that classes that say they implement that interface actually have the methods that that interface is all about. For example,
iFuelable Interface:
void AddSomeFuel()
void UseSomeFuel()
int percentageFull()
then you can have a method somewhere else
private void FillHerUp(iFuelable : objectToFill) {
Do while (objectToFill.percentageFull() <= 100) {
objectToFill.AddSomeFuel();
}
Strange example, but it's shows that this method doesn't care what it's filling up, because the object implements iUsesFuel
, it can be filled. End of story.
If you used Inheritance instead, you would need different FillHerUp
methods to deal with MotorVehicles
and Barbecues
, unless you had some rather weird "ObjectThatUsesFuel" base object from which to inherit.
I had same issue but problem went off after going back and fixing DbContext
incorrect syntax issue such as it should have been ExampleDbContextClass: DbContext
whereas I had missed DbContext
part in Context Class where you define your DbSet
. Also, I verified following dependencies are needed in order to achieve connection to SqlServer.
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" />
Also verify that Version you install is less than your project's current version to be on safe side. Such as if your project is using 3.1 do not try to use newer one which would be for example 3.1.9. I had issue with that too.
I would like to recommend using the scrollTo plugin
http://demos.flesler.com/jquery/scrollTo/
You can the set scrollto by jquery css selector.
$('html,body').scrollTo( $(target), 800 );
I have had great luck with the accuracy of this plugin and its methods, where other methods of achieving the same effect like using .offset()
or .position()
have failed to be cross browser for me in the past. Not saying you can't use such methods, I'm sure there is a way to do it cross browser, I've just found scrollTo to be more reliable.
Convert an ArrayList to an object array
ArrayList has a constructor that takes a Collection, so the common idiom is:
List<T> list = new ArrayList<T>(Arrays.asList(array));
Which constructs a copy of the list created by the array.
now, Arrays.asList(array)
will wrap the array, so changes to the list
will affect the array, and visa versa. Although you can't add or remove
i will get my answer as follow:
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class findclass {
public static void main(String[] args) throws Exception, IllegalAccessException {
new findclass().findclass(new Object(), "objectName");
new findclass().findclass(1213, "int");
new findclass().findclass("ssdfs", "String");
}
public Map<String, String>map=new HashMap<String, String>();
public void findclass(Object c,String name) throws IllegalArgumentException, IllegalAccessException {
if(map.containsKey(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))){
System.out.println(c.getClass().getSimpleName()+" "+name+" = "+map.get(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))+" = "+c);
return;}
map.put(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()), name);
Class te=c.getClass();
if(te.equals(Integer.class)||te.equals(Double.class)||te.equals(Float.class)||te.equals(Boolean.class)||te.equals(Byte.class)||te.equals(Long.class)||te.equals(String.class)||te.equals(Character.class)){
System.out.println(c.getClass().getSimpleName()+" "+name+" = "+c);
return;
}
if(te.isArray()){
if(te==int[].class||te==char[].class||te==double[].class||te==float[].class||te==byte[].class||te==long[].class||te==boolean[].class){
boolean dotflag=true;
for (int i = 0; i < Array.getLength(c); i++) {
System.out.println(Array.get(c, i).getClass().getSimpleName()+" "+name+"["+i+"] = "+Array.get(c, i));
}
return;
}
Object[]arr=(Object[])c;
for (Object object : arr) {
if(object==null)
System.out.println(c.getClass().getSimpleName()+" "+name+" = null");
else {
findclass(object, name+"."+object.getClass().getSimpleName());
}
}
}
Field[] fields=c.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if(field.get(c)==null){
System.out.println(field.getType().getSimpleName()+" "+name+"."+field.getName()+" = null");
continue;
}
findclass(field.get(c),name+"."+field.getName());
}
if(te.getSuperclass()==Number.class||te.getSuperclass()==Object.class||te.getSuperclass()==null)
return;
Field[]faFields=c.getClass().getSuperclass().getDeclaredFields();
for (Field field : faFields) {
field.setAccessible(true);
if(field.get(c)==null){
System.out.println(field.getType().getSimpleName()+" "+name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName()+" = null");
continue;
}
Object check=field.get(c);
findclass(field.get(c),name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName());
}
}
public void findclass(Object c,String name,Writer writer) throws IllegalArgumentException, IllegalAccessException, IOException {
if(map.containsKey(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))){
writer.append(c.getClass().getSimpleName()+" "+name+" = "+map.get(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()))+" = "+c+"\n");
return;}
map.put(c.getClass().getName() + "@" + Integer.toHexString(c.hashCode()), name);
Class te=c.getClass();
if(te.equals(Integer.class)||te.equals(Double.class)||te.equals(Float.class)||te.equals(Boolean.class)||te.equals(Byte.class)||te.equals(Long.class)||te.equals(String.class)||te.equals(Character.class)){
writer.append(c.getClass().getSimpleName()+" "+name+" = "+c+"\n");
return;
}
if(te.isArray()){
if(te==int[].class||te==char[].class||te==double[].class||te==float[].class||te==byte[].class||te==long[].class||te==boolean[].class){
boolean dotflag=true;
for (int i = 0; i < Array.getLength(c); i++) {
writer.append(Array.get(c, i).getClass().getSimpleName()+" "+name+"["+i+"] = "+Array.get(c, i)+"\n");
}
return;
}
Object[]arr=(Object[])c;
for (Object object : arr) {
if(object==null){
writer.append(c.getClass().getSimpleName()+" "+name+" = null"+"\n");
}else {
findclass(object, name+"."+object.getClass().getSimpleName(),writer);
}
}
}
Field[] fields=c.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if(field.get(c)==null){
writer.append(field.getType().getSimpleName()+" "+name+"."+field.getName()+" = null"+"\n");
continue;
}
findclass(field.get(c),name+"."+field.getName(),writer);
}
if(te.getSuperclass()==Number.class||te.getSuperclass()==Object.class||te.getSuperclass()==null)
return;
Field[]faFields=c.getClass().getSuperclass().getDeclaredFields();
for (Field field : faFields) {
field.setAccessible(true);
if(field.get(c)==null){
writer.append(field.getType().getSimpleName()+" "+name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName()+" = null"+"\n");
continue;
}
Object check=field.get(c);
findclass(field.get(c),name+"<"+c.getClass().getSuperclass().getSimpleName()+"."+field.getName(),writer);
}
}
}
Mike's solution will just show the image, but any title set on the button will not be visible, because you can either set the title or the image.
If you want to set both (your image and title) use the following code:
btnImage = [UIImage imageNamed:@"image.png"];
[btnTwo setBackgroundImage:btnImage forState:UIControlStateNormal];
[btnTwo setTitle:@"Title" forState:UIControlStateNormal];
For "Visual Studio Team Test" it appears you apply the ExpectedException attribute to the test's method.
Sample from the documentation here: A Unit Testing Walkthrough with Visual Studio Team Test
[TestMethod]
[ExpectedException(typeof(ArgumentException),
"A userId of null was inappropriately allowed.")]
public void NullUserIdInConstructor()
{
LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");
}
SELECT b.Emp_id, b.Emp_name,e.emp_id as managerID, e.emp_name as managerName
FROM Employee b
JOIN Employee e ON b.Emp_ID = e.emp_mgr_id
Try this, it's a JOIN on itself to get the manager :)
Although as other answers here have said you can change the "Output type" to "Windows Application", please be aware that this will mean that you cannot use Console.In
as it will become a NullStreamReader.
Console.Out
and Console.Error
seem to still work fine however.
Objects in JavaScript inherit directly from objects. What can be more object oriented?
It's much easier if you use Response.raw
and shutil.copyfileobj()
:
import requests
import shutil
def download_file(url):
local_filename = url.split('/')[-1]
with requests.get(url, stream=True) as r:
with open(local_filename, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return local_filename
This streams the file to disk without using excessive memory, and the code is simple.
Because it's not.
Indexing is covered by IList
. IEnumerable
means "I have some of the powers of IList, but not all of them."
Some collections (like a linked list), cannot be indexed in a practical way. But they can be accessed item-by-item. IEnumerable
is intended for collections like that. Note that a collection can implement both IList & IEnumerable (and many others). You generally only find IEnumerable
as a function parameter, meaning the function can accept any kind of collection, because all it needs is the simplest access mode.
You can trigger Lambda functions directly from other Lambda functions directly in an asynchronous manner.
https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations
Just in case someone really needs a closure like that, it can be done in the following way:
var categoriesPerPage = [[Int]]()
var numPagesClosure: ()->Int {
return {
return self.categoriesPerPage.count
}
}
PrincipalContext pc1 = new PrincipalContext(ContextType.Domain, "DomainName", UserAccountOU, UserName, Password);
UserPrincipal UserPrincipalID = UserPrincipal.FindByIdentity(pc1, IdentityType.SamAccountName, UserID);
searcher.Filter = "(&(ObjectClass=group)(member = " + UserPrincipalID.DistinguishedName + "));
It hasn't been mentioned yet, so I'll write it for posterity:
If you're migrating between DB servers (or have another reason you'd dump and reload your dta), you can just modify the output from mysqldump
:
mysqldump --no-data DBNAME | sed 's/ENGINE=MyISAM/ENGINE=InnoDB/' > my_schema.sql;
mysqldump --no-create-info DBNAME > my_data.sql;
Then load it again:
mysql DBNAME < my_schema.sql && mysql DBNAME < my_data.sql
(Also, in my limited experience, this can be a much faster process than altering the tables ‘live’. It probably depends on the type of data and indexes.)
In C++, struct
s do not have a comparison operator generated by default. You need to write your own:
bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
return /* your comparison code goes here */
}
In my case, installing visual studio SP1 unbroke the uninstall/repair functionality.
This is completely new working code with sample AJAX call.
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
<div>
<div id="project-label">Select a project (type "j" for a start):</div>
<img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="" />
<input id="project" />
<input type="hidden" id="project-i" />
</div>
@*Auto Complete*@
<script>
$(function () {
$("#project").autocomplete({
minLength: 0,
source : function( request, response ) {
$.ajax({
url: "http://jsonplaceholder.typicode.com/posts/1/comments",
dataType: "jsonp",
data: {
q: request.term
},
success: function (data) {
response( data );
}
});
},
focus: function (event, ui) {
$("#project").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#project").val(ui.item.name);
$("#project-id").val(ui.item.email);
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("ui-autocomplete-item", item)
.append("<a> " + item.name + "<br>" + item.email + "</a>")
.appendTo(ul);
};
});
</script>
I think there is a lot of confusion about which weights are used for what. I am not sure I know precisely what bothers you so I am going to cover different topics, bear with me ;).
The weights from the class_weight
parameter are used to train the classifier.
They are not used in the calculation of any of the metrics you are using: with different class weights, the numbers will be different simply because the classifier is different.
Basically in every scikit-learn classifier, the class weights are used to tell your model how important a class is. That means that during the training, the classifier will make extra efforts to classify properly the classes with high weights.
How they do that is algorithm-specific. If you want details about how it works for SVC and the doc does not make sense to you, feel free to mention it.
Once you have a classifier, you want to know how well it is performing.
Here you can use the metrics you mentioned: accuracy
, recall_score
, f1_score
...
Usually when the class distribution is unbalanced, accuracy is considered a poor choice as it gives high scores to models which just predict the most frequent class.
I will not detail all these metrics but note that, with the exception of accuracy
, they are naturally applied at the class level: as you can see in this print
of a classification report they are defined for each class. They rely on concepts such as true positives
or false negative
that require defining which class is the positive one.
precision recall f1-score support
0 0.65 1.00 0.79 17
1 0.57 0.75 0.65 16
2 0.33 0.06 0.10 17
avg / total 0.52 0.60 0.51 50
F1 score:/usr/local/lib/python2.7/site-packages/sklearn/metrics/classification.py:676: DeprecationWarning: The
default `weighted` averaging is deprecated, and from version 0.18,
use of precision, recall or F-score with multiclass or multilabel data
or pos_label=None will result in an exception. Please set an explicit
value for `average`, one of (None, 'micro', 'macro', 'weighted',
'samples'). In cross validation use, for instance,
scoring="f1_weighted" instead of scoring="f1".
You get this warning because you are using the f1-score, recall and precision without defining how they should be computed! The question could be rephrased: from the above classification report, how do you output one global number for the f1-score? You could:
avg / total
result above. It's also called macro averaging.'weighted'
in scikit-learn will weigh the f1-score by the support of the class: the more elements a class has, the more important the f1-score for this class in the computation.These are 3 of the options in scikit-learn, the warning is there to say you have to pick one. So you have to specify an average
argument for the score method.
Which one you choose is up to how you want to measure the performance of the classifier: for instance macro-averaging does not take class imbalance into account and the f1-score of class 1 will be just as important as the f1-score of class 5. If you use weighted averaging however you'll get more importance for the class 5.
The whole argument specification in these metrics is not super-clear in scikit-learn right now, it will get better in version 0.18 according to the docs. They are removing some non-obvious standard behavior and they are issuing warnings so that developers notice it.
Last thing I want to mention (feel free to skip it if you're aware of it) is that scores are only meaningful if they are computed on data that the classifier has never seen. This is extremely important as any score you get on data that was used in fitting the classifier is completely irrelevant.
Here's a way to do it using StratifiedShuffleSplit
, which gives you a random splits of your data (after shuffling) that preserve the label distribution.
from sklearn.datasets import make_classification
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix
# We use a utility to generate artificial classification data.
X, y = make_classification(n_samples=100, n_informative=10, n_classes=3)
sss = StratifiedShuffleSplit(y, n_iter=1, test_size=0.5, random_state=0)
for train_idx, test_idx in sss:
X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
svc.fit(X_train, y_train)
y_pred = svc.predict(X_test)
print(f1_score(y_test, y_pred, average="macro"))
print(precision_score(y_test, y_pred, average="macro"))
print(recall_score(y_test, y_pred, average="macro"))
Hope this helps.
While editing the file, make marks where you want the start and end to be using
ma
- sets the a
mark
mb
- sets the b
mark
Then, to copy that into another file, just use the w
command:
:'a,'bw /name/of/output/file.txt
To avoid that issue, when incrementing time you should convert back to UTC and then add or subtract.
This way you will be able to walk through any periods where hours or minutes happen twice.
If you converted to UTC, add each second, and convert to local time for display. You would go through 11:54:08 p.m. LMT - 11:59:59 p.m. LMT and then 11:54:08 p.m. CST - 11:59:59 p.m. CST.
So here I am, once again, not satisfied with the answer. I was tasked to upgrade JIRA 6.4.x to JIRA Software 7.x and I went to that particular problem with the database and column collation.
In SQL Server, if you do not drop constrains such as primary key or foreign key or even indexes, the script provided above as an answer doesn't work at all. It will however change those without those properties. This is really problematic, because I don't want to manually drop all constrains and create them back. That operation could probably ends up with errors. On the other side, creating a script automating the change could take ages to make.
So I found a way to make the migration simply by using SQL Management Studio. Here's the procedure:
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
exec sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
Once completed, I've restarted JIRA and my database collation was in order. Hope it helps a lot of people!
Found answer in similar question - Rendering Nullable Bool as CheckBox. It's very straightforward and just works:
@Html.CheckBox("RFP.DatesFlexible", Model.RFP.DatesFlexible ?? false)
@Html.Label("RFP.DatesFlexible", "My Dates are Flexible")
It's like accepted answer from @afinkelstein except we don't need special 'editor template'
use this dependency:
toast: ^0.1.3
then import the dependency of toast in the page :
import 'package:toast/toast.dart';
then on onTap() of the widget:
Toast.show("Toast plugin app", context,duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
In addition to the above you can use the System.exit()
to return an exit code which may be very usuefull specially if your calling the process automatically using the System.exit(code);
this can help you determine for example if an error has occured during the run.
You can revert uncommitted changes only to particular file or directory:
git checkout [some_dir|file.txt]
This is not an answer to your original question: "Appending output of a Batch file To log file?"
For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"
(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")
Timeout:
Example (1 second):
TIMEOUT /T 1000 /NOBREAK
Sleep:
Example (1 second):
sleep -m 1000
Alternative methods:
Here's an answer to your 2nd followup question: "Along with the Timestamp?"
Create a date and time stamp in your batch files
Example:
echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log
This thing works well.It put radio button or checkbox with label in same line without any css.
<label><input type="radio" value="new" name="filter">NEW</label>
<label><input type="radio" value="wow" name="filter">WOW</label>
This works for me :
$scope.array1 = $scope.array1.concat(array2)
In your case it would be :
$scope.actions.data = $scope.actions.data.concat(data)
For Python3 the following code grabs the word list from the web and returns a list. Answer based on accepted answer above by Kyle Kelley.
import urllib.request
word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_url)
long_txt = response.read().decode()
words = long_txt.splitlines()
Output:
>>> words
['a', 'AAA', 'AAAS', 'aardvark', 'Aarhus', 'Aaron', 'ABA', 'Ababa',
'aback', 'abacus', 'abalone', 'abandon', 'abase', 'abash', 'abate',
'abbas', 'abbe', 'abbey', 'abbot', 'Abbott', 'abbreviate', ... ]
And to generate (because it was my objective) a list of 1) upper case only words, 2) only "name like" words, and 3) a sort-of-realistic-but-fun sounding random name:
import random
upper_words = [word for word in words if word[0].isupper()]
name_words = [word for word in upper_words if not word.isupper()]
rand_name = ' '.join([name_words[random.randint(0, len(name_words))] for i in range(2)])
And some random names:
>>> for n in range(10):
' '.join([name_words[random.randint(0,len(name_words))] for i in range(2)])
'Semiramis Sicilian'
'Julius Genevieve'
'Rwanda Cohn'
'Quito Sutherland'
'Eocene Wheller'
'Olav Jove'
'Weldon Pappas'
'Vienna Leyden'
'Io Dave'
'Schwartz Stromberg'
I've been pulling my hair out over this one for a couple of hours also. fakeartist appears correct though - I changed the file extension from .htm to .php and I can now see my page in Facebook! It also works if you change the extension to .aspx - perhaps it just needs to be a server side extension (I've not tried with .jsp).
I think the real answer to the OP's question is succinctly contained in this excerpt from the Numpy.correlate documentation:
mode : {'valid', 'same', 'full'}, optional
Refer to the `convolve` docstring. Note that the default
is `valid`, unlike `convolve`, which uses `full`.
This implies that, when used with no 'mode' definition, the Numpy.correlate function will return a scalar, when given the same vector for its two input arguments (i.e. - when used to perform autocorrelation).
Use this:
mocha server-test
Or if you have subdirectories use this:
mocha "server-test/**/*.js"
Note the use of double quotes. If you omit them you may not be able to run tests in subdirectories.
results = context.Orders.Where(o => o.OrderDate <= today && today <= o.OrderDate)
The select is uneeded as you are already working with an order.
you can use android:inputType="textMultiLine"
<TextView android:id="@+id/address1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:maxLines="4"
android:inputType="textMultiLine"
android:text="Johar Mor, Gulistan-e-Johar, Karachi" />
try this ..
<input type="submit" value="submit" name="submit" id="submit">
$(document).ready(function () {
$('#submit').click(function () {
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
});
});
In addition to the answer of eldos I also needed gcc
in CentOS 7:
yum install libcurl-devel gcc
the cross browser code is:
$(window).scrollTop(300);
it is without animation but works everywhere
Solution:
var answerInt = [];
var answerString = "1,2,3,4";
answerString.split(',').forEach(function (item) {
answerInt.push(parseInt(item))
});
You can use lsof -i:3000
.
That is "List Open Files". This gives you a list of the processes and which files and ports they use.
There is a pretty library at http://256stuff.com/sources/md5/, with example of use. This is the simplest library for MD5.
Worked for me perfectly as this:
Trims all selected cells. Beware of selecting full columns/rows :P.
Sub TrimSelected()
Dim rng As Range, cell As Range
Set rng = Selection
For Each cell In rng
cell = Trim(cell)
Next cell
End Sub
You can try U2U Query Builder http://www.u2u.net/res/Tools/CamlQueryBuilder.aspx you can use their API U2U.SharePoint.CAML.Server.dll and U2U.SharePoint.CAML.Client.dll
I didn't use them but I'm sure it will help you achieving your task.
The API doc for IllegalArgumentException
:
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
From looking at how it is used in the JDK libraries, I would say:
It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.
It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).
I would use IllegalArgumentException
to do last ditch defensive argument checking for common utilities (trying to stay consistent with the JDK usage). Or where the expectation is that a bad argument is a programmer error, similar to an NullPointerException
. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.
Make a temporary table (tempP) from a subquery
UPDATE pers P
SET P.gehalt = P.gehalt * 1.05
WHERE P.persID IN (
SELECT tempP.tempId
FROM (
SELECT persID as tempId
FROM pers P
WHERE
P.chefID IS NOT NULL OR gehalt <
(SELECT (
SELECT MAX(gehalt * 1.05)
FROM pers MA
WHERE MA.chefID = MA.chefID)
AS _pers
)
) AS tempP
)
I've introduced a separate name (alias) and give a new name to 'persID' column for temporary table
Though @Test(expected = MyException.class)
and the ExpectedException rule are very good choices, there are some instances where the JUnit3-style exception catching is still the best way to go:
@Test public void yourTest() {
try {
systemUnderTest.doStuff();
fail("MyException expected.");
} catch (MyException expected) {
// Though the ExpectedException rule lets you write matchers about
// exceptions, it is sometimes useful to inspect the object directly.
assertEquals(1301, expected.getMyErrorCode());
}
// In both @Test(expected=...) and ExpectedException code, the
// exception-throwing line will be the last executed line, because Java will
// still traverse the call stack until it reaches a try block--which will be
// inside the JUnit framework in those cases. The only way to prevent this
// behavior is to use your own try block.
// This is especially useful to test the state of the system after the
// exception is caught.
assertTrue(systemUnderTest.isInErrorState());
}
Another library that claims to help here is catch-exception; however, as of May 2014, the project appears to be in maintenance mode (obsoleted by Java 8), and much like Mockito catch-exception can only manipulate non-final
methods.
Coupled with reflection, I found Activator.CreateInstance to be very helpful in mapping stored procedure result to a custom class as described in the following answer.
Do I need to double the size of the .box div to 400px by 400px to match the new high res background image
No, but you do need to set the background-size
property to match the original dimensions:
@media (-webkit-min-device-pixel-ratio: 2),
(min-resolution: 192dpi) {
.box{
background:url('images/[email protected]') no-repeat top left;
background-size: 200px 200px;
}
}
EDIT
To add a little more to this answer, here is the retina detection query I tend to use:
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and ( min--moz-device-pixel-ratio: 2),
only screen and ( -o-min-device-pixel-ratio: 2/1),
only screen and ( min-device-pixel-ratio: 2),
only screen and ( min-resolution: 192dpi),
only screen and ( min-resolution: 2dppx) {
}
NB. This min--moz-device-pixel-ratio:
is not a typo. It is a well documented bug in certain versions of Firefox and should be written like this in order to support older versions (prior to Firefox 16).
- Source
As @LiamNewmarch mentioned in the comments below, you can include the background-size
in your shorthand background
declaration like so:
.box{
background:url('images/[email protected]') no-repeat top left / 200px 200px;
}
However, I personally would not advise using the shorthand form as it is not supported in iOS <= 6 or Android making it unreliable in most situations.
The easiest is probably to create a PKCS#12 file using OpenSSL:
openssl pkcs12 -export -in abc.crt -inkey abc.key -out abc.p12
You should be able to use the resulting file directly using the PKCS12
keystore type.
If you really need to, you can convert it to JKS using keytool -importkeystore
(available in keytool
from Java 6):
keytool -importkeystore -srckeystore abc.p12 \
-srcstoretype PKCS12 \
-destkeystore abc.jks \
-deststoretype JKS
First off, the facts:
if (booleanValue)
Will satisfy the if
statement for any truthy value of booleanValue
including true
, any non-zero number, any non-empty string value, any object or array reference, etc...
On the other hand:
if (booleanValue === true)
This will only satisfy the if
condition if booleanValue
is exactly equal to true
. No other truthy value will satisfy it.
On the other hand if you do this:
if (someVar == true)
Then, what Javascript will do is type coerce true
to match the type of someVar
and then compare the two variables. There are lots of situations where this is likely not what one would intend. Because of this, in most cases you want to avoid ==
because there's a fairly long set of rules on how Javascript will type coerce two things to be the same type and unless you understand all those rules and can anticipate everything that the JS interpreter might do when given two different types (which most JS developers cannot), you probably want to avoid ==
entirely.
As an example of how confusing it can be:
var x;_x000D_
_x000D_
x = 0;_x000D_
console.log(x == true); // false, as expected_x000D_
console.log(x == false); // true as expected_x000D_
_x000D_
x = 1;_x000D_
console.log(x == true); // true, as expected_x000D_
console.log(x == false); // false as expected_x000D_
_x000D_
x = 2;_x000D_
console.log(x == true); // false, ??_x000D_
console.log(x == false); // false
_x000D_
For the value 2
, you would think that 2
is a truthy value so it would compare favorably to true
, but that isn't how the type coercion works. It is converting the right hand value to match the type of the left hand value so its converting true
to the number 1
so it's comparing 2 == 1
which is certainly not what you likely intended.
So, buyer beware. It's likely best to avoid ==
in nearly all cases unless you explicitly know the types you will be comparing and know how all the possible types coercion algorithms work.
So, it really depends upon the expected values for booleanValue
and how you want the code to work. If you know in advance that it's only ever going to have a true
or false
value, then comparing it explicitly with
if (booleanValue === true)
is just extra code and unnecessary and
if (booleanValue)
is more compact and arguably cleaner/better.
If, on the other hand, you don't know what booleanValue
might be and you want to test if it is truly set to true
with no other automatic type conversions allowed, then
if (booleanValue === true)
is not only a good idea, but required.
For example, if you look at the implementation of .on()
in jQuery, it has an optional return value. If the callback returns false
, then jQuery will automatically stop propagation of the event. In this specific case, since jQuery wants to ONLY stop propagation if false
was returned, they check the return value explicity for === false
because they don't want undefined
or 0
or ""
or anything else that will automatically type-convert to false to also satisfy the comparison.
For example, here's the jQuery event handling callback code:
ret = ( specialHandle || handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
You can see that jQuery is explicitly looking for ret === false
.
But, there are also many other places in the jQuery code where a simpler check is appropriate given the desire of the code. For example:
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
...
This is not possible.
Instead, you should create a fake window in Javascript, using something like jQuery UI Dialog.
If you are using Gradle then you can find the line that applies the java plugin:
apply plugin: 'java'
Then set the encoding for the compile task to be UTF-8:
compileJava {options.encoding = "UTF-8"}
If you have unit tests, then you probably want to compile those with UTF-8 too:
compileTestJava {options.encoding = "UTF-8"}
This means that the overall gradle code would look something like this:
apply plugin: 'java'
compileJava {options.encoding = "UTF-8"}
compileTestJava {options.encoding = "UTF-8"}
In order to have completely custom facebook login button without using com.facebook.widget.LoginButton
.
According to facebook sdk 4.x,
There new concept of login as from facebook
LoginManager and AccessToken - These new classes perform Facebook Login
So, Now you can access Facebook authentication without Facebook login button as
layout.xml
<Button
android:id="@+id/btn_fb_login"
.../>
MainActivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
}
@Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();
}
@Override
public void onError(FacebookException exception) {
Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
setContentView(R.layout.activity_main);
Button btn_fb_login = (Button)findViewById(R.id.btn_fb_login);
btn_fb_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile", "user_friends"));
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
Set JAVA_HOME and PATH, Open Command line with admin rights, Run in command line >>netbeans-6.5.1-ml-windows.exe --extract, Run in command line >>java -jar bundle.jar
With PostgreSQL there is the ANY
or ALL
form:
WHERE col LIKE ANY( subselect )
or
WHERE col LIKE ALL( subselect )
where the subselect returns exactly one column of data.
For python, there is PDFMiner and pyPDF2. For more information on these, see Python module for converting PDF to text.
EDIT: I can see that this is listed under your first edit link as "the GDI way". This is still a decent way to go even with the performance advisory on that site, you can get to 30fps easily I would think.
From this comment (I have no experience doing this, I'm just referencing someone who does):
HDC hdc = GetDC(NULL); // get the desktop device context
HDC hDest = CreateCompatibleDC(hdc); // create a device context to use yourself
// get the height and width of the screen
int height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
int width = GetSystemMetrics(SM_CXVIRTUALSCREEN);
// create a bitmap
HBITMAP hbDesktop = CreateCompatibleBitmap( hdc, width, height);
// use the previously created device context with the bitmap
SelectObject(hDest, hbDesktop);
// copy from the desktop device context to the bitmap device context
// call this once per 'frame'
BitBlt(hDest, 0,0, width, height, hdc, 0, 0, SRCCOPY);
// after the recording is done, release the desktop context you got..
ReleaseDC(NULL, hdc);
// ..delete the bitmap you were using to capture frames..
DeleteObject(hbDesktop);
// ..and delete the context you created
DeleteDC(hDest);
I'm not saying this is the fastest, but the BitBlt
operation is generally very fast if you're copying between compatible device contexts.
For reference, Open Broadcaster Software implements something like this as part of their "dc_capture" method, although rather than creating the destination context hDest
using CreateCompatibleDC
they use an IDXGISurface1
, which works with DirectX 10+. If there is no support for this they fall back to CreateCompatibleDC
.
To change it to use a specific application, you need to change the first line to GetDC(game)
where game
is the handle of the game's window, and then set the right height
and width
of the game's window too.
Once you have the pixels in hDest/hbDesktop, you still need to save it to a file, but if you're doing screen capture then I would think you would want to buffer a certain number of them in memory and save to the video file in chunks, so I will not point to code for saving a static image to disk.
In Python, creating a new object is often better than modifying an existing one:
item_list = ['item', 5, 'foo', 3.14, True]
item_list = [e for e in item_list if e not in ('item', 5)]
Which is equivalent to:
item_list = ['item', 5, 'foo', 3.14, True]
new_list = []
for e in item_list:
if e not in ('item', 5):
new_list.append(e)
item_list = new_list
In case of a big list of filtered out values (here, ('item', 5)
is a small set of elements), using a set
is faster as the in
operation is O(1) time complexity on average. It's also a good idea to build the iterable you're removing first, so that you're not creating it on every iteration of the list comprehension:
unwanted = {'item', 5}
item_list = [e for e in item_list if e not in unwanted]
A bloom filter is also a good solution if memory is not cheap.
@list($url) = explode("?", $url, 2);
You could break by RETURN
. For example
def a = [1, 2, 3, 4, 5, 6, 7]
def ret = 0
a.each {def n ->
if (n > 5) {
ret = n
return ret
}
}
It works for me!
if somehow you don't wanna use String split method then you can use StringTokenizer class in Java as..
StringTokenizer tokens = new StringTokenizer("Hello I'm your String", " ");
String[] splited = new String[tokens.countTokens()];
int index = 0;
while(tokens.hasMoreTokens()){
splited[index] = tokens.nextToken();
++index;
}
The Algorithm for given flow chart :
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Step :01
Step :02 [Variable initialization]
Step :03[Condition Check]
Step:04
This is what I use to control headers/caching, I'm not an Apache pro, so let me know if there is room for improvement, but I know that this has been working well on all of my sites for some time now.
http://httpd.apache.org/docs/2.2/mod/mod_expires.html
This module controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses. The expiration date can set to be relative to either the time the source file was last modified, or to the time of the client access.
These HTTP headers are an instruction to the client about the document's validity and persistence. If cached, the document may be fetched from the cache rather than from the source until this time has passed. After that, the cache copy is considered "expired" and invalid, and a new copy must be obtained from the source.
# BEGIN Expires
<ifModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 seconds"
ExpiresByType text/html "access plus 1 seconds"
ExpiresByType image/gif "access plus 2592000 seconds"
ExpiresByType image/jpeg "access plus 2592000 seconds"
ExpiresByType image/png "access plus 2592000 seconds"
ExpiresByType text/css "access plus 604800 seconds"
ExpiresByType text/javascript "access plus 216000 seconds"
ExpiresByType application/x-javascript "access plus 216000 seconds"
</ifModule>
# END Expires
http://httpd.apache.org/docs/2.2/mod/mod_headers.html
This module provides directives to control and modify HTTP request and response headers. Headers can be merged, replaced or removed.
# BEGIN Caching
<ifModule mod_headers.c>
<filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
<filesMatch "\.(css)$">
Header set Cache-Control "max-age=604800, public"
</filesMatch>
<filesMatch "\.(js)$">
Header set Cache-Control "max-age=216000, private"
</filesMatch>
<filesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=216000, public, must-revalidate"
</filesMatch>
<filesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=1, private, must-revalidate"
</filesMatch>
</ifModule>
# END Caching
The answer above is causing an error in my build environment.
This doesn't work in Swift 4.0:
attributedText.addAttribute(NSUnderlineStyleAttributeName,
value: NSUnderlineStyle.styleSingle.rawValue,
range: textRange)
Try this instead:
attributedText.addAttribute(NSAttributedStringKey.underlineStyle,
value: NSUnderlineStyle.styleSingle.rawValue,
range: textRange)
hope this helps someone.
Old question I know. You don't need to convert it. See this function:
function getType( oObj )
{
if( typeof oObj === "object" )
{
return ( oObj === null )?'Null':
// Check if it is an alien object, for example created as {world:'hello'}
( typeof oObj.constructor !== "function" )?'Object':
// else return object name (string)
oObj.constructor.name;
}
// Test simple types (not constructed types)
return ( typeof oObj === "boolean")?'Boolean':
( typeof oObj === "number")?'Number':
( typeof oObj === "string")?'String':
( typeof oObj === "function")?'Function':false;
};
Examples:
function MyObject() {}; // Just for example
console.log( getType( new String( "hello ") )); // String
console.log( getType( new Function() ); // Function
console.log( getType( {} )); // Object
console.log( getType( [] )); // Array
console.log( getType( new MyObject() )); // MyObject
var bTest = false,
uAny, // Is undefined
fTest function() {};
// Non constructed standard types
console.log( getType( bTest )); // Boolean
console.log( getType( 1.00 )); // Number
console.log( getType( 2000 )); // Number
console.log( getType( 'hello' )); // String
console.log( getType( "hello" )); // String
console.log( getType( fTest )); // Function
console.log( getType( uAny )); // false, cannot produce
// a string
Low cost and simple.
Maybe powershell -Command "Get-AppLockerFileInformation....."
Take a look at powershell /?
I faced this problem
Forbidden You don't have permission to access /phpmyadmin/ on this server
Some help about this:
First check you installed a fresh wamp or replace the existing one. If it's fresh there is no problem, For done existing installation.
Follow these steps.
getline
, as it name states, read a whole line, or at least till a delimiter that can be specified.
So the answer is "no", getline
does not match your need.
But you can do something like:
inFile >> first_name >> last_name >> age;
name = first_name + " " + last_name;
If you're doing jQuery, and you've got a serializeArray thing going on concerning your form data, such as :
var postData = $('#yourform').serializeArray();
// postData (array with objects) :
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, etc]
...and you need to add a key/value to this array with the same structure, for instance when posting to a PHP ajax request then this :
postData.push({"name": "phone", "value": "1234-123456"});
Result:
// postData :
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, {"name":"phone","value":"1234-123456"}]
Laravel does not need mcrypt
extension anymore. mcrypt
is obsolete, the last update to libmcrypt was in 2007. Laravel 4.2 is obsolete too and has no more support. The best (=secure) solution is to update to Laravel >5.1 (there is no LTS before Laravel 5.2).
Mcrypt was removed from Laravel in June 2015: https://github.com/laravel/framework/pull/9041
There could be 3 solution from this posting and other stackoverflow article.
Solution 1
var lastScrollTop = 0;
$(window).on('scroll', function() {
st = $(this).scrollTop();
if(st < lastScrollTop) {
console.log('up 1');
}
else {
console.log('down 1');
}
lastScrollTop = st;
});
Solution 2
$('body').on('DOMMouseScroll', function(e){
if(e.originalEvent.detail < 0) {
console.log('up 2');
}
else {
console.log('down 2');
}
});
Solution 3
$('body').on('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
console.log('up 3');
}
else {
console.log('down 3');
}
});
I couldn't tested it on Safari
chrome 42 (Win 7)
Firefox 37 (Win 7)
IE 11 (Win 8)
IE 10 (Win 7)
IE 9 (Win 7)
IE 8 (Win 7)
I checked that side effect from IE 11 and IE 8 is come from
if else
statement. So, I replaced it withif else if
statement as following.
From the multi browser test, I decided to use Solution 3 for common browsers and Solution 1 for firefox and IE 11.
I referred this answer to detect IE 11.
// Detect IE version
var iev=0;
var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var rv=navigator.userAgent.indexOf("rv:11.0");
if (ieold) iev=new Number(RegExp.$1);
if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
if (trident&&rv!=-1) iev=11;
// Firefox or IE 11
if(typeof InstallTrigger !== 'undefined' || iev == 11) {
var lastScrollTop = 0;
$(window).on('scroll', function() {
st = $(this).scrollTop();
if(st < lastScrollTop) {
console.log('Up');
}
else if(st > lastScrollTop) {
console.log('Down');
}
lastScrollTop = st;
});
}
// Other browsers
else {
$('body').on('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
console.log('Up');
}
else if(e.originalEvent.wheelDelta < 0) {
console.log('Down');
}
});
}
you're comparing the result against a string ('false') not the built-in negative constant (false)
just use
if(ValidateForm() == false) {
or better yet
if(!ValidateForm()) {
also why are you calling validateForm twice?
I had this problem to install laravel/lumen.
It can be resolved with the following command:
$ sudo chown -R $USER ~/.composer/
Just a small addition...
If it works for you to only supply the http_proxy setting and not username and password I'd recommend putting the proxy settings in a project local nuget.config file and commit it to source control. That way all team members get the same settings.
Create an empty .\nuget.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>
Then:
nuget config -Set http_proxy="http://myproxy.example.com:8080" -ConfigFile .\Nuget.Config
And finally commit your new project local Nuget.config file.
For ex .. add class:
btn-lg - LARGE
btn-sm - SMALL
btn-xs - Very small
<button type=button class="btn btn-default btn-lg">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button>
<button type=button class="btn btn-default">
<span class="glyphicon glyphicon-star" aria-hidden=true></span>Star
</button>
<button type=button class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button>
<button type=button class="btn btn-default btn-xs">
<span class="glyphicon glyphicon-star" aria-hidden=true></span> Star
</button>
Ref link Bootstrap : Glyphicons Bootstrap
Just in case you're using .NET 2.0 and don't have access to LINQ:
static T First<T>(IEnumerable<T> items)
{
using(IEnumerator<T> iter = items.GetEnumerator())
{
iter.MoveNext();
return iter.Current;
}
}
This should do what you're looking for...it uses generics so you to get the first item on any type IEnumerable.
Call it like so:
List<string> items = new List<string>() { "A", "B", "C", "D", "E" };
string firstItem = First<string>(items);
Or
int[] items = new int[] { 1, 2, 3, 4, 5 };
int firstItem = First<int>(items);
You could modify it readily enough to mimic .NET 3.5's IEnumerable.ElementAt() extension method:
static T ElementAt<T>(IEnumerable<T> items, int index)
{
using(IEnumerator<T> iter = items.GetEnumerator())
{
for (int i = 0; i <= index; i++, iter.MoveNext()) ;
return iter.Current;
}
}
Calling it like so:
int[] items = { 1, 2, 3, 4, 5 };
int elemIdx = 3;
int item = ElementAt<int>(items, elemIdx);
Of course if you do have access to LINQ, then there are plenty of good answers posted already...
Pax is correct about the reasons for TIME_WAIT, and why you should be careful about lowering the default setting.
A better solution is to vary the port numbers used for the originating end of your sockets. Once you do this, you won't really care about time wait for individual sockets.
For listening sockets, you can use SO_REUSEADDR to allow the listening socket to bind despite the TIME_WAIT sockets sitting around.
I assume you are using gcc
, to simply link object files do:
$ gcc -o output file1.o file2.o
To get the object-files simply compile using
$ gcc -c file1.c
this yields file1.o and so on.
If you want to link your files to an executable do
$ gcc -o output file1.c file2.c
Close nodejs app
running in another shell.
Restart the terminal and run the program again.
Another server might be also using the same port that you have used for nodejs. Kill the process that is using nodejs port
and run the app.
To find the PID of the application that is using port:8000
$ fuser 8000/tcp
8000/tcp: 16708
Here PID is 16708 Now kill the process using the kill [PID]
command
$ kill 16708
This is the simplest way to do it if you need multiple lines. Wrap you span
'd text in another span
and specify its height with line-height
. The trick to multiple lines is resetting the inner span
's line-height
.
<span class="textvalignmiddle"><span>YOUR TEXT HERE</span></span>
.textvalignmiddle {
line-height: /*set height*/;
}
.textvalignmiddle > span {
display: inline-block;
vertical-align: middle;
line-height: 1em; /*set line height back to normal*/
}
Of course the outer span
could be a div
or whathaveyou
It can be if you created new directory at the disk BEFORE create/commit it in the SVN. All that you need is just create it in SVN and do move after:
$ svn mv etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/
svn: E155010: Path '/home/dyr/svn/nagioscore/etc/nagios/hosts/us0101/ccs' is not a directory
$ svn status
? etc/nagios/hosts/us0101/ccs
$ rm -rvf etc/nagios/hosts/us0101/ccs
removed directory 'etc/nagios/hosts/us0101/ccs'
$ svn mkdir etc/nagios/hosts/us0101/ccs
A etc/nagios/hosts/us0101/ccs
$ svn move etc/nagios/hosts/us0101/cs/us0101ccs001.cfg etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
A etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
D etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
$ svn status
A etc/nagios/hosts/us0101/ccs
A + etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
> moved from etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
D etc/nagios/hosts/us0101/cs/us0101ccs001.cfg
> moved to etc/nagios/hosts/us0101/ccs/us0101accs001.cfg
simply,
select sysdate-1 from dual
there's a bunch more info and detail here: http://www.orafaq.com/faq/how_does_one_add_a_day_hour_minute_second_to_a_date_value
Another aspect is security (obfuscation). Once a piece of code is extracted from the main application and put in a "separated" Dynamic-Link Library, it is easier to attack, analyse (reverse-engineer) the code, since it has been isolated. When the same piece of code is kept in a LIB Library, it is part of the compiled (linked) target application, and this thus harder to isolate (differentiate) that piece of code from the rest of the target binaries.
My gremlin for this problem was bad directory permissions:
Good permissions:
drwxr-x--x u0_a20 u0_a20 2013-11-13 20:45 com.google.earth
drwxr-x--x u0_a63 u0_a63 2013-11-13 20:46 com.nuance.xt9.input
drwxr-x--x u0_a53 u0_a53 2013-11-13 20:45 com.tf.thinkdroid.sg
drwxr-x--x u0_a68 u0_a68 2013-12-24 15:03 eu.chainfire.supersu
drwxr-x--x u0_a59 u0_a59 2013-11-13 20:45 jp.co.omronsoft.iwnnime.ml
drwxr-x--x u0_a60 u0_a60 2013-11-13 20:45 jp.co.omronsoft.iwnnime.ml.kbd.white
drwxr-x--x u0_a69 u0_a69 2013-12-24 15:03 org.mozilla.firefox
Bad permissions:
root@grouper:/data/data # ls -lad com.mypackage
drw-rw-r-- u0_a70 u0_a70 2014-01-11 14:18 com.mypackage
How did they get that way? I set them that way, while fiddling around trying to get adb pull
to work. Clearly I did it wrong.
Hey Google, it would be awful nice if a permission error produced a meaningful error message, or failing that if you didnt have to hand tweak permissions to use the tools.
Make an /login url, than accept "user" and "password" parameters via GET and don't require basic auth. Here, use php, node, java, whatever and parse your passwd file and match parameters (user/pass) against it. If there is a match then redirect to http://user:[email protected]/ (this will set credential on your browser) if not, send 401 response (without WWW-Authenticate header).
(copy-paste/adapted from https://stackoverflow.com/a/24048772/1733117).
First you can subclass urllib2.BaseHandler
or urllib2.HTTPBasicAuthHandler
, and implement http_request
so that each request has the appropriate Authorization
header.
import urllib2
import base64
class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
'''Preemptive basic auth.
Instead of waiting for a 403 to then retry with the credentials,
send the credentials if the url is handled by the password manager.
Note: please use realm=None when calling add_password.'''
def http_request(self, req):
url = req.get_full_url()
realm = None
# this is very similar to the code from retry_http_basic_auth()
# but returns a request object.
user, pw = self.passwd.find_user_password(realm, url)
if pw:
raw = "%s:%s" % (user, pw)
auth = 'Basic %s' % base64.b64encode(raw).strip()
req.add_unredirected_header(self.auth_header, auth)
return req
https_request = http_request
Then if you are lazy like me, install the handler globally
api_url = "http://api.foursquare.com/"
api_username = "johndoe"
api_password = "some-cryptic-value"
auth_handler = PreemptiveBasicAuthHandler()
auth_handler.add_password(
realm=None, # default realm.
uri=api_url,
user=api_username,
passwd=api_password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
for single array Item use reset($item)
You can't verify (with enough accuracy to rely on) if an email actually exists using just a single PHP method. You can send an email to that account, but even that alone won't verify the account exists (see below). You can, at least, verify it's at least formatted like one
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
//Email is valid
}
You can add another check if you want. Parse the domain out and then run checkdnsrr
if(checkdnsrr($domain)) {
// Domain at least has an MX record, necessary to receive email
}
Many people get to this point and are still unconvinced there's not some hidden method out there. Here are some notes for you to consider if you're bound and determined to validate email:
Spammers also know the "connection trick" (where you start to send an email and rely on the server to bounce back at that point). One of the other answers links to this library which has this caveat
Some mail servers will silently reject the test message, to prevent spammers from checking against their users' emails and filter the valid emails, so this function might not work properly with all mail servers.
In other words, if there's an invalid address you might not get an invalid address response. In fact, virtually all mail servers come with an option to accept all incoming mail (here's how to do it with Postfix). The answer linking to the validation library neglects to mention that caveat.
Spam blacklists. They blacklist by IP address and if your server is constantly doing verification connections you run the risk of winding up on Spamhaus or another block list. If you get blacklisted, what good does it do you to validate the email address?
If it's really that important to verify an email address, the accepted way is to force the user to respond to an email. Send them a full email with a link they have to click to be verified. It's not spammy, and you're guaranteed that any responses have a valid address.
I developed an inelegant solution. Consider that we have the X axis and also a list of labels for each point in X.
Example:import matplotlib.pyplot as plt
x = [0,1,2,3,4,5]
y = [10,20,15,18,7,19]
xlabels = ['jan','feb','mar','apr','may','jun']
Let's say that I want to show ticks labels only for 'feb' and 'jun'
xlabelsnew = []
for i in xlabels:
if i not in ['feb','jun']:
i = ' '
xlabelsnew.append(i)
else:
xlabelsnew.append(i)
Good, now we have a fake list of labels. First, we plotted the original version.
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabels,rotation=45)
plt.show()
Now, the modified version.
plt.plot(x,y)
plt.xticks(range(0,len(x)),xlabelsnew,rotation=45)
plt.show()
The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :
connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
Initial Catalog=databaseName;
User ID=theuser if u use it;
Password=thepassword if u use it;
integrated security=true(if u don t use user and pass; else change it false)"
Without to knowing your instance, I could help with this one. Hope it helped
Change . to / as the path separator and use getResourceAsStream
:
reader = new BufferedReader(new InputStreamReader(
getClass().getClassLoader().getResourceAsStream(
"com/company/app/dao/sql/SqlQueryFile.sql")));
or
reader = new BufferedReader(new InputStreamReader(
getClass().getResourceAsStream(
"/com/company/app/dao/sql/SqlQueryFile.sql")));
Note the leading slash when using Class.getResourceAsStream()
vs ClassLoader.getResourceAsStream
.
getSystemResourceAsStream
uses the system classloader which isn't what you want.
I suspect that using slashes instead of dots would work for ClassPathResource
too.
Found my solution on Apache/2.2.15 (Unix).
And Thanks for answer from @QuantumHive:
First: I finded all
Order allow,deny
Deny from all
instead of
Order allow,deny
Allow from all
and then:
I setted
#
# Control access to UserDir directories. The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /var/www/html>
# AllowOverride FileInfo AuthConfig Limit
# Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
# <Limit GET POST OPTIONS>
# Order allow,deny
# Allow from all
# </Limit>
# <LimitExcept GET POST OPTIONS>
# Order deny,allow
# Deny from all
# </LimitExcept>
#</Directory>
Remove the previous "#" annotation to
#
# Control access to UserDir directories. The following is an example
# for a site where these directories are restricted to read-only.
#
<Directory /var/www/html>
AllowOverride FileInfo AuthConfig Limit
Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
<Limit GET POST OPTIONS>
Order allow,deny
Allow from all
</Limit>
<LimitExcept GET POST OPTIONS>
Order deny,allow
Deny from all
</LimitExcept>
</Directory>
ps. my WebDir is: /var/www/html
If the file is long, you can optimize your code by appending to a StringBuilder instead of using a String concatenation for each line.
Just do nothing once the criteria is met, otherwise do the processing you require and the For
loop will go to the next item.
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If Return = 0 And Level = 0 Then
'Do nothing
Else
'Do something
End If
Next i
Or change the clause so it only processes if the conditions are met:
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If Return <> 0 Or Level <> 0 Then
'Do something
End If
Next i
Depending on your needs, you can probably rely on node's path
module.
You may not be able to hit the filesystem (e.g. the file hasn't been created yet) and tbh you probably want to avoid hitting the filesystem unless you really need the extra validation. If you can make the assumption that what you are checking for follows .<extname>
format, just look at the name.
Obviously if you are looking for a file without an extname you will need to hit the filesystem to be sure. But keep it simple until you need more complicated.
const path = require('path');
function isFile(pathItem) {
return !!path.extname(pathItem);
}
File > Workspace Settings > Build System > Legacy Build System
This worked for me. Xcode 10.0
Here's how I do it.
function validate(phone) {_x000D_
const regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
console.log(regex.test(phone))_x000D_
}_x000D_
_x000D_
validate('1234567890') // true_x000D_
validate(1234567890) // true_x000D_
validate('(078)789-8908') // true_x000D_
validate('123-345-3456') // true
_x000D_
I guess anther way, possibly faster, to achieve this is
1) Use dict comprehension to get desired dict (i.e., taking 2nd col of each array)
2) Then use pd.DataFrame
to create an instance directly from the dict without loop over each col and concat.
Assuming your mat
looks like this (you can ignore this since your mat
is loaded from file):
In [135]: mat = {'a': np.random.randint(5, size=(4,2)),
.....: 'b': np.random.randint(5, size=(4,2))}
In [136]: mat
Out[136]:
{'a': array([[2, 0],
[3, 4],
[0, 1],
[4, 2]]), 'b': array([[1, 0],
[1, 1],
[1, 0],
[2, 1]])}
Then you can do:
In [137]: df = pd.DataFrame ({name:mat[name][:,1] for name in mat})
In [138]: df
Out[138]:
a b
0 0 0
1 4 1
2 1 0
3 2 1
[4 rows x 2 columns]
get_fields()
returns a tuple
and each element is a Model field
type, which can't be used directly as a string. So, field.name
will return the field name
my_model_fields = [field.name for field in MyModel._meta.get_fields()]
The above code will return a list conatining all fields name
Example
In [11]: from django.contrib.auth.models import User
In [12]: User._meta.get_fields()
Out[12]:
(<ManyToOneRel: admin.logentry>,
<django.db.models.fields.AutoField: id>,
<django.db.models.fields.CharField: password>,
<django.db.models.fields.DateTimeField: last_login>,
<django.db.models.fields.BooleanField: is_superuser>,
<django.db.models.fields.CharField: username>,
<django.db.models.fields.CharField: first_name>,
<django.db.models.fields.CharField: last_name>,
<django.db.models.fields.EmailField: email>,
<django.db.models.fields.BooleanField: is_staff>,
<django.db.models.fields.BooleanField: is_active>,
<django.db.models.fields.DateTimeField: date_joined>,
<django.db.models.fields.related.ManyToManyField: groups>,
<django.db.models.fields.related.ManyToManyField: user_permissions>)
In [13]: [field.name for field in User._meta.get_fields()]
Out[13]:
['logentry',
'id',
'password',
'last_login',
'is_superuser',
'username',
'first_name',
'last_name',
'email',
'is_staff',
'is_active',
'date_joined',
'groups',
'user_permissions']
You are not seeding the number.
Use This:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(static_cast<unsigned int>(time(0)));
cout << (rand() % 100) << endl;
return 0;
}
You only need to seed it once though. Basically don't seed it every random number.
The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2:
The use of the static keyword is deprecated when declaring objects in a namespace scope, the unnamed-namespace provides a superior alternative.
Static only applies to names of objects, functions, and anonymous unions, not to type declarations.
The decision to deprecate this use of the static
keyword (affecting visibility of a variable declaration in a translation unit) has been reversed (ref). In this case using a static
or an unnamed namespace
are back to being essentially two ways of doing the exact same thing. For more discussion please see this SO question.
Unnamed namespace
's still have the advantage of allowing you to define translation-unit-local types. Please see this SO question for more details.
Credit goes to Mike Percy for bringing this to my attention.
How about this:
BEGIN
Do Something
END
GO 10
... of course you could put an incremental counter inside it if you need to count.
Use the annotation @Deprecated
for your method, and you should also mention it in your javadocs.
The solution that work for me is the following:
$('#myModal').modal({backdrop: 'static', keyboard: false})
backdrop: disabled the click outside event
keyboard: disabled the scape keyword event
The clean
, install
and deploy
phases are valid lifecycle phases and invoking them will trigger all the phases preceding them, and the goals bound to these phases.
mvn clean install
This command invokes the clean
phase and then the install
phase sequentially:
clean
: removes files generated at build-time in a project's directory (target
by default)install
: installs the package into the local repository, for use as a dependency in other projects locally.mvn deploy
This command invokes the deploy
phase:
deploy
: copies the final package to the remote repository for sharing with other developers and projects.mvn release
This is not a valid phase nor a goal so this won't do anything. But if refers to the Maven Release Plugin that is used to automate release management. Releasing a project is done in two steps: prepare
and perform
. As documented:
Preparing a release goes through the following release phases:
- Check that there are no uncommitted changes in the sources
- Check that there are no SNAPSHOT dependencies
- Change the version in the POMs from x-SNAPSHOT to a new version (you will be prompted for the versions to use)
- Transform the SCM information in the POM to include the final destination of the tag
- Run the project tests against the modified POMs to confirm everything is in working order
- Commit the modified POMs
- Tag the code in the SCM with a version name (this will be prompted for)
- Bump the version in the POMs to a new value y-SNAPSHOT (these values will also be prompted for)
- Commit the modified POMs
And then:
Performing a release runs the following release phases:
- Checkout from an SCM URL with optional tag
- Run the predefined Maven goals to release the project (by default, deploy site-deploy)
Here is the C# method. Int.TryParse Method (String, Int32)
function Map() {
this.keys = new Array();
this.data = new Object();
this.put = function (key, value) {
if (this.data[key] == null) {
this.keys.push(key);
}
this.data[key] = value;
};
this.get = function (key) {
return this.data[key];
};
this.remove = function (key) {
this.keys.remove(key);
this.data[key] = null;
};
this.each = function (fn) {
if (typeof fn != 'function') {
return;
}
var len = this.keys.length;
for (var i = 0; i < len; i++) {
var k = this.keys[i];
fn(k, this.data[k], i);
}
};
this.entrys = function () {
var len = this.keys.length;
var entrys = new Array(len);
for (var i = 0; i < len; i++) {
entrys[i] = {
key: this.keys[i],
value: this.data[i]
};
}
return entrys;
};
this.isEmpty = function () {
return this.keys.length == 0;
};
this.size = function () {
return this.keys.length;
};
}
<manifest xmlns:tools="http://schemas.android.com/tools" ... >
<uses-sdk tools:overrideLibrary="nl.innovalor.ocr, nl.innovalor.corelib" />
I was facing the issue of conflict between different min sdk versions. So this solution worked for me.
Use VSC or any other editor that has Live server, it will give you a proxy that will allow you to use GET or FETCH
Simply translating the "old for loop way" into streams:
private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {
int subLength = prefix.length();
return input.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey().substring(subLength),
entry -> AttributeType.GetByName(entry.getValue())));
}
Turns out for me this error was actually telling the truth - I was trying to resize a Null image, which was usually the 'last' frame of a video file, so the assertion was valid.
Now I have an extra step before attempting the resize operation, which is to do the assertion myself:
def getSizedFrame(width, height):
"""Function to return an image with the size I want"""
s, img = self.cam.read()
# Only process valid image frames
if s:
img = cv2.resize(img, (width, height), interpolation = cv2.INTER_AREA)
return s, img
Now I don't see the error.
Open MySQL Command Line Client
Create a new user with a new pass
Considering an example of a path to a bin folder on top, here's the code you need to run in the command prompt, line by line:
cd C:\Program Files\MySQL\MySQL Server 5.7\bin
MySQL -u root -p
current password...***
CREATE USER 'nativeuser'@'localhost'
IDENTIFIED WITH mysql_native_password BY 'new_password';
Set up a new local host connection with the user name mentioned above (native user), login using the password (new_password)
Courtesy: UDEMY FAQs answered by Career365 Team
Here is a code example that proves the fault in the class. I've checked: the problem occurs when using parse and also when you are only using format.
You can raise a notice in Postgres
as follows:
raise notice 'Value: %', deletedContactId;
Read here
It can work well as you guess
python testMyCase.py MyCase.testItIsHot
And there is another way to just test testItIsHot
:
suite = unittest.TestSuite()
suite.addTest(MyCase("testItIsHot"))
runner = unittest.TextTestRunner()
runner.run(suite)
Note that if you rely on sleep taking exactly 50 ms, you won't get that. It will just be about it.
You can use:
jQuery('[name="' + nameAttributeValue + '"]');
this will be an inefficient way to select elements though, so it would be best to also use the tag name or restrict the search to a specific element:
jQuery('div[name="' + nameAttributeValue + '"]'); // with tag name
jQuery('div[name="' + nameAttributeValue + '"]',
document.getElementById('searcharea')); // with a search base
Because a label element is not loaded when a script is executed. Swap the label and script elements, and it will work:
<label id="lbltipAddedComment"></label>
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>
Results in a string representation of tomorrow's date. Use new Date() to get today's date, adding one day using Date.getDate() and Date.setDate(), and converting the Date object to a string.
const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
t.getDate()
).padStart(2, '0')}`;
};
tomorrow();
For anyone who has this issue with an already running container, and they don't necessarily want to rebuild, the following command connects to a running container with root privileges:
docker exec -ti -u root container_name bash
You can also connect using its ID, rather than its name, by finding it with:
docker ps -l
To save your changes so that they are still there when you next launch the container (or docker-compose cluster):
docker commit container_id image_name
To roll back to a previous image version (warning: this deletes history rather than appends to the end, so to keep a reference to the current image, tag it first using the optional step):
docker history image_name
docker tag latest_image_id my_descriptive_tag_name # optional
docker tag desired_history_image_id image_name
To start a container that isn't running and connect as root:
docker run -ti -u root --entrypoint=/bin/bash image_id_or_name -s
To copy from a running container:
docker cp <containerId>:/file/path/within/container /host/path/target
To export a copy of the image:
docker save container | gzip > /dir/file.tar.gz
Which you can restore to another Docker install using:
gzcat /dir/file.tar.gz | docker load
It is much quicker but takes more space to not compress, using:
docker save container | dir/file.tar
And:
cat dir/file.tar | docker load
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
The simplest answer of all is...
<a href="javascript:alert('You clicked!')">My link</a>
_x000D_
Or to answer the question of calling a javascript function:
<script type="text/javascript">_x000D_
function myFunction(myMessage) {_x000D_
alert(myMessage);_x000D_
}_x000D_
</script>_x000D_
_x000D_
<a href="javascript:myFunction('You clicked!')">My link</a>
_x000D_
In my case it was fixed by adding a reference to the constraint-layout package
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
A CustomValidator would also work here:
<asp:CustomValidator runat="server"
ID="valDateRange"
ControlToValidate="txtDatecompleted"
onservervalidate="valDateRange_ServerValidate"
ErrorMessage="enter valid date" />
Code-behind:
protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
DateTime minDate = DateTime.Parse("1000/12/28");
DateTime maxDate = DateTime.Parse("9999/12/28");
DateTime dt;
args.IsValid = (DateTime.TryParse(args.Value, out dt)
&& dt <= maxDate
&& dt >= minDate);
}
One thing you can do is, you might have subfolders for each projects. So, install mongoose in that subfolders and require() mongoose from own folders in each sub applications. Not from the project root or from global. So one sub project, one mongoose installation and one mongoose instance.
-app_root/
--foo_app/
---db_access.js
---foo_db_connect.js
---node_modules/
----mongoose/
--bar_app/
---db_access.js
---bar_db_connect.js
---node_modules/
----mongoose/
In foo_db_connect.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/foo_db');
module.exports = exports = mongoose;
In bar_db_connect.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/bar_db');
module.exports = exports = mongoose;
In db_access.js files
var mongoose = require("./foo_db_connect.js"); // bar_db_connect.js for bar app
Now, you can access multiple databases with mongoose.
It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:
if (Model.Model2 == null
|| Model.Model2.Model3 == null
|| Model.Model2.Model3.Model4 == null
|| Model.Model2.Model3.Model4.Name == null)
{
mapped.Name = "N/A"
}
else
{
mapped.Name = Model.Model2.Model3.Model4.Name;
}
It can be written like (same logic as above)
mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";
DotNetFiddle.Net Working Example.
(the ?? or null-coalescing operator is different than the ? or null conditional operator).
It can also be used out side of assignment operators with Action. Instead of
Action<TValue> myAction = null;
if (myAction != null)
{
myAction(TValue);
}
It can be simplified to:
myAction?.Invoke(TValue);
using System;
public class Program
{
public static void Main()
{
Action<string> consoleWrite = null;
consoleWrite?.Invoke("Test 1");
consoleWrite = (s) => Console.WriteLine(s);
consoleWrite?.Invoke("Test 2");
}
}
Result:
Test 2
<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>
$('#fire').on('click', function (e) {
//your awesome code here
})
Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/
and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1
.
See this link for the official GlassFish documentation about logging.
Below could be the better way:
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
//your code to implement
cursor.moveToNext();
}
}
cursor.close();
The above code would insure that it would go through entire iteration and won't escape first and last iteration.
Use string formats;
console.log("%s %O", "My Object", obj);
Chrome has Format Specifiers with the following;
%s
Formats the value as a string. %d
or %i
Formats the value as
an integer. %f
Formats the value as a floating point value.%o
Formats the value as an expandable DOM element (as in the
Elements panel). %O
Formats the value as an expandable JavaScript
object. %c
Formats the output string according to CSS styles you
provide.Firefox also has String Substitions which have similar options.
%o
Outputs a hyperlink to a JavaScript object. Clicking the link opens an inspector.%d
or %i
Outputs an integer. Formatting is not yet supported.%s
Outputs a string.%f
Outputs a floating-point value. Formatting is not yet supported.Safari has printf style formatters
%d
or %i
Integer%[0.N]f
Floating-point value with N digits of precision%o
Object%s
StringUse iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
It doesn't compile because T could be anything, and not everything will have the myvar
field.
You could make myvar
a property on ITest
:
public ITest
{
string myvar{get;}
}
and implement it on the classes as a property:
public class MyClass1 : ITest
{
public string myvar{ get { return "hello 1"; } }
}
and then put a generic constraint on your method:
public void PrintGeneric<T>(T test) where T : ITest
{
Console.WriteLine("Generic : " + test.myvar);
}
but in that case to be honest you are better off just passing in an ITest:
public void PrintGeneric(ITest test)
{
Console.WriteLine("Generic : " + test.myvar);
}
This is really just an explaination of Yuzem's answer, but I didn't feel like this much editing should be done to someone else, and comments don't allow formatting, so...
rdom () { local IFS=\> ; read -d \< E C ;}
Let's call that "read_dom" instead of "rdom", space it out a bit and use longer variables:
read_dom () {
local IFS=\>
read -d \< ENTITY CONTENT
}
Okay so it defines a function called read_dom. The first line makes IFS (the input field separator) local to this function and changes it to >. That means that when you read data instead of automatically being split on space, tab or newlines it gets split on '>'. The next line says to read input from stdin, and instead of stopping at a newline, stop when you see a '<' character (the -d for deliminator flag). What is read is then split using the IFS and assigned to the variable ENTITY and CONTENT. So take the following:
<tag>value</tag>
The first call to read_dom
get an empty string (since the '<' is the first character). That gets split by IFS into just '', since there isn't a '>' character. Read then assigns an empty string to both variables. The second call gets the string 'tag>value'. That gets split then by the IFS into the two fields 'tag' and 'value'. Read then assigns the variables like: ENTITY=tag
and CONTENT=value
. The third call gets the string '/tag>'. That gets split by the IFS into the two fields '/tag' and ''. Read then assigns the variables like: ENTITY=/tag
and CONTENT=
. The fourth call will return a non-zero status because we've reached the end of file.
Now his while loop cleaned up a bit to match the above:
while read_dom; do
if [[ $ENTITY = "title" ]]; then
echo $CONTENT
exit
fi
done < xhtmlfile.xhtml > titleOfXHTMLPage.txt
The first line just says, "while the read_dom functionreturns a zero status, do the following." The second line checks if the entity we've just seen is "title". The next line echos the content of the tag. The four line exits. If it wasn't the title entity then the loop repeats on the sixth line. We redirect "xhtmlfile.xhtml" into standard input (for the read_dom
function) and redirect standard output to "titleOfXHTMLPage.txt" (the echo from earlier in the loop).
Now given the following (similar to what you get from listing a bucket on S3) for input.xml
:
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Name>sth-items</Name>
<IsTruncated>false</IsTruncated>
<Contents>
<Key>[email protected]</Key>
<LastModified>2011-07-25T22:23:04.000Z</LastModified>
<ETag>"0032a28286680abee71aed5d059c6a09"</ETag>
<Size>1785</Size>
<StorageClass>STANDARD</StorageClass>
</Contents>
</ListBucketResult>
and the following loop:
while read_dom; do
echo "$ENTITY => $CONTENT"
done < input.xml
You should get:
=>
ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/" =>
Name => sth-items
/Name =>
IsTruncated => false
/IsTruncated =>
Contents =>
Key => [email protected]
/Key =>
LastModified => 2011-07-25T22:23:04.000Z
/LastModified =>
ETag => "0032a28286680abee71aed5d059c6a09"
/ETag =>
Size => 1785
/Size =>
StorageClass => STANDARD
/StorageClass =>
/Contents =>
So if we wrote a while
loop like Yuzem's:
while read_dom; do
if [[ $ENTITY = "Key" ]] ; then
echo $CONTENT
fi
done < input.xml
We'd get a listing of all the files in the S3 bucket.
EDIT
If for some reason local IFS=\>
doesn't work for you and you set it globally, you should reset it at the end of the function like:
read_dom () {
ORIGINAL_IFS=$IFS
IFS=\>
read -d \< ENTITY CONTENT
IFS=$ORIGINAL_IFS
}
Otherwise, any line splitting you do later in the script will be messed up.
EDIT 2
To split out attribute name/value pairs you can augment the read_dom()
like so:
read_dom () {
local IFS=\>
read -d \< ENTITY CONTENT
local ret=$?
TAG_NAME=${ENTITY%% *}
ATTRIBUTES=${ENTITY#* }
return $ret
}
Then write your function to parse and get the data you want like this:
parse_dom () {
if [[ $TAG_NAME = "foo" ]] ; then
eval local $ATTRIBUTES
echo "foo size is: $size"
elif [[ $TAG_NAME = "bar" ]] ; then
eval local $ATTRIBUTES
echo "bar type is: $type"
fi
}
Then while you read_dom
call parse_dom
:
while read_dom; do
parse_dom
done
Then given the following example markup:
<example>
<bar size="bar_size" type="metal">bars content</bar>
<foo size="1789" type="unknown">foos content</foo>
</example>
You should get this output:
$ cat example.xml | ./bash_xml.sh
bar type is: metal
foo size is: 1789
EDIT 3 another user said they were having problems with it in FreeBSD and suggested saving the exit status from read and returning it at the end of read_dom like:
read_dom () {
local IFS=\>
read -d \< ENTITY CONTENT
local RET=$?
TAG_NAME=${ENTITY%% *}
ATTRIBUTES=${ENTITY#* }
return $RET
}
I don't see any reason why that shouldn't work
Assuming your json object from your GET request looks like the one you posted above simply do:
let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});
Or am I missing something that prevents you from doing it this way?
in your tsconfig you have to add: "esModuleInterop": true - it should help.
Here, a simple function in Pascal (Delphi).
function GetColLetterFromNum(Sheet : Variant; Col : Integer) : String;
begin
Result := Sheet.Columns[Col].Address; // from Col=100 --> '$CV:$CV'
Result := Copy(Result, 2, Pos(':', Result) - 2);
end;
You could try passing a callback function to perform the replacement:
var tagsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
function replaceTag(tag) {
return tagsToReplace[tag] || tag;
}
function safe_tags_replace(str) {
return str.replace(/[&<>]/g, replaceTag);
}
Here is a performance test: http://jsperf.com/encode-html-entities to compare with calling the replace
function repeatedly, and using the DOM method proposed by Dmitrij.
Your way seems to be faster...
Why do you need it, though?
TLDR; Uninstall and re-install using admin account.
I encountered this error after installing Oracle Express 11g 64 bit using a standard account. After looking for a fix on various sites I realized that the issue was most likely caused by an incorrect setting. Different people suggested editing various files which I was not interested in doing. I found one person who claimed that the issue was a registry setting. Since I used a standard account to install I thought that maybe the registry setting could not be altered using a standard account. So I uninstalled and re-installed using an admin account and it just worked.
Use CALL
as in
CALL nameOfOtherFile.bat
This will block (pause) the execution of the current batch file, and it will wait until the CALL
ed one completes.
If you don't want it to block, use START
instead.
Get the nitty-gritty details by using CALL /?
or START /?
from the cmd prompt.
I can't remember where I found this method, but it's pretty simple and works well.
HTML:
<nav role="navigation">
<ul>
<li ui-sref-active="selected" class="inactive"><a ui-sref="tab-01">Tab 01</a></li>
<li ui-sref-active="selected" class="inactive"><a ui-sref="tab-02">Tab 02</a></li>
</ul>
</nav>
CSS:
.selected {
background-color: $white;
color: $light-blue;
text-decoration: none;
border-color: $light-grey;
}
When you import a module (or a member of it) for the first time, the code inside the module is executed sequentially like any other code; e.g., it is not treated any differently that the body of a function. An import
is just a command like any other (assignment, a function call, def
, class
). Assuming your imports occur at the top of the script, then here's what's happening:
World
from world
, the world
script gets executed.world
script imports Field
, which causes the entities.field
script to get executed.entities.post
script because you tried to import Post
entities.post
script causes physics
module to be executed because it tries to import PostBody
physics
tries to import Post
from entities.post
entities.post
module exists in memory yet, but it really doesn't matter. Either the module is not in memory, or the module doesn't yet have a Post
member because it hasn't finished executing to define Post
Post
is not there to be importedSo no, it's not "working further up in the call stack". This is a stack trace of where the error occurred, which means it errored out trying to import Post
in that class. You shouldn't use circular imports. At best, it has negligible benefit (typically, no benefit), and it causes problems like this. It burdens any developer maintaining it, forcing them to walk on egg shells to avoid breaking it. Refactor your module organization.
For anyone looking for a solution to this with also wanting to cycle the elements, below might work -
from collections import deque
foo = ['A', 'B', 'C', 'D']
def prev_and_next(input_list):
CURRENT = input_list
PREV = deque(input_list)
PREV.rotate(-1)
PREV = list(PREV)
NEXT = deque(input_list)
NEXT.rotate(1)
NEXT = list(NEXT)
return zip(PREV, CURRENT, NEXT)
for previous_, current_, next_ in prev_and_next(foo):
print(previous_, current_, next)
If a case-insensitive comparison is acceptable, just use =
:
=IF(A1="ENG",1,0)
At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.
What is Git Bash?
Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.
I gave Eclipse a 3 months ride at my new work, but after that I found out that normal Maven project can be run in IntelliJ IDEA too (unless it's Eclipse plugin/EMF/something of course ;-)). 3 months are not enough to compare it with 8+ years with IDEA, but it's enough to claim I gave it a fair try. I decided to live with its perspectives (other IDEs don't need them), with its poor debugger (doesn't show date values unless you click on them! etc.), with its comparatively worse completion than IDEA has.
Now after all those years IDEA is also free (community edition) and I use it without much trouble. Of course I miss some of those "Ultimate" features of paid version, but it's far better than Eclipse. Biggest difference is the whole mindset needed for both of these IDEs. But after you master the mindset of either I can't understand what can anyone hold to Eclipse - unless you need its plugin ecosystem or you have some serious investments there.
Example of "mindset" differences: You have to save in Eclipse, not in IDEA, and I don't care what is better or worse - but you have to save in Eclipse to let him clean up underlined errors that are not errors anymore, etc. ;-) You have to save there in order to get rid of errors in other files too, because other file doesn't see the changes otherwise.
I blogged much more about this topic - and yes, I'm biased, though I tried to be as little as possible. But after some time it wasn't simply possible: :-)
And no, not even IDEA is perfect, I know it. Because I use it a lot. But it is the best Java IDE if you ask me. Even the Community edition.
If you want any java
process, not just ant or Tomcat, to pick up options like -Xmx
use the environment variable _JAVA_OPTIONS
.
In bash: export _JAVA_OPTIONS="-Xmx1g"
TRY
<?php
$rowID=$productid=$name=$price=$description="";
if (isset($_POST['submit'])) {
$rowID = $_POST['rowID'];
$productid = $_POST['productid']; //this is line 32 and so on...
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
}
I don't know any native cmdlet in powershell but you can use com object instead:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()
you can create a powershell script save as set-shortcut.ps1 in your $pwd
param ( [string]$SourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()
and call it like this
Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"
If you want to pass arguments to the target exe, it can be done by:
#Set the additional parameters for the shortcut
$Shortcut.Arguments = "/argument=value"
before $Shortcut.Save().
For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.
param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()
We like one-liners : Get the difference between the current culture's first day of week and the current day then subtract the number of days from the current day
var weekStartDate = DateTime.Now.AddDays(-((int)now.DayOfWeek - (int)DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek));
set -x
enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x
: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.
set +x
disables it.
sqrt=x**(1/2)
is doing integer division. 1/2 == 0
.
So you're computing x(1/2) in the first instance, x(0) in the second.
So it's not wrong, it's the right answer to a different question.
Main issue is that you first need to set the location of your x and y ticks. Also, it helps to use the more object-oriented interface to matplotlib. Namely, interact with the axes
object directly.
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data)
# put the major ticks at the middle of each cell, notice "reverse" use of dimension
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()
Hope that helps.
Using query builder, get the single column value such as groupName
$groupName = DB::table('users')->where('username', $username)->pluck('groupName');
For Laravel 5.1
$groupName=DB::table('users')->where('username', $username)->value('groupName');
Or, Using user model, get the single column value
$groupName = User::where('username', $username)->pluck('groupName');
Or, get the first row and then split for getting single column value
$data = User::where('username', $username)->first();
if($data)
$groupName=$data->groupName;
Oracle, PostgreSQL, SQL Server and many more RDBMS engines have analytic functions called LAG
and LEAD
that do this very thing.
In SQL Server prior to 2012 you'd need to do the following:
SELECT value - (
SELECT TOP 1 value
FROM mytable m2
WHERE m2.col1 < m1.col1 OR (m2.col1 = m1.col1 AND m2.pk < m1.pk)
ORDER BY
col1, pk
)
FROM mytable m1
ORDER BY
col1, pk
, where COL1
is the column you are ordering by.
Having an index on (COL1, PK)
will greatly improve this query.
If you are on Azure you need you can now, you need to have Manag. Studio 2014 and update hotfix: http://blogs.msdn.com/b/sqlreleaseservices/archive/2014/12/18/sql-server-2014-management-studio-updated-support-for-the-latest-azure-sql-database-update-v12-preview.aspx
Here's another way to do it instead of using foreach loops for looking inside EntityValidationErrors. Of course you can format the message to your own liking :
try {
// your code goes here...
}
catch (DbEntityValidationException ex)
{
Console.Write($"Validation errors: {string.Join(Environment.NewLine, ex.EntityValidationErrors.SelectMany(vr => vr.ValidationErrors.Select(err => $"{err.PropertyName} - {err.ErrorMessage}")))}", ex);
throw;
}
Bit old, but doesn't hurt to add some notes.
When you write something like this
let a: any;
let b: Object;
let c: {};
And that's why
a.doSomething(); // Ok: the compiler trusts you on that
b.doSomething(); // Error: Object has no doSomething member
c.doSomething(); // Error: c neither has doSomething nor inherits it from Object
and why
a.toString(); // Ok: whatever, dude, have it your way
b.toString(); // Ok: toString is defined in Object
c.toString(); // Ok: c inherits toString from Object
So Object
and {}
are equivalents in TypeScript.
If you declare functions like these
function fa(param: any): void {}
function fb(param: Object): void {}
with the intention of accepting anything for param (maybe you're going to check types at run-time to decide what to do with it), remember that
It is worth noting, though, that if param is supposed to accept multiple known types, a better approach is to declare it using union types, as in
function fc(param: string|number): void {}
Obviously, OO inheritance rules still apply, so if you want to accept instances of derived classes and treat them based on their base type, as in
interface IPerson {
gender: string;
}
class Person implements IPerson {
gender: string;
}
class Teacher extends Person {}
function func(person: IPerson): void {
console.log(person.gender);
}
func(new Person()); // Ok
func(new Teacher()); // Ok
func({gender: 'male'}); // Ok
func({name: 'male'}); // Error: no gender..
the base type is the way to do it, not any. But that's OO, out of scope, I just wanted to clarify that any should only be used when you don't know whats coming, and for anything else you should annotate the correct type.
UPDATE:
Typescript 2.2 added an object
type, which specifies that a value is a non-primitive: (i.e. not a number
, string
, boolean
, symbol
, undefined
, or null
).
Consider functions defined as:
function b(x: Object) {}
function c(x: {}) {}
function d(x: object) {}
x
will have the same available properties within all of these functions, but it's a type error to call d
with a primitive:
b("foo"); //Okay
c("foo"); //Okay
d("foo"); //Error: "foo" is a primitive
Idea is to avoid using a Signal like above. Pumping int values into a struct prevents those values from changing (in the struct). I had the following Problem: loop var i would change before DoSomething(i) was called (i was incremented at end of loop before ()=> DoSomething(i,ii) was called). With the structs it doesn't happen anymore. Nasty bug to find: DoSomething(i, ii) looks great, but never sure if it gets called each time with a different value for i (or just a 100 times with i=100), hence -> struct
struct Job { public int P1; public int P2; }
…
for (int i = 0; i < 100; i++) {
var job = new Job { P1 = i, P2 = i * i}; // structs immutable...
Task.Run(() => DoSomething(job));
}
What's the correct way to copy entire database (its structure and data) to a new one in pgAdmin?
Answer:
CREATE DATABASE newdb WITH TEMPLATE originaldb;
Tried and tested.
ASP.NET controls should rather be placed in aspx markup file. That is the preferred way of working with them. So add FileUpload
control to your page. Make sure it has all required attributes including ID
and runat
:
<asp:FileUpload ID="FileUpload1" runat="server" />
Instance of FileUpload1
will be automatically created in auto-generated/updated *.designer.cs file which is a partial class for your page. You usually do not have to care about what's in it, just assume that any control on an aspx page is automatically instantiated.
Add a button that will do the post back:
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Then go to your *.aspx.cs file where you have your code and add button click handler. In C# it looks like this:
protected void Button1_Click(object sender, EventArgs e)
{
if (this.FileUpload1.HasFile)
{
this.FileUpload1.SaveAs("c:\\" + this.FileUpload1.FileName);
}
}
And that's it. All should work as expected.
In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.
Yes. Only comments and the end tag for the html element are allowed after the end tag for the body.
Browsers may perform error recovery, but you should never depend on that.
I do get the same information while debugging. Though not while I am checking the stacktrace. Most probably you would have used the optimization flag I think. Check this link - something related.
Try compiling with -g3
remove any optimization flag.
Then it might work.
HTH!
This extension that @Rob suggested works for Swift 3.0.1
I wasn't able to compile the version he included in his post with Xcode 8.1 (8B62)
extension Dictionary {
/// Build string representation of HTTP parameter dictionary of keys and objects
///
/// :returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped
func stringFromHttpParameters() -> String {
var parametersString = ""
for (key, value) in self {
if let key = key as? String,
let value = value as? String {
parametersString = parametersString + key + "=" + value + "&"
}
}
parametersString = parametersString.substring(to: parametersString.index(before: parametersString.endIndex))
return parametersString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
}
I think you want to change the setting called "DropDownStyle" to be "DropDownList".
I have encountered this problem in Eclipse Luna EE. My solution was simply restart eclipse and it magically started loading servlet properly.
Before the days of jQuery you would use:
document.getElementById('findmebyid');
If this one line will save you an entire jQuery library, it might be worth while using it instead.
For those concerned about performance: Beginning your selector with an ID is always best as it uses native function document.getElementById.
// Fast:
$( "#container div.robotarm" );
// Super-fast:
$( "#container" ).find( "div.robotarm" );
If you are mocking the behavior (with something like doNothing()
) there should really be no need to call to verify*()
. That said, here's my stab at re-writing your test method:
@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest { //Note the renaming of the test class.
public void testProcessOrder() {
//Variables
InternalService is = new InternalService();
Order order = mock(Order.class);
//Mock Behavior
when(order.isSuccessful()).thenReturn(true);
mockStatic(Internalutils.class);
doNothing().when(InternalUtils.class); //This is the preferred way
//to mock static void methods.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
//Execute
is.processOrder(order);
//Verify
verifyStatic(InternalUtils.class); //Similar to how you mock static methods
//this is how you verify them.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
}
}
I grouped into four sections to better highlight what is going on:
I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.
This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.
Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.
This is when you call any method starting with verify
or assert
. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.
This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.
I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:
All Integers are modulo of 1. So below check must give you the answer.
if(d % 1 == 0)
Firstly, you have to create a Console Project within your VS Solution(Add -> New Project -> Console Application).
Within the new project, create a class "ConsoleHost" with that code:
class ConsoleHost : IDisposable
{
public static Uri BaseAddress = new Uri(http://localhost:8161/MyService/mex);
private ServiceHost host;
public void Start(Uri baseAddress)
{
if (host != null) return;
host = new ServiceHost(typeof(MyService), baseAddress ?? BaseAddress);
//binding
var binding = new BasicHttpBinding()
{
Name = "MyService",
MessageEncoding = WSMessageEncoding.Text,
TextEncoding = Encoding.UTF8,
MaxBufferPoolSize = 2147483647,
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647
};
host.Description.Endpoints.Clear();
host.AddServiceEndpoint(typeof(IMyService), binding, baseAddress ?? BaseAddress);
// Enable metadata publishing.
var smb = new ServiceMetadataBehavior
{
HttpGetEnabled = true,
MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 },
};
host.Description.Behaviors.Add(smb);
var defaultBehaviour = host.Description.Behaviors.OfType<ServiceDebugBehavior>().FirstOrDefault();
if (defaultBehaviour != null)
{
defaultBehaviour.IncludeExceptionDetailInFaults = true;
}
host.Open();
}
public void Stop()
{
if (host == null)
return;
host.Close();
host = null;
}
public void Dispose()
{
this.Stop();
}
}
And this is the code for the Program.cs class:
public static class Program
{
[STAThread]
public static void Main(string[] args)
{
var baseAddress = new Uri(http://localhost:8161/MyService);
var host = new ConsoleHost();
host.Start(null);
Console.WriteLine("The service is ready at {0}", baseAddress);
Console.WriteLine("Press <Enter> to stop the service.");
Console.ReadLine();
host.Stop();
}
}
Configurations such as connectionstrings should be copied in the App.config file of the Console project.
To sturt up the console, righ-click on Console project and click Debug -> Start new instance.
Well, the simplest way using LINQ would be something like this:
list = list.OrderBy(x => x.AVC ? 0 : 1)
.ToList();
or
list = list.OrderByDescending(x => x.AVC)
.ToList();
I believe that the natural ordering of bool
values is false < true
, but the first form makes it clearer IMO, because everyone knows that 0 < 1
.
Note that this won't sort the original list itself - it will create a new list, and assign the reference back to the list
variable. If you want to sort in place, you should use the List<T>.Sort
method.
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
Handles Button3.Click
Dim box = New AboutBox1()
box.Show()
End Sub
Using functions as spencer7593 mentioned is a correct approach for dynamic data. For static data, a more performant approach which is consistent with SQL data design (versus the anti-pattern of writting massive procedural code in sprocs) is to create a separate table with the static values and join to it. This is extremely beneficial from a performace perspective since the SQL Engine can build effective execution plans around a JOIN, and you have the potential to add indexes as well if needed.
The disadvantage of using functions (or any inline calculated values) is the callout happens for every potential row returned, which is costly. Why? Because SQL has to first create a full dataset with the calculated values and then apply the WHERE clause to that dataset.
Nine times out of ten you should not need dynamically calculated cell values in your queries. Its much better to figure out what you will need, then design a data model that supports it, and populate that data model with semi-dynamic data (via batch jobs for instance) and use the SQL Engine to do the heavy lifting via standard SQL.
You can use .issubset() as well
>>> {"key1", "key2"}.issubset({"key1":1, "key2":2, "key3": 3})
True
>>> {"key4", "key2"}.issubset({"key1":1, "key2":2, "key3": 3})
False
>>>
Your syntax is incorrect, you should pass the value as the second parameter:
jQuery(this).prev("li").attr("id","newId");
If you just need to await
to avoid nesting code:
let json;
await new Promise(done => $.getJSON('https://***', async function (data) {
json = data;
done();
}));
Update: 19 -11-2019
The below answer is no more relevant to present day.
So for any one looking for answers you should look at the documentation linked below
https://developer.android.com/training/articles/user-data-ids
Old Answer - Not relevant now. You check this blog in the link below
http://android-developers.blogspot.in/2011/03/identifying-app-installations.html
ANDROID_ID
import android.provider.Settings.Secure;
private String android_id = Secure.getString(getContext().getContentResolver(),
Secure.ANDROID_ID);
The above is from the link @ Is there a unique Android device ID?
More specifically, Settings.Secure.ANDROID_ID. This is a 64-bit quantity that is generated and stored when the device first boots. It is reset when the device is wiped.
ANDROID_ID seems a good choice for a unique device identifier. There are downsides: First, it is not 100% reliable on releases of Android prior to 2.2 (“Froyo”). Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.
The below solution is not a good one coz the value survives device wipes (“Factory resets”) and thus you could end up making a nasty mistake when one of your customers wipes their device and passes it on to another person.
You get the imei number of the device using the below
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.getDeviceId();
http://developer.android.com/reference/android/telephony/TelephonyManager.html#getDeviceId%28%29
Add this is manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
I found a workaround for this via this link. In a nutshell, you have to:
Put this command inside the above file(Replace the path for executable if necessary):
#!/bin/sh
"C:\Program Files\Sublime Text 2\sublime_text.exe" $1 &
Place that subl file inside the adequate command directory according to your OS and Sublime Text version (If you have doubts, check the above link comments section). In my case, I'm using Sublime Text 3 with Windows 10 64bit so I placed it in:
C:\Program Files (x86)\Git\usr\bin
Now, in order for you to open the desired file, in git bash use (within file folder)
subl filename
To get it at any time, you can do SELECT MAX(Id) FROM Customers
.
In the procedure you add it in, however, you can also make use of SCOPE_IDENTITY
-- to get the id last added by that procedure.
This is safer, because it will guarantee you get your Id
--just in case others are being added to the database at the same time.
Sometimes if a Thread
was started and it loaded a downside dynamic class which is processing with lots of Thread
/currentThread
sleep while ignoring interrupted Exception
catch(es), one interrupt might not be enough to completely exit execution.
In that case, we can supply these loop-based interrupts:
while(th.isAlive()){
log.trace("Still processing Internally; Sending Interrupt;");
th.interrupt();
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
In a recent project I changed the default activity in AndroidManifest.xml with:
<activity android:name=".MyAppRuntimePermissions">
</activity>
<activity android:name=".MyAppDisplay">
<intent-filter>
<action android:name="android.intent.activity.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
In Android Studio 3.6; this seems to broken. I've used this technique in example applications, but when I use it in this real-world application it falls flat. The IDE once again reports:
Error running app: Default activity not found.
The IDE still showed a configuration error in the "run app" space in the toolbar (yellow arrow in this screenshot)
To correct this error I've tried several rebuilds of the project, and finally File >> "Invalidate Cache/Restart". This did not help. To run the application I had to "Edit Configurations" and point at the specific activity instead of the default activity:
For maven users:
Using the accepted answer my script kept returning exceptionally early (right after 'exec > >(tee ...)') leaving the rest of my script running in the background. As I couldn't get that solution to work my way I found another solution/work around to the problem:
# Logging setup
logfile=mylogfile
mkfifo ${logfile}.pipe
tee < ${logfile}.pipe $logfile &
exec &> ${logfile}.pipe
rm ${logfile}.pipe
# Rest of my script
This makes output from script go from the process, through the pipe into the sub background process of 'tee' that logs everything to disc and to original stdout of the script.
Note that 'exec &>' redirects both stdout and stderr, we could redirect them separately if we like, or change to 'exec >' if we just want stdout.
Even thou the pipe is removed from the file system in the beginning of the script it will continue to function until the processes finishes. We just can't reference it using the file name after the rm-line.