Well one thing you could do is if you have a switch:
switch(SomeEnum)
{
case SomeEnum.One:
DoThings(someUser);
break;
case SomeEnum.Two:
DoSomethingElse(someUser);
break;
}
And with the might power of actions you can turn that switch into a dictionary:
Dictionary<SomeEnum, Action<User>> methodList =
new Dictionary<SomeEnum, Action<User>>()
methodList.Add(SomeEnum.One, DoSomething);
methodList.Add(SomeEnum.Two, DoSomethingElse);
...
methodList[SomeEnum](someUser);
Or you could take this farther:
SomeOtherMethod(Action<User> someMethodToUse, User someUser)
{
someMethodToUse(someUser);
}
....
var neededMethod = methodList[SomeEnum];
SomeOtherMethod(neededMethod, someUser);
Just a couple of examples. Of course the more obvious use would be Linq extension methods.
A predicate in T is a delegate that takes in a T and returns a bool. List<T>.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.
{
List<Vehicle> vehicles;
// Using a lambda
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
// Using an equivalent anonymous method
vehicles.RemoveAll(delegate(Vehicle vehicle)
{
return vehicle.EnquiryID == 123;
});
// Using an equivalent actual method
vehicles.RemoveAll(VehiclePredicate);
}
private static bool VehiclePredicate(Vehicle vehicle)
{
return vehicle.EnquiryID == 123;
}
Kind of a messy workaround, but assignment in lambdas is illegal anyway, so it doesn't really matter. You can use the builtin exec()
function to run assignment from inside the lambda, such as this example:
>>> val
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
val
NameError: name 'val' is not defined
>>> d = lambda: exec('val=True', globals())
>>> d()
>>> val
True
Generally i prefer the lambda syntax with LINQ, but Join
is one example where i prefer the query syntax - purely for readability.
Nonetheless, here is the equivalent of your above query (i think, untested):
var query = db.Categories // source
.Join(db.CategoryMaps, // target
c => c.CategoryId, // FK
cm => cm.ChildCategoryId, // PK
(c, cm) => new { Category = c, CategoryMaps = cm }) // project result
.Select(x => x.Category); // select result
You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.
You can use the following code for your requirement
map.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
You can explicitly specify the return type of a lambda by using -> Type
after the arguments list:
[]() -> Type { }
However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.
Since Java 9, you can create instances of Map.Entry
easier than before:
Entry<Integer, String> pair = Map.entry(1, "a");
Map.entry
returns an unmodifiable Entry
and forbids nulls.
I'd like to promote factory methods for creating helpers for functional APIs:
Optional<R> result = things.stream()
.flatMap(streamopt(this::resolve))
.findFirst();
The factory method:
<T, R> Function<T, Stream<R>> streamopt(Function<T, Optional<R>> f) {
return f.andThen(Optional::stream); // or the J8 alternative:
// return t -> f.apply(t).map(Stream::of).orElseGet(Stream::empty);
}
Reasoning:
As with method references in general, compared to lambda expressions, you can't accidentaly capture a variable from the accessible scope, like:
t -> streamopt(resolve(o))
It's composable, you can e.g. call Function::andThen
on the factory method result:
streamopt(this::resolve).andThen(...)
Whereas in the case of a lambda, you'd need to cast it first:
((Function<T, Stream<R>>) t -> streamopt(resolve(t))).andThen(...)
You could use reflection to access the property.
public List<Employee> Sort(List<Employee> list, String sortBy, String sortDirection)
{
PropertyInfo property = list.GetType().GetGenericArguments()[0].
GetType().GetProperty(sortBy);
if (sortDirection == "ASC")
{
return list.OrderBy(e => property.GetValue(e, null));
}
if (sortDirection == "DESC")
{
return list.OrderByDescending(e => property.GetValue(e, null));
}
else
{
throw new ArgumentOutOfRangeException();
}
}
Notes
We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...
Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(),
p -> p,
(person1, person2) -> person1+";"+person2)
);
You can also throw an exception:
For the sake of readability each step of stream should be listed in new line.
players.stream()
.filter(player -> player.getName().contains(name))
.findFirst()
.orElseThrow(MyCustomRuntimeException::new);
if your logic is loosely "exception driven" such as there is one place in your code that catches all exceptions and decides what to do next. Only use exception driven development when you can avoid littering your code base with multiples try-catch
and throwing these exceptions are for very special cases that you expect them and can be handled properly.)
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
And for those of you using an anonymous expression:
await Task.Run(async () =>
{
SQLLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupname);
});
Whilst the accepted answer works and is good for Linq to Objects it bugged me that the SQL query isn't just a straight Left Outer Join.
The following code relies on the LinkKit Project that allows you to pass expressions and invoke them to your query.
static IQueryable<TResult> LeftOuterJoin<TSource,TInner, TKey, TResult>(
this IQueryable<TSource> source,
IQueryable<TInner> inner,
Expression<Func<TSource,TKey>> sourceKey,
Expression<Func<TInner,TKey>> innerKey,
Expression<Func<TSource, TInner, TResult>> result
) {
return from a in source.AsExpandable()
join b in inner on sourceKey.Invoke(a) equals innerKey.Invoke(b) into c
from d in c.DefaultIfEmpty()
select result.Invoke(a,d);
}
It can be used as follows
Table1.LeftOuterJoin(Table2, x => x.Key1, x => x.Key2, (x,y) => new { x,y});
Most of the answers listed, miss a case when the list has duplicate items. In that case there answer will throw IllegalStateException
. Refer the below code to handle list duplicates as well:
public Map<String, Choice> convertListToMap(List<Choice> choices) {
return choices.stream()
.collect(Collectors.toMap(Choice::getName, choice -> choice,
(oldValue, newValue) -> newValue));
}
Ctrl + Alt + Shift + S and then from project select the language level 1.8, read more about Lambda Expressions here
LINQ is a "query" language (thats the Q), so modifying data is outside its scope.
That said, your DataGridView
is presumably bound to an ItemsSource
, perhaps of type ObservableCollection<T>
or similar. In that case, just do something like X.ToList().ForEach(yourGridSource.Add)
(this might have to be adapted based on the type of source in your grid).
If listOfIds
is a list, this will work, but, List.Contains() is a linear search, so this isn't terribly efficient.
You're better off storing the ids you want to look up into a container that is suited for searching, like Set.
List<int> listOfIds = new List(GetListOfIds());
lists.Where(r=>listOfIds.Contains(r.Id));
The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.
Your criticism is entirely justified.
I discuss this problem in detail here:
Closing over the loop variable considered harmful
Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?
The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.
I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.
The for
loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.
An alternate method that limits the scope of the lambda rather than giving it access to the whole this
is to pass in a local reference to the member variable, e.g.
auto& localGrid = grid;
int i;
for_each(groups.cbegin(),groups.cend(),[localGrid,&i](pair<int,set<int>> group){
i++;
cout<<i<<endl;
});
For List<List<List<x>>>
and so on, use
list.SelectMany(x => x.SelectMany(y => y)).ToList();
This has been posted in a comment, but it does deserves a separate reply in my opinion.
To make the use of lambda : There are three type of operation:
1. Accept parameter --> Consumer
2. Test parameter return boolean --> Predicate
3. Manipulate parameter and return value --> Function
Java Functional interface upto two parameter:
Single parameter interface
Consumer
Predicate
Function
Two parameter interface
BiConsumer
BiPredicate
BiFunction
For more than two, you have to create functional interface as follow(Consumer type):
@FunctionalInterface
public interface FiveParameterConsumer<T, U, V, W, X> {
public void accept(T t, U u, V v, W w, X x);
}
In Python, lambda
is just a way of defining functions inline,
a = lambda x: x + 1
print a(1)
and..
def a(x): return x + 1
print a(1)
..are the exact same.
There is nothing you can do with lambda which you cannot do with a regular function—in Python functions are an object just like anything else, and lambdas simply define a function:
>>> a = lambda x: x + 1
>>> type(a)
<type 'function'>
I honestly think the lambda
keyword is redundant in Python—I have never had the need to use them (or seen one used where a regular function, a list-comprehension or one of the many builtin functions could have been better used instead)
For a completely random example, from the article "Python’s lambda is broken!":
To see how lambda is broken, try generating a list of functions
fs=[f0,...,f9]
wherefi(n)=i+n
. First attempt:>>> fs = [(lambda n: i + n) for i in range(10)] >>> fs[3](4) 13
I would argue, even if that did work, it's horribly and "unpythonic", the same functionality could be written in countless other ways, for example:
>>> n = 4
>>> [i + n for i in range(10)]
[4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
Yes, it's not the same, but I have never seen a cause where generating a group of lambda functions in a list has been required. It might make sense in other languages, but Python is not Haskell (or Lisp, or ...)
Please note that we can use lambda and still achieve the desired results in this way :
>>> fs = [(lambda n,i=i: i + n) for i in range(10)] >>> fs[3](4) 7
Edit:
There are a few cases where lambda is useful, for example it's often convenient when connecting up signals in PyQt applications, like this:
w = PyQt4.QtGui.QLineEdit()
w.textChanged.connect(lambda event: dothing())
Just doing w.textChanged.connect(dothing)
would call the dothing
method with an extra event
argument and cause an error. Using the lambda means we can tidily drop the argument without having to define a wrapping function.
With Eclipse Collections you can use detectIndex
along with remove(int)
on any java.util.List.
List<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int index = Iterate.detectIndex(integers, i -> i > 2);
if (index > -1) {
integers.remove(index);
}
Assert.assertEquals(Lists.mutable.with(1, 2, 4, 5), integers);
If you use the MutableList
type from Eclipse Collections, you can call the detectIndex
method directly on the list.
MutableList<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5);
int index = integers.detectIndex(i -> i > 2);
if (index > -1) {
integers.remove(index);
}
Assert.assertEquals(Lists.mutable.with(1, 2, 4, 5), integers);
Note: I am a committer for Eclipse Collections
While the accepted answer is correct, I'll add a more elegant version (in my opinion):
boolean idExists = tabPane.getTabs().stream()
.map(Tab::getId)
.anyMatch(idToCheck::equals);
Don't neglect using Stream#map() which allows to flatten the data structure before applying the Predicate
.
using LINQ query expression
IEnumerable<SelectListItem> stores =
from store in database.Stores
where store.CompanyID == curCompany.ID
select new SelectListItem { Value = store.Name, Text = store.ID };
ViewBag.storeSelector = stores;
or using LINQ extension methods with lambda expressions
IEnumerable<SelectListItem> stores = database.Stores
.Where(store => store.CompanyID == curCompany.ID)
.Select(store => new SelectListItem { Value = store.Name, Text = store.ID });
ViewBag.storeSelector = stores;
Question might be a little dated, but you could simply use AbstractMap.SimpleEntry<> as follows:
private Map<String, AttributeType> mapConfig(
Map<String, String> input, String prefix) {
int subLength = prefix.length();
return input.entrySet()
.stream()
.map(e -> new AbstractMap.SimpleEntry<>(
e.getKey().substring(subLength),
AttributeType.GetByName(e.getValue()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
any other Pair-like value object would work too (ie. ApacheCommons Pair tuple).
I am starting with python but coming from Javascript the most obvious way is extract the expression as a function....
Contrived example, multiply expression (x*2)
is extracted as function and therefore I can use multiline:
def multiply(x):
print('I am other line')
return x*2
r = map(lambda x : multiply(x), [1, 2, 3, 4])
print(list(r))
https://repl.it/@datracka/python-lambda-function
Maybe it does not answer exactly the question if that was how to do multiline in the lambda expression itself, but in case somebody gets this thread looking how to debug the expression (like me) I think it will help
Mine would be this in c# 3.0 :)
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
Basically, the least amount of iterations will always be:
loop assemblies
loop types
see if implemented.
var boxSummary = from b in boxes
group b by b.Owner into g
let nrBoxes = g.Count()
let totalWeight = g.Sum(w => w.Weight)
let totalVolume = g.Sum(v => v.Volume)
select new { Owner = g.Key, Boxes = nrBoxes,
TotalWeight = totalWeight,
TotalVolume = totalVolume }
If you want to stick with the original List instead of creating a new one, you can something similar to what the Distinct()
extension method does internally, i.e. use a HashSet to check for uniqueness:
HashSet<long> set = new HashSet<long>(longs.Count);
longs.RemoveAll(x => !set.Add(x));
The List class provides this convenient RemoveAll(predicate)
method that drops all elements not satisfying the condition specified by the predicate. The predicate is a delegate taking a parameter of the list's element type and returning a bool value. The HashSet's Add()
method returns true only if the set doesn't contain the item yet. Thus by removing any items from the list that can't be added to the set you effectively remove all duplicates.
If you want to sort by Object's date type property then
public class Visit implements Serializable, Comparable<Visit>{
private static final long serialVersionUID = 4976278839883192037L;
private Date dos;
public Date getDos() {
return dos;
}
public void setDos(Date dos) {
this.dos = dos;
}
@Override
public int compareTo(Visit visit) {
return this.getDos().compareTo(visit.getDos());
}
}
List<Visit> visits = getResults();//Method making the list
Collections.sort(visits, Collections.reverseOrder());//Reverser order
I'm not sure precisely what you're looking for, but this program:
public class Building
{
public enum StatusType
{
open,
closed,
weird,
};
public string Name { get; set; }
public StatusType Status { get; set; }
}
public static List <Building> buildingList = new List<Building> ()
{
new Building () { Name = "one", Status = Building.StatusType.open },
new Building () { Name = "two", Status = Building.StatusType.closed },
new Building () { Name = "three", Status = Building.StatusType.weird },
new Building () { Name = "four", Status = Building.StatusType.open },
new Building () { Name = "five", Status = Building.StatusType.closed },
new Building () { Name = "six", Status = Building.StatusType.weird },
};
static void Main (string [] args)
{
var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };
var q = from building in buildingList
where statusList.Contains (building.Status)
select building;
foreach ( var b in q )
Console.WriteLine ("{0}: {1}", b.Name, b.Status);
}
produces the expected output:
one: open
two: closed
four: open
five: closed
This program compares a string representation of the enum and produces the same output:
public class Building
{
public enum StatusType
{
open,
closed,
weird,
};
public string Name { get; set; }
public string Status { get; set; }
}
public static List <Building> buildingList = new List<Building> ()
{
new Building () { Name = "one", Status = "open" },
new Building () { Name = "two", Status = "closed" },
new Building () { Name = "three", Status = "weird" },
new Building () { Name = "four", Status = "open" },
new Building () { Name = "five", Status = "closed" },
new Building () { Name = "six", Status = "weird" },
};
static void Main (string [] args)
{
var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };
var statusStringList = statusList.ConvertAll <string> (st => st.ToString ());
var q = from building in buildingList
where statusStringList.Contains (building.Status)
select building;
foreach ( var b in q )
Console.WriteLine ("{0}: {1}", b.Name, b.Status);
Console.ReadKey ();
}
I created this extension method to convert one IEnumerable to another, but I'm not sure how efficient it is; it may just create a list behind the scenes.
public static IEnumerable <TResult> ConvertEach (IEnumerable <TSource> sources, Func <TSource,TResult> convert)
{
foreach ( TSource source in sources )
yield return convert (source);
}
Then you can change the where clause to:
where statusList.ConvertEach <string> (status => status.GetCharValue()).
Contains (v.Status)
and skip creating the List<string>
with ConvertAll ()
at the beginning.
Forgot to relate to the first code snippet. I wouldn't use forEach
at all. Since you are collecting the elements of the Stream
into a List
, it would make more sense to end the Stream
processing with collect
. Then you would need peek
in order to set the ID.
List<Entry> updatedEntries =
entryList.stream()
.peek(e -> e.setTempId(tempId))
.collect (Collectors.toList());
For the second snippet, forEach
can execute multiple expressions, just like any lambda expression can :
entryList.forEach(entry -> {
if(entry.getA() == null){
printA();
}
if(entry.getB() == null){
printB();
}
if(entry.getC() == null){
printC();
}
});
However (looking at your commented attempt), you can't use filter in this scenario, since you will only process some of the entries (for example, the entries for which entry.getA() == null
) if you do.
Keep it Simple and use Java 8:-
Map<String, AccountGroupMappingModel> mapAccountGroup=CustomerDAO.getAccountGroupMapping();
Map<String, AccountGroupMappingModel> mapH2ToBydAccountGroups =
mapAccountGroup.entrySet().stream()
.collect(Collectors.toMap(e->e.getValue().getH2AccountGroup(),
e ->e.getValue())
);
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
Actually, above codes can be:
>>> sorted(['Some','words','sort','differently'],key=str.lower)
According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
All solutions I've seen here rely on selecting an already comparable field. If one needs to compare in a different way, though, this solution here seems to work generally, for something like:
somedoubles.Distinct(new LambdaComparer<double>((x, y) => Math.Abs(x - y) < double.Epsilon)).Count()
For anyone who is googling this, a good method would be to use java.util.function.BiConsumer
.
ex:
Import java.util.function.Consumer
public Class Main {
public static void runLambda(BiConsumer<Integer, Integer> lambda) {
lambda.accept(102, 54)
}
public static void main(String[] args) {
runLambda((int1, int2) -> System.out.println(int1 + " + " + int2 + " = " + (int1 + int2)));
}
The outprint would be: 166
C++ includes useful generic functions like std::for_each
and std::transform
, which can be very handy. Unfortunately they can also be quite cumbersome to use, particularly if the functor you would like to apply is unique to the particular function.
#include <algorithm>
#include <vector>
namespace {
struct f {
void operator()(int) {
// do something
}
};
}
void func(std::vector<int>& v) {
f f;
std::for_each(v.begin(), v.end(), f);
}
If you only use f
once and in that specific place it seems overkill to be writing a whole class just to do something trivial and one off.
In C++03 you might be tempted to write something like the following, to keep the functor local:
void func2(std::vector<int>& v) {
struct {
void operator()(int) {
// do something
}
} f;
std::for_each(v.begin(), v.end(), f);
}
however this is not allowed, f
cannot be passed to a template function in C++03.
C++11 introduces lambdas allow you to write an inline, anonymous functor to replace the struct f
. For small simple examples this can be cleaner to read (it keeps everything in one place) and potentially simpler to maintain, for example in the simplest form:
void func3(std::vector<int>& v) {
std::for_each(v.begin(), v.end(), [](int) { /* do something here*/ });
}
Lambda functions are just syntactic sugar for anonymous functors.
In simple cases the return type of the lambda is deduced for you, e.g.:
void func4(std::vector<double>& v) {
std::transform(v.begin(), v.end(), v.begin(),
[](double d) { return d < 0.00001 ? 0 : d; }
);
}
however when you start to write more complex lambdas you will quickly encounter cases where the return type cannot be deduced by the compiler, e.g.:
void func4(std::vector<double>& v) {
std::transform(v.begin(), v.end(), v.begin(),
[](double d) {
if (d < 0.0001) {
return 0;
} else {
return d;
}
});
}
To resolve this you are allowed to explicitly specify a return type for a lambda function, using -> T
:
void func4(std::vector<double>& v) {
std::transform(v.begin(), v.end(), v.begin(),
[](double d) -> double {
if (d < 0.0001) {
return 0;
} else {
return d;
}
});
}
So far we've not used anything other than what was passed to the lambda within it, but we can also use other variables, within the lambda. If you want to access other variables you can use the capture clause (the []
of the expression), which has so far been unused in these examples, e.g.:
void func5(std::vector<double>& v, const double& epsilon) {
std::transform(v.begin(), v.end(), v.begin(),
[epsilon](double d) -> double {
if (d < epsilon) {
return 0;
} else {
return d;
}
});
}
You can capture by both reference and value, which you can specify using &
and =
respectively:
[&epsilon]
capture by reference[&]
captures all variables used in the lambda by reference[=]
captures all variables used in the lambda by value[&, epsilon]
captures variables like with [&], but epsilon by value[=, &epsilon]
captures variables like with [=], but epsilon by referenceThe generated operator()
is const
by default, with the implication that captures will be const
when you access them by default. This has the effect that each call with the same input would produce the same result, however you can mark the lambda as mutable
to request that the operator()
that is produced is not const
.
I like the explanation of Lambdas in this article: The Evolution Of LINQ And Its Impact On The Design Of C#. It made a lot of sense to me as it shows a real world for Lambdas and builds it out as a practical example.
Their quick explanation: Lambdas are a way to treat code (functions) as data.
The simple answer to your question is: You can't, at least not directly. And it's not your fault. Oracle messed it up. They cling on the concept of checked exceptions, but inconsistently forgot to take care of checked exceptions when designing the functional interfaces, streams, lambda etc. That's all grist to the mill of experts like Robert C. Martin who call checked exceptions a failed experiment.
In my opinion, this is a huge bug in the API and a minor bug in the language specification.
The bug in the API is that it provides no facility for forwarding checked exceptions where this actually would make an awful lot of sense for functional programming. As I will demonstrate below, such a facility would've been easily possible.
The bug in the language specification is that it does not allow a type parameter to infer a list of types instead of a single type as long as the type parameter is only used in situations where a list of types is permissable (throws
clause).
Our expectation as Java programmers is that the following code should compile:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class CheckedStream {
// List variant to demonstrate what we actually had before refactoring.
public List<Class> getClasses(final List<String> names) throws ClassNotFoundException {
final List<Class> classes = new ArrayList<>();
for (final String name : names)
classes.add(Class.forName(name));
return classes;
}
// The Stream function which we want to compile.
public Stream<Class> getClasses(final Stream<String> names) throws ClassNotFoundException {
return names.map(Class::forName);
}
}
However, it gives:
cher@armor1:~/playground/Java/checkedStream$ javac CheckedStream.java
CheckedStream.java:13: error: incompatible thrown types ClassNotFoundException in method reference
return names.map(Class::forName);
^
1 error
The way in which the functional interfaces are defined currently prevents the Compiler from forwarding the exception - there is no declaration which would tell Stream.map()
that if Function.apply() throws E
, Stream.map() throws E
as well.
What's missing is a declaration of a type parameter for passing through checked exceptions. The following code shows how such a pass-through type parameter actually could have been declared with the current syntax. Except for the special case in the marked line, which is a limit discussed below, this code compiles and behaves as expected.
import java.io.IOException;
interface Function<T, R, E extends Throwable> {
// Declare you throw E, whatever that is.
R apply(T t) throws E;
}
interface Stream<T> {
// Pass through E, whatever mapper defined for E.
<R, E extends Throwable> Stream<R> map(Function<? super T, ? extends R, E> mapper) throws E;
}
class Main {
public static void main(final String... args) throws ClassNotFoundException {
final Stream<String> s = null;
// Works: E is ClassNotFoundException.
s.map(Class::forName);
// Works: E is RuntimeException (probably).
s.map(Main::convertClass);
// Works: E is ClassNotFoundException.
s.map(Main::throwSome);
// Doesn't work: E is Exception.
s.map(Main::throwSomeMore); // error: unreported exception Exception; must be caught or declared to be thrown
}
public static Class convertClass(final String s) {
return Main.class;
}
static class FooException extends ClassNotFoundException {}
static class BarException extends ClassNotFoundException {}
public static Class throwSome(final String s) throws FooException, BarException {
throw new FooException();
}
public static Class throwSomeMore(final String s) throws ClassNotFoundException, IOException {
throw new FooException();
}
}
In the case of throwSomeMore
we would like to see IOException
being missed, but it actually misses Exception
.
This is not perfect because type inference seems to be looking for a single type, even in the case of exceptions. Because the type inference needs a single type, E
needs to resolve to a common super
of ClassNotFoundException
and IOException
, which is Exception
.
A tweak to the definition of type inference is needed so that the compiler would look for multiple types if the type parameter is used where a list of types is permissible (throws
clause). Then the exception type reported by the compiler would be as specific as the original throws
declaration of the checked exceptions of the referenced method, not a single catch-all super type.
The bad news is that this means that Oracle messed it up. Certainly they won't break user-land code, but introducing exception type parameters to the existing functional interfaces would break compilation of all user-land code that uses these interfaces explicitly. They'll have to invent some new syntax sugar to fix this.
The even worse news is that this topic was already discussed by Brian Goetz in 2010 https://blogs.oracle.com/briangoetz/entry/exception_transparency_in_java (new link: http://mail.openjdk.java.net/pipermail/lambda-dev/2010-June/001484.html) but I'm informed that this investigation ultimately did not pan out, and that there is no current work at Oracle that I know of to mitigate the interactions between checked exceptions and lambdas.
Why write complicated code when you could make it simple?
Indeed, if you are absolutely going to use the Optional
class, the most simple code is what you have already written ...
if (user.isPresent())
{
doSomethingWithUser(user.get());
}
This code has the advantages of being
Just because Oracle has added the Optional
class in Java 8 doesn't mean that this class must be used in all situation.
Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.
return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
.Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
.SelectMany(a => a)
.ToList();
Where CustomerGroupingKey takes the group keys:
private class CustomerGroupingKey
{
public CustomerGroupingKey(string country, string gender)
{
Country = country;
Gender = gender;
}
public string Country { get; }
public string Gender { get; }
}
Use the map
-function instead. It transforms the value inside the optional.
Like this:
private String getStringIfObjectIsPresent(Optional<Object> object) {
return object.map(() -> {
String result = "result";
//some logic with result and return it
return result;
}).orElseThrow(MyCustomException::new);
}
Suppose you have the following code:
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Test {
public static void main(String[] s) {
Map<String, Boolean> whoLetDogsOut = new ConcurrentHashMap<>();
whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
whoLetDogsOut.computeIfAbsent("snoop", k -> f(k));
}
static boolean f(String s) {
System.out.println("creating a value for \""+s+'"');
return s.isEmpty();
}
}
Then you will see the message creating a value for "snoop"
exactly once as on the second invocation of computeIfAbsent
there is already a value for that key. The k
in the lambda expression k -> f(k)
is just a placeolder (parameter) for the key which the map will pass to your lambda for computing the value. So in the example the key is passed to the function invocation.
Alternatively you could write: whoLetDogsOut.computeIfAbsent("snoop", k -> k.isEmpty());
to achieve the same result without a helper method (but you won’t see the debugging output then). And even simpler, as it is a simple delegation to an existing method you could write: whoLetDogsOut.computeIfAbsent("snoop", String::isEmpty);
This delegation does not need any parameters to be written.
To be closer to the example in your question, you could write it as whoLetDogsOut.computeIfAbsent("snoop", key -> tryToLetOut(key));
(it doesn’t matter whether you name the parameter k
or key
). Or write it as whoLetDogsOut.computeIfAbsent("snoop", MyClass::tryToLetOut);
if tryToLetOut
is static
or whoLetDogsOut.computeIfAbsent("snoop", this::tryToLetOut);
if tryToLetOut
is an instance method.
As Brannon says, it's OrderByDescending
and ThenByDescending
:
var query = from person in people
orderby person.Name descending, person.Age descending
select person.Name;
is equivalent to:
var query = people.OrderByDescending(person => person.Name)
.ThenByDescending(person => person.Age)
.Select(person => person.Name);
To add on to chepner's answer for Python 3.0 you can alternatively do:
x = lambda x: list(map(print, x))
Of course this is only if you have the means of using Python > 3 in the future... Looks a bit cleaner in my opinion, but it also has a weird return value, but you're probably discarding it anyway.
I'll just leave this here for reference.
An important difference is that list comprehension will return a list
while the filter returns a filter
, which you cannot manipulate like a list
(ie: call len
on it, which does not work with the return of filter
).
My own self-learning brought me to some similar issue.
That being said, if there is a way to have the resulting list
from a filter
, a bit like you would do in .NET when you do lst.Where(i => i.something()).ToList()
, I am curious to know it.
EDIT: This is the case for Python 3, not 2 (see discussion in comments).
It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.
Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
Map<String, DataSet> result = new HashMap<>();
multiDataPoints.forEach(pt ->
pt.keyToData.forEach((key, value) ->
result.computeIfAbsent(
key, k -> new DataSet(k, new ArrayList<>()))
.dataPoints.add(new DataPoint(pt.timestamp, value))));
return result.values();
}
Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
new Object() {
String key = e.getKey();
DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
}))
.collect(
collectingAndThen(
groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}
Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.map(mdp -> mdp.keyToData.entrySet().stream()
.collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
.reduce(new HashMap<>(), mapMerger())
.entrySet().stream()
.map(e -> new DataSet(e.getKey(), e.getValue()))
.collect(toList());
}
You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:
<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
return (lhs, rhs) -> {
Map<K, List<V>> result = new HashMap<>();
lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
return result;
};
}
Predicate<Client> hasSameNameAsOneUser =
c -> users.stream().anyMatch(u -> u.getName().equals(c.getName()));
return clients.stream()
.filter(hasSameNameAsOneUser)
.collect(Collectors.toList());
But this is quite inefficient, because it's O(m * n). You'd better create a Set of acceptable names:
Set<String> acceptableNames =
users.stream()
.map(User::getName)
.collect(Collectors.toSet());
return clients.stream()
.filter(c -> acceptableNames.contains(c.getName()))
.collect(Collectors.toList());
Also note that it's not strictly equivalent to the code you have (if it compiled), which adds the same client twice to the list if several users have the same name as the client.
I don't see any answers yet that mention performance. Passing Func<>
s into Where()
or Count()
is bad. Real bad. If you use a Func<>
then it calls the IEnumerable
LINQ stuff instead of IQueryable
, which means that whole tables get pulled in and then filtered. Expression<Func<>>
is significantly faster, especially if you are querying a database that lives another server.
lambda
is an anonymous function, it is equivalent to:
def func(p):
return p.totalScore
Now max
becomes:
max(players, key=func)
But as def
statements are compound statements they can't be used where an expression is required, that's why sometimes lambda
's are used.
Note that lambda
is equivalent to what you'd put in a return statement of a def
. Thus, you can't use statements inside a lambda
, only expressions are allowed.
What does max
do?
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.
So, it simply returns the object that is the largest.
How does key
work?
By default in Python 2 key
compares items based on a set of rules based on the type of the objects (for example a string is always greater than an integer).
To modify the object before comparison, or to compare based on a particular attribute/index, you've to use the key
argument.
Example 1:
A simple example, suppose you have a list of numbers in string form, but you want to compare those items by their integer value.
>>> lis = ['1', '100', '111', '2']
Here max
compares the items using their original values (strings are compared lexicographically so you'd get '2'
as output) :
>>> max(lis)
'2'
To compare the items by their integer value use key
with a simple lambda
:
>>> max(lis, key=lambda x:int(x)) # compare `int` version of each item
'111'
Example 2: Applying max
to a list of tuples.
>>> lis = [(1,'a'), (3,'c'), (4,'e'), (-1,'z')]
By default max
will compare the items by the first index. If the first index is the same then it'll compare the second index. As in my example, all items have a unique first index, so you'd get this as the answer:
>>> max(lis)
(4, 'e')
But, what if you wanted to compare each item by the value at index 1? Simple: use lambda
:
>>> max(lis, key = lambda x: x[1])
(-1, 'z')
Comparing items in an iterable that contains objects of different type:
List with mixed items:
lis = ['1','100','111','2', 2, 2.57]
In Python 2 it is possible to compare items of two different types:
>>> max(lis) # works in Python 2
'2'
>>> max(lis, key=lambda x: int(x)) # compare integer version of each item
'111'
But in Python 3 you can't do that any more:
>>> lis = ['1', '100', '111', '2', 2, 2.57]
>>> max(lis)
Traceback (most recent call last):
File "<ipython-input-2-0ce0a02693e4>", line 1, in <module>
max(lis)
TypeError: unorderable types: int() > str()
But this works, as we are comparing integer version of each object:
>>> max(lis, key=lambda x: int(x)) # or simply `max(lis, key=int)`
'111'
Probably the worst python line I've written so far:
f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])
If x == 2 you print,
if x != 2 you raise.
As it was mentioned by the others you can substitute Lambda function instead of function pointer. I am using this method in my C++ interface to F77 ODE solver RKSUITE.
//C interface to Fortran subroutine UT
extern "C" void UT(void(*)(double*,double*,double*),double*,double*,double*,
double*,double*,double*,int*);
// C++ wrapper which calls extern "C" void UT routine
static void rk_ut(void(*)(double*,double*,double*),double*,double*,double*,
double*,double*,double*,int*);
// Call of rk_ut with lambda passed instead of function pointer to derivative
// routine
mathlib::RungeKuttaSolver::rk_ut([](double* T,double* Y,double* YP)->void{YP[0]=Y[1]; YP[1]= -Y[0];}, TWANT,T,Y,YP,YMAX,WORK,UFLAG);
You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting
countByType.entrySet()
.stream()
.sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator
.map(e -> e.getKey())
.collect(Collectors.toList());
I find that if you're familiar with SQL syntax, using the LINQ query syntax is much clearer, more natural, and makes it easier to spot errors:
var id = 1;
var query =
from post in database.Posts
join meta in database.Post_Metas on post.ID equals meta.Post_ID
where post.ID == id
select new { Post = post, Meta = meta };
If you're really stuck on using lambdas though, your syntax is quite a bit off. Here's the same query, using the LINQ extension methods:
var id = 1;
var query = database.Posts // your starting point - table in the "from" statement
.Join(database.Post_Metas, // the source table of the inner join
post => post.ID, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
meta => meta.Post_ID, // Select the foreign key (the second part of the "on" clause)
(post, meta) => new { Post = post, Meta = meta }) // selection
.Where(postAndMeta => postAndMeta.Post.ID == id); // where statement
I believe something like this should work:
origList.Select(a => new TargetType() { SomeValue = a.SomeValue});
The proposed answers are great. Just would like to suggest an improvement to handle the case of null list using Optional.ofNullable
, new feature in Java 8:
List<String> carsFiltered = Optional.ofNullable(cars)
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
So, the full answer will be:
List<String> carsFiltered = Optional.ofNullable(cars)
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull) //filtering car object that are null
.map(Car::getName) //now it's a stream of Strings
.filter(Objects::nonNull) //filtering null in Strings
.filter(name -> name.startsWith("M"))
.collect(Collectors.toList()); //back to List of Strings
My StreamEx library which enhances the Java 8 streams provides a special operation distinct(atLeast)
which can retain only elements appearing at least the specified number of times. So your problem can be solved like this:
List<Integer> repeatingNumbers = StreamEx.of(numbers).distinct(2).toList();
Internally it's similar to @Dave solution, it counts objects, to support other wanted quantities and it's parallel-friendly (it uses ConcurrentHashMap
for parallelized stream, but HashMap
for sequential). For big amounts of data you can get a speed-up using .parallel().distinct(2)
.
An alternative to AtomicInteger
is to use an array (or any other object able to store a value):
final int ordinal[] = new int[] { 0 };
list.forEach ( s -> s.setOrdinal ( ordinal[ 0 ]++ ) );
But see the Stuart's answer: there might be a better way to deal with your case.
Collector
:public static <T> Collector<T, ?, Optional<T>> toSingleton() {
return Collectors.collectingAndThen(
Collectors.toList(),
list -> list.size() == 1 ? Optional.of(list.get(0)) : Optional.empty()
);
}
Optional<User> result = users.stream()
.filter((user) -> user.getId() < 0)
.collect(toSingleton());
We return an Optional
, since we usually can't assume the Collection
to contain exactly one element. If you already know this is the case, call:
User user = result.orElseThrow();
This puts the burden of handeling the error on the caller - as it should.
Use ThenBy
:
var orderedCustomers = Customer.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)
See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx
To much code, you can use it like this:
#include<array>
#include<functional>
int main()
{
std::array<int, 10> vec = { 1,2,3,4,5,6,7,8,9 };
std::sort(std::begin(vec),
std::end(vec),
[](int a, int b) {return a > b; });
for (auto item : vec)
std::cout << item << " ";
return 0;
}
Replace "vec" with your class and that's it.
The lambda you pass to Where
can include any normal C# code, for example the &&
operator:
.Where(l => l.Title != string.Empty && l.InternalName != string.Empty)
You need to add else
in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.
sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x)
'Effectively final' is a variable which would not give compiler error if it were to be appended by 'final'
From a article by 'Brian Goetz',
Informally, a local variable is effectively final if its initial value is never changed -- in other words, declaring it final would not cause a compilation failure.
Java 8 has a new concept called “Effectively final” variable. It means that a non-final local variable whose value never changes after initialization is called “Effectively Final”.
This concept was introduced because prior to Java 8, we could not use a non-final local variable in an anonymous class. If you wanna have access to a local variable in anonymous class, you have to make it final.
When lambda was introduced, this restriction was eased. Hence to the need to make local variable final if it’s not changed once it is initialized as lambda in itself is nothing but an anonymous class.
Java 8 realized the pain of declaring local variable final every time a developer used lambda, introduced this concept, and made it unnecessary to make local variables final. So if you see the rule for anonymous classes has not changed, it’s just you don’t have to write the final
keyword every time when using lambdas.
I found a good explanation here
static void Main(string[] args)
{
var prop = GetPropertyInfo<MyDto>(_ => _.MyProperty);
MyDto dto = new MyDto();
dto.MyProperty = 666;
var value = prop.GetValue(dto);
// value == 666
}
class MyDto
{
public int MyProperty { get; set; }
}
public static PropertyInfo GetPropertyInfo<TSource>(Expression<Func<TSource, object>> propertyLambda)
{
Type type = typeof(TSource);
var member = propertyLambda.Body as MemberExpression;
if (member == null)
{
var unary = propertyLambda.Body as UnaryExpression;
if (unary != null)
{
member = unary.Operand as MemberExpression;
}
}
if (member == null)
{
throw new ArgumentException(string.Format("Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
}
var propInfo = member.Member as PropertyInfo;
if (propInfo == null)
{
throw new ArgumentException(string.Format("Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
}
if (type != propInfo.ReflectedType && !type.IsSubclassOf(propInfo.ReflectedType))
{
throw new ArgumentException(string.Format("Expression '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(), type));
}
return propInfo;
}
It saves having to have methods that are only used once in a specific place from being defined far away from the place they are used. Good uses are as comparators for generic algorithms such as sorting, where you can then define a custom sort function where you are invoking the sort rather than further away forcing you to look elsewhere to see what you are sorting on.
And it's not really an innovation. LISP has had lambda functions for about 30 years or more.
I combined some beautiful answers here to make it possible to easily support more Expression operators.
This is based on the answer of @Dejan but now it's quite easy to add the OR as well. I chose not to make the Combine
function public, but you could do that to be even more flexible.
public static class ExpressionExtensions
{
public static Expression<Func<T, bool>> AndAlso<T>(this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression) =>
Combine(leftExpression, rightExpression, Expression.AndAlso);
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> leftExpression,
Expression<Func<T, bool>> rightExpression) =>
Combine(leftExpression, rightExpression, Expression.Or);
public static Expression<Func<T, bool>> Combine<T>(Expression<Func<T, bool>> leftExpression, Expression<Func<T, bool>> rightExpression, Func<Expression, Expression, BinaryExpression> combineOperator)
{
var leftParameter = leftExpression.Parameters[0];
var rightParameter = rightExpression.Parameters[0];
var visitor = new ReplaceParameterVisitor(rightParameter, leftParameter);
var leftBody = leftExpression.Body;
var rightBody = visitor.Visit(rightExpression.Body);
return Expression.Lambda<Func<T, bool>>(combineOperator(leftBody, rightBody), leftParameter);
}
private class ReplaceParameterVisitor : ExpressionVisitor
{
private readonly ParameterExpression _oldParameter;
private readonly ParameterExpression _newParameter;
public ReplaceParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
{
_oldParameter = oldParameter;
_newParameter = newParameter;
}
protected override Expression VisitParameter(ParameterExpression node)
{
return ReferenceEquals(node, _oldParameter) ? _newParameter : base.VisitParameter(node);
}
}
}
Usage is not changed and still like this:
Expression<Func<Result, bool>> noFilterExpression = item => filters == null;
Expression<Func<Result, bool>> laptopFilterExpression = item => item.x == ...
Expression<Func<Result, bool>> dateFilterExpression = item => item.y == ...
var combinedFilterExpression = noFilterExpression.Or(laptopFilterExpression.AndAlso(dateFilterExpression));
efQuery.Where(combinedFilterExpression);
(This is an example based on my actual code, but read is as pseudo-code)
you can use linq :) using :
System.linq;
var newList = people.OrderBy(x=>x.Name).ToList();
The code that has to be executed for both alternatives is so similar that you can’t predict a result reliably. The underlying object structure might differ but that’s no challenge to the hotspot optimizer. So it depends on other surrounding conditions which will yield to a faster execution, if there is any difference.
Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x.isCool())
by filter(ItemType::isCool)
. That way you have eliminated the synthetic delegating method created for your lambda expression. So combining two filters using two method references might create the same or lesser delegation code than a single filter
invocation using a lambda expression with &&
.
But, as said, this kind of overhead will be eliminated by the HotSpot optimizer and is negligible.
In theory, two filters could be easier parallelized than a single filter but that’s only relevant for rather computational intense tasks¹.
So there is no simple answer.
The bottom line is, don’t think about such performance differences below the odor detection threshold. Use what is more readable.
¹…and would require an implementation doing parallel processing of subsequent stages, a road currently not taken by the standard Stream implementation
To add to the solutions, here is a LINQ statement that might help
Utilities.DIMENSION_MemTbl.Where(a => a.DIMENSION_ID == format.ContentBrief.DimensionID).Select(a=>a.DIMENSION1).DefaultIfEmpty("").FirstOrDefault();
The result will be an empty string if the result of the query is a null..
Your second delegate is not a rewrite of the first in anonymous delegate (rather than lambda) format. Look at your conditions.
First:
x.ID == packageId || x.Parent.ID == packageId || x.Parent.Parent.ID == packageId
Second:
(x.ID == packageId) || (x.Parent != null && x.Parent.ID == packageId) ||
(x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
The call to the lambda would throw an exception for any x
where the ID doesn't match and either the parent is null or doesn't match and the grandparent is null. Copy the null checks into the lambda and it should work correctly.
If your original object is not a List<T>
, then we have no way of knowing what the return type of FindAll()
is, and whether or not this implements the IQueryable
interface. If it does, then that likely explains the discrepancy. Because lambdas can be converted at compile time into an Expression<Func<T>>
but anonymous delegates cannot, then you may be using the implementation of IQueryable
when using the lambda version but LINQ-to-Objects when using the anonymous delegate version.
This would also explain why your lambda is not causing a NullReferenceException
. If you were to pass that lambda expression to something that implements IEnumerable<T>
but not IQueryable<T>
, runtime evaluation of the lambda (which is no different from other methods, anonymous or not) would throw a NullReferenceException
the first time it encountered an object where ID
was not equal to the target and the parent or grandparent was null.
Consider the following simple example:
IQueryable<MyObject> source = ...; // some object that implements IQueryable<MyObject>
var anonymousMethod = source.Where(delegate(MyObject o) { return o.Name == "Adam"; });
var expressionLambda = source.Where(o => o.Name == "Adam");
These two methods produce entirely different results.
The first query is the simple version. The anonymous method results in a delegate that's then passed to the IEnumerable<MyObject>.Where
extension method, where the entire contents of source
will be checked (manually in memory using ordinary compiled code) against your delegate. In other words, if you're familiar with iterator blocks in C#, it's something like doing this:
public IEnumerable<MyObject> MyWhere(IEnumerable<MyObject> dataSource, Func<MyObject, bool> predicate)
{
foreach(MyObject item in dataSource)
{
if(predicate(item)) yield return item;
}
}
The salient point here is that you're actually performing your filtering in memory on the client side. For example, if your source were some SQL ORM, there would be no WHERE
clause in the query; the entire result set would be brought back to the client and filtered there.
The second query, which uses a lambda expression, is converted to an Expression<Func<MyObject, bool>>
and uses the IQueryable<MyObject>.Where()
extension method. This results in an object that is also typed as IQueryable<MyObject>
. All of this works by then passing the expression to the underlying provider. This is why you aren't getting a NullReferenceException
. It's entirely up to the query provider how to translate the expression (which, rather than being an actual compiled function that it can just call, is a representation of the logic of the expression using objects) into something it can use.
An easy way to see the distinction (or, at least, that there is) a distinction, would be to put a call to AsEnumerable()
before your call to Where
in the lambda version. This will force your code to use LINQ-to-Objects (meaning it operates on IEnumerable<T>
like the anonymous delegate version, not IQueryable<T>
like the lambda version currently does), and you'll get the exceptions as expected.
The long and the short of it is that your lambda expression is being translated into some kind of query against your data source, whereas the anonymous method version is evaluating the entire data source in memory. Whatever is doing the translating of your lambda into a query is not representing the logic that you're expecting, which is why it isn't producing the results you're expecting.
In C++20 this is possible using the following syntax:
auto lambda = []<typename T>(T t){
// do something
};
Use a Func<T1, T2, TResult>
delegate as the parameter type and pass it in to your Query
:
public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
using (SqlConnection connection = new SqlConnection(getConnectionString())) {
connection.Open();
return connection.Query<FullTimeJob, Student, FullTimeJob>(sql,
lambda,
splitOn: "user_id",
param: parameters).ToList<IJob>();
}
}
You would call it:
getJobs((job, student) => {
job.Student = student;
job.StudentId = student.Id;
return job;
});
Or assign the lambda to a variable and pass it in.
public ActionResult Index()
{
List<CustomerOrder_Result> obj = new List<CustomerOrder_Result>();
var orderlist = (from a in db.OrderMasters
join b in db.Customers on a.CustomerId equals b.Id
join c in db.CustomerAddresses on b.Id equals c.CustomerId
where a.Status == "Pending"
select new
{
Customername = b.Customername,
Phone = b.Phone,
OrderId = a.OrderId,
OrderDate = a.OrderDate,
NoOfItems = a.NoOfItems,
Order_amt = a.Order_amt,
dis_amt = a.Dis_amt,
net_amt = a.Net_amt,
status=a.Status,
address = c.address,
City = c.City,
State = c.State,
Pin = c.Pin
}) ;
foreach (var item in orderlist)
{
CustomerOrder_Result clr = new CustomerOrder_Result();
clr.Customername=item.Customername;
clr.Phone = item.Phone;
clr.OrderId = item.OrderId;
clr.OrderDate = item.OrderDate;
clr.NoOfItems = item.NoOfItems;
clr.Order_amt = item.Order_amt;
clr.net_amt = item.net_amt;
clr.address = item.address;
clr.City = item.City;
clr.State = item.State;
clr.Pin = item.Pin;
clr.status = item.status;
obj.Add(clr);
}
Use the exp1 if cond else exp2
syntax.
rate = lambda T: 200*exp(-T) if T>200 else 400*exp(-T)
Note you don't use return
in lambda expressions.
You can potentially roll your own Stream
variant by wrapping your lambda to throw an unchecked exception and then later unwrapping that unchecked exception on terminal operations:
@FunctionalInterface
public interface ThrowingPredicate<T, X extends Throwable> {
public boolean test(T t) throws X;
}
@FunctionalInterface
public interface ThrowingFunction<T, R, X extends Throwable> {
public R apply(T t) throws X;
}
@FunctionalInterface
public interface ThrowingSupplier<R, X extends Throwable> {
public R get() throws X;
}
public interface ThrowingStream<T, X extends Throwable> {
public ThrowingStream<T, X> filter(
ThrowingPredicate<? super T, ? extends X> predicate);
public <R> ThrowingStream<T, R> map(
ThrowingFunction<? super T, ? extends R, ? extends X> mapper);
public <A, R> R collect(Collector<? super T, A, R> collector) throws X;
// etc
}
class StreamAdapter<T, X extends Throwable> implements ThrowingStream<T, X> {
private static class AdapterException extends RuntimeException {
public AdapterException(Throwable cause) {
super(cause);
}
}
private final Stream<T> delegate;
private final Class<X> x;
StreamAdapter(Stream<T> delegate, Class<X> x) {
this.delegate = delegate;
this.x = x;
}
private <R> R maskException(ThrowingSupplier<R, X> method) {
try {
return method.get();
} catch (Throwable t) {
if (x.isInstance(t)) {
throw new AdapterException(t);
} else {
throw t;
}
}
}
@Override
public ThrowingStream<T, X> filter(ThrowingPredicate<T, X> predicate) {
return new StreamAdapter<>(
delegate.filter(t -> maskException(() -> predicate.test(t))), x);
}
@Override
public <R> ThrowingStream<R, X> map(ThrowingFunction<T, R, X> mapper) {
return new StreamAdapter<>(
delegate.map(t -> maskException(() -> mapper.apply(t))), x);
}
private <R> R unmaskException(Supplier<R> method) throws X {
try {
return method.get();
} catch (AdapterException e) {
throw x.cast(e.getCause());
}
}
@Override
public <A, R> R collect(Collector<T, A, R> collector) throws X {
return unmaskException(() -> delegate.collect(collector));
}
}
Then you could use this the same exact way as a Stream
:
Stream<Account> s = accounts.values().stream();
ThrowingStream<Account, IOException> ts = new StreamAdapter<>(s, IOException.class);
return ts.filter(Account::isActive).map(Account::getNumber).collect(toSet());
This solution would require quite a bit of boilerplate, so I suggest you take a look at the library I already made which does exactly what I have described here for the entire Stream
class (and more!).
sum(l) / float(len(l))
is the right answer, but just for completeness you can compute an average with a single reduce:
>>> reduce(lambda x, y: x + y / float(len(l)), l, 0)
20.111111111111114
Note that this can result in a slight rounding error:
>>> sum(l) / float(len(l))
20.111111111111111
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
@FunctionalInterface
annotation is useful for compilation time checking of your code. You cannot have more than one method besides static
, default
and abstract methods that override methods in Object
in your @FunctionalInterface
or any other interface used as a functional interface.
But you can use lambdas without this annotation as well as you can override methods without @Override
annotation.
From docs
a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere
This can be used in lambda expression:
public interface Foo {
public void doSomething();
}
This cannot be used in lambda expression:
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
But this will give compilation error:
@FunctionalInterface
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
Invalid '@FunctionalInterface' annotation; Foo is not a functional interface
Use Supplier
if it takes nothing, but returns something.
Use Consumer
if it takes something, but returns nothing.
Use Callable
if it returns a result and might throw (most akin to Thunk
in general CS terms).
Use Runnable
if it does neither and cannot throw.
int valueToMatch = 7;
Stream.of(1,2,3,4,5,6,7,8).anyMatch(val->{
boolean isMatch = val == valueToMatch;
if(isMatch) {
/*Do whatever you want...*/
System.out.println(val);
}
return isMatch;
});
It will do only operation where it find match, and after find match it stop it's iteration.
The keyword you're looking for is list comprehensions:
>>> x = [1, 2, 3, 4, 5]
>>> y = [2*a for a in x if a % 2 == 1]
>>> print(y)
[2, 6, 10]
Just use Task.Run
var task = Task.Run(() =>
{
//this will already share scope with rawData, no need to use a placeholder
});
Or, if you would like to use it in a method and await the task later
public Task<T> SomethingAsync<T>()
{
var task = Task.Run(() =>
{
//presumably do something which takes a few ms here
//this will share scope with any passed parameters in the method
return default(T);
});
return task;
}
You can.
Extending @marcg 's UtilException
and adding generic <E extends Exception>
where necessary: this way, the compiler will force you again to add throw clauses and everything's as if you could throw checked exceptions natively on java 8's streams.
public final class LambdaExceptionUtil {
@FunctionalInterface
public interface Function_WithExceptions<T, R, E extends Exception> {
R apply(T t) throws E;
}
/**
* .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName))
*/
public static <T, R, E extends Exception> Function<T, R> rethrowFunction(Function_WithExceptions<T, R, E> function) throws E {
return t -> {
try {
return function.apply(t);
} catch (Exception exception) {
throwActualException(exception);
return null;
}
};
}
@SuppressWarnings("unchecked")
private static <E extends Exception> void throwActualException(Exception exception) throws E {
throw (E) exception;
}
}
public class LambdaExceptionUtilTest {
@Test
public void testFunction() throws MyTestException {
List<Integer> sizes = Stream.of("ciao", "hello").<Integer>map(rethrowFunction(s -> transform(s))).collect(toList());
assertEquals(2, sizes.size());
assertEquals(4, sizes.get(0).intValue());
assertEquals(5, sizes.get(1).intValue());
}
private Integer transform(String value) throws MyTestException {
if(value==null) {
throw new MyTestException();
}
return value.length();
}
private static class MyTestException extends Exception { }
}
You could use ForEach
, but you have to convert the IEnumerable<T>
to a List<T>
first.
list.Where(w => w.Name == "height").ToList().ForEach(s => s.Value = 30);
What you are doing may be the simplest way, provided your stream stays sequential—otherwise you will have to put a call to sequential() before forEach
.
[later edit: the reason the call to sequential() is necessary is that the code as it stands (forEach(targetLongList::add)
) would be racy if the stream was parallel. Even then, it will not achieve the effect intended, as forEach
is explicitly nondeterministic—even in a sequential stream the order of element processing is not guaranteed. You would have to use forEachOrdered
to ensure correct ordering. The intention of the Stream API designers is that you will use collector in this situation, as below.]
An alternative is
targetLongList = sourceLongList.stream()
.filter(l -> l > 100)
.collect(Collectors.toList());
Since the usage of lambda was asked in the context of sorted()
, take a look at this as well https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions
It's as simple as this: lambda is a language construct, i.e. simply syntax for anonymous functions; a closure is a technique to implement it -- or any first-class functions, for that matter, named or anonymous.
More precisely, a closure is how a first-class function is represented at runtime, as a pair of its "code" and an environment "closing" over all the non-local variables used in that code. This way, those variables are still accessible even when the outer scopes where they originate have already been exited.
Unfortunately, there are many languages out there that do not support functions as first-class values, or only support them in crippled form. So people often use the term "closure" to distinguish "the real thing".
For List :
List<Integer> intList
= stringList.stream().map(Integer::valueOf).collect(Collectors.toList());
For Array :
int[] intArray = Arrays.stream(stringArray).mapToInt(Integer::valueOf).toArray();
EventHandler handler = (s, e) => MessageBox.Show("Woho");
button.Click += handler;
button.Click -= handler;
In my case, I had to add using System.Data.Entity;
Want to put out there that there is not much to worry about if someone provides an answer as an extension method because an extension method is just a cool way to call an instance method. I understand that you want the answer without using an extension method. Regardless if the method is defined as static, instance or extension - the result is the same.
The code below uses the code from the accepted answer to define an extension method and an instance method and creates a unit test to show the output is the same.
public static class Extensions
{
public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
}
[TestFixture]
public class ForEachTests
{
public void Each<T>(IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
private string _extensionOutput;
private void SaveExtensionOutput(string value)
{
_extensionOutput += value;
}
private string _instanceOutput;
private void SaveInstanceOutput(string value)
{
_instanceOutput += value;
}
[Test]
public void Test1()
{
string[] teams = new string[] {"cowboys", "falcons", "browns", "chargers", "rams", "seahawks", "lions", "heat", "blackhawks", "penguins", "pirates"};
Each(teams, SaveInstanceOutput);
teams.Each(SaveExtensionOutput);
Assert.AreEqual(_extensionOutput, _instanceOutput);
}
}
Quite literally, the only thing you need to do to convert an extension method to an instance method is remove the static
modifier and the first parameter of the method.
This method
public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
becomes
public void Each<T>(Action<T> action)
{
foreach (var item in items)
{
action(item);
}
}
Yes, you can do this by creating a DoubleStream
from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:
double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]
If you want to filter a reference array that is not an Object[]
you will need to use the toArray
method which takes an IntFunction
to get an array of the original type as the result:
String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);
I had the same sittuation , I had many buttongroup insite my item on listview and I was changing some boolean values inside my item like holder.rbVar.setOnclik...
my problem occured because I was calling a method inside getView(); and was saving an object inside sharepreference, so I had same error above
How I solved it; I removed my method inside getView() to notifyDataSetInvalidated() and problem gone
@Override
public void notifyDataSetChanged() {
saveCurrentTalebeOnShare(currentTalebe);
super.notifyDataSetChanged();
}
// find the first select and bind a click handler
$('#column_select').bind('click', function(){
// retrieve the selected value
var value = $(this).val(),
// build a regular expression that does a head-match
expression = new RegExp('^' + value),
// find the second select
$select = $('#layout_select);
// hide all children (<option>s) of the second select,
// check each element's value agains the regular expression built from the first select's value
// show elements that match the expression
$select.children().hide().filter(function(){
return !!$(this).val().match(expression);
}).show();
});
(this is far from perfect, but should get you there…)
You can use joblib
library to do parallel computation and multiprocessing.
from joblib import Parallel, delayed
You can simply create a function foo
which you want to be run in parallel and based on the following piece of code implement parallel processing:
output = Parallel(n_jobs=num_cores)(delayed(foo)(i) for i in input)
Where num_cores
can be obtained from multiprocessing
library as followed:
import multiprocessing
num_cores = multiprocessing.cpu_count()
If you have a function with more than one input argument, and you just want to iterate over one of the arguments by a list, you can use the the partial
function from functools
library as follow:
from joblib import Parallel, delayed
import multiprocessing
from functools import partial
def foo(arg1, arg2, arg3, arg4):
'''
body of the function
'''
return output
input = [11,32,44,55,23,0,100,...] # arbitrary list
num_cores = multiprocessing.cpu_count()
foo_ = partial(foo, arg2=arg2, arg3=arg3, arg4=arg4)
# arg1 is being fetched from input list
output = Parallel(n_jobs=num_cores)(delayed(foo_)(i) for i in input)
You can find a complete explanation of the python and R multiprocessing with couple of examples here.
Yes you can create a nested data structure people
which can be indexed by Anna
and Ben
. However, you can't index it directly by age
and profession
(I will get to this part in the code).
The data type of people
is of type Json::Value
(which is defined in jsoncpp). You are right, it is similar to the nested map, but Value
is a data structure which is defined such that multiple types can be stored and accessed. It is similar to a map with a string
as the key and Json::Value
as the value. It could also be a map between an unsigned int
as key and Json::Value
as the value (In case of json arrays).
Here's the code:
#include <json/value.h>
#include <fstream>
std::ifstream people_file("people.json", std::ifstream::binary);
people_file >> people;
cout<<people; //This will print the entire json object.
//The following lines will let you access the indexed objects.
cout<<people["Anna"]; //Prints the value for "Anna"
cout<<people["ben"]; //Prints the value for "Ben"
cout<<people["Anna"]["profession"]; //Prints the value corresponding to "profession" in the json for "Anna"
cout<<people["profession"]; //NULL! There is no element with key "profession". Hence a new empty element will be created.
As you can see, you can index the json object only based on the hierarchy of the input data.
// plugins/moment.js
import moment from 'moment';
moment.locale('ru');
export default function install (Vue) {
Object.defineProperties(Vue.prototype, {
$moment: {
get () {
return moment;
}
}
})
}
// main.js
import moment from './plugins/moment.js';
Vue.use(moment);
// use this.$moment in your components
Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:
just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens
that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)
an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants
You could use the Morpha stemmer. UW has uploaded morpha stemmer to Maven central if you plan to use it from a Java application. There's a wrapper that makes it much easier to use. You just need to add it as a dependency and use the edu.washington.cs.knowitall.morpha.MorphaStemmer
class. Instances are threadsafe (the original JFlex had class fields for local variables unnecessarily). Instantiate a class and run morpha
and the word you want to stem.
new MorphaStemmer().morpha("climbed") // goes to "climb"
Download source code from here (Open pdf in webview android)
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<WebView
android:layout_width="match_parent"
android:background="#ffffff"
android:layout_height="match_parent"
android:id="@+id/webview"></WebView>
</RelativeLayout>
MainActivity.java
package com.pdfwebview;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
WebView webview;
ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
listener();
}
private void init() {
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setTitle("PDF");
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
webview.loadUrl("https://drive.google.com/file/d/0B534aayZ5j7Yc3RhcnRlcl9maWxl/view");
}
private void listener() {
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
pDialog.show();
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
pDialog.dismiss();
}
});
}
}
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
Java always uses at least 32 bit values for calculations. This is due to the 32-bit architecture which was common 1995 when java was introduced. The register size in the CPU was 32 bit and the arithmetic logic unit accepted 2 numbers of the length of a cpu register. So the cpus were optimized for such values.
This is the reason why all datatypes which support arithmetic opperations and have less than 32-bits are converted to int (32 bit) as soon as you use them for calculations.
So to sum up it mainly was due to performance issues and is kept nowadays for compatibility.
Thank you Kris!
It worked for me without using parameters to the query, whenever I used more than one parameter it showed me the error: 32 Could not authenticate you.
The problem for me, was in the ampersand encoding. So in your code where it's the following line
$url .= "?".http_build_query($query);
I added the following line below:
$url=str_replace("&","&",$url);
And it worked using two or more parameters like screen_name and count.
The whole code looks like this:
$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY SECRET';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path
$query = array( // query parameters
'screen_name' => 'twitterapi',
'count' => '2'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_token' => $token,
'oauth_nonce' => (string)mt_rand(), // a stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// mash everything together for the text to hash
$base_string = $method."&".rawurlencode($url)."&".rawurlencode($querystring);
// same with the key
$key = rawurlencode($consumer_secret)."&".rawurlencode($token_secret);
// generate the hash
$signature = rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
// this time we're using a normal GET query, and we're only encoding the query params
// (without the oauth params)
$url .= "?".http_build_query($query);
$url=str_replace("&","&",$url); //Patch by @Frewuill
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// this is the full value of the Authorization line
$auth = "OAuth " . urldecode(http_build_query($oauth, '', ', '));
// if you're doing post, you need to skip the GET building above
// and instead supply query parameters to CURLOPT_POSTFIELDS
$options = array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
Hope It helps somebody with the same problem I had.
Documentation for crypto: http://nodejs.org/api/crypto.html
const crypto = require('crypto')
const text = 'I love cupcakes'
const key = 'abcdeg'
crypto.createHmac('sha1', key)
.update(text)
.digest('hex')
export class MyComponent implements OnInit {_x000D_
_x000D_
items: any[] = [_x000D_
{ id: 1, name: 'one' },_x000D_
{ id: 2, name: 'two' },_x000D_
{ id: 3, name: 'three' },_x000D_
{ id: 4, name: 'four' },_x000D_
{ id: 5, name: 'five' },_x000D_
{ id: 6, name: 'six' }_x000D_
];_x000D_
selected: number = 1;_x000D_
_x000D_
constructor() {_x000D_
}_x000D_
_x000D_
ngOnInit() {_x000D_
}_x000D_
_x000D_
selectOption(id: number) {_x000D_
//getted from event_x000D_
console.log(id);_x000D_
//getted from binding_x000D_
console.log(this.selected)_x000D_
}_x000D_
_x000D_
}
_x000D_
<div>_x000D_
<select (change)="selectOption($event.target.value)"_x000D_
[(ngModel)]="selected">_x000D_
<option [value]="item.id" *ngFor="let item of items">{{item.name}}</option>_x000D_
</select>_x000D_
</div>
_x000D_
The first argument to parse() is the expected format. You have to change that to Date.parse("E MMM dd H:m:s z yyyy", testDate)
for it to work. (Note you don't need to create a new Date object, it's a static method)
If you don't know in advance what format, you'll have to find a special parsing library for that. In Ruby there's a library called Chronic, but I'm not aware of a Groovy equivalent. Edit: There is a Java port of the library called jChronic, you might want to check it out.
I prefer Google Collections over Apache StringUtils for this particular problem:
Joiner.on(separator).join(array)
Compared to StringUtils, the Joiner API has a fluent design and is a bit more flexible, e.g. null
elements may be skipped or replaced by a placeholder. Also, Joiner
has a feature for joining maps with a separator between key and value.
update tablename set coldate=DATE_ADD(coldate, INTERVAL 2 DAY)
It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.
Above things are really helpful.
While creating web services, If you will take case of services consumer will greatly appreciated. I tried to maintain uniformity of the output. Also you can give remark or actual error message. The web service consumer can only check IsSuccess true or not else will sure there is problem, and act as per situation.
public class Response
{
/// <summary>
/// Gets or sets a value indicating whether this instance is success.
/// </summary>
/// <value>
/// <c>true</c> if this instance is success; otherwise, <c>false</c>.
/// </value>
public bool IsSuccess { get; set; } = false;
/// <summary>
/// Actual response if succeed
/// </summary>
/// <value>
/// Actual response if succeed
/// </value>
public object Data { get; set; } = null;
/// <summary>
/// Remark if anythig to convey
/// </summary>
/// <value>
/// Remark if anythig to convey
/// </value>
public string Remark { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the error message.
/// </summary>
/// <value>
/// The error message.
/// </value>
public object ErrorMessage { get; set; } = null;
}
[HttpGet]
public IHttpActionResult Employees()
{
Response _res = new Response();
try
{
DalTest objDal = new DalTest();
_res.Data = objDal.GetTestData();
_res.IsSuccess = true;
return Ok<Response>(_res);
}
catch (Exception ex)
{
_res.IsSuccess = false;
_res.ErrorMessage = ex;
return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, _res ));
}
}
You are welcome to give suggestion if any :)
Try this
> dt.columns.Add("ColumnName", typeof(Give the type you want));
> dt.Rows[give the row no like or or any no]["Column name in which you want to add data"] = Value;
Still if it doesn't work, just lock all the files and unlock. Now clean up again, It will work.
svn update svn cleanup
Instead of using $_POST, use $_REQUEST:
HTML:
<form action="" method="post">
<input type="text" name="firstname">
<input type="submit" name="submit" value="Submit">
</form>
PHP:
if(isset($_REQUEST['submit'])){
$test = $_REQUEST['firstname'];
echo $test;
}
The standard way to add vertical lines that will cover your entire plot window without you having to specify their actual height is plt.axvline
import matplotlib.pyplot as plt
plt.axvline(x=0.22058956)
plt.axvline(x=0.33088437)
plt.axvline(x=2.20589566)
OR
xcoords = [0.22058956, 0.33088437, 2.20589566]
for xc in xcoords:
plt.axvline(x=xc)
You can use many of the keywords available for other plot commands (e.g. color
, linestyle
, linewidth
...). You can pass in keyword arguments ymin
and ymax
if you like in axes corrdinates (e.g. ymin=0.25
, ymax=0.75
will cover the middle half of the plot). There are corresponding functions for horizontal lines (axhline
) and rectangles (axvspan
).
const returnedTarget = Object.assign(target, source);
and pass empty array to target
in case complex objects this way works for me
$.extend(true, [], originalArray)
in case of array
$.extend(true, {}, originalObject)
in case of object
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
Your pattern does not correspond to the input string at all... It is not surprising that it does not work. This would probably work better:
SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
Locale.ENGLISH);
Then to print with your required format you need a second SimpleDateFormat:
Date parsedDate = sdf.parse(date);
SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss");
System.out.println(print.format(parsedDate));
Notes:
A simpler one would be
list(dictionary.items()) # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys())) # list of (key, value) tuples
A custom map seems appropriate in this case. This is what I use to paste yanked items in insert mode:
inoremap <Leader>p <ESC>pa
My Leader
key here is \
; this means hitting \p
in insert mode would paste the previously yanked items/lines.
You may need to call frame.repaint()
as well to force the frame to actually redraw itself. I've had issues before where I tried to repaint a component and it wasn't updating what was displayed until the parent's repaint() method was called.
Ok. I found problem.
It was not on the Angular side. To be honest, there were no problem at all.
Reason why I was unable to perform my request succesfuly was that my server app was not properly handling OPTIONS request.
Why OPTIONS, not POST? My server app is on different host, then frontend. Because of CORS my browser was converting POST to OPTION: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
With help of this answer: Standalone Spring OAuth2 JWT Authorization Server + CORS
I implemented proper filter on my server-side app.
Thanks to @Supamiu - the person which fingered me that I am not sending POST at all.
I had the same problem once this is how I solved it.
Suppose I want 12 delays with an interval of 2 secs
function animate(i){
myVar=setTimeout(function(){
alert(i);
if(i==12){
clearTimeout(myVar);
return;
}
animate(i+1)
},2000)
}
var i=1; //i is the start point 1 to 12 that is
animate(i); //1,2,3,4..12 will be alerted with 2 sec delay
With a SimpleXml object, you can simply
$domxml = new DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
/* @var $xml SimpleXMLElement */
$domxml->loadXML($xml->asXML());
$domxml->save($newfile);
$xml
is your simplexml object
So then you simpleXml can be saved as a new file specified by $newfile
You will need to configure your Win7 PC as a Time Server, and then configure the RasPi to connect to it for NTP services.
Configure Win7 as authoritative time server. Configure RasPi time server lookup.
And to complement Rich's recursive answer, a non-recursive method.
Public Sub NonRecursiveMethod()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder("your folder path variable") 'obviously replace
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
'...insert any folder processing code here...
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
'...insert any file processing code here...
Next oFile
Loop
End Sub
You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1)
with Set oFolder = queue(queue.Count)
and replace queue.Remove(1)
with queue.Remove(queue.Count)
, and probably rename the variable...)
As some people already pointed out, spring-boot 1.4+, has specific namespaces for the four connections pools. By default, hikaricp is used in spring-boot 2+. So you will have to specify the SQL here. The default is SELECT 1
. Here's what you would need for DB2 for example:
spring.datasource.hikari.connection-test-query=SELECT current date FROM sysibm.sysdummy1
Caveat: If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" drivers that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none
There are three options, that you can use. -I
is to exclude binary files in grep. Other are for line numbers and file names.
grep -I -n -H
-I -- process a binary file as if it did not contain matching data;
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match
So this might be a way to run grep:
grep -InH your-word *
black magic:
<style>
body { float:left;}
.success { background-color: #ccffcc;}
</style>
If anyone has a clear explanation of why this works, please comment. I think it has something to do with a side effect of the float that removes the constraint that the body must fit into the page width.
There's a simpler way than a whole bunch of if statements. Use the or (||) operator.
function getBrowserDimensions() {
return {
width: (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth),
height: (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight)
};
}
var browser_dims = getBrowserDimensions();
alert("Width = " + browser_dims.width + "\nHeight = " + browser_dims.height);
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
int temp = 0;
for (int write = 0; write < arr.Length; write++)
{
for (int sort = 0; sort < arr.Length - 1 - write ; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
Console.ReadKey();
do setup by following bellow link and domain name you need to mention as like wht you have mentioned in facebook app domain name.
Go to https://developers.facebook.com/
Click on the Apps menu on the top bar.
As pointed out by other answers, in python they return floats probably because of historical reasons to prevent overflow problems. However, they return integers in python 3.
>>> import math
>>> type(math.floor(3.1))
<class 'int'>
>>> type(math.ceil(3.1))
<class 'int'>
You can find more information in PEP 3141.
in the latest version of android studio, you can just do:
./gradlew assembleRelease
or aR
for short. This will produce an unsigned release apk. Building a signed apk can be done similarly or you can use Build -> Generate Signed Apk in Android Studio.
Here is my build.gradle for reference:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android'
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
// Move the tests to tests/java, tests/res, etc...
instrumentTest.setRoot('tests')
// Move the build types to build-types/<type>
// For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
// This moves them out of them default location under src/<type>/... which would
// conflict with src/ being used by the main source set.
// Adding new build types or product flavors should be accompanied
// by a similar customization.
debug.setRoot('build-types/debug')
release.setRoot('build-types/release')
}
buildTypes {
release {
}
}
Well, I figured out the problem.
Basically Go starting path for import is $HOME/go/src
So I just needed to add myapp
in front of the package names, that is, the import should be:
import (
"log"
"net/http"
"myapp/common"
"myapp/routers"
)
Not sure, but you should be able to do something by setting a default active profile in your settings.xml
See
See http://maven.apache.org/guides/introduction/introduction-to-profiles.html
Actually this is possible and the accepted answer only deals with centralising, which is straightforward enough. Also you really don't need to use JavaScript.
Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute
, but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.
For example:
/* Main site body */_x000D_
.wrapper {_x000D_
width: 940px;_x000D_
margin: 0 auto;_x000D_
position: relative; /* Ensure absolute positioned child elements are relative to this*/_x000D_
}_x000D_
_x000D_
/* Absolute positioned wrapper for the element you want to fix position */_x000D_
.fixed-wrapper {_x000D_
width: 220px;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: -240px; /* Move this out to the left of the site body, leaving a 20px gutter */_x000D_
}_x000D_
_x000D_
/* The element you want to fix the position of */_x000D_
.fixed {_x000D_
width: 220px;_x000D_
position: fixed;_x000D_
/* Do not set top / left! */_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="fixed-wrapper">_x000D_
<div class="fixed">_x000D_
Content in here will be fixed position, but 240px to the left of the site body._x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Sadly, I was hoping this thread might solve my issue with Android's WebKit rendering box-shadow blur pixels as margins on fixed position elements, but it seems it's a bug.
Anyway, I hope this helps!
You can use the \c
escape sequence anywhere in the pattern. For example:
/\ccopyright
or /copyright\c
or even /copyri\cght
To do the inverse (case sensitive matching), use \C
(capital C) instead.
ctrl + L clears the screen on Ubuntu Linux.
You can use a static Map in your enum that maps Strings to enum constants. Use it in a 'getEnum' static method. This skips the need to iterate through the enums each time you want to get one from its String value.
public enum RandomEnum {
StartHere("Start Here"),
StopHere("Stop Here");
private final String strVal;
private RandomEnum(String strVal) {
this.strVal = strVal;
}
public static RandomEnum getEnum(String strVal) {
if(!strValMap.containsKey(strVal)) {
throw new IllegalArgumentException("Unknown String Value: " + strVal);
}
return strValMap.get(strVal);
}
private static final Map<String, RandomEnum> strValMap;
static {
final Map<String, RandomEnum> tmpMap = Maps.newHashMap();
for(final RandomEnum en : RandomEnum.values()) {
tmpMap.put(en.strVal, en);
}
strValMap = ImmutableMap.copyOf(tmpMap);
}
@Override
public String toString() {
return strVal;
}
}
Just make sure the static initialization of the map occurs below the declaration of the enum constants.
BTW - that 'ImmutableMap' type is from the Google guava API, and I definitely recommend it in cases like this.
EDIT - Per the comments:
You can use the filter and then for the filter function use a reduction of the filtering array which checks and returns true when it finds a match then invert on return (!). The filter function is called once per element in the array. You are not doing a comparison of any of the elements in the function in your post.
var a1 = [1, 2, 3, 4],_x000D_
a2 = [2, 3];_x000D_
_x000D_
var filtered = a1.filter(function(x) {_x000D_
return !a2.reduce(function(y, z) {_x000D_
return x == y || x == z || y == true;_x000D_
})_x000D_
});_x000D_
_x000D_
document.write(filtered);
_x000D_
You can stop the docker container and once it is stopped you can remove the container.
Stop the container:
$ docker stop "containerID" - you can also mention the first two letters of the container ID, and it works.
Remove the container
$ docker rm "containerID" - again you can also mention the first two letters of the container
If these command do not let you stop/remove the containers, m,ake sure you have sudo access to docker host.
Also for anyone using properties such as Props or Refs without your "DocgetId's" then you can:
("" as HTMLInputElement).value;
Where the inverted quotes is your props value so an example would be like so:
var val = (this.refs.newText as HTMLInputElement).value;
alert("Saving this:" + val);
Rather than using a DisplayFilter you could use a very simple CaptureFilter like
port 53
See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.
It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.
Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.
DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj
...
The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.
var DyObjectsList = new List<dynamic>;
if (condition1) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = true;
DyObj.Message = "Message 1";
DyObjectsList .Add(DyObj);
}
if (condition2) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = false;
DyObj.Message = "Message 2";
DyObjectsList .Add(DyObj);
}
your resulting List essentially looks like this
DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj
Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.
However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.
rm -rf
was much more performant than FileUtils.cleanDirectory
.Not a one-liner solution but after extensive benchmarking, we found that using rm -rf
was multiple times faster than using FileUtils.cleanDirectory
.
Of course, if you have a small or simple directory, it won't matter but in our case we had multiple gigabytes and deeply nested sub directories where it would take over 10 minutes with FileUtils.cleanDirectory
and only 1 minute with rm -rf
.
Here's our rough Java implementation to do that:
// Delete directory given and all subdirectories and files (i.e. recursively).
//
static public boolean clearDirectory( File file ) throws IOException, InterruptedException {
if ( file.exists() ) {
String deleteCommand = "rm -rf " + file.getAbsolutePath();
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec( deleteCommand );
process.waitFor();
file.mkdirs(); // Since we only want to clear the directory and not delete it, we need to re-create the directory.
return true;
}
return false;
}
Worth trying if you're dealing with large or complex directories.
I had an error where my project was compiled as x64 project. and I've used a Library that was compiled as x86.
I've recompiled the library as x64 and it solved it.
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.
Natively WebAPI doesn't support binding of multiple POST parameters. As Colin points out there are a number of limitations that are outlined in my blog post he references.
There's a workaround by creating a custom parameter binder. The code to do this is ugly and convoluted, but I've posted code along with a detailed explanation on my blog, ready to be plugged into a project here:
Try the Arrays.deepToString method.
Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings
For existing mysql 8.0 installs on Windows 10 mysql,
launch installer,
click "Reconfigure" under QuickAction (to the left of MySQL Server), then
click next to advance through the next 2 screens until arriving
at "Authentication Method", select "Use Legacy Authentication Method (Retain MySQL 5.x compatibility"
Keep clicking until install is complete
gnu sed has an option -z
for null separated records (lines). You can just call:
sed -z 's/\n/ /g'
Is this possible:
Example:
Benchmark result window is open, take a screenshot. Open C:\Benchmarks Right click -> Paste screenshot A file named screenshot00x.jpg appears, with text screenshot00x selected. Type Overclock5
Thats it. No need to open anything. If you do not write anything, default name stays.
To avoid this problem you can use native method Bitmap.recycle()
before null
-ing Bitmap
object (or setting another value). Example:
public final void setMyBitmap(Bitmap bitmap) {
if (this.myBitmap != null) {
this.myBitmap.recycle();
}
this.myBitmap = bitmap;
}
And next you can change myBitmap
w/o calling System.gc()
like:
setMyBitmap(null);
setMyBitmap(anotherBitmap);
Well, I assume you like to copy data to the Sd-card from the developers computer? You might have rooted the devise and made the area you address available?) I had about the same problem to upload data files for my application(Android Studio 1.3.2 in Win7), but.
So for instance the the adb command can look like this:
adb push C:\testdata\t.txt /sdcard/download/t.txt
since olden times, the correct syntax for if/else if
in Python is elif
. By the way, you can use dictionary if you have alot of if/else
.eg
d={"1":"1a","2":"2a"}
if not a in d: print("3a")
else: print (d[a])
For msw, example of executing functions using dictionary.
def print_one(arg=None):
print "one"
def print_two(num):
print "two %s" % num
execfunctions = { 1 : (print_one, ['**arg'] ) , 2 : (print_two , ['**arg'] )}
try:
execfunctions[1][0]()
except KeyError,e:
print "Invalid option: ",e
try:
execfunctions[2][0]("test")
except KeyError,e:
print "Invalid option: ",e
else:
sys.exit()
Best practices :
Contrary to what you may think, the favicon can be of any size and of any image type. Follow this link for details.
Not putting a link to your favicon can slow down the page load.
In a django project, suppose the path to your favicon is :
myapp/static/icons/favicon.png
in your django templates (preferably in the base template), add this line to head of the page :
<link rel="shortcut icon" href="{% static 'icons/favicon.png' %}">
Note :
We suppose, the static settings are well configured in settings.py.
BEST SOLUTION IS:
// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
// ...
// restore index and position
mList.post(new Runnable() {
@Override
public void run() {
mList.setSelectionFromTop(index, top);
}
});
YOU MUST CALL IN POST AND IN THREAD!
Answer provided by Nicholas Krasnov
SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';
A function inside of a function is commonly used for closures.
(There is a lot of contention over what exactly makes a closure a closure.)
Here's an example using the built-in sum()
. It defines start
once and uses it from then on:
def sum_partial(start):
def sum_start(iterable):
return sum(iterable, start)
return sum_start
In use:
>>> sum_with_1 = sum_partial(1)
>>> sum_with_3 = sum_partial(3)
>>>
>>> sum_with_1
<function sum_start at 0x7f3726e70b90>
>>> sum_with_3
<function sum_start at 0x7f3726e70c08>
>>> sum_with_1((1,2,3))
7
>>> sum_with_3((1,2,3))
9
Built-in python closure
functools.partial
is an example of a closure.
From the python docs, it's roughly equivalent to:
def partial(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*(args + fargs), **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
(Kudos to @user225312 below for the answer. I find this example easier to figure out, and hopefully will help answer @mango's comment.)
How about getSelectedDate? Anyway, specifically on your code question, the problem is with this line:
new SimpleDateFormat("yyyy-MM-dd");
The string that goes in the constructor has to match the format of the date. The documentation for how to do that is here. Looks like you need something close to "EEE MMM d HH:mm:ss zzz yyyy"
If the input video has multiple audio tracks and you need to add one more then use the following command:
ffmpeg -i input_video_with_audio.avi -i new_audio.ac3 -map 0 -map 1 -codec copy output_video.avi
-map 0
means to copy (include) all streams from the first input file (input_video_with_audio.avi
) and -map 1
means to include all streams (in this case one) from the second input file (new_audio.ac3
).
I know this is old but you could create a custom extension if you needed to create that form over and over:
public static MvcForm BeginMultipartForm(this HtmlHelper htmlHelper)
{
return htmlHelper.BeginForm(null, null, FormMethod.Post,
new Dictionary<string, object>() { { "enctype", "multipart/form-data" } });
}
Usage then just becomes
<% using(Html.BeginMultipartForm()) { %>
If you are using mongoose as a source for a restful api have a look at 'restify-mongoose' and its queries. It has exactly this functionality built in.
Any query on a collection provides headers that are helpful here
test-01:~$ curl -s -D - localhost:3330/data?sort=-created -o /dev/null
HTTP/1.1 200 OK
link: </data?sort=-created&p=0>; rel="first", </data?sort=-created&p=1>; rel="next", </data?sort=-created&p=134715>; rel="last"
.....
Response-Time: 37
So basically you get a generic server with a relatively linear load time for queries to collections. That is awesome and something to look at if you want to go into a own implementation.
In the latest version of iOS this method is now deprecated. To support both iOS 7 and iOS 8 use:
UIApplication *application = [UIApplication sharedApplication];
BOOL enabled;
// Try to use the newer isRegisteredForRemoteNotifications otherwise use the enabledRemoteNotificationTypes.
if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
enabled = [application isRegisteredForRemoteNotifications];
}
else
{
UIRemoteNotificationType types = [application enabledRemoteNotificationTypes];
enabled = types & UIRemoteNotificationTypeAlert;
}
To add onto the answer from Rishabh and make it able to handle files that are not images that are found in the folder.
import matplotlib.image as mpimg
images = []
folder = './your/folder/'
for filename in os.listdir(folder):
try:
img = mpimg.imread(os.path.join(folder, filename))
if img is not None:
images.append(img)
except:
print('Cant import ' + filename)
images = np.asarray(images)
For a more web-like feel:
const B = (props) => <Text style={{fontWeight: 'bold'}}>{props.children}</Text>
<Text>I am in <B>bold</B> yo.</Text>
I suppose it is better to use UTF-8 encoding in the string MD5.
public static string MD5(this string s)
{
using (var provider = System.Security.Cryptography.MD5.Create())
{
StringBuilder builder = new StringBuilder();
foreach (byte b in provider.ComputeHash(Encoding.UTF8.GetBytes(s)))
builder.Append(b.ToString("x2").ToLower());
return builder.ToString();
}
}
With MongoDb 3.4.4 and newer, you can leverage the use of $arrayToObject
operator and a $replaceRoot
pipeline to get the counts.
For example, suppose you have a collection of users with different roles and you would like to calculate the distinct counts of the roles. You would need to run the following aggregate pipeline:
db.users.aggregate([
{ "$group": {
"_id": { "$toLower": "$role" },
"count": { "$sum": 1 }
} },
{ "$group": {
"_id": null,
"counts": {
"$push": { "k": "$_id", "v": "$count" }
}
} },
{ "$replaceRoot": {
"newRoot": { "$arrayToObject": "$counts" }
} }
])
Example Output
{
"user" : 67,
"superuser" : 5,
"admin" : 4,
"moderator" : 12
}
def getitems(iterable, items):
items = list(items) # get a list from any iterable and make our own copy
# since we modify it
if items:
items.sort()
for n, v in enumerate(iterable):
if n == items[0]:
yield v
items.pop(0)
if not items:
break
print list(getitems(open("/usr/share/dict/words"), [25, 29]))
# ['Abelson\n', 'Abernathy\n']
# note that index 25 is the 26th item
As of latest Chrome/FF and on IE11 there's no need for -ms/-moz/-webkit prefix. Here's a shorter code (based on previous answers):
div {
margin: 20px;
width: 100px;
height: 100px;
background: #f00;
/* The animation part: */
animation-name: spin;
animation-duration: 4000ms;
animation-iteration-count: infinite;
animation-timing-function: linear;
}
@keyframes spin {
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
}
Live Demo: http://jsfiddle.net/9Ryvs/3057/
Whenever a record has updated a record is "deleted". Here is my example:
ALTER TRIGGER [dbo].[UpdatePhyDate]
ON [dbo].[M_ContractDT1]
AFTER UPDATE
AS
BEGIN
-- on ContarctDT1 PhyQty is updated
-- I want system date in Phytate automatically saved
SET NOCOUNT ON;
declare @dt1ky as int
if(update(Phyqty))
begin
select @dt1ky = dt1ky from deleted
update M_ContractDT1 set PhyDate=GETDATE() where Dt1Ky= @dt1ky
end
END
It works fine
this states that Account.deposit(Double.MAX_VALUE);
it is setting deposit value to MAX value of Double
dataType.to procced for running tests.
$insert = $this->db->insert('email_notification', $data);
$this->session->set_flashdata("msg", "<div class='alert alert-success'> Cafe has been added Successfully.</div>");
//require ("plugins/mailer/PHPMailerAutoload.php");
$mail = new PHPMailer;
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
),
);
$message="
Your Account Has beed created successfully by Admin:
Username: ".$this->input->post('username')." <br><br>
Email: ".$this->input->post('sender_email')." <br><br>
Regargs<br>
<div class='background-color:#666;color:#fff;padding:6px;
text-align:center;'>
Bookly Admin.
</div>
";
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true;
$subject = "Hello ".$this->input->post('username');
$mail->SMTDebug=2;
$email = $this->input->post('sender_email'); //this email is user email
$from_label = "Account Creation";
$mail->Username = 'your email'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;
$mail->setFrom($from_label);
$mail->addAddress($email, 'Bookly Admin');
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if($mail->send()){
}
class A {
int i;
// Hashing Algorithm
if even number return 0 else return 1
// Equals Algorithm,
if i = this.i return true else false
}
hashCode()
to determine the
bucket and uses equals()
method to find whether the value is already
present in the Bucket. If not it will added else it will be replaced with current valuehashCode()
to find the Entry (bucket) first and
equals()
to find the value in Entryif Both are overridden,
Map<A>
Map.Entry 1 --> 1,3,5,...
Map.Entry 2 --> 2,4,6,...
if equals is not overridden
Map<A>
Map.Entry 1 --> 1,3,5,...,1,3,5,... // Duplicate values as equals not overridden
Map.Entry 2 --> 2,4,6,...,2,4,..
If hashCode is not overridden
Map<A>
Map.Entry 1 --> 1
Map.Entry 2 --> 2
Map.Entry 3 --> 3
Map.Entry 4 --> 1
Map.Entry 5 --> 2
Map.Entry 6 --> 3 // Same values are Stored in different hasCodes violates Contract 1
So on...
HashCode Equal Contract
I did
git branch -f new_local_branch_name origin/remote_branch_name
Instead of
git branch -f new_local_branch_name upstream/remote_branch_name
As suggested by @innaM.
When I used the upstream version, it said 'fatal: Not a valid object name: 'upstream/remote_branch_name''. I did not do git fetch origin
as a comment suggested, but instead simply replaced upstream
with origin
. I guess they are equivalent.
In Mac, Open Oracle Virtual Box and Goto VirtualBox -> Preferences -> Network. Select the tab'Host Only Networks' & delete vboxnet0. It will be recreated next time you launch genymotion emulator.
try this
$('#Selector_ID').attr("placeholder", "your Placeholder");
Following is snippet of code from Arrays
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
/**
* @serial include
*/
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;
so what happens is that when asList method is called then it returns list of its own private static class version which does not override add funcion from AbstractList to store element in array. So by default add method in abstract list throws exception.
So it is not regular array list.
The second important use of this
(beside hiding with a local variable as many answers already say) is when accessing an outer instance from a nested non-static class:
public class Outer {
protected int a;
public class Inner {
protected int a;
public int foo(){
return Outer.this.a;
}
public Outer getOuter(){
return Outer.this;
}
}
}
This simple script allows you to uncheck an already checked radio button. Works on all javascript enabled browsers.
var allRadios = document.getElementsByName('re');_x000D_
var booRadio;_x000D_
var x = 0;_x000D_
for(x = 0; x < allRadios.length; x++){_x000D_
allRadios[x].onclick = function() {_x000D_
if(booRadio == this){_x000D_
this.checked = false;_x000D_
booRadio = null;_x000D_
} else {_x000D_
booRadio = this;_x000D_
}_x000D_
};_x000D_
}
_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
$
is short-hand for String.Format
and is used with string interpolations, which is a new feature of C# 6. As used in your case, it does nothing, just as string.Format()
would do nothing.
It is comes into its own when used to build strings with reference to other values. What previously had to be written as:
var anInt = 1;
var aBool = true;
var aString = "3";
var formated = string.Format("{0},{1},{2}", anInt, aBool, aString);
Now becomes:
var anInt = 1;
var aBool = true;
var aString = "3";
var formated = $"{anInt},{aBool},{aString}";
There's also an alternative - less well known - form of string interpolation using $@
(the order of the two symbols is important). It allows the features of a @""
string to be mixed with $""
to support string interpolations without the need for \\
throughout your string. So the following two lines:
var someDir = "a";
Console.WriteLine($@"c:\{someDir}\b\c");
will output:
c:\a\b\c
Had the very same problem, but in my case the reason was update of Ubuntu and php version - from 18.04 and php-7.2 up to 20.04 and php-7.4.
The Nginx server was the same, so in my /etc/nginx/sites-available/default was old data:
server {
location /pma {
location ~ ^/pma/(.+\.php)$ {
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
}
}
}
I could not get phpmyadmin to work with any of php.ini changes and all answers from this thread, but at some moment I had opened the /etc/nginx/sites-available/default and realised, that I still had old version of php. So I just changed it to
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
and the issue was gone, phpmyadmin magically started to work without any mysqli-file complaint. I even double checked it, but yeap, that's how it works - if you have wrong version for php-fpm.sock in your nginx config file, your phpmyadmin will not work, but the shown reason will be 'The mysqli extension is missing'
import inspect
def s(template, **kwargs):
"Usage: s(string, **locals())"
if not kwargs:
frame = inspect.currentframe()
try:
kwargs = frame.f_back.f_locals
finally:
del frame
if not kwargs:
kwargs = globals()
return template.format(**kwargs)
Usage:
a = 123
s('{a}', locals()) # print '123'
s('{a}') # it is equal to the above statement: print '123'
s('{b}') # raise an KeyError: b variable not found
PS: performance may be a problem. This is useful for local scripts, not for production logs.
Duplicated:
I received the same error message. To resolve this I just replaced the Oracle.ManagedDataAccess
assembly with the older Oracle.DataAccess
assembly. This solution may not work if you require new features found in the new assembly. In my case I have many more higher priority issues then trying to configure the new Oracle
assembly.
I got this message when I drag and dropped some source files from another project. When I deleted them and then added them via the "Add Files..." from the File menu, it built without the error.
Note that there is one interesting difference (at least with the MS C++ compiler):
If you have a plain vanilla struct like this
struct MyStruct {
int id;
double x;
double y;
} MYSTRUCT;
then somewhere else you might initialize an array of such objects like this:
MYSTRUCT _pointList[] = {
{ 1, 1.0, 1.0 },
{ 2, 1.0, 2.0 },
{ 3, 2.0, 1.0 }
};
however, as soon as you add a user-defined constructor to MyStruct such as the ones discussed above, you'd get an error like this:
'MyStruct' : Types with user defined constructors are not aggregate <file and line> : error C2552: '_pointList' : non-aggregates cannot be initialized with initializer list.
So that's at least one other difference between a struct and a class. This kind of initialization may not be good OO practice, but it appears all over the place in the legacy WinSDK c++ code that I support. Just so you know...
In Android Studio 3.0, I had the same issue. This fixed it:
Arrays.sort(arr);
int max=0,mode=0,count=0;
for(int i=0;i<N;i=i+count) {
count = 1;
for(int j=i+1; j<N; j++) {
if(arr[i] == arr[j])
count++;
}
if(count>max) {
max=count;
mode = arr[i];
}
}
Just Add scrolling="no"
and seamless="seamless"
attributes to iframe tag. like this:-
1. XHTML => scrolling="no"
2. HTML5 => seamless="seamless"
UPDATE:
seamless
attribute has been removed in all major browsers
See this JSFiddle
input[type="text"]_x000D_
{_x000D_
border: 0;_x000D_
border-bottom: 1px solid red;_x000D_
outline: 0;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
</form>
_x000D_
You need to set the LayoutParams of the ViewGroup the ImageView is sitting in. For example if your ImageView is inside a LinearLayout, then you create a
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
This is because it's the parent of the View that needs to know what size to allocate to the View.
Echo is so nineties and so fraught with perils that its use should result in core dumps no less than 4GB. Seriously, echo's problems were the reason why the Unix Standardization process finally invented the printf
utility, doing away with all the problems.
So to get a newline in a string:
FOO="hello
world"
BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deleted
printf '<%s>\n' "$FOO"
printf '<%s>\n' "$BAR"
There! No SYSV vs BSD echo madness, everything gets neatly printed and fully portable support for C escape sequences. Everybody please use printf
now and never look back.
On Windows 10, I was able to search for set path environment variable and got these instructions:
C:\Program Files;C:\Winnt;C:\Winnt\System32
The first time I searched for it, it immediately popped up the System Properties Window. After that, I found the above instructions.
For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5"
.
The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:
IE implements the HTML 3.2 definition, it sets
colspan=0
ascolspan=1
.
The bug is well documented.
At my last job we ran statistics once a week. If I remember correctly, we scheduled them on a Thursday night, and on Friday the DBAs were very careful to monitor the longest running queries for anything unexpected. (Friday was picked because it was often just after a code release, and tended to be a fairly low traffic day.) When they saw a bad query they would find a better query plan and save that one so it wouldn't change again unexpectedly. (Oracle has tools to do this for you automatically, you tell it the query to optimize and it does.)
Many organizations avoid running statistics out of fear of bad query plans popping up unexpectedly. But this usually means that their query plans get worse and worse over time. And when they do run statistics then they encounter a number of problems. The resulting scramble to fix those issues confirms their fears about the dangers of running statistics. But if they ran statistics regularly, used the monitoring tools as they are supposed to, and fixed issues as they came up then they would have fewer headaches, and they wouldn't encounter them all at once.
For .htaccess rewrite: http://learn.iis.net/page.aspx/557/translate-htaccess-content-to-iis-webconfig/
Or try aping .htaccess: http://www.helicontech.com/ape/
To understand how PreparedStatement prevents SQL Injection, we need to understand phases of SQL Query execution.
1. Compilation Phase. 2. Execution Phase.
Whenever SQL server engine receives a query, it has to pass through below phases,
Parsing and Normalization Phase: In this phase, Query is checked for syntax and semantics. It checks whether references table and columns used in query exist or not. It also has many other tasks to do, but let's not go in detail.
Compilation Phase: In this phase, keywords used in query like select, from, where etc are converted into format understandable by machine. This is the phase where query is interpreted and corresponding action to be taken is decided. It also has many other tasks to do, but let's not go in detail.
Query Optimization Plan: In this phase, Decision Tree is created for finding the ways in which query can be executed. It finds out the number of ways in which query can be executed and the cost associated with each way of executing Query. It chooses the best plan for executing a query.
Cache: Best plan selected in Query optimization plan is stored in cache, so that whenever next time same query comes in, it doesn't have to pass through Phase 1, Phase 2 and Phase 3 again. When next time query come in, it will be checked directly in Cache and picked up from there to execute.
Execution Phase:
In this phase, supplied query gets executed and data is returned to user as ResultSet
object.
PreparedStatements are not complete SQL queries and contain placeholder(s), which at run time are replaced by actual user-provided data.
Whenever any PreparedStatment containing placeholders is passed in to SQL Server engine, It passes through below phases
UPDATE user set username=? and password=? WHERE id=?
Above query will get parsed, compiled with placeholders as special treatment, optimized and get Cached. Query at this stage is already compiled and converted in machine understandable format. So we can say that Query stored in cache is Pre-Compiled and only placeholders need to be replaced with user-provided data.
Now at run-time when user-provided data comes in, Pre-Compiled Query is picked up from Cache and placeholders are replaced with user-provided data.
(Remember, after place holders are replaced with user data, final query is not compiled/interpreted again and SQL Server engine treats user data as pure data and not a SQL that needs to be parsed or compiled again; that is the beauty of PreparedStatement.)
If the query doesn't have to go through compilation phase again, then whatever data replaced on the placeholders are treated as pure data and has no meaning to SQL Server engine and it directly executes the query.
Note: It is the compilation phase after parsing phase, that understands/interprets the query structure and gives meaningful behavior to it. In case of PreparedStatement, query is compiled only once and cached compiled query is picked up all the time to replace user data and execute.
Due to one time compilation feature of PreparedStatement, it is free of SQL Injection attack.
You can get detailed explanation with example here: https://javabypatel.blogspot.com/2015/09/how-prepared-statement-in-java-prevents-sql-injection.html
double d = Double.parseDouble(aString);
This should convert the string aString into the double d.
there is one more difference, but only in internet explorer. It occurs when you mix HTML and SVG. if the parent is the 'other' of those two, then .parentNode gives the parent, while .parentElement gives undefined.
You can put up all your JS like this, so it doesn't execute before your HTML is ready
$(document).ready(function() {
// some code here
});
Remember this is jQuery so include it in the head section. Also see Why you should use jQuery and not onload
Knowing the scope of each can make things easier to remember.
process
is node
's global object, and .cwd()
returns where node is running.
__dirname
is module
's property, and represents the file path of the module. In node, one module resides in one file.
Similarly, __filename
is another module
's property, which holds the file name of the module.
If you put the plus sign on the beginning of the line, it formats differently:
String query =
"SELECT FOO, BAR, BAZ"
+ " FROM ABC"
+ " WHERE BAR > 4";
A wrapper class is a class that serves the sole purpose of holding something and adding some functionality to it. In Java since the primitives (like ints,floats,chars...) are not objects so if you want to treat them like one then you have to use a wrapper class. Suppose you want to create a Vector of ints, the problem is a Vector only holds Objects not primitives. So what you will do is put all the ints in an Integer wrapper and use that. Example:
int number = 5;
Integer numberWrapped = new Integer(number);
//now you have the int in an object.
//and this is how to access the int value that is being wrapped.
int again = numberWrapped.intValue();
You can see the println()
statements in the Run
window of Android Studio.
See detailed answer with screenshot here.
try this
sudo update-secureboot-policy --enroll-key
and restart your system, when restart it shows option and select Mok key and you will work fine.
It would make sens if your code was like this:
#include <iostream>
using namespace std;
class Monster
{
public:
Monster() { cout << "Monster!" << endl; }
virtual ~Monster() { cout << "Monster Died" << endl; }
};
int main(int argc, const char* argv[])
{
Monster *mon = new Monster[6];
delete [] mon;
return 0;
}
Use this code:
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileWork
{
public static void main(String[] args) throws IOException {
String line = Files.readAllLines(Paths.get("D:/abc.txt")).get(1);
System.out.println(line);
}
}
I wrote an updated version of Kees C. Bakker's answer:
const hasVerticalScroll = (node) => {
if (!node) {
if (window.innerHeight) {
return document.body.offsetHeight > window.innerHeight
}
return (document.documentElement.scrollHeight > document.documentElement.offsetHeight)
|| (document.body.scrollHeight > document.body.offsetHeight)
}
return node.scrollHeight > node.offsetHeight
}
if (hasVerticalScroll(document.querySelector('body'))) {
this.props.handleDisableDownScrollerButton()
}
The function returns true or false depending whether the page has a vertical scrollbar or not.
For example:
const hasVScroll = hasVerticalScroll(document.querySelector('body'))
if (hasVScroll) {
console.log('HAS SCROLL', hasVScroll)
}
You might need to enable the table for full-text indexing.
If this is a BAT file in a different directory than the current directory, you may see an error like "python: can't open file 'somescript.py': [Errno 2] No such file or directory". This can be fixed by specifying an absolute path to the BAT file using %~dp0
(the drive letter and path of that batch file).
@echo off
python %~dp0\somescript.py %*
(This way you can ignore the c:\
or whatever, because perhaps you may want to move this script)
Try this method for uploading Image file from camera
package com.example.imageupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds() {
if (!isSetFirst) {
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if (isSetLast) {
return;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
.getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName,
final InputStream fin) {
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName,
final InputStream fin, String type) {
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: " + type + "\r\n";
out.write(("Content-Disposition: form-data; name=\"" + key
+ "\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
}
public boolean isChunked() {
return false;
}
public boolean isRepeatable() {
return false;
}
public boolean isStreaming() {
return false;
}
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
public Header getContentEncoding() {
return null;
}
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
Use of class for uploading
private void doFileUpload(File file_path) {
Log.d("Uri", "Do file path" + file_path);
try {
HttpClient client = new DefaultHttpClient();
//use your server path of php file
HttpPost post = new HttpPost(ServerUploadPath);
Log.d("ServerPath", "Path" + ServerUploadPath);
FileBody bin1 = new FileBody(file_path);
Log.d("Enter", "Filebody complete " + bin1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploaded_file", bin1);
reqEntity.addPart("email", new StringBody(useremail));
post.setEntity(reqEntity);
Log.d("Enter", "Image send complete");
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
Log.d("Enter", "Get Response");
try {
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE", response_str);
JSONObject jobj = new JSONObject(response_str);
result = jobj.getString("ResponseCode");
Log.e("Result", "...." + result);
}
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
} catch (Exception e) {
Log.e("Upload Exception", "");
e.printStackTrace();
}
}
Service for uploading
<?php
$image_name = $_FILES["uploaded_file"]["name"];
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;
$flag=0;
if (file_exists("Images/".$new_image_name))
{
$msg=$new_image_name . " already exists."
header('Content-type: application/json');
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));
}else{
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
$flag = 1;
}
if($flag == 1){
require 'db.php';
$static_url =$new_image_name;
$conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
$db=mysql_select_db($db_database,$conn) or die("unable to select message_app");
$email = "";
if((isset($_REQUEST['email'])))
{
$email = $_REQUEST['email'];
}
$sql ="insert into alert(images) values('$static_url')";
$result=mysql_query($sql);
if($result){
echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
} else
{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
}
}
else{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));
}
?>
In my case, I had a OneToOne relation which I was using with @Column
by mistake. I changed it to @JoinColumn
and added @OneToOne
annotation and it fixed the exception.
Safari is blocking any call to window.open() which is made inside an async call.
The solution that I found to this problem is to call window.open before making an asnyc call and set the location when the promise resolves.
var windowReference = window.open();
myService.getUrl().then(function(url) {
windowReference.location = url;
});
Based on Haim's answer here's a simplified example if you're looking to compare values that exist in BOTH tables, otherwise if there's a row in one table but not the other it will also return it....
Took me a couple of hours to figure out. Here's a fully tested simply query for comparing "tbl_a" and "tbl_b"
SELECT ID, col
FROM
(
SELECT
tbl_a.ID, tbl_a.col FROM tbl_a
UNION ALL
SELECT
tbl_b.ID, tbl_b.col FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
ORDER BY ID
So you need to add the extra "where in" clause:
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
Also:
For ease of reading if you want to indicate the table names you can use the following:
SELECT tbl, ID, col
FROM
(
SELECT
tbl_a.ID, tbl_a.col, "name_to_display1" as "tbl" FROM tbl_a
UNION ALL
SELECT
tbl_b.ID, tbl_b.col, "name_to_display2" as "tbl" FROM tbl_b
) t
WHERE ID IN (select ID from tbl_a) AND ID IN (select ID from tbl_b)
GROUP BY
ID, col
HAVING COUNT(*) = 1
ORDER BY ID
In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date
(usually GNU date).
As such:
# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T\n' -1
# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T\n' -1
# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T\n' -1
# -> current date printed to terminal
In bash (<4.2):
# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')
# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')
# print current date directly
echo $(date '+%Y-%m-%d')
Other available date formats can be viewed from the date man pages (for external non-bash specific command):
man date
OK guys, this is a small solution, but it works fine.
suppose the following code:
<div id='the_div_holder' style='height: 400px; overflow-y: scroll'>
<div class='post'>1st post</div>
<div class='post'>2nd post</div>
<div class='post'>3rd post</div>
</div>
you want when a new post is added to 'the_div_holder' then it scrolls its inner content (the div's .post) to the last one like a chat. So, do the following whenever a new .post is added to the main div holder:
var scroll = function(div) {
var totalHeight = 0;
div.find('.post').each(function(){
totalHeight += $(this).outerHeight();
});
div.scrollTop(totalHeight);
}
// call it:
scroll($('#the_div_holder'));
As far as I know this can't be done with the router in Angular 2. But you could just do:
window.location.href = window.location.href
To reload the view.
Concatenate the attribute selectors:
input[name="Sex"][value="M"]
I solved my issue by doing this:
Strangely it started working again after that.
Parent table data missing causes the problem. In your problem non availability of data in "dbo.Sup_Item_Cat" causes the problem
<a href="#Foo" onclick="return runMyFunction();">Do it!</a>
and
function runMyFunction() {
//code
return true;
}
This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.
I agree with much that Manuel has said. In fact, his comments refer to this url...
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
... which states:
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
However, for me it would come down to tool/framework support.
If you get a clear idea of your users, and how they'll make use of your API, then that will help you decide. If you make the upload of files hard for your API users then they'll move away, of you'll spend a lot of time on supporting them.
Secondary to this would be the tool support YOU have for writing your API and how easy it is for your to accommodate one upload mechanism over the other.
Just divide the number of td to 100%. Example, you have 4 td's:
<html>
<table>
<tr>
<td style="width:25%">This is a text</td>
<td style="width:25%">This is some text, this is some text</td>
<td style="width:25%">This is another text, this is another text</td>
<td style="width:25%">This is the last text, this is the last text</td>
</tr>
</table>
</html>
We use 25% in each td to maximize the 100% space of the entire table
You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.
use each() wrap within another each() until the last array.
for result.data[0].stuff[0].onetype[0]
in jQuery you could do the following:
`
$.each(data.result.data, function(index0, v) {
$.each(v, function (index1, w) {
$.each(w, function (index2, x) {
alert(x.id);
});
});
});
`
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
What if you've got array of fieldsets?
<fieldset>
<input type="text" name="item[1]" />
<input type="text" name="item[2]" />
<input type="hidden" name="fset[]"/>
</fieldset>
<fieldset>
<input type="text" name="item[3]" />
<input type="text" name="item[4]" />
<input type="hidden" name="fset[]"/>
</fieldset>
I added a hidden field to count the number of the fieldsets. The user can add or delete the fields and then save it.
There's parameter substitution, though it may be un-PC as well ...like indirection.
#!/bin/bash
# Array pretending to be a Pythonic dictionary
ARRAY=( "cow:moo"
"dinosaur:roar"
"bird:chirp"
"bash:rock" )
for animal in "${ARRAY[@]}" ; do
KEY="${animal%%:*}"
VALUE="${animal##*:}"
printf "%s likes to %s.\n" "$KEY" "$VALUE"
done
printf "%s is an extinct animal which likes to %s\n" "${ARRAY[1]%%:*}" "${ARRAY[1]##*:}"
The BASH 4 way is better of course, but if you need a hack ...only a hack will do. You could search the array/hash with similar techniques.
here is my answer:
public class WigetControl {
private Resources res;
public WigetControl(Resources res)
{
this.res = res;
}
public void setButtonDisable(Button mButton)
{
mButton.setBackgroundColor(res.getColor(R.color.loginbutton_unclickable));
mButton.setEnabled(false);
}
}
and the call can be like this:
WigetControl control = new WigetControl(getResources());
control.setButtonDisable(btNext);
Assuming that you are using UTF-8 encoding:
string convert = "This is the string to be converted";
// From string to byte array
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert);
// From byte array to string
string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);
much simpler code:
import java.util.Arrays; int[][] array = new int[][];
Arrays.sort(array, ( a, b) -> a[1] - b[1]);
Now Update word-wrap is replace by :
overflow-wrap:break-word;
Compatible old navigator and css 3 it's good alternative !
it's evolution of word-wrap ( since 2012... )
See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap
See compatibility full : http://caniuse.com/#search=overflow-wrap
I'll post this comment as answer, as I'm confident enough that what I asked is not possible.
I) Couple of similar questions trying to do the same, without success:
II) This article: Excel Pivot Table Calculated Field for example lists many restrictions of Calculated Field:
III) There is tiny limited possibility to use AVERAGE()
and similar function for a range of cells, but that applies only if Pivot table doesn't have grouped cells, which allows listing the cells as items in new group (right to "Fileds" listbox in above screenshot) and then user can calculate AVERAGE()
, referencing explicitly every item (cell), from Items listbox, as argument. Maybe it's better explained here: Calculate values in a PivotTable report
For my Pivot table it wasn't applicable because my range wasn't small enough, this option to be sane choice.
This code works for me:
public void Run()
{
Dog myDog = new Dog();
myDog.Name= "Foo";
myDog.Color = DogColor.Brown;
System.Console.WriteLine("{0}", myDog.ToString());
MemoryStream stream = SerializeToStream(myDog);
Dog newDog = (Dog)DeserializeFromStream(stream);
System.Console.WriteLine("{0}", newDog.ToString());
}
Where the types are like this:
[Serializable]
public enum DogColor
{
Brown,
Black,
Mottled
}
[Serializable]
public class Dog
{
public String Name
{
get; set;
}
public DogColor Color
{
get;set;
}
public override String ToString()
{
return String.Format("Dog: {0}/{1}", Name, Color);
}
}
and the utility methods are:
public static MemoryStream SerializeToStream(object o)
{
MemoryStream stream = new MemoryStream();
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, o);
return stream;
}
public static object DeserializeFromStream(MemoryStream stream)
{
IFormatter formatter = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
object o = formatter.Deserialize(stream);
return o;
}
I have the almost the same situation as yours; that if the screen width is less than the my specified width it should hide the div. This is the jquery code I used that worked for me.
$(window).resize(function() {
if ($(this).width() < 1024) {
$('.divIWantedToHide').hide();
} else {
$('.divIWantedToHide').show();
}
});
i have tried this one and it worked for me. hope it works for others too.
Here i have attached screenshot to explain things. Go through this steps
happy to help.
thanks.
This is what i did for merging two datatables and bind the final result to the gridview
DataTable dtTemp=new DataTable();
for (int k = 0; k < GridView2.Rows.Count; k++)
{
string roomno = GridView2.Rows[k].Cells[1].Text;
DataTable dtx = GetRoomDetails(chk, roomno, out msg);
if (dtx.Rows.Count > 0)
{
dtTemp.Merge(dtx);
dtTemp.AcceptChanges();
}
}
Another example which uses function in ref rather than string
class List extends React.Component {
constructor(props) {
super(props);
this.state = { items:[], index: 0 };
this._nodes = new Map();
this.handleAdd = this.handleAdd.bind(this);
this.handleRemove = this.handleRemove.bind(this);
}
handleAdd() {
let startNumber = 0;
if (this.state.items.length) {
startNumber = this.state.items[this.state.items.length - 1];
}
let newItems = this.state.items.splice(0);
for (let i = startNumber; i < startNumber + 100; i++) {
newItems.push(i);
}
this.setState({ items: newItems });
}
handleRemove() {
this.setState({ items: this.state.items.slice(1) });
}
handleShow(i) {
this.setState({index: i});
const node = this._nodes.get(i);
console.log(this._nodes);
if (node) {
ReactDOM.findDOMNode(node).scrollIntoView({block: 'end', behavior: 'smooth'});
}
}
render() {
return(
<div>
<ul>{this.state.items.map((item, i) => (<Item key={i} ref={(element) => this._nodes.set(i, element)}>{item}</Item>))}</ul>
<button onClick={this.handleShow.bind(this, 0)}>0</button>
<button onClick={this.handleShow.bind(this, 50)}>50</button>
<button onClick={this.handleShow.bind(this, 99)}>99</button>
<button onClick={this.handleAdd}>Add</button>
<button onClick={this.handleRemove}>Remove</button>
{this.state.index}
</div>
);
}
}
class Item extends React.Component
{
render() {
return (<li ref={ element => this.listItem = element }>
{this.props.children}
</li>);
}
}
Cleanest way I have come across is inspired by the sql style guide.
sql = """
SELECT field1, field2, field3, field4
FROM table
WHERE condition1 = 1
AND condition2 = 2;
"""
Essentially, the keywords that begin a clause should be right-aligned and the field names etc, should be left aligned. This looks very neat and is easier to debug as well.
Was having an issue getting the "Run in Postman" links to work with the browsers until I added this to the .desktop file
MimeType=application/postman;x-scheme-handler/postman;
This is very useful for custom ArrayAdapter
using. It is some kind of optimization. There setTag
used as reference to object that references on some parts of layout (that displaying in ListView
) instead of findViewById
.
static class ViewHolder {
TextView tvPost;
TextView tvDate;
ImageView thumb;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = myContext.getLayoutInflater();
convertView = inflater.inflate(R.layout.postitem, null);
ViewHolder vh = new ViewHolder();
vh.tvPost = (TextView)convertView.findViewById(R.id.postTitleLabel);
vh.tvDate = (TextView)convertView.findViewById(R.id.postDateLabel);
vh.thumb = (ImageView)convertView.findViewById(R.id.postThumb);
convertView.setTag(vh);
}
....................
}
Font myFont = new Font("Serif", Font.BOLD, 12);
, then use a setFont method on your components like
JButton b = new JButton("Hello World");
b.setFont(myFont);
You can obfuscate it, but there's no way of protecting it completely.
example obfuscator: https://obfuscator.io
I think inline scripts are hard to stop instead you can try with this:
<div id="test">
<div>Click Me</div>
</div>
and script:
$(function () {
$('#test').children().click(function(){
alert('hello');
});
$('#test').children().off('click');
});
With a union, you're only supposed to use one of the elements, because they're all stored at the same spot. This makes it useful when you want to store something that could be one of several types. A struct, on the other hand, has a separate memory location for each of its elements and they all can be used at once.
To give a concrete example of their use, I was working on a Scheme interpreter a little while ago and I was essentially overlaying the Scheme data types onto the C data types. This involved storing in a struct an enum indicating the type of value and a union to store that value.
union foo {
int a; // can't use both a and b at once
char b;
} foo;
struct bar {
int a; // can use both a and b simultaneously
char b;
} bar;
union foo x;
x.a = 3; // OK
x.b = 'c'; // NO! this affects the value of x.a!
struct bar y;
y.a = 3; // OK
y.b = 'c'; // OK
edit: If you're wondering what setting x.b to 'c' changes the value of x.a to, technically speaking it's undefined. On most modern machines a char is 1 byte and an int is 4 bytes, so giving x.b the value 'c' also gives the first byte of x.a that same value:
union foo x;
x.a = 3;
x.b = 'c';
printf("%i, %i\n", x.a, x.b);
prints
99, 99
Why are the two values the same? Because the last 3 bytes of the int 3 are all zero, so it's also read as 99. If we put in a larger number for x.a, you'll see that this is not always the case:
union foo x;
x.a = 387439;
x.b = 'c';
printf("%i, %i\n", x.a, x.b);
prints
387427, 99
To get a closer look at the actual memory values, let's set and print out the values in hex:
union foo x;
x.a = 0xDEADBEEF;
x.b = 0x22;
printf("%x, %x\n", x.a, x.b);
prints
deadbe22, 22
You can clearly see where the 0x22 overwrote the 0xEF.
BUT
In C, the order of bytes in an int are not defined. This program overwrote the 0xEF with 0x22 on my Mac, but there are other platforms where it would overwrite the 0xDE instead because the order of the bytes that make up the int were reversed. Therefore, when writing a program, you should never rely on the behavior of overwriting specific data in a union because it's not portable.
For more reading on the ordering of bytes, check out endianness.
Save your files as ~/.config/fish/functions/{some_function_name}.fish
and they should get autoloaded when you start fish.
You need to make sure your pandas dataframe columns are appropriate for the type spark is inferring. If your pandas dataframe lists something like:
pd.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5062 entries, 0 to 5061
Data columns (total 51 columns):
SomeCol 5062 non-null object
Col2 5062 non-null object
And you're getting that error try:
df[['SomeCol', 'Col2']] = df[['SomeCol', 'Col2']].astype(str)
Now, make sure .astype(str)
is actually the type you want those columns to be. Basically, when the underlying Java code tries to infer the type from an object in python it uses some observations and makes a guess, if that guess doesn't apply to all the data in the column(s) it's trying to convert from pandas to spark it will fail.
I was able to find a simple way to achieve both scrolling behaviors.
Here is the xml for it:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:scrollbars="vertical">
<HorizontalScrollView
android:layout_width="320px" android:layout_height="fill_parent">
<TableLayout
android:id="@+id/linlay" android:layout_width="320px"
android:layout_height="fill_parent" android:stretchColumns="1"
android:background="#000000"/>
</HorizontalScrollView>
</ScrollView>
Message queues are asynchronous and can retry a number of times if delivery fails. Use a message queue if the requester doesn't need to wait for a response.
The phrase "web services" make me think of synchronous calls to a distributed component over HTTP. Use web services if the requester needs a response back.
The Uri
class implements Parcelable
, so you can add and extract it directly from the Intent
// Add a Uri instance to an Intent
intent.putExtra("imageUri", uri);
// Get a Uri from an Intent
Uri uri = intent.getParcelableExtra("imageUri");
You can use the same method for any objects that implement Parcelable
, and you can implement Parcelable
on your own objects if required.
you can use detox
by Doug Harple
detox -r <folder>
How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:
Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.
You need to use this function.
JSON.parse(yourJsonString);
And it will return the object / array that was contained within the string.
You can use HTML5 pattern attribute to do this:
<form>
<input type='text' pattern='[A-Za-z\\s]*'/>
</form>
If the user enters an input that conflicts with the pattern, it will show an error dialogue automatically.
It depends. The System.Timers.Timer
has two modes of operation.
If SynchronizingObject
is set to an ISynchronizeInvoke
instance then the Elapsed
event will execute on the thread hosting the synchronizing object. Usually these ISynchronizeInvoke
instances are none other than plain old Control
and Form
instances that we are all familiar with. So in that case the Elapsed
event is invoked on the UI thread and it behaves similar to the System.Windows.Forms.Timer
. Otherwise, it really depends on the specific ISynchronizeInvoke
instance that was used.
If SynchronizingObject
is null then the Elapsed
event is invoked on a ThreadPool
thread and it behaves similar to the System.Threading.Timer
. In fact, it actually uses a System.Threading.Timer
behind the scenes and does the marshaling operation after it receives the timer callback if needed.
As @David Heffeman indicates the recommendation is to use .yaml
when possible, and the recommendation has been that way since September 2006.
That some projects use .yml
is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).
The best way to approach this is to be rigorous when creating new files (i.e. use .yaml
) and be permissive when accepting input (i.e. allow .yml
when you encounter it), possible automatically upgrading/correcting these errors when possible.
The other recommendation I have is to document the argument(s) why you have to use .yml
, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml
has more pages than .yaml
" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml
extension instead of the correct .yaml
, but I think you will be hard pressed to do so.
Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose
used .yml
, but in later versions started to use .yaml
, although they still support .yml
). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml
instead of appveyor.yml
for building the windows wheels of my YAML parser for Python).
On the other hand:
The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.
So it seems fitting that they also use a subset of the recommended extension.
When an element, such as a div
is floated
, its parent container no longer considers its height, i.e.
<div id="main">
<div id="child" style="float:left;height:40px;"> Hi</div>
</div>
The parent container will not be be 40 pixels tall by default. This causes a lot of weird little quirks if you're using these containers to structure layout.
So the clearfix
class that various frameworks use fixes this problem by making the parent container "acknowledge" the contained elements.
Day to day, I normally just use frameworks such as 960gs, Twitter Bootstrap for laying out and not bothering with the exact mechanics.
Can read more here
string today = DateTime.Today.ToString("M/d");
You should use the EndXXX of your async method to return the value. EndXXX should wait until there is a result using the IAsyncResult's WaitHandle and than return with the value.
As said by @Nancom
<mvc:resources location="/resources/" mapping="/resource/**"/>
So for clarity lets our image is in
resources/images/logo.png"
The location attribute of the mvc:resources tag defines the base directory location of static resources that you want to serve. It can be images path that are available under the src/main/webapp/resources/images/
directory; you may wonder why we have given only /resources/ as the location value instead of src/main/webapp/resources/images/
. This is because we consider the resources
directory as the base directory for all resources, we can have multiple sub-directories under resources
directory to put our images and other static resource files.
The second attribute, mapping, just indicates the request path that needs to be mapped to this resources
directory. In our case, we have assigned /resource/**
as the mapping value. So, if any web request starts with the /resource
request path, then it will be mapped to the resources
directory, and the /**
symbol indicates the recursive look for any resource files underneath the base resources
directory.
So for url like
http://localhost:8080/webstore/resource/images/logo.png
. So, while serving this web request, Spring MVC will consider /resource/images/logo.png
as the request path. So, it will try to map /resource
to the base directory specified by the location attribute, resources
. From this directory, it will try to look for the remaining path of the URL, which is /images/logo.png
. Since we have the images
directory under the resources
directory, Spring can easily locate the image file from the images
directory.
So
<mvc:resources location="/resources/" mapping="/resource/**"/>
gives us for given [requests] -> [resource mapping]:
http://localhost:8080/webstore/resource/images/logo.png
-> searches in resources/images/logo.png
http://localhost:8080/webstore/resource/images/small/picture.png
-> searches in resources/images/small/picture.png
http://localhost:8080/webstore/resource/css/main.css
-> searches in resources/css/main.css
http://localhost:8080/webstore/resource/pdf/index.pdf
-> searches in resources/pdf/index.pdf
As I can't comment yet, I want to show the solution I used based on the method Umair Ahmed posted, but when you want to search for a key instead of a value:
[{"a":true}, {"f":true}, {"g":false}]
.findIndex(function(element){return Object.keys(element)[0] == "g"});
I understand that it doesn't answer the expanded question, but the title doesn't specify what was wanted from each object, so I want to humbly share this to save headaches to others in the future, while I undestart it may not be the fastest solution.
maybe like this - all last month DATE(recDate) BETWEEN DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) AND LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 1 MONTH) )
if you've installed php
and mysql
in your linux machine, php needs php-mysql
extention to communicate with mysql. so make sure you've also installed this extention using:
sudo yum install php-mysql
in redhat based machines.
and
sudo apt-get install php-mysql
in debian machines.
What do I need to do to make this function wait for the result of the promise?
Use async/await
(NOT Part of ECMA6, but
available for Chrome, Edge, Firefox and Safari since end of 2017, see canIuse)
MDN
async function waitForPromise() {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
Added due to comment: An async function always returns a Promise, and in TypeScript it would look like:
async function waitForPromise(): Promise<string> {
// let result = await any Promise, like:
let result = await Promise.resolve('this is a sample promise');
}
I've recently found that blanks in the name of the redirect file will cause the "ambiguous redirect" message.
For example if you redirect to application$(date +%Y%m%d%k%M%S).log
and you specify the wrong formatting characters, the redirect will fail before 10 AM for example. If however, you used application$(date +%Y%m%d%H%M%S).log
it would succeed. This is because the %k
format yields ' 9'
for 9AM where %H
yields '09'
for 9AM.
echo $(date +%Y%m%d%k%M%S)
gives 20140626 95138
echo $(date +%Y%m%d%H%M%S)
gives 20140626095138
The erroneous date might give something like:
echo "a" > myapp20140626 95138.log
where the following is what would be desired:
echo "a" > myapp20140626095138.log
The show()
method only affects the display
CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button
element is a button and does not raise a submit
event. You would need to change your selector to the form
for that to work:
$('#login_form').submit(function() {
$('#gif').css('visibility', 'visible');
});
Also note that return true;
is redundant in your logic, so it can be removed.
Just set the value for scaleStartValue in your options.
var options = {
// ....
scaleStartValue: 0,
}
See the documentation for this here.
I managed to fix it in Android Studio 1.3.1 by doing the following:
File -> New -> New Module
.iml
file from an existing library module and change the name of the file and rename references in the .iml
fileIt's strange to see so many people using shell scripting for this. I was looking for a way to use native makefile syntax, because I'm writing this outside of any target. You can use the wildcard
function to check if file exists:
ifeq ($(UNAME),Darwin)
SHELL := /opt/local/bin/bash
OS_X := true
else ifneq (,$(wildcard /etc/redhat-release))
OS_RHEL := true
else
OS_DEB := true
SHELL := /bin/bash
endif
Update:
I found a way which is really working for me:
ifneq ("$(wildcard $(PATH_TO_FILE))","")
FILE_EXISTS = 1
else
FILE_EXISTS = 0
endif
The answers above are good. Adding a case that I used. Just if you don't want to use numpy and keep it as list without changing the contents.
You can run a small loop and change the dimension from 1xN to Nx1.
tmp=[]
for b in bus:
tmp.append([b])
bus=tmp
It is maybe not efficient while in case of very large numbers. But it works for a small set of numbers. Thanks
Use JSON_UNESCAPED_UNICODE
inside json_encode()
if your php version >=5.4.
You can use plt.subplots_adjust
to change the spacing between the subplots (source)
call signature:
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
The parameter meanings (and suggested defaults) are:
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
The actual defaults are controlled by the rc file
If you're using lodash you can do something like
_.sum(_.values({ 'a': 1 , 'b': 2 , 'c':3 }))
As Mystere Man suggested, getting just a view first and then again making an ajax call again to get the json result is unnecessary in this case. that is 2 calls to the server. I think you can directly return an HTML table of Users in the first call.
We will do this in this way. We will have a strongly typed view which will return the markup of list of users to the browser and this data is being supplied by an action method which we will invoke from our browser using an http request.
Have a ViewModel for the User
public class UserViewModel
{
public int UserID { set;get;}
public string FirstName { set;get;}
//add remaining properties as per your requirement
}
and in your controller have a method to get a list of Users
public class UserController : Controller
{
[HttpGet]
public ActionResult List()
{
List<UserViewModel> objList=UserService.GetUsers(); // this method should returns list of Users
return View("users",objList)
}
}
Assuming that UserService.GetUsers() method will return a List of UserViewModel object which represents the list of usres in your datasource (Tables)
and in your users.cshtml ( which is under Views/User folder),
@model List<UserViewModel>
<table>
@foreach(UserViewModel objUser in Model)
{
<tr>
<td>@objUser.UserId.ToString()</td>
<td>@objUser.FirstName</td>
</tr>
}
</table>
All Set now you can access the url like yourdomain/User/List
and it will give you a list of users in an HTML table.
tabindex
is a global attribute responsible for two things:
In my mind the second thing is even more important than the first one. There are very few elements that are focusable by default (e.g. <a> and form controls). Developers very often add some JavaScript event handlers (like 'onclick') on not focusable elements (<div>, <span> and so on), and the way to make your interface be responsive not only to mouse events but also to keyboard events (e.g. 'onkeypress') is to make such elements focusable. Lastly, if you don't want to set the order but just make your element focusable use tabindex="0"
on all such elements:
<div tabindex="0"></div>
Also, if you don't want it to be focusable via the tab key then use tabindex="-1"
. For example, the below link will not be focused while using tab keys to traverse.
<a href="#" tabindex="-1">Tab key cannot reach here!</a>
I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.
**Note have used Python 2.7 so some minor modification might be required for Python 3+
class a:
global d
d={}
def get_config(self,x):
if x=='GENESYS':
d['host'] = 'host name'
d['port'] = '15222'
return d
Calling get_config method using class instance in a separate python file:
from constant import a
class b:
a().get_config('GENESYS')
print a().get_config('GENESYS').get('host')
print a().get_config('GENESYS').get('port')
Based on http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
What about:
Create Table New_Users Select * from Old_Users Where 1=2;
and if that doesn't work, just select a row and truncate after creation:
Create table New_Users select * from Old_Users Limit 1;
Truncate Table New_Users;
EDIT:
I noticed your comment below about needing indexes, etc. Try:
show create table old_users;
#copy the output ddl statement into a text editor and change the table name to new_users
#run the new query
insert into new_users(id,name...) select id,name,... form old_users group by id;
That should do it. It appears that you are doing this to get rid of duplicates? In which case you may want to put a unique index on id. if it's a primary key, this should already be in place. You can either:
#make primary key
alter table new_users add primary key (id);
#make unique
create unique index idx_new_users_id_uniq on new_users (id);
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source=CHANCHAL\SQLEXPRESS;initial catalog=AssetManager;user id=GIPL-PC\GIPL;password=";
con.Open();
SqlDataAdapter ad = new SqlDataAdapter("select * from detail1", con);
SqlCommandBuilder cmdbl = new SqlCommandBuilder(ad);
DataSet ds = new DataSet("detail1");
ad.Fill(ds, "detail1");
DataRow row = ds.Tables["detail1"].NewRow();
row["Name"] = textBox1.Text;
row["address"] =textBox2.Text;
ds.Tables["detail1"].Rows.Add(row);
ad.Update(ds, "detail1");
con.Close();
MessageBox.Show("insert secussfully");
}
Use the matplotlib savefig
function with the keyword argument transparent=True
to save the image as a png file.
In [30]: x = np.linspace(0,6,31)
In [31]: y = np.exp(-0.5*x) * np.sin(x)
In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]
In [33]: savefig('demo.png', transparent=True)
Result:
Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display
command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.
Or
import smtplib
from email.message import EmailMessage
from getpass import getpass
password = getpass()
message = EmailMessage()
message.set_content('Message content here')
message['Subject'] = 'Your subject here'
message['From'] = "USERNAME@DOMAIN"
message['To'] = "[email protected]"
try:
smtp_server = None
smtp_server = smtplib.SMTP("YOUR.MAIL.SERVER", 587)
smtp_server.ehlo()
smtp_server.starttls()
smtp_server.ehlo()
smtp_server.login("USERNAME@DOMAIN", password)
smtp_server.send_message(message)
except Exception as e:
print("Error: ", str(e))
finally:
if smtp_server is not None:
smtp_server.quit()
If you want to use Port 465 you have to create an SMTP_SSL
object.
Utilizing the fact that you can do set operations on arrays by doing &
(intersection), -
(difference), and |
(union).
Obviously I didn't implement the MultiSet to spec, but this should get you started:
class MultiSet
attr_accessor :set
def initialize(set)
@set = set
end
# intersection
def &(other)
@set & other.set
end
# difference
def -(other)
@set - other.set
end
# union
def |(other)
@set | other.set
end
end
x = MultiSet.new([1,1,2,2,3,4,5,6])
y = MultiSet.new([1,3,5,6])
p x - y # [2,2,4]
p x & y # [1,3,5,6]
p x | y # [1,2,3,4,5,6]
select * from table_name LIMIT 100
remember this only works with MYSQL
In your comment in response to John, you suggest that you want the keys and values of the dictionary, not just the values.
PEP 256 suggests this for sorting a dictionary by values.
import operator
sorted(d.iteritems(), key=operator.itemgetter(1))
If you want descending order, do this
sorted(d.iteritems(), key=itemgetter(1), reverse=True)
Given the following sample
myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)
then
myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)
or you could select your columns altogether and wrap it up nicely:
# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))
levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")
To obtain
> myData
A B Pulse
1 long 1kg 20
2 short 2kg 21
3 long 3kg 22
4 short 1kg 23
5 long 2kg 24
6 short 3kg 25
$('#hello').hide('slide', {direction: 'left'}, 1000);
requires the jQuery-ui library. See http://www.jqueryui.com
I have a feeling the module I wrote will produce similar results to photoshop, as it preserves color data by averaging them, not applying an algorithm. It's kind of slow, but to me it is the best, because it preserves all the color data.
https://github.com/danschumann/limby-resize/blob/master/lib/canvas_resize.js
It doesn't take the nearest neighbor and drop other pixels, or sample a group and take a random average. It takes the exact proportion each source pixel should output into the destination pixel. The average pixel color in the source will be the average pixel color in the destination, which these other formulas, I think they will not be.
an example of how to use is at the bottom of https://github.com/danschumann/limby-resize
UPDATE OCT 2018: These days my example is more academic than anything else. Webgl is pretty much 100%, so you'd be better off resizing with that to produce similar results, but faster. PICA.js does this, I believe. –
From Zvon.org XSLT Reference:
XPath function: boolean contains (string, string)
Hope this helps.
Read about using docstrings in your Python code.
As per the Python docstring conventions:
The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.
There will be no golden rule, but rather provide comments that mean something to the other developers on your team (if you have one) or even to yourself when you come back to it six months down the road.
Just set this extra line in catalina.bat
file
LINE NO AROUND: 143
set "CATALINA_OPTS=-Xms512m -Xmx512m"
And restart Tomcat service
If you want the external public IP and you're in a cloud environment like AWS or Azure, you can use the ipify_facts module:
# TODO: SECURITY: This requires that we trust ipify to provide the correct public IP. We could run our own ipify server.
- name: Get my public IP from ipify.org
ipify_facts:
This will place the public IP into the variable ipify_public_ip
.