Programs & Examples On #Linq

Language Integrated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages. Please consider using more detailed tags when appropriate, for example [linq-to-sql], [linq-to-entities] / [entity-framework], or [plinq]

How to use LINQ Distinct() with multiple fields

public List<ItemCustom2> GetBrandListByCat(int id)
    {

        var OBJ = (from a in db.Items
                   join b in db.Brands on a.BrandId equals b.Id into abc1
                   where (a.ItemCategoryId == id)
                   from b in abc1.DefaultIfEmpty()
                   select new
                   {
                       ItemCategoryId = a.ItemCategoryId,
                       Brand_Name = b.Name,
                       Brand_Id = b.Id,
                       Brand_Pic = b.Pic,

                   }).Distinct();


        List<ItemCustom2> ob = new List<ItemCustom2>();
        foreach (var item in OBJ)
        {
            ItemCustom2 abc = new ItemCustom2();
            abc.CategoryId = item.ItemCategoryId;
            abc.BrandId = item.Brand_Id;
            abc.BrandName = item.Brand_Name;
            abc.BrandPic = item.Brand_Pic;
            ob.Add(abc);
        }
        return ob;

    }

How to Select Min and Max date values in Linq Query

If you are looking for the oldest date (minimum value), you'd sort and then take the first item returned. Sorry for the C#:

var min = myData.OrderBy( cv => cv.Date1 ).First();

The above will return the entire object. If you just want the date returned:

var min = myData.Min( cv => cv.Date1 );

Regarding which direction to go, re: Linq to Sql vs Linq to Entities, there really isn't much choice these days. Linq to Sql is no longer being developed; Linq to Entities (Entity Framework) is the recommended path by Microsoft these days.

From Microsoft Entity Framework 4 in Action (MEAP release) by Manning Press:

What about the future of LINQ to SQL?

It's not a secret that LINQ to SQL is included in the Framework 4.0 for compatibility reasons. Microsoft has clearly stated that Entity Framework is the recommended technology for data access. In the future it will be strongly improved and tightly integrated with other technologies while LINQ to SQL will only be maintained and little evolved.

Convert Linq Query Result to Dictionary

Try using the ToDictionary method like so:

var dict = TableObj.ToDictionary( t => t.Key, t => t.TimeStamp );

How do I concatenate two arrays in C#?

I've found an elegant one line solution using LINQ or Lambda expression, both work the same (LINQ is converted to Lambda when program is compiled). The solution works for any array type and for any number of arrays.

Using LINQ:

public static T[] ConcatArraysLinq<T>(params T[][] arrays)
{
    return (from array in arrays
            from arr in array
            select arr).ToArray();
}

Using Lambda:

public static T[] ConcatArraysLambda<T>(params T[][] arrays)
{
    return arrays.SelectMany(array => array.Select(arr => arr)).ToArray();
}

I've provided both for one's preference. Performance wise @Sergey Shteyn's or @deepee1's solutions are a bit faster, Lambda expression being the slowest. Time taken is dependant on type(s) of array elements, but unless there are millions of calls, there is no significant difference between the methods.

Select distinct using linq

You should override Equals and GetHashCode meaningfully, in this case to compare the ID:

public class LinqTest
{
    public int id { get; set; }
    public string value { get; set; }

    public override bool Equals(object obj)
    {
        LinqTest obj2 = obj as LinqTest;
        if (obj2 == null) return false;
        return id == obj2.id;
    }

    public override int GetHashCode()
    {
        return id;
    }
}

Now you can use Distinct:

List<LinqTest> uniqueIDs = myList.Distinct().ToList();

Why is this error, 'Sequence contains no elements', happening?

Check again. Use debugger if must. My guess is that for some item in userResponseDetails this query finds no elements:

.Where(y => y.ResponseId.Equals(item.ResponseId))

so you can't call

.First()

on it. Maybe try

.FirstOrDefault()

if it solves the issue.

Do NOT return NULL value! This is purely so that you can see and diagnose where problem is. Handle these cases properly.

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

I know this question already has an accepted answer, but for me, a .NET beginner, there was a simple solution to what I was doing wrong and I thought I'd share.

I had been doing this:

@Html.HiddenFor(Model.Foo.Bar.ID)

What worked for me was changing to this:

@Html.HiddenFor(m => m.Foo.Bar.ID)

(where "m" is an arbitrary string to represent the model object)

Using Linq select list inside list

You have to use the SelectMany extension method or its equivalent syntax in pure LINQ.

(from model in list
 where model.application == "applicationname"
 from user in model.users
 where user.surname == "surname"
 select new { user, model }).ToList();

How to Count Duplicates in List with LINQ

Slightly shorter version using methods chain:

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
            .Select(g => new {Value = g.Key, Count = g.Count()})
            .OrderByDescending(x=>x.Count);

foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

The model backing the 'ApplicationDbContext' context has changed since the database was created

I just solved a similar problem by deleting all files in the website folder and then republished it.

Better way to sort array in descending order

Use LINQ OrderByDescending method. It returns IOrderedIEnumerable<int>, which you can convert back to Array if you need so. Generally, List<>s are more functional then Arrays.

array = array.OrderByDescending(c => c).ToArray();

Linq: GroupBy, Sum and Count

The following query works. It uses each group to do the select instead of SelectMany. SelectMany works on each element from each collection. For example, in your query you have a result of 2 collections. SelectMany gets all the results, a total of 3, instead of each collection. The following code works on each IGrouping in the select portion to get your aggregate operations working correctly.

var results = from line in Lines
              group line by line.ProductCode into g
              select new ResultLine {
                ProductName = g.First().Name,
                Price = g.Sum(pc => pc.Price).ToString(),
                Quantity = g.Count().ToString(),
              };

LINQ to SQL - Left Outer Join with multiple join conditions

I know it's "a bit late" but just in case if anybody needs to do this in LINQ Method syntax (which is why I found this post initially), this would be how to do that:

var results = context.Periods
    .GroupJoin(
        context.Facts,
        period => period.id,
        fk => fk.periodid,
        (period, fact) => fact.Where(f => f.otherid == 17)
                              .Select(fact.Value)
                              .DefaultIfEmpty()
    )
    .Where(period.companyid==100)
    .SelectMany(fact=>fact).ToList();

How to use orderby with 2 fields in linq?

MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

LINQ query to select top five

Just thinking you might be feel unfamiliar of the sequence From->Where->Select, as in sql script, it is like Select->From->Where.

But you may not know that inside Sql Engine, it is also parse in the sequence of 'From->Where->Select', To validate it, you can try a simple script

select id as i from table where i=3

and it will not work, the reason is engine will parse Where before Select, so it won't know alias i in the where. To make this work, you can try

select * from (select id as i from table) as t where i = 3

ToList().ForEach in Linq

As xanatos said, this is a misuse of ForEach.

If you are going to use linq to handle this, I would do it like this:

var departments = employees.SelectMany(x => x.Departments);
foreach (var item in departments)
{
    item.SomeProperty = null;
}
collection.AddRange(departments);

However, the Loop approach is more readable and therefore more maintainable.

LINQ: Select an object and change some properties without creating a new object

I'm not sure what the query syntax is. But here is the expanded LINQ expression example.

var query = someList.Select(x => { x.SomeProp = "foo"; return x; })

What this does is use an anonymous method vs and expression. This allows you to use several statements in one lambda. So you can combine the two operations of setting the property and returning the object into this somewhat succinct method.

How do I get the MAX row with a GROUP BY in LINQ query?

var q = from s in db.Serials
        group s by s.Serial_Number into g
        select new {Serial_Number = g.Key, MaxUid = g.Max(s => s.uid) }

How to perform Join between multiple tables in LINQ lambda

For joins, I strongly prefer query-syntax for all the details that are happily hidden (not the least of which are the transparent identifiers involved with the intermediate projections along the way that are apparent in the dot-syntax equivalent). However, you asked regarding Lambdas which I think you have everything you need - you just need to put it all together.

var categorizedProducts = product
    .Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
    .Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new { ppc, c })
    .Select(m => new { 
        ProdId = m.ppc.p.Id, // or m.ppc.pc.ProdId
        CatId = m.c.CatId
        // other assignments
    });

If you need to, you can save the join into a local variable and reuse it later, however lacking other details to the contrary, I see no reason to introduce the local variable.

Also, you could throw the Select into the last lambda of the second Join (again, provided there are no other operations that depend on the join results) which would give:

var categorizedProducts = product
    .Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
    .Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new {
        ProdId = ppc.p.Id, // or ppc.pc.ProdId
        CatId = c.CatId
        // other assignments
    });

...and making a last attempt to sell you on query syntax, this would look like this:

var categorizedProducts =
    from p in product
    join pc in productcategory on p.Id equals pc.ProdId
    join c in category on pc.CatId equals c.Id
    select new {
        ProdId = p.Id, // or pc.ProdId
        CatId = c.CatId
        // other assignments
    };

Your hands may be tied on whether query-syntax is available. I know some shops have such mandates - often based on the notion that query-syntax is somewhat more limited than dot-syntax. There are other reasons, like "why should I learn a second syntax if I can do everything and more in dot-syntax?" As this last part shows - there are details that query-syntax hides that can make it well worth embracing with the improvement to readability it brings: all those intermediate projections and identifiers you have to cook-up are happily not front-and-center-stage in the query-syntax version - they are background fluff. Off my soap-box now - anyhow, thanks for the question. :)

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

Change it like this and it should work:

var key = item.Key.ToString();
IQueryable<entity> pages = from p in context.pages
                           where  p.Serial == key
                           select p;

The reason why the exception is not thrown in the line the LINQ query is declared but in the line of the foreach is the deferred execution feature, i.e. the LINQ query is not executed until you try to access the result. And this happens in the foreach and not earlier.

Creating a LINQ select from multiple tables

You can use anonymous types for this, i.e.:

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                  where pg.PageID == page.PageID
                  select new { pg, op }).SingleOrDefault();

This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:-

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                  where pg.PageID == page.PageID
                  select new
                  {
                      PermissionName = pg, 
                      ObjectPermission = op
                  }).SingleOrDefault();

This will enable you to say:-

if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit();

For example :-)

EF LINQ include multiple and nested entities

Include is a part of fluent interface, so you can write multiple Include statements each following other

 db.Courses.Include(i => i.Modules.Select(s => s.Chapters))
           .Include(i => i.Lab)
           .Single(x => x.Id == id); 

IEnumerable vs List - What to Use? How do they work?

There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List

Here some basics points about scenarios and functions:

enter image description here enter image description here

How to merge a list of lists with same type of items to a single list of items?

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.

LINQ's Distinct() on a particular property

In case you need a Distinct method on multiple properties, you can check out my PowerfulExtensions library. Currently it's in a very young stage, but already you can use methods like Distinct, Union, Intersect, Except on any number of properties;

This is how you use it:

using PowerfulExtensions.Linq;
...
var distinct = myArray.Distinct(x => x.A, x => x.B);

Linq select to new object

If you want to be able to perform a lookup on each type to get its frequency then you will need to transform the enumeration into a dictionary.

var types = new[] {typeof(string), typeof(string), typeof(int)};
var x = types
        .GroupBy(type => type)
        .ToDictionary(g => g.Key, g => g.Count());
foreach (var kvp in x) {
    Console.WriteLine("Type {0}, Count {1}", kvp.Key, kvp.Value);
}
Console.WriteLine("string has a count of {0}", x[typeof(string)]);

Querying Datatable with where condition

Something like this...

var res = from row in myDTable.AsEnumerable()
where row.Field<int>("EmpID") == 5 &&
(row.Field<string>("EmpName") != "abc" ||
row.Field<string>("EmpName") != "xyz")
select row;

See also LINQ query on a DataTable

Get a list of distinct values in List

public class KeyNote
{
    public long KeyNoteId { get; set; }
    public long CourseId { get; set; }
    public string CourseName { get; set; }
    public string Note { get; set; }
    public DateTime CreatedDate { get; set; }
}

public List<KeyNote> KeyNotes { get; set; }
public List<RefCourse> GetCourses { get; set; }    

List<RefCourse> courses = KeyNotes.Select(x => new RefCourse { CourseId = x.CourseId, Name = x.CourseName }).Distinct().ToList();

By using the above logic, we can get the unique Courses.

If Else in LINQ

I assume from db that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);

Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).

For a trivial example of the type of thing you can do:

select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" };

You can do much richer things, but I really doubt you can pick the table in the conditional. You're welcome to try, of course...

SQL to LINQ Tool

Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.

[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.

Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.

Entity framework left join

If you prefer method call notation, you can force a left join using SelectMany combined with DefaultIfEmpty. At least on Entity Framework 6 hitting SQL Server. For example:

using(var ctx = new MyDatabaseContext())
{
    var data = ctx
    .MyTable1
    .SelectMany(a => ctx.MyTable2
      .Where(b => b.Id2 == a.Id1)
      .DefaultIfEmpty()
      .Select(b => new
      {
        a.Id1,
        a.Col1,
        Col2 = b == null ? (int?) null : b.Col2,
      }));
}

(Note that MyTable2.Col2 is a column of type int). The generated SQL will look like this:

SELECT 
    [Extent1].[Id1] AS [Id1], 
    [Extent1].[Col1] AS [Col1], 
    CASE WHEN ([Extent2].[Col2] IS NULL) THEN CAST(NULL AS int) ELSE  CAST( [Extent2].[Col2] AS int) END AS [Col2]
    FROM  [dbo].[MyTable1] AS [Extent1]
    LEFT OUTER JOIN [dbo].[MyTable2] AS [Extent2] ON [Extent2].[Id2] = [Extent1].[Id1]

How to get first object out from List<Object> using Linq

I would to it like this:

//Dictionary object with Key as string and Value as List of Component type object
Dictionary<String, List<Component>> dic = new Dictionary<String, List<Component>>();

//from each element of the dictionary select first component if any
IEnumerable<Component> components = dic.Where(kvp => kvp.Value.Any()).Select(kvp => (kvp.Value.First() as Component).ComponentValue("Dep"));

but only if it is sure that list contains only objects of Component class or children

Entity Framework - Linq query with order by and group by

Try moving the order by after group by:

var groupByReference = (from m in context.Measurements
                        group m by new { m.Reference } into g
                        order by g.Avg(i => i.CreationTime)
                        select g).Take(numOfEntries).ToList();

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

dt is nullable you need to access its Value

if (datetime.HasValue)
    dt = datetime.Value;

It is important to remember that it can be NULL. That is why the nullablestruct has the HasValue property that tells you if it is NULL or not.

You can also use the null-coalescing operator ?? to assign a default value

dt = datetime ?? DateTime.Now;

This will assign the value on the right if the value on the left is NULL

Use LINQ to get items in one List<>, that are not in another List<>

This Enumerable Extension allow you to define a list of item to exclude and a function to use to find key to use to perform comparison.

public static class EnumerableExtensions
{
    public static IEnumerable<TSource> Exclude<TSource, TKey>(this IEnumerable<TSource> source,
    IEnumerable<TSource> exclude, Func<TSource, TKey> keySelector)
    {
       var excludedSet = new HashSet<TKey>(exclude.Select(keySelector));
       return source.Where(item => !excludedSet.Contains(keySelector(item)));
    }
}

You can use it this way

list1.Exclude(list2, i => i.ID);

Select multiple records based on list of Id's with linq

Nice answers abowe, but don't forget one IMPORTANT thing - they provide different results!

  var idList = new int[1, 2, 2, 2, 2]; // same user is selected 4 times
  var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e)).ToList();

This will return 2 rows from DB (and this could be correct, if you just want a distinct sorted list of users)

BUT in many cases, you could want an unsorted list of results. You always have to think about it like about a SQL query. Please see the example with eshop shopping cart to illustrate what's going on:

  var priceListIDs = new int[1, 2, 2, 2, 2]; // user has bought 4 times item ID 2
  var shoppingCart = _dataContext.ShoppingCart
                     .Join(priceListIDs, sc => sc.PriceListID, pli => pli, (sc, pli) => sc)
                     .ToList();

This will return 5 results from DB. Using 'contains' would be wrong in this case.

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

Using LINQ to remove elements from a List<T>

Well, it would be easier to exclude them in the first place:

authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();

However, that would just change the value of authorsList instead of removing the authors from the previous collection. Alternatively, you can use RemoveAll:

authorsList.RemoveAll(x => x.FirstName == "Bob");

If you really need to do it based on another collection, I'd use a HashSet, RemoveAll and Contains:

var setToRemove = new HashSet<Author>(authors);
authorsList.RemoveAll(x => setToRemove.Contains(x));

Using LINQ to concatenate strings

I'm going to cheat a little and throw out a new answer to this that seems to sum up the best of everything on here instead of sticking it inside of a comment.

So you can one line this:

List<string> strings = new List<string>() { "one", "two", "three" };

string concat = strings        
    .Aggregate(new StringBuilder("\a"), 
                    (current, next) => current.Append(", ").Append(next))
    .ToString()
    .Replace("\a, ",string.Empty); 

Edit: You'll either want to check for an empty enumerable first or add an .Replace("\a",string.Empty); to the end of the expression. Guess I might have been trying to get a little too smart.

The answer from @a.friend might be slightly more performant, I'm not sure what Replace does under the hood compared to Remove. The only other caveat if some reason you wanted to concat strings that ended in \a's you would lose your separators... I find that unlikely. If that is the case you do have other fancy characters to choose from.

LINQ query on a DataTable

For VB.NET The code will look like this:

Dim results = From myRow In myDataTable  
Where myRow.Field(Of Int32)("RowNo") = 1 Select myRow

Handling 'Sequence has no elements' Exception

Part of the answer to 'handle' the 'Sequence has no elements' Exception in VB is to test for empty

If Not (myMap Is Nothing) Then
' execute code
End if

Where MyMap is the sequence queried returning empty/null. FYI

LINQ to read XML

XDocument xdoc = XDocument.Load("data.xml");
var lv1s = xdoc.Root.Descendants("level1"); 
var lvs = lv1s.SelectMany(l=>
     new string[]{ l.Attribute("name").Value }
     .Union(
         l.Descendants("level2")
         .Select(l2=>"   " + l2.Attribute("name").Value)
      )
    );
foreach (var lv in lvs)
{
   result.AppendLine(lv);
}

Ps. You have to use .Root on any of these versions.

LINQ Where with AND OR condition

from item in db.vw_Dropship_OrderItems
    where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
    (listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
    select item;

Might give strange behavior if both listMerchants and listStatus are both null.

Apply function to all elements of collection through LINQ

Or you can hack it up.

Items.All(p => { p.IsAwesome = true; return true; });

Quickest way to compare two generic lists for differences

Use Except:

var firstNotSecond = list1.Except(list2).ToList();
var secondNotFirst = list2.Except(list1).ToList();

I suspect there are approaches which would actually be marginally faster than this, but even this will be vastly faster than your O(N * M) approach.

If you want to combine these, you could create a method with the above and then a return statement:

return !firstNotSecond.Any() && !secondNotFirst.Any();

One point to note is that there is a difference in results between the original code in the question and the solution here: any duplicate elements which are only in one list will only be reported once with my code, whereas they'd be reported as many times as they occur in the original code.

For example, with lists of [1, 2, 2, 2, 3] and [1], the "elements in list1 but not list2" result in the original code would be [2, 2, 2, 3]. With my code it would just be [2, 3]. In many cases that won't be an issue, but it's worth being aware of.

Conversion from List<T> to array T[]

To go twice as fast by using multiple processor cores HPCsharp nuget package provides:

list.ToArrayPar();

LINQ select one field from list of DTO objects to array

In the case you're interested in extremely minor, almost immeasurable performance increases, add a constructor to your Line class, giving you such:

public class Line
{
    public Line(string sku, int qty)
    {
        this.Sku = sku;
        this.Qty = qty;
    }

    public string Sku { get; set; }
    public int Qty    { get; set; }
}

Then create a specialized collection class based on List<Line> with one new method, Add:

public class LineList : List<Line>
{
    public void Add(string sku, int qty)
    {
        this.Add(new Line(sku, qty));
    }
}

Then the code which populates your list gets a bit less verbose by using a collection initializer:

LineList myLines = new LineList
{
    { "ABCD1", 1 },
    { "ABCD2", 1 },
    { "ABCD3", 1 }
};

And, of course, as the other answers state, it's trivial to extract the SKUs into a string array with LINQ:

string[] mySKUsArray = myLines.Select(myLine => myLine.Sku).ToArray();

LINQ syntax where string value is not null or empty

http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367077

Problem Statement
It's possible to write LINQ to SQL that gets all rows that have either null or an empty string in a given field, but it's not possible to use string.IsNullOrEmpty to do it, even though many other string methods map to LINQ to SQL. Proposed Solution Allow string.IsNullOrEmpty in a LINQ to SQL where clause so that these two queries have the same result:

var fieldNullOrEmpty =
from item in db.SomeTable
where item.SomeField == null || item.SomeField.Equals(string.Empty)
select item;

var fieldNullOrEmpty2 =
from item in db.SomeTable
where string.IsNullOrEmpty(item.SomeField)
select item;

Other Reading:
1. DevArt
2. Dervalp.com
3. StackOverflow Post

How to get index using LINQ?

myCars.Select((v, i) => new {car = v, index = i}).First(myCondition).index;

or the slightly shorter

myCars.Select((car, index) => new {car, index}).First(myCondition).index;

Entity Framework: There is already an open DataReader associated with this Command

Alternatively to using MARS (MultipleActiveResultSets) you can write your code so you dont open multiple result sets.

What you can do is to retrieve the data to memory, that way you will not have the reader open. It is often caused by iterating through a resultset while trying to open another result set.

Sample Code:

public class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

public class Blog
{
    public int BlogID { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostID { get; set; }
    public virtual Blog Blog { get; set; }
    public string Text { get; set; }
}

Lets say you are doing a lookup in your database containing these:

var context = new MyContext();

//here we have one resultset
var largeBlogs = context.Blogs.Where(b => b.Posts.Count > 5); 

foreach (var blog in largeBlogs) //we use the result set here
{
     //here we try to get another result set while we are still reading the above set.
    var postsWithImportantText = blog.Posts.Where(p=>p.Text.Contains("Important Text"));
}

We can do a simple solution to this by adding .ToList() like this:

var largeBlogs = context.Blogs.Where(b => b.Posts.Count > 5).ToList();

This forces entityframework to load the list into memory, thus when we iterate though it in the foreach loop it is no longer using the data reader to open the list, it is instead in memory.

I realize that this might not be desired if you want to lazyload some properties for example. This is mostly an example that hopefully explains how/why you might get this problem, so you can make decisions accordingly

LINQ to Entities how to update a record

In most cases @tster's answer will suffice. However, I had a scenario where I wanted to update a row without first retrieving it.

My situation is this: I've got a table where I want to "lock" a row so that only a single user at a time will be able to edit it in my app. I'm achieving this by saying

update items set status = 'in use', lastuser = @lastuser, lastupdate = @updatetime where ID = @rowtolock and @status = 'free'

The reason being, if I were to simply retrieve the row by ID, change the properties and then save, I could end up with two people accessing the same row simultaneously. This way, I simply send and update claiming this row as mine, then I try to retrieve the row which has the same properties I just updated with. If that row exists, great. If, for some reason it doesn't (someone else's "lock" command got there first), I simply return FALSE from my method.

I do this by using context.Database.ExecuteSqlCommand which accepts a string command and an array of parameters.

Just wanted to add this answer to point out that there will be scenarios in which retrieving a row, updating it, and saving it back to the DB won't suffice and that there are ways of running a straight update statement when necessary.

Proper Linq where clauses

The second one would be more efficient as it just has one predicate to evaluate against each item in the collection where as in the first one, it's applying the first predicate to all items first and the result (which is narrowed down at this point) is used for the second predicate and so on. The results get narrowed down every pass but still it involves multiple passes.

Also the chaining (first method) will work only if you are ANDing your predicates. Something like this x.Age == 10 || x.Fat == true will not work with your first method.

Linq to SQL how to do "where [column] in (list of values)"

You could also use:

List<int> codes = new List<int>();

codes.add(1);
codes.add(2);

var foo = from codeData in channel.AsQueryable<CodeData>()
          where codes.Any(code => codeData.CodeID.Equals(code))
          select codeData;

Split List into Sublists with LINQ

If the list is of type system.collections.generic you can use the "CopyTo" method available to copy elements of your array to other sub arrays. You specify the start element and number of elements to copy.

You could also make 3 clones of your original list and use the "RemoveRange" on each list to shrink the list to the size you want.

Or just create a helper method to do it for you.

Entity framework linq query Include() multiple children entities

You might find this article of interest which is available at codeplex.com.

The article presents a new way of expressing queries that span multiple tables in the form of declarative graph shapes.

Moreover, the article contains a thorough performance comparison of this new approach with EF queries. This analysis shows that GBQ quickly outperforms EF queries.

How to compare only date components from DateTime in EF?

You can also use this:

DbFunctions.DiffDays(date1, date2) == 0

Check if a string within a list contains a specific string with Linq

Try this:

bool matchFound = myList.Any(s => s.Contains("Mdd LH"));

The Any() will stop searching the moment it finds a match, so is quite efficient for this task.

Select distinct values from a list using LINQ in C#

You can use GroupBy with anonymous type, and then get First:

list.GroupBy(e => new { 
                          empLoc = e.empLoc, 
                          empPL = e.empPL, 
                          empShift = e.empShift 
                       })

    .Select(g => g.First());

SELECT COUNT in LINQ to SQL C#

Like that

var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();

or even easier

var purchCount = myBlaContext.purchases.Count()

Entity Framework. Delete all rows in table

This avoids using any sql

using (var context = new MyDbContext())
{
    var itemsToDelete = context.Set<MyTable>();
    context.MyTables.RemoveRange(itemsToDelete);
    context.SaveChanges();
}

Update records using LINQ

Just as an addition to the accepted answer, you might find your code looking more consistent when using the LINQ method syntax:

Context.person_account_portfolio
.Where(p => person_id == personId)
.ToList()
.ForEach(x => x.is_default = false);

.ToList() is neccessary because .ForEach() is defined only on List<T>, not on IEnumerable<T>. Just be aware .ToList() is going to execute the query and load ALL matching rows from database before executing the loop.

Sequence contains no matching element

Use FirstOrDefault. First will never return null - if it can't find a matching element it throws the exception you're seeing.

_dsACL.Documents.FirstOrDefault(o => o.ID == id);

Linq Query Group By and Selecting First Items

var results = list.GroupBy(x => x.Category)
            .Select(g => g.OrderBy(x => x.SortByProp).FirstOrDefault());

For those wondering how to do this for groups that are not necessarily sorted correctly, here's an expansion of this answer that uses method syntax to customize the sort order of each group and hence get the desired record from each.

Note: If you're using LINQ-to-Entities you will get a runtime exception if you use First() instead of FirstOrDefault() here as the former can only be used as a final query operation.

C# LINQ select from list

In likeness of how I found this question using Google, I wanted to take it one step further. Lets say I have a string[] states and a db Entity of StateCounties and I just want the states from the list returned and not all of the StateCounties.

I would write:

db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();

I found this within the sample of CheckBoxList for nu-get.

Returning IEnumerable<T> vs. IQueryable<T>

Yes, both will give you deferred execution.

The difference is that IQueryable<T> is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable<T>, that query will be executed in the database, if possible.

For the IEnumerable<T> case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database.

In code:

IQueryable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:

IEnumerable<Customer> custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);

This is quite an important difference, and working on IQueryable<T> can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take and Skip on IQueryable, you will only get the number of rows requested; doing that on an IEnumerable<T> will cause all of your rows to be loaded in memory.

Find element in List<> that contains a value

You can use the Where to filter and Select to get the desired value.

MyList.Where(i=>i.name == yourName).Select(j=>j.value);

Multiple "order by" in LINQ

use the following line on your DataContext to log the SQL activity on the DataContext to the console - then you can see exactly what your linq statements are requesting from the database:

_db.Log = Console.Out

The following LINQ statements:

var movies = from row in _db.Movies 
             orderby row.CategoryID, row.Name
             select row;

AND

var movies = _db.Movies.OrderBy(m => m.CategoryID).ThenBy(m => m.Name);

produce the following SQL:

SELECT [t0].ID, [t0].[Name], [t0].CategoryID
FROM [dbo].[Movies] as [t0]
ORDER BY [t0].CategoryID, [t0].[Name]

Whereas, repeating an OrderBy in Linq, appears to reverse the resulting SQL output:

var movies = from row in _db.Movies 
             orderby row.CategoryID
             orderby row.Name
             select row;

AND

var movies = _db.Movies.OrderBy(m => m.CategoryID).OrderBy(m => m.Name);

produce the following SQL (Name and CategoryId are switched):

SELECT [t0].ID, [t0].[Name], [t0].CategoryID
FROM [dbo].[Movies] as [t0]
ORDER BY [t0].[Name], [t0].CategoryID

Select All distinct values in a column using LINQ

I have to find distinct rows with the following details class : Scountry
columns: countryID, countryName,isactive
There is no primary key in this. I have succeeded with the followin queries

public DbSet<SCountry> country { get; set; }
    public List<SCountry> DoDistinct()
    {
        var query = (from m in country group m by new { m.CountryID, m.CountryName, m.isactive } into mygroup select mygroup.FirstOrDefault()).Distinct();
        var Countries = query.ToList().Select(m => new SCountry { CountryID = m.CountryID, CountryName = m.CountryName, isactive = m.isactive }).ToList();
        return Countries;
    }

How to get the index of an element in an IEnumerable?

I think the best option is to implement like this:

public static int IndexOf<T>(this IEnumerable<T> enumerable, T element, IEqualityComparer<T> comparer = null)
{
    int i = 0;
    comparer = comparer ?? EqualityComparer<T>.Default;
    foreach (var currentElement in enumerable)
    {
        if (comparer.Equals(currentElement, element))
        {
            return i;
        }

        i++;
    }

    return -1;
}

It will also not create the anonymous object

Flatten List in LINQ

If you have a List<List<int>> k you can do

List<int> flatList= k.SelectMany( v => v).ToList();

LINQ-to-SQL vs stored procedures?

All these answers leaning towards LINQ are mainly talking about EASE of DEVELOPMENT which is more or less connected to poor quality of coding or laziness in coding. I am like that only.

Some advantages or Linq, I read here as , easy to test, easy to debug etc, but these are no where connected to Final output or end user. This is always going cause the trouble the end user on performance. Whats the point loading many things in memory and then applying filters on in using LINQ?

Again TypeSafety, is caution that "we are careful to avoid wrong typecasting" which again poor quality we are trying to improve by using linq. Even in that case, if anything in database changes, e.g. size of String column, then linq needs to be re-compiled and would not be typesafe without that .. I tried.

Although, we found is good, sweet, interesting etc while working with LINQ, it has shear disadvantage of making developer lazy :) and it is proved 1000 times that it is bad (may be worst) on performance compared to Stored Procs.

Stop being lazy. I am trying hard. :)

Sequence contains no elements?

From "Fixing LINQ Error: Sequence contains no elements":

When you get the LINQ error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault().

This can also be caused by the following commands:

  • FirstAsync()
  • SingleAsync()
  • Last()
  • LastAsync()
  • Max()
  • Min()
  • Average()
  • Aggregate()

How to store a list in a column of a database table

No, there is no "better" way to store a sequence of items in a single column. Relational databases are designed specifically to store one value per row/column combination. In order to store more than one value, you must serialize your list into a single value for storage, then deserialize it upon retrieval. There is no other way to do what you're talking about (because what you're talking about is a bad idea that should, in general, never be done).

I understand that you think it's silly to create another table to store that list, but this is exactly what relational databases do. You're fighting an uphill battle and violating one of the most basic principles of relational database design for no good reason. Since you state that you're just learning SQL, I would strongly advise you to avoid this idea and stick with the practices recommended to you by more seasoned SQL developers.

The principle you're violating is called first normal form, which is the first step in database normalization.

At the risk of oversimplifying things, database normalization is the process of defining your database based upon what the data is, so that you can write sensible, consistent queries against it and be able to maintain it easily. Normalization is designed to limit logical inconsistencies and corruption in your data, and there are a lot of levels to it. The Wikipedia article on database normalization is actually pretty good.

Basically, the first rule (or form) of normalization states that your table must represent a relation. This means that:

  • You must be able to differentiate one row from any other row (in other words, you table must have something that can serve as a primary key. This also means that no row should be duplicated.
  • Any ordering of the data must be defined by the data, not by the physical ordering of the rows (SQL is based upon the idea of a set, meaning that the only ordering you should rely on is that which you explicitly define in your query)
  • Every row/column intersection must contain one and only one value

The last point is obviously the salient point here. SQL is designed to store your sets for you, not to provide you with a "bucket" for you to store a set yourself. Yes, it's possible to do. No, the world won't end. You have, however, already crippled yourself in understanding SQL and the best practices that go along with it by immediately jumping into using an ORM. LINQ to SQL is fantastic, just like graphing calculators are. In the same vein, however, they should not be used as a substitute for knowing how the processes they employ actually work.

Your list may be entirely "atomic" now, and that may not change for this project. But you will, however, get into the habit of doing similar things in other projects, and you'll eventually (likely quickly) run into a scenario where you're now fitting your quick-n-easy list-in-a-column approach where it is wholly inappropriate. There is not much additional work in creating the correct table for what you're trying to store, and you won't be derided by other SQL developers when they see your database design. Besides, LINQ to SQL is going to see your relation and give you the proper object-oriented interface to your list automatically. Why would you give up the convenience offered to you by the ORM so that you can perform nonstandard and ill-advised database hackery?

How to resolve Value cannot be null. Parameter name: source in linq?

System.ArgumentNullException: Value cannot be null. Parameter name: value

This error message is not very helpful!

You can get this error in many different ways. The error may not always be with the parameter name: value. It could be whatever parameter name is being passed into a function.

As a generic way to solve this, look at the stack trace or call stack:

Test method GetApiModel threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: value
    at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)

You can see that the parameter name value is the first parameter for DeserializeObject. This lead me to check my AutoMapper mapping where we are deserializing a JSON string. That string is null in my database.

You can change the code to check for null.

LINQ Group By into a Dictionary Object

For @atari2600, this is what the answer would look like using ToLookup in lambda syntax:

var x = listOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToLookup(customObject => customObject);

Basically, it takes the IGrouping and materializes it for you into a dictionary of lists, with the values of PropertyName as the key.

Using LINQ to group a list of objects

var result = from cx in CustomerList
         group cx by cx.GroupID into cxGroup
     orderby cxGroup.Key
     select cxGroup; 

foreach (var cxGroup in result) { 
Console.WriteLine(String.Format("GroupID = {0}", cxGroup.Key)); 
  foreach (var cx in cxGroup) { 
    Console.WriteLine(String.Format("\tUserID = {0}, UserName = {1}, GroupID = {2}", 
      new object[] { cx.ID, cx.Name, cx.GroupID })); 
  }
}

Linq select object from list depending on objects attribute

Your expression is never going to evaluate.

You are comparing a with a property of a.

a is of type Answer. a.Correct, I'm guessing is a boolean.

Long form:-

Answer = answer.SingleOrDefault(a => a.Correct == true);

Short form:-

Answer = answer.SingleOrDefault(a => a.Correct);

OrderBy descending in Lambda expression?

Try this:

List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(4);
list.Add(3);
list.Add(2);

foreach (var item in list.OrderByDescending(x => x))
{
    Console.WriteLine(item);                
}

LEFT JOIN in LINQ to entities?

May be I come later to answer but right now I'm facing with this... if helps there are one more solution (the way i solved it).

    var query2 = (
    from users in Repo.T_Benutzer
    join mappings in Repo.T_Benutzer_Benutzergruppen on mappings.BEBG_BE equals users.BE_ID into tmpMapp
    join groups in Repo.T_Benutzergruppen on groups.ID equals mappings.BEBG_BG into tmpGroups
    from mappings in tmpMapp.DefaultIfEmpty()
    from groups in tmpGroups.DefaultIfEmpty()
    select new
    {
         UserId = users.BE_ID
        ,UserName = users.BE_User
        ,UserGroupId = mappings.BEBG_BG
        ,GroupName = groups.Name
    }

);

By the way, I tried using the Stefan Steiger code which also helps but it was slower as hell.

Equivalent of SQL ISNULL in LINQ?

I often have this problem with sequences (as opposed to discrete values). If I have a sequence of ints, and I want to SUM them, when the list is empty I'll receive the error "InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.".

I find I can solve this by casting the sequence to a nullable type. SUM and the other aggregate operators don't throw this error if a sequence of nullable types is empty.

So for example something like this

MySum = MyTable.Where(x => x.SomeCondtion).Sum(x => x.AnIntegerValue);

becomes

MySum = MyTable.Where(x => x.SomeCondtion).Sum(x => (int?) x.AnIntegerValue);

The second one will return 0 when no rows match the where clause. (the first one throws an exception when no rows match).

Directory.GetFiles of certain extension

I would have done using just single line like

List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
      .Where(file => new string[] { ".jpg", ".gif", ".png" }
      .Contains(Path.GetExtension(file)))
      .ToList();

Sorting a list using Lambda/Linq to objects

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Linq.Expressions;

public static class EnumerableHelper
{

    static MethodInfo orderBy = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderBy" && x.GetParameters().Length == 2).First();

    public static IEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName)
    {
        var pi = typeof(TSource).GetProperty(propertyName, BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
        var selectorParam = Expression.Parameter(typeof(TSource), "keySelector");
        var sourceParam = Expression.Parameter(typeof(IEnumerable<TSource>), "source");
        return 
            Expression.Lambda<Func<IEnumerable<TSource>, IOrderedEnumerable<TSource>>>
            (
                Expression.Call
                (
                    orderBy.MakeGenericMethod(typeof(TSource), pi.PropertyType), 
                    sourceParam, 
                    Expression.Lambda
                    (
                        typeof(Func<,>).MakeGenericType(typeof(TSource), pi.PropertyType), 
                        Expression.Property(selectorParam, pi), 
                        selectorParam
                    )
                ), 
                sourceParam
            )
            .Compile()(source);
    }

    public static IEnumerable<TSource> OrderBy<TSource>(this IEnumerable<TSource> source, string propertyName, bool ascending)
    {
        return ascending ? source.OrderBy(propertyName) : source.OrderBy(propertyName).Reverse();
    }

}

Another one, this time for any IQueryable:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

public static class IQueryableHelper
{

    static MethodInfo orderBy = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderBy" && x.GetParameters().Length == 2).First();
    static MethodInfo orderByDescending = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(x => x.Name == "OrderByDescending" && x.GetParameters().Length == 2).First();

    public static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, params string[] sortDescriptors)
    {
        return sortDescriptors.Length > 0 ? source.OrderBy(sortDescriptors, 0) : source;
    }

    static IQueryable<TSource> OrderBy<TSource>(this IQueryable<TSource> source, string[] sortDescriptors, int index)
    {
        if (index < sortDescriptors.Length - 1) source = source.OrderBy(sortDescriptors, index + 1);
        string[] splitted = sortDescriptors[index].Split(' ');
        var pi = typeof(TSource).GetProperty(splitted[0], BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.IgnoreCase);
        var selectorParam = Expression.Parameter(typeof(TSource), "keySelector");
        return source.Provider.CreateQuery<TSource>(Expression.Call((splitted.Length > 1 && string.Compare(splitted[1], "desc", StringComparison.Ordinal) == 0 ? orderByDescending : orderBy).MakeGenericMethod(typeof(TSource), pi.PropertyType), source.Expression, Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(TSource), pi.PropertyType), Expression.Property(selectorParam, pi), selectorParam)));
    }

}

You can pass multiple sort criteria, like this:

var q = dc.Felhasznalos.OrderBy(new string[] { "Email", "FelhasznaloID desc" });

How to check list A contains any value from list B?

I've profiled Justins two solutions. a.Any(a => b.Contains(a)) is fastest.

using System;
using System.Collections.Generic;
using System.Linq;

namespace AnswersOnSO
{
    public class Class1
    {
        public static void Main(string []args)
        {
//            How to check if list A contains any value from list B?
//            e.g. something like A.contains(a=>a.id = B.id)?
            var a = new List<int> {1,2,3,4};
            var b = new List<int> {2,5};
            var times = 10000000;

            DateTime dtAny = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Any(b.Contains);
            }
            var timeAny = (DateTime.Now - dtAny).TotalSeconds;

            DateTime dtIntersect = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Intersect(b).Any();
            }
            var timeIntersect = (DateTime.Now - dtIntersect).TotalSeconds;

            // timeAny: 1.1470656 secs
            // timeIn.: 3.1431798 secs
        }
    }
}

LINQ: combining join and group by

I met the same problem as you.

I push two tables result into t1 object and group t1.

 from p in Products                         
  join bp in BaseProducts on p.BaseProductId equals bp.Id
  select new {
   p,
   bp
  } into t1
 group t1 by t1.p.SomeId into g
 select new ProductPriceMinMax { 
  SomeId = g.FirstOrDefault().p.SomeId, 
  CountryCode = g.FirstOrDefault().p.CountryCode, 
  MinPrice = g.Min(m => m.bp.Price), 
  MaxPrice = g.Max(m => m.bp.Price),
  BaseProductName = g.FirstOrDefault().bp.Name
};

LEFT OUTER JOIN in LINQ

Overview: In this code snippet, I demonstrate how to group by ID where Table1 and Table2 have a one to many relationship. I group on Id, Field1, and Field2. The subquery is helpful, if a third Table lookup is required and it would have required a left join relationship. I show a left join grouping and a subquery linq. The results are equivalent.

class MyView
{
public integer Id {get,set};
    public String Field1  {get;set;}
public String Field2 {get;set;}
    public String SubQueryName {get;set;}                           
}

IList<MyView> list = await (from ci in _dbContext.Table1
                                               join cii in _dbContext.Table2
                                                   on ci.Id equals cii.Id

                                               where ci.Field1 == criterion
                                               group new
                                               {
                                                   ci.Id
                                               } by new { ci.Id, cii.Field1, ci.Field2}

                                           into pg
                                               select new MyView
                                               {
                                                   Id = pg.Key.Id,
                                                   Field1 = pg.Key.Field1,
                                                   Field2 = pg.Key.Field2,
                                                   SubQueryName=
                                                   (from chv in _dbContext.Table3 where chv.Id==pg.Key.Id select chv.Field1).FirstOrDefault()
                                               }).ToListAsync<MyView>();


 Compared to using a Left Join and Group new

IList<MyView> list = await (from ci in _dbContext.Table1
                                               join cii in _dbContext.Table2
                                                   on ci.Id equals cii.Id

                       join chv in _dbContext.Table3
                                                  on cii.Id equals chv.Id into lf_chv
                                                from chv in lf_chv.DefaultIfEmpty()

                                               where ci.Field1 == criterion
                                               group new
                                               {
                                                   ci.Id
                                               } by new { ci.Id, cii.Field1, ci.Field2, chv.FieldValue}

                                           into pg
                                               select new MyView
                                               {
                                                   Id = pg.Key.Id,
                                                   Field1 = pg.Key.Field1,
                                                   Field2 = pg.Key.Field2,
                                                   SubQueryName=pg.Key.FieldValue
                                               }).ToListAsync<MyView>();

Distinct in Linq based on only one field of the table

Try this:

table1.GroupBy(x => x.Text).Select(x => x.FirstOrDefault());

This will group the table by Text and use the first row from each groups resulting in rows where Text is distinct.

Filtering lists using LINQ

            var result = Data.Where(x =>
            {
            bool condition = true;
            double accord = (double)x[Table.Columns.IndexOf(FiltercomboBox.Text)];
            return condition && accord >= double.Parse(FilterLowertextBox.Text) && accord <= double.Parse(FilterUppertextBox.Text); 
        });

Remove item from list based on condition

You can only remove something you have a reference to. So you will have to search the entire list:

stuff r;
foreach(stuff s in prods) {
  if(s.ID == 1) {
      r = s;
      break;
  }
}
prods.Remove(r);

or

for(int i = 0; i < prods.Length; i++) {
    if(prods[i].ID == 1) {
        prods.RemoveAt(i);
        break;
    }
}

Linq to Entities join vs groupjoin

According to eduLINQ:

The best way to get to grips with what GroupJoin does is to think of Join. There, the overall idea was that we looked through the "outer" input sequence, found all the matching items from the "inner" sequence (based on a key projection on each sequence) and then yielded pairs of matching elements. GroupJoin is similar, except that instead of yielding pairs of elements, it yields a single result for each "outer" item based on that item and the sequence of matching "inner" items.

The only difference is in return statement:

Join:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    foreach (var innerElement in lookup[key]) 
    { 
        yield return resultSelector(outerElement, innerElement); 
    } 
} 

GroupJoin:

var lookup = inner.ToLookup(innerKeySelector, comparer); 
foreach (var outerElement in outer) 
{ 
    var key = outerKeySelector(outerElement); 
    yield return resultSelector(outerElement, lookup[key]); 
} 

Read more here:

Return anonymous type results?

You could do something like this:


public System.Collections.IEnumerable GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                        {
                            Name = d.Name,
                            BreedName = b.BreedName
                        };
    return result.ToList();
}

Sort list in C# with LINQ

Well, the simplest way using LINQ would be something like this:

list = list.OrderBy(x => x.AVC ? 0 : 1)
           .ToList();

or

list = list.OrderByDescending(x => x.AVC)
           .ToList();

I believe that the natural ordering of bool values is false < true, but the first form makes it clearer IMO, because everyone knows that 0 < 1.

Note that this won't sort the original list itself - it will create a new list, and assign the reference back to the list variable. If you want to sort in place, you should use the List<T>.Sort method.

Linq order by, group by and order by each group?

I think you want an additional projection that maps each group to a sorted-version of the group:

.Select(group => group.OrderByDescending(student => student.Grade))

It also appears like you might want another flattening operation after that which will give you a sequence of students instead of a sequence of groups:

.SelectMany(group => group)

You can always collapse both into a single SelectMany call that does the projection and flattening together.


EDIT: As Jon Skeet points out, there are certain inefficiencies in the overall query; the information gained from sorting each group is not being used in the ordering of the groups themselves. By moving the sorting of each group to come before the ordering of the groups themselves, the Max query can be dodged into a simpler First query.

Difference Between Select and SelectMany

Consider this example :

        var array = new string[2]
        {
            "I like what I like",
            "I like what you like"
        };
        //query1 returns two elements sth like this:
        //fisrt element would be array[5]  :[0] = "I" "like" "what" "I" "like"
        //second element would be array[5] :[1] = "I" "like" "what" "you" "like"
        IEnumerable<string[]> query1 = array.Select(s => s.Split(' ')).Distinct();

        //query2 return back flat result sth like this :
        // "I" "like" "what" "you"
        IEnumerable<string> query2 = array.SelectMany(s => s.Split(' ')).Distinct();

So as you see duplicate values like "I" or "like" have been removed from query2 because "SelectMany" flattens and projects across multiple sequences. But query1 returns sequence of string arrays. and since there are two different arrays in query1 (first and second element), nothing would be removed.

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

I guess it would work to use reflection to get whatever property you want to sort on:

IEnumerable<T> myEnumerables
var query=from enumerable in myenumerables
          where some criteria
          orderby GetPropertyValue(enumerable,"SomeProperty")
          select enumerable

private static object GetPropertyValue(object obj, string property)
{
    System.Reflection.PropertyInfo propertyInfo=obj.GetType().GetProperty(property);
    return propertyInfo.GetValue(obj, null);
}

Note that using reflection is considerably slower than accessing the property directly, so the performance would have to be investigated.

LINQ: Select where object does not contain items from list

dump this into a more specific collection of just the ids you don't want

var notTheseBarIds = filterBars.Select(fb => fb.BarId);

then try this:

fooSelect = (from f in fooBunch
             where !notTheseBarIds.Contains(f.BarId)
             select f).ToList();

or this:

fooSelect = fooBunch.Where(f => !notTheseBarIds.Contains(f.BarId)).ToList();

Max or Default?

Since DefaultIfEmpty isn't implemented in LINQ to SQL, I did a search on the error it returned and found a fascinating article that deals with null sets in aggregate functions. To summarize what I found, you can get around this limitation by casting to a nullable within your select. My VB is a little rusty, but I think it'd go something like this:

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select CType(y.MyCounter, Integer?)).Max

Or in C#:

var x = (from y in context.MyTable
         where y.MyField == value
         select (int?)y.MyCounter).Max();

Create a list from two object lists with linq

public void Linq95()
{
    List<Customer> customers = GetCustomerList();
    List<Product> products = GetProductList();

    var customerNames =
        from c in customers
        select c.CompanyName;
    var productNames =
        from p in products
        select p.ProductName;

    var allNames = customerNames.Concat(productNames);

    Console.WriteLine("Customer and product names:");
    foreach (var n in allNames)
    {
        Console.WriteLine(n);
    }
}

LINQ Orderby Descending Query

You need to choose a Property to sort by and pass it as a lambda expression to OrderByDescending

like:

.OrderByDescending(x => x.Delivery.SubmissionDate);

Really, though the first version of your LINQ statement should work. Is t.Delivery.SubmissionDate actually populated with valid dates?

How to Convert the value in DataTable into a string array in c#

    private string[] GetPrimaryKeysofTable(string TableName)
    {
        string stsqlCommand = "SELECT column_name FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE " +
                              "WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1" +
                              "AND table_name = '" +TableName+ "'";
        SqlCommand command = new SqlCommand(stsqlCommand, Connection);
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = command;

        DataTable table = new DataTable();
        table.Locale = System.Globalization.CultureInfo.InvariantCulture;

        adapter.Fill(table);

        string[] result = new string[table.Rows.Count];
        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            result[i++] = dr[0].ToString();
        }

        return result;
    }

Concat all strings inside a List<string> using LINQ

using System.Linq;

public class Person
{
  string FirstName { get; set; }
  string LastName { get; set; }
}

List<Person> persons = new List<Person>();

string listOfPersons = string.Join(",", persons.Select(p => p.FirstName));

How to "select distinct" across multiple data frame columns in pandas?

You can use the drop_duplicates method to get the unique rows in a DataFrame:

In [29]: df = pd.DataFrame({'a':[1,2,1,2], 'b':[3,4,3,5]})

In [30]: df
Out[30]:
   a  b
0  1  3
1  2  4
2  1  3
3  2  5

In [32]: df.drop_duplicates()
Out[32]:
   a  b
0  1  3
1  2  4
3  2  5

You can also provide the subset keyword argument if you only want to use certain columns to determine uniqueness. See the docstring.

Android SDK manager won't open

I encountered a similar problem where SDK manager would flash a command window and die.

This is what worked for me: My processor and OS both are 64-bit. I had installed 64-bit JDK version. The problem wouldn't go away with reinstalling JDK or modifying path. My theory was that SDK Manager may be needed 32-bit version of JDK. Don't know why that should matter but I ended up installing 32-bit version of JDK and magic. And SDK Manager successfully launched.

Sending multipart/formdata with jQuery.ajax

If the file input name indicates an array and flags multiple, and you parse the entire form with FormData, it is not necessary to iteratively append() the input files. FormData will automatically handle multiple files.

_x000D_
_x000D_
$('#submit_1').on('click', function() {_x000D_
  let data = new FormData($("#my_form")[0]);_x000D_
_x000D_
  $.ajax({_x000D_
    url: '/path/to/php_file',_x000D_
    type: 'POST',_x000D_
    data: data,_x000D_
    processData: false,_x000D_
    contentType: false,_x000D_
    success: function(r) {_x000D_
      console.log('success', r);_x000D_
    },_x000D_
    error: function(r) {_x000D_
      console.log('error', r);_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="my_form">_x000D_
  <input type="file" name="multi_img_file[]" id="multi_img_file" accept=".gif,.jpg,.jpeg,.png,.svg" multiple="multiple" />_x000D_
  <button type="button" name="submit_1" id="submit_1">Not type='submit'</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Note that a regular button type="button" is used, not type="submit". This shows there is no dependency on using submit to get this functionality.

The resulting $_FILES entry is like this in Chrome dev tools:

multi_img_file:
  error: (2) [0, 0]
  name: (2) ["pic1.jpg", "pic2.jpg"]
  size: (2) [1978036, 2446180]
  tmp_name: (2) ["/tmp/phphnrdPz", "/tmp/phpBrGSZN"]
  type: (2) ["image/jpeg", "image/jpeg"]

Note: There are cases where some images will upload just fine when uploaded as a single file, but they will fail when uploaded in a set of multiple files. The symptom is that PHP reports empty $_POST and $_FILES without AJAX throwing any errors. Issue occurs with Chrome 75.0.3770.100 and PHP 7.0. Only seems to happen with 1 out of several dozen images in my test set.

Jenkins - passing variables between jobs?

(for fellow googlers)

If you are building a serious pipeline with the Build Flow Plugin, you can pass parameters between jobs with the DSL like this :

Supposing an available string parameter "CVS_TAG", in order to pass it to other jobs :

build("pipeline_begin", CVS_TAG: params['CVS_TAG'])
parallel (
   // will be scheduled in parallel.
   { build("pipeline_static_analysis", CVS_TAG: params['CVS_TAG']) },
   { build("pipeline_nonreg", CVS_TAG: params['CVS_TAG']) }
)
// will be triggered after previous jobs complete
build("pipeline_end", CVS_TAG: params['CVS_TAG'])

Hint for displaying available variables / params :

// output values
out.println '------------------------------------'
out.println 'Triggered Parameters Map:'
out.println params
out.println '------------------------------------'
out.println 'Build Object Properties:'
build.properties.each { out.println "$it.key -> $it.value" }
out.println '------------------------------------'

Check for a substring in a string in Oracle without LIKE

I'm guessing the reason you're asking is performance? There's the instr function. But that's likely to work pretty much the same behind the scenes.

Maybe you could look into full text search.

As last resorts you'd be looking at caching or precomputed columns/an indexed view.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

select convert(varchar(8), getdate(), 3)

simply use this for dd/mm/yy and this

select convert(varchar(8), getdate(), 1) 

for mm/dd/yy

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

I found to many long and confusing answer and after reading few of the answers My conclusion is

if (!ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE))
                Toast.makeText(this, "permanently denied", Toast.LENGTH_SHORT).show();

Export specific rows from a PostgreSQL table as INSERT SQL script

I tried to write a procedure doing that, based on @PhilHibbs codes, on a different way. Please have a look and test.

 CREATE OR REPLACE FUNCTION dump(IN p_schema text, IN p_table text, IN p_where text)
   RETURNS setof text AS
 $BODY$
 DECLARE
     dumpquery_0 text;
     dumpquery_1 text;
     selquery text;
     selvalue text;
     valrec record;
     colrec record;
 BEGIN

     -- ------ --
     -- GLOBAL --
     --   build base INSERT
     --   build SELECT array[ ... ]
     dumpquery_0 := 'INSERT INTO ' ||  quote_ident(p_schema) || '.' || quote_ident(p_table) || '(';
     selquery    := 'SELECT array[';

     <<label0>>
     FOR colrec IN SELECT table_schema, table_name, column_name, data_type
                   FROM information_schema.columns
                   WHERE table_name = p_table and table_schema = p_schema
                   ORDER BY ordinal_position
     LOOP
         dumpquery_0 := dumpquery_0 || quote_ident(colrec.column_name) || ',';
         selquery    := selquery    || 'CAST(' || quote_ident(colrec.column_name) || ' AS TEXT),';
     END LOOP label0;

     dumpquery_0 := substring(dumpquery_0 ,1,length(dumpquery_0)-1) || ')';
     dumpquery_0 := dumpquery_0 || ' VALUES (';
     selquery    := substring(selquery    ,1,length(selquery)-1)    || '] AS MYARRAY';
     selquery    := selquery    || ' FROM ' ||quote_ident(p_schema)||'.'||quote_ident(p_table);
     selquery    := selquery    || ' WHERE '||p_where;
     -- GLOBAL --
     -- ------ --

     -- ----------- --
     -- SELECT LOOP --
     --   execute SELECT built and loop on each row
     <<label1>>
     FOR valrec IN  EXECUTE  selquery
     LOOP
         dumpquery_1 := '';
         IF not found THEN
             EXIT ;
         END IF;

         -- ----------- --
         -- LOOP ARRAY (EACH FIELDS) --
         <<label2>>
         FOREACH selvalue in ARRAY valrec.MYARRAY
         LOOP
             IF selvalue IS NULL
             THEN selvalue := 'NULL';
             ELSE selvalue := quote_literal(selvalue);
             END IF;
             dumpquery_1 := dumpquery_1 || selvalue || ',';
         END LOOP label2;
         dumpquery_1 := substring(dumpquery_1 ,1,length(dumpquery_1)-1) || ');';
         -- LOOP ARRAY (EACH FIELD) --
         -- ----------- --

         -- debug: RETURN NEXT dumpquery_0 || dumpquery_1 || ' --' || selquery;
         -- debug: RETURN NEXT selquery;
         RETURN NEXT dumpquery_0 || dumpquery_1;

     END LOOP label1 ;
     -- SELECT LOOP --
     -- ----------- --

 RETURN ;
 END
 $BODY$
   LANGUAGE plpgsql VOLATILE;

And then :

-- for a range
SELECT dump('public', 'my_table','my_id between 123456 and 123459'); 
-- for the entire table
SELECT dump('public', 'my_table','true');

tested on my postgres 9.1, with a table with mixed field datatype (text, double, int,timestamp without time zone, etc).

That's why the CAST in TEXT type is needed. My test run correctly for about 9M lines, looks like it fail just before 18 minutes of running.

ps : I found an equivalent for mysql on the WEB.

ES6 export all values from object

I suggest the following, let's expect a module.js:

const values = { a: 1, b: 2, c: 3 };

export { values }; // you could use default, but I'm specific here

and then you can do in an index.js:

import { values } from "module";

// directly access the object
console.log(values.a); // 1

// object destructuring
const { a, b, c } = values; 
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

// selective object destructering with renaming
const { a:k, c:m } = values;
console.log(k); // 1
console.log(m); // 3

// selective object destructering with renaming and default value
const { a:x, b:y, d:z = 0 } = values;
console.log(x); // 1
console.log(y); // 2
console.log(z); // 0

More examples of destructering objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

Accessing the last entry in a Map

Find missing all elements from array
        int[] array = {3,5,7,8,2,1,32,5,7,9,30,5};
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for(int i=0;i<array.length;i++) {
            map.put(array[i], 1);
        }
        int maxSize = map.lastKey();
        for(int j=0;j<maxSize;j++) {
            if(null == map.get(j))
                System.out.println("Missing `enter code here`No:"+j);
        }

Calculate days between two Dates in Java 8

Get number of days before Christmas from current day , try this

System.out.println(ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25)));

How to set environment variable or system property in spring tests?

You can set the System properties as VM arguments.

If your project is a maven project then you can execute following command while running the test class:

mvn test -Dapp.url="https://stackoverflow.com"

Test class:

public class AppTest  {
@Test
public void testUrl() {
    System.out.println(System.getProperty("app.url"));
    }
}

If you want to run individual test class or method in eclipse then :

1) Go to Run -> Run Configuration

2) On left side select your Test class under the Junit section.

3) do the following :

enter image description here

How to display and hide a div with CSS?

To hide an element, use:

display: none;
visibility: hidden;

To show an element, use:

display: block;
visibility: visible;

The difference is:

Visibility handles the visibility of the tag, the display handles space it occupies on the page.

If you set the visibility and do not change the display, even if the tags are not seen, it still occupies space.

Certificate is trusted by PC but not by Android

I had the same issue and my issue was the device not having the right date and time. Once I fixed that the certificate is being trusted.

Cookie blocked/not saved in IFRAME in Internet Explorer

I had this issue as well, thought I'd post the code that I used in my MVC2 project. Be careful when in the page life cycle you add in the header or you'll get an HttpException "Server cannot append header after HTTP headers have been sent." I used a custom ActionFilterAttribute on the OnActionExecuting method (called before the action is executed).

/// <summary>
/// Privacy Preferences Project (P3P) serve a compact policy (a "p3p" HTTP header) for all requests
/// P3P provides a standard way for Web sites to communicate about their practices around the collection, 
/// use, and distribution of personal information. It's a machine-readable privacy policy that can be 
/// automatically fetched and viewed by users, and it can be tailored to fit your company's specific policies.
/// </summary>
/// <remarks>
/// More info http://www.oreillynet.com/lpt/a/1554
/// </remarks>
public class P3PAttribute : ActionFilterAttribute
{
    /// <summary>
    /// On Action Executing add a compact policy "p3p" HTTP header
    /// </summary>
    /// <param name="filterContext"></param>
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContext.Current.Response.AddHeader("p3p","CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");

        base.OnActionExecuting(filterContext);
    }
}

Example use:

[P3P]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

Dropdownlist validation in Asp.net Using Required field validator

<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic" 
    ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
    Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>

How do I match any character across multiple lines in a regular expression?

Often we have to modify a substring with a few keywords spread across lines preceding the substring. Consider an xml element:

<TASK>
  <UID>21</UID>
  <Name>Architectural design</Name>
  <PercentComplete>81</PercentComplete>
</TASK>

Suppose we want to modify the 81, to some other value, say 40. First identify .UID.21..UID., then skip all characters including \n till .PercentCompleted.. The regular expression pattern and the replace specification are:

String hw = new String("<TASK>\n  <UID>21</UID>\n  <Name>Architectural design</Name>\n  <PercentComplete>81</PercentComplete>\n</TASK>");
String pattern = new String ("(<UID>21</UID>)((.|\n)*?)(<PercentComplete>)(\\d+)(</PercentComplete>)");
String replaceSpec = new String ("$1$2$440$6");
//note that the group (<PercentComplete>) is $4 and the group ((.|\n)*?) is $2.

String  iw = hw.replaceFirst(pattern, replaceSpec);
System.out.println(iw);

<TASK>
  <UID>21</UID>
  <Name>Architectural design</Name>
  <PercentComplete>40</PercentComplete>
</TASK>

The subgroup (.|\n) is probably the missing group $3. If we make it non-capturing by (?:.|\n) then the $3 is (<PercentComplete>). So the pattern and replaceSpec can also be:

pattern = new String("(<UID>21</UID>)((?:.|\n)*?)(<PercentComplete>)(\\d+)(</PercentComplete>)");
replaceSpec = new String("$1$2$340$5")

and the replacement works correctly as before.

How to modify memory contents using GDB?

As Nikolai has said you can use the gdb 'set' command to change the value of a variable.

You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20

This should work for any valid pointer, and can be cast to any appropriate data type.

Can I get JSON to load into an OrderedDict?

You could always write out the list of keys in addition to dumping the dict, and then reconstruct the OrderedDict by iterating through the list?

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

For me worked the answer I found on CodeRanch, by user Maneesh Godbole:

  1. Close eclipse.
  2. Navigate to your "workspace" folder
  3. Ensure the setting on your OS to view hidden files is turned on
  4. Identify and delete the .metadata directory
  5. Restart eclipse
  6. Import project

Docker: How to use bash with an Alpine based docker image?

RUN /bin/sh -c "apk add --no-cache bash"

worked for me.

How to remove item from a python list in a loop?

hymloth and sven's answers work, but they do not modify the list (the create a new one). If you need the object modification you need to assign to a slice:

x[:] = [value for value in x if len(value)==2]

However, for large lists in which you need to remove few elements, this is memory consuming, but it runs in O(n).

glglgl's answer suffers from O(n²) complexity, because list.remove is O(n).

Depending on the structure of your data, you may prefer noting the indexes of the elements to remove and using the del keywork to remove by index:

to_remove = [i for i, val in enumerate(x) if len(val)==2]
for index in reversed(to_remove): # start at the end to avoid recomputing offsets
    del x[index]

Now del x[i] is also O(n) because you need to copy all elements after index i (a list is a vector), so you'll need to test this against your data. Still this should be faster than using remove because you don't pay for the cost of the search step of remove, and the copy step cost is the same in both cases.

[edit] Very nice in-place, O(n) version with limited memory requirements, courtesy of @Sven Marnach. It uses itertools.compress which was introduced in python 2.7:

from itertools import compress

selectors = (len(s) == 2 for s in x)
for i, s in enumerate(compress(x, selectors)): # enumerate elements of length 2
    x[i] = s # move found element to beginning of the list, without resizing
del x[i+1:]  # trim the end of the list

Java integer list

If you want to rewrite a line on console, print a control character \r (carriage return).

List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
Iterator<Integer> myListIterator = myCoords.iterator(); 
while (myListIterator.hasNext()) {
    Integer coord = myListIterator.next();     
    System.out.print("\r");
    System.out.print(coord);
    Thread.sleep(2000);
}

Drop rows with all zeros in pandas data frame

To drop all columns with values 0 in any row:

new_df = df[df.loc[:]!=0].dropna()

How to create a release signed apk file using Gradle?

You can also use -P command line option of gradle to help the signing. In your build.gradle, add singingConfigs like this:

signingConfigs {
   release {
       storeFile file("path/to/your/keystore")
       storePassword RELEASE_STORE_PASSWORD
       keyAlias "your.key.alias"
       keyPassword RELEASE_KEY_PASSWORD
   }
}

Then call gradle build like this:

gradle -PRELEASE_KEYSTORE_PASSWORD=******* -PRELEASE_KEY_PASSWORD=****** build

You can use -P to set storeFile and keyAlias if you prefer.

This is basically Destil's solution but with the command line options.

For more details on gradle properties, check the gradle user guide.

Add Keypair to existing EC2 instance

You can actually add a key pair through the elastic beanstalk config page. it then restarts your instance for you and everything works.

What's the Android ADB shell "dumpsys" tool and what are its benefits?

i use dumpsys to catch if app is crashed and process is still active. situation i used it is to find about remote machine app is crashed or not.

dumpsys | grep myapp | grep "Application Error" 

or

adb shell dumpsys | grep myapp | grep Error

or anything that helps...etc

if app is not running you will get nothing as result. When app is stoped messsage is shown on screen by android, process is still active and if you check via "ps" command or anything else, you will see process state is not showing any error or crash meaning. But when you click button to close message, app process will cleaned from process list. so catching crash state without any code in application is hard to find. but dumpsys helps you.

How Should I Declare Foreign Key Relationships Using Code First Entity Framework (4.1) in MVC3?

If you have an Order class, adding a property that references another class in your model, for instance Customer should be enough to let EF know there's a relationship in there:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    public virtual Customer Customer { get; set; }
}

You can always set the FK relation explicitly:

public class Order
{
    public int ID { get; set; }

    // Some other properties

    // Foreign key to customer
    [ForeignKey("Customer")]
    public string CustomerID { get; set; }
    public virtual Customer Customer { get; set; }
}

The ForeignKeyAttribute constructor takes a string as a parameter: if you place it on a foreign key property it represents the name of the associated navigation property. If you place it on the navigation property it represents the name of the associated foreign key.

What this means is, if you where to place the ForeignKeyAttribute on the Customer property, the attribute would take CustomerID in the constructor:

public string CustomerID { get; set; }
[ForeignKey("CustomerID")]
public virtual Customer Customer { get; set; }

EDIT based on Latest Code You get that error because of this line:

[ForeignKey("Parent")]
public Patient Patient { get; set; }

EF will look for a property called Parent to use it as the Foreign Key enforcer. You can do 2 things:

1) Remove the ForeignKeyAttribute and replace it with the RequiredAttribute to mark the relation as required:

[Required]
public virtual Patient Patient { get; set; }

Decorating a property with the RequiredAttribute also has a nice side effect: The relation in the database is created with ON DELETE CASCADE.

I would also recommend making the property virtual to enable Lazy Loading.

2) Create a property called Parent that will serve as a Foreign Key. In that case it probably makes more sense to call it for instance ParentID (you'll need to change the name in the ForeignKeyAttribute as well):

public int ParentID { get; set; }

In my experience in this case though it works better to have it the other way around:

[ForeignKey("Patient")]
public int ParentID { get; set; }

public virtual Patient Patient { get; set; }

How can I delay a :hover effect in CSS?

For a more aesthetic appearance :) can be:

left:-9999em; 
top:-9999em; 

position for .sNv2 .nav UL can be replaced by z-index:-1 and z-index:1 for .sNv2 .nav LI:Hover UL

remove double quotes from Json return data using Jquery

I dont think there is a need to replace any quotes, this is a perfectly formed JSON string, you just need to convert JSON string into object.This article perfectly explains the situation : Link

Example :

success: function (data) {

        // assuming that everything is correct and there is no exception being thrown
        // output string {"d":"{"username":"hi","email":"[email protected]","password":"123"}"}
        // now we need to remove the double quotes (as it will create problem and 
        // if double quotes aren't removed then this JSON string is useless)
        // The output string : {"d":"{"username":"hi","email":"[email protected]","password":"123"}"}
        // The required string : {"d":{username:"hi",email:"[email protected]",password:"123"}"}
        // For security reasons the d is added (indicating the return "data")
        // so actually we need to convert data.d into series of objects
        // Inbuilt function "JSON.Parse" will return streams of objects
        // JSON String : "{"username":"hi","email":"[email protected]","password":"123"}"
        console.log(data);                     // output  : Object {d="{"username":"hi","email":"[email protected]","password":"123"}"}
        console.log(data.d);                   // output : {"username":"hi","email":"[email protected]","password":"123"} (accessing what's stored in "d")
        console.log(data.d[0]);                // output : {  (just accessing the first element of array of "strings")
        var content = JSON.parse(data.d);      // output : Object {username:"hi",email:"[email protected]",password:"123"}" (correct)
        console.log(content.username);         // output : hi 
        var _name = content.username;
        alert(_name);                         // hi

}

How to drop a table if it exists?

I hope this helps:

begin try drop table #tempTable end try
begin catch end catch

How to use confirm using sweet alert?

_x000D_
_x000D_
document.querySelector('#from1').onsubmit = function(e){_x000D_
_x000D_
 swal({_x000D_
    title: "Are you sure?",_x000D_
    text: "You will not be able to recover this imaginary file!",_x000D_
    type: "warning",_x000D_
    showCancelButton: true,_x000D_
    confirmButtonColor: '#DD6B55',_x000D_
    confirmButtonText: 'Yes, I am sure!',_x000D_
    cancelButtonText: "No, cancel it!",_x000D_
    closeOnConfirm: false,_x000D_
    closeOnCancel: false_x000D_
 },_x000D_
 function(isConfirm){_x000D_
_x000D_
   if (isConfirm.value){_x000D_
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");_x000D_
_x000D_
    } else {_x000D_
      swal("Cancelled", "Your imaginary file is safe :)", "error");_x000D_
         e.preventDefault();_x000D_
    }_x000D_
 });_x000D_
};
_x000D_
_x000D_
_x000D_

How to write one new line in Bitbucket markdown?

I was facing the same issue in bitbucket, and this worked for me:

line1
##<2 white spaces><enter>
line2

How do I check if a property exists on a dynamic anonymous type in c#?

In case someone need to handle a dynamic object come from Json, I has modified Seth Reno answer to handle dynamic object deserialized from NewtonSoft.Json.JObjcet.

public static bool PropertyExists(dynamic obj, string name)
    {
        if (obj == null) return false;
        if (obj is ExpandoObject)
            return ((IDictionary<string, object>)obj).ContainsKey(name);
        if (obj is IDictionary<string, object> dict1)
            return dict1.ContainsKey(name);
        if (obj is IDictionary<string, JToken> dict2)
            return dict2.ContainsKey(name);
        return obj.GetType().GetProperty(name) != null;
    }

How to remove all namespaces from XML with C#?

user892217's answer is almost correct. It won't compile as is, so needs a slight correction to the recursive call:

private static XElement RemoveAllNamespaces(XElement xmlDocument)
{
    XElement xElement;

    if (!xmlDocument.HasElements)
    {
        xElement = new XElement(xmlDocument.Name.LocalName) { Value = xmlDocument.Value };
    }
    else
    {
        xElement = new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(x => RemoveAllNamespaces(x)));
    }

    foreach (var attribute in xmlDocument.Attributes())
    {
        if (!attribute.IsNamespaceDeclaration)
        {
            xElement.Add(attribute);
        }
    }

    return xElement;
}

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

My solution;

Ubuntu 18.04 (WSL)

/etc/mysql/my.cnf

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

/etc/mysql/mysql.conf.d/mysqld.cnf

[mysqld]
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306

I changed the port. It's worked for me. You can write another port. Example 3355

A Generic error occurred in GDI+ in Bitmap.Save method

When either a Bitmap object or an Image object is constructed from a file, the file remains locked for the lifetime of the object. As a result, you cannot change an image and save it back to the same file where it originated. http://support.microsoft.com/?id=814675

A generic error occurred in GDI+, JPEG Image to MemoryStream

Image.Save(..) throws a GDI+ exception because the memory stream is closed

http://alperguc.blogspot.in/2008/11/c-generic-error-occurred-in-gdi.html

EDIT:
just writing from memory...

save to an 'intermediary' memory stream, that should work

e.g. try this one - replace

    Bitmap newBitmap = new Bitmap(thumbBMP);
    thumbBMP.Dispose();
    thumbBMP = null;
    newBitmap.Save("~/image/thumbs/" + "t" + objPropBannerImage.ImageId, ImageFormat.Jpeg);

with something like:

string outputFileName = "...";
using (MemoryStream memory = new MemoryStream())
{
    using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
    {
        thumbBMP.Save(memory, ImageFormat.Jpeg);
        byte[] bytes = memory.ToArray();
        fs.Write(bytes, 0, bytes.Length);
    }
}

How to split a comma separated string and process in a loop using JavaScript

My two cents, adding trim to remove the initial whitespaces left in sAc's answer.

var str = 'Hello, World, etc';
var str_array = str.split(',');

for(var i = 0; i < str_array.length; i++) {
   // Trim the excess whitespace.
   str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
   // Add additional code here, such as:
   alert(str_array[i]);
}

Edit:

After getting several upvotes on this answer, I wanted to revisit this. If you want to split on comma, and perform a trim operation, you can do it in one method call without any explicit loops due to the fact that split will also take a regular expression as an argument:

'Hello, cruel , world!'.split(/\s*,\s*/);
//-> ["Hello", "cruel", "world!"]

This solution, however, will not trim the beginning of the first item and the end of the last item which is typically not an issue.

And so to answer the question in regards to process in a loop, if your target browsers support ES5 array extras such as the map or forEach methods, then you could just simply do the following:

myStringWithCommas.split(/\s*,\s*/).forEach(function(myString) {
    console.log(myString);
});

Group dataframe and get sum AND count?

try this:

In [110]: (df.groupby('Company Name')
   .....:    .agg({'Organisation Name':'count', 'Amount': 'sum'})
   .....:    .reset_index()
   .....:    .rename(columns={'Organisation Name':'Organisation Count'})
   .....: )
Out[110]:
          Company Name   Amount  Organisation Count
0  Vifor Pharma UK Ltd  4207.93                   5

or if you don't want to reset index:

df.groupby('Company Name')['Amount'].agg(['sum','count'])

or

df.groupby('Company Name').agg({'Amount': ['sum','count']})

Demo:

In [98]: df.groupby('Company Name')['Amount'].agg(['sum','count'])
Out[98]:
                         sum  count
Company Name
Vifor Pharma UK Ltd  4207.93      5

In [99]: df.groupby('Company Name').agg({'Amount': ['sum','count']})
Out[99]:
                      Amount
                         sum count
Company Name
Vifor Pharma UK Ltd  4207.93     5

How to delete a remote tag?

Up to 100x faster method for thousands of remote tags

After reading through these answers while needing to delete over 11,000 tags, I learned these methods relying or xargs take far too long, unless you have hours to burn.

Struggling, I found two much faster ways. For both, start with git tag or git ls-remote --tags to make a list of tags you want to delete on the remote. In the examples below you can omit or replace sorting_proccessing_etc with any greping, sorting, tailing or heading you want (e.g. grep -P "my_regex" | sort | head -n -200 etc) :


This first method is by far the fastest, maybe 20 to 100 times faster than using xargs, and works with a least several thousand tags at a time.

git push origin $(< git tag | sorting_processing_etc \
| sed -e 's/^/:/' | paste -sd " ") #note exclude "<" for zsh

How does this work? The normal, line-separated list of tags is converted to a single line of space-separated tags, each prepended with : so . . .

tag1   becomes
tag2   ======>  :tag1 :tag2 :tag3
tag3

Using git push with this format tag pushes nothing into each remote ref, erasing it (the normal format for pushing this way is local_ref_path:remote_ref_path).

Method two is broken out as a separate answer elsewhere on this same page


After both of these methods, you'll probably want to delete your local tags too. This is much faster so we can go back to using xargs and git tag -d, which is sufficient.

git tag | sorting_processing_etc | xargs -L 1 git tag -d

OR similar to the remote delete:

git tag -d $(< git tag | sorting_processing_etc | paste -sd " ")

How to stop IIS asking authentication for default website on localhost

This is most likely a NT file permissions problem. IUSR_ needs to have file system permissions to read whatever file you're requesting (like /inetpub/wwwroot/index.htm).

If you still have trouble, check the IIS logs, typically at \windows\system32\logfiles\W3SVC*.

Convert Little Endian to Big Endian

One slightly different way of tackling this that can sometimes be useful is to have a union of the sixteen or thirty-two bit value and an array of chars. I've just been doing this when getting serial messages that come in with big endian order, yet am working on a little endian micro.

union MessageLengthUnion
{

    uint16_t asInt;
    uint8_t asChars[2];

};

Then when I get the messages in I put the first received uint8 in .asChars[1], the second in .asChars[0] then I access it as the .asInt part of the union in the rest of my program.

If you have a thirty-two bit value to store you can have the array four long.

Open two instances of a file in a single Visual Studio session

I came up with a hack that might produce the result intended in the original answer.

If you have the file you want in two windows in a source control, you can right-click on the file and select compare, you can compare the

If you do compare you will have a new window Called diff, showing you the contents of you file.

This is of course not ideal as the diff window will have the diff colors polluting the text. Note: you can compare the file you want to open to and empty file, and then you will have the window in a very ugly green background.

This is not perfect, it is a hack, but it was the only way I found to really have the same file in two windows.

How can I change text color via keyboard shortcut in MS word 2010

For Word 2010 and 2013, go to File > Options > Customize Ribbon > Keyboard Shortcuts > All Commands (in left list) > Color: (in right list) -- at this point, you type in the short cut (such as Alt+r) and select the color (such as red). (This actually goes back to 2003 but I don't have that installed to provide the pathway.)

Tool to Unminify / Decompress JavaScript

Got it! JSBeautifier does exactly this, and you even have options for the auto-formatting.

How to pass a single object[] to a params object[]

Another way to solve this problem (it's not so good practice but looks beauty):

static class Helper
{
    public static object AsSingleParam(this object[] arg)
    {
       return (object)arg;
    }
}

Usage:

f(new object[] { 1, 2, 3 }.AsSingleParam());

Number of visitors on a specific page

Go to Behavior > Site Content > All Pages and put your URI into the search box.enter image description here

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

How to compare datetime with only date in SQL Server

If you are on SQL Server 2008 or later you can use the date datatype:

SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2014-02-07'

It should be noted that if date column is indexed then this will still utilise the index and is SARGable. This is a special case for dates and datetimes.

enter image description here

You can see that SQL Server actually turns this into a > and < clause:

enter image description here

I've just tried this on a large table, with a secondary index on the date column as per @kobik's comments and the index is still used, this is not the case for the examples that use BETWEEN or >= and <:

SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2016-07-05'

showing index usage with secondary index

Updating user data - ASP.NET Identity

I am using .Net Core 3.1 or higher version.Please follow the solution:

  public class UpdateAssignUserRole
    {
        public string username { get; set; }
        public string rolename { get; set; }
        public bool IsEdit { get; set; }

    }

 private async Task UpdateSeedUsers(UserManager<IdentityUser> userManager, UpdateAssignUserRole updateassignUsername)
        {
            IList<Users> Users = await FindByUserName(updateassignUsername.username);

            if (await userManager.FindByNameAsync(updateassignUsername.username) != null)
            {
                var user = new IdentityUser
                {
                    UserName = updateassignUsername.username,
                    Email = Users[0].Email,
 
                };
                var result = await userManager.FindByNameAsync(updateassignUsername.username);
                if (result != null)
                {
                    IdentityResult deletionResult = await userManager.RemoveFromRolesAsync(result, await userManager.GetRolesAsync(result));
                    if (deletionResult != null)
                    {
                        await userManager.AddToRoleAsync(result, updateassignUsername.rolename);
                    }
                }
            }

        }

Simple insecure two-way data "obfuscation"?

Yes, add the System.Security assembly, import the System.Security.Cryptography namespace. Here's a simple example of a symmetric (DES) algorithm encryption:

DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.GenerateKey();
byte[] key = des.Key; // save this!

ICryptoTransform encryptor = des.CreateEncryptor();
// encrypt
byte[] enc = encryptor.TransformFinalBlock(new byte[] { 1, 2, 3, 4 }, 0, 4);

ICryptoTransform decryptor = des.CreateDecryptor();

// decrypt
byte[] originalAgain = decryptor.TransformFinalBlock(enc, 0, enc.Length);
Debug.Assert(originalAgain[0] == 1);

Difference between margin and padding?

Margin and padding are both types of padding really....One (margin) goes outside of the elements border to distance it from other elements and the other (padding) goes outside of the elements content to distance the content from the elements border.

Python: Ignore 'Incorrect padding' error when base64 decoding

It seems you just need to add padding to your bytes before decoding. There are many other answers on this question, but I want to point out that (at least in Python 3.x) base64.b64decode will truncate any extra padding, provided there is enough in the first place.

So, something like: b'abc=' works just as well as b'abc==' (as does b'abc=====').

What this means is that you can just add the maximum number of padding characters that you would ever need—which is three (b'===')—and base64 will truncate any unnecessary ones.

This lets you write:

base64.b64decode(s + b'===')

which is simpler than:

base64.b64decode(s + b'=' * (-len(s) % 4))

Avoid Adding duplicate elements to a List C#

If your check would have worked, it would have either added all the items, or none at all. However, calling the ToString method on an array returns the name of the data type, not the contents of the array, and the Contains method can only look for a single item, not a collection of items anyway.

You have to check each string in the array:

string[] lines3;
List<string> lines2 = new List<string>();

lines3 = Regex.Split(s1, @"\s*,\s*");

foreach (string s in lines3) {
  if (!lines2.Contains(s)) {
    lines2.Add(s);
  }
}

However, if you start with an empty list, you can use the Distinct method to remove the duplicates, and you only need a single line of code:

List<string> lines2 = Regex.Split(s1, @"\s*,\s*").Distinct().ToList();

Disable future dates in jQuery UI Datepicker

$(function() { $("#datepicker").datepicker({  maxDate: '0'}); });

error: expected primary-expression before ')' token (C)

You're passing a type as an argument, not an object. You need to do characterSelection(screen, test); where test is of type SelectionneNonSelectionne.

android: data binding error: cannot find symbol class

make all your packages name's in the project that you used in binding to lower case.

How to exit an Android app programmatically?

Try this on a call. I sometimes use it in onClick of a button.

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

It instead of closing your app , opens the dashboard so kind of looks like your app is closed.

read this question for more clearity android - exit application code

html text input onchange event

Well unless I misunderstand you can just use the onChange attribute:

<input type="text" onChange="return bar()">

Note: in FF 3 (at least) this is not called until some the user has confirmed they are changed either by clicking away from the element, clicking enter, or other.

Use of 'prototype' vs. 'this' in JavaScript?

When you use prototype, the function will only be loaded only once into memory (independently on the amount of objects you create) and you can override the function whenever you want.

Usage of unicode() and encode() functions in Python

Make sure you've set your locale settings right before running the script from the shell, e.g.

$ locale -a | grep "^en_.\+UTF-8"
en_GB.UTF-8
en_US.UTF-8
$ export LC_ALL=en_GB.UTF-8
$ export LANG=en_GB.UTF-8

Docs: man locale, man setlocale.

EOFError: end of file reached issue with Net::HTTP

I had a similar problem with a request to a non-SSL service.

This blog suggested vaguely to try URI encoding the URL that is passed to 'get': http://www.loudthinking.org/2010/02/ruby-eoferror-end-of-file-reached.html

I took a shot at it, based on desperation, and in my limiting testing this seems to have fixed it for me. My new code is:

@http = Net::HTTP.new('domain.com')  
@http = @http.start    
url = 'http://domain.com/requested_url?blah=blah&etc=1'
req = Net::HTTP::Get.new(URI.encode(url))
req.basic_auth USERNAME, API_KEY
res = @http.request(req) 

Note that I use @http.start as I want to maintain the HTTP session over multiple requests. Other than that, you might like to try the most relevant part which is: URI.encode(url) inside the get call

Using the passwd command from within a shell script

Read the wise words from:

I quote:

Nothing you can do in bash can possibly work. passwd(1) does not read from standard input. This is intentional. It is for your protection. Passwords were never intended to be put into programs, or generated by programs. They were intended to be entered only by the fingers of an actual human being, with a functional brain, and never, ever written down anywhere.

Nonetheless, we get hordes of users asking how they can circumvent 35 years of Unix security.

It goes on to explain how you can set your shadow(5) password properly, and shows you the GNU-I-only-care-about-security-if-it-doesn't-make-me-think-too-much-way of abusing passwd(1).

Lastly, if you ARE going to use the silly GNU passwd(1) extension --stdin, do not pass the password putting it on the command line.

echo $mypassword | passwd --stdin # Eternal Sin.
echo "$mypassword" | passwd --stdin # Eternal Sin, but at least you remembered to quote your PE.
passwd --stdin <<< "$mypassword" # A little less insecure, still pretty insecure, though.
passwd --stdin < "passwordfile" # With a password file that was created with a secure `umask(1)`, a little bit secure.

The last is the best you can do with GNU passwd. Though I still wouldn't recommend it.

Putting the password on the command line means anyone with even the remotest hint of access to the box can be monitoring ps or such and steal the password. Even if you think your box is safe; it's something you should really get in the habit of avoiding at all cost (yes, even the cost of doing a bit more trouble getting the job done).

Why is access to the path denied?

If you're using BitDefender there's a good chance its Safe Files feature blocked your operation. This is a form of Ransomware protection that comes with some of its more advanced versions.

Make sure to grant your application access in BitDefender and try again.

Some more details can be found in this BitDefender support page.

Add a pipe separator after items in an unordered list unless that item is the last on a line

Use :after pseudo selector. Look http://jsfiddle.net/A52T8/1/

<ul>
    <li>Dogs</li>
    <li>Cats</li>
    <li>Lions</li>
    <li>Tigers</li>
    <li>Zebras</li>
    <li>Giraffes</li>
    <li>Bears</li>
    <li>Hippopotamuses</li>
    <li>Antelopes</li>
    <li>Unicorns</li>
    <li>Seagulls</li>
</ul>

ul li { float: left; }
ul li:after { content: "|"; padding: 0 .5em; }

EDIT:

jQuery solution:

html:

<div>
    <ul id="animals">
        <li>Dogs</li>
        <li>Cats</li>
        <li>Lions</li>
        <li>Tigers</li>
        <li>Zebras</li>
        <li>Giraffes</li>
        <li>Bears</li>
        <li>Hippopotamuses</li>
        <li>Antelopes</li>
        <li>Unicorns</li>
        <li>Seagulls</li>
        <li>Monkey</li>
        <li>Hedgehog</li>
        <li>Chicken</li>
        <li>Rabbit</li>
        <li>Gorilla</li>
    </ul>
</div>

css:

div { width: 300px; }
ul li { float: left; border-right: 1px solid black; padding: 0 .5em; }
ul li:last-child { border: 0; }

jQuery

var maxWidth = 300, // Your div max-width
    totalWidth = 0;
$('#animals li').each(function(){
    var currentWidth = $(this).outerWidth(),
        nextWidth = $(this).next().outerWidth();
    totalWidth += currentWidth;
    if ( (totalWidth + nextWidth) > maxWidth ) {
        $(this).css('border', 'none');
        totalWidth = 0;
    }
});

Take a look here. I also added a few more animals. http://jsfiddle.net/A52T8/10/

Pandas: sum DataFrame rows for given columns

This is a simpler way using iloc to select which columns to sum:

df['f']=df.iloc[:,0:2].sum(axis=1)
df['g']=df.iloc[:,[0,1]].sum(axis=1)
df['h']=df.iloc[:,[0,3]].sum(axis=1)

Produces:

   a  b   c  d   e  f  g   h
0  1  2  dd  5   8  3  3   6
1  2  3  ee  9  14  5  5  11
2  3  4  ff  1   8  7  7   4

I can't find a way to combine a range and specific columns that works e.g. something like:

df['i']=df.iloc[:,[[0:2],3]].sum(axis=1)
df['i']=df.iloc[:,[0:2,3]].sum(axis=1)

What does 'URI has an authority component' mean?

I also faced similar problem while working on Affable Bean e-commerce site development. I received an error:

Module has not been deployed.

I checked the sun-resources.xml file and found the following statements which resulted in the error.

<resources>
    <jdbc-resource enabled="true"
                   jndi-name="jdbc/affablebean"
                   object-type="user"
                   pool-name="AffableBeanPool">
    </jdbc-resource>

    <jdbc-connection-pool allow-non-component-callers="false"
                          associate-with-thread="false"
                          connection-creation-retry-attempts="0"
                          connection-creation-retry-interval-in-seconds="10"
                          connection-leak-reclaim="false"
                          connection-leak-timeout-in-seconds="0"
                          connection-validation-method="auto-commit"
                          datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
                          fail-all-connections="false"
                          idle-timeout-in-seconds="300"
                          is-connection-validation-required="false"
                          is-isolation-level-guaranteed="true"
                          lazy-connection-association="false"
                          lazy-connection-enlistment="false"
                          match-connections="false"
                          max-connection-usage-count="0"
                          max-pool-size="32"
                          max-wait-time-in-millis="60000"
                          name="AffableBeanPool"
                          non-transactional-connections="false"
                          pool-resize-quantity="2"
                          res-type="javax.sql.ConnectionPoolDataSource"
                          statement-timeout-in-seconds="-1"
                          steady-pool-size="8"
                          validate-atmost-once-period-in-seconds="0"
                          wrap-jdbc-objects="false">

        <description>Connects to the affablebean database</description>
        <property name="URL" value="jdbc:mysql://localhost:3306/affablebean"/>
        <property name="User" value="root"/>
        <property name="Password" value="nbuser"/>
    </jdbc-connection-pool>
</resources>

Then I changed the statements to the following which is simple and works. I was able to run the file successfully.

<resources>
    <jdbc-resource enabled="true" jndi-name="jdbc/affablebean" object-type="user" pool-name="AffablebeanPool">
        <description/>
    </jdbc-resource>
    <jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="AffablebeanPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.ConnectionPoolDataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="URL" value="jdbc:mysql://localhost:3306/AffableBean"/>
        <property name="User" value="root"/>
        <property name="Password" value="nbuser"/>
    </jdbc-connection-pool>
</resources>

What is the difference between git pull and git fetch + git rebase?

TLDR:

git pull is like running git fetch then git merge
git pull --rebase is like git fetch then git rebase

In reply to your first statement,

git pull is like a git fetch + git merge.

"In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD" More precisely, git pull runs git fetch with the given parameters and then calls git merge to merge the retrieved branch heads into the current branch"

(Ref: https://git-scm.com/docs/git-pull)


For your second statement/question:

'But what is the difference between git pull VS git fetch + git rebase'

Again, from same source:
git pull --rebase

"With --rebase, it runs git rebase instead of git merge."


Now, if you wanted to ask

'the difference between merge and rebase'

that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)

Can't access Eclipse marketplace

And also check with your antivirus, in case of me its avast, its blocking me from accessing market place, so i disabled it for few mins and tried accessing market place from eclipse , it worked!!!

Style the first <td> column of a table differently

The :nth-child() and :nth-of-type() pseudo-classes allows you to select elements with a formula.

The syntax is :nth-child(an+b), where you replace a and b by numbers of your choice.

For instance, :nth-child(3n+1) selects the 1st, 4th, 7th etc. child.

td:nth-child(3n+1) {  
  /* your stuff here */
}

:nth-of-type() works the same, except that it only considers element of the given type ( in the example).

Mark error in form using Bootstrap

One can also use the following class while using bootstrap modal class (v 3.3.7) ... help-inline and help-block did not work in modal.

<span class="error text-danger">Some Errors related to something</span>

Output looks like something below:

Example of error text in modal

starting file download with JavaScript

I have created an open source jQuery File Download plugin (Demo with examples) (GitHub) which could also help with your situation. It works pretty similarly with an iframe but has some cool features that I have found quite handy:

  • User never leaves the same page they initiated a file download from. This feature is becoming crucial for modern web applications
  • Tested cross browser support (including mobile!)
  • It supports POST and GET requests in a manner similar to jQuery's AJAX API
  • successCallback and failCallback functions allow for you to be explicit about what the user sees in either situation
  • In conjunction with jQuery UI a developer can easily show a modal telling the user that a file download is occurring, disband the modal after the download starts or even inform the user in a friendly manner that an error has occurred. See the Demo for an example of this.

How to delete from a table where ID is in a list of IDs?

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

ssh-copy-id no identities found error

I had faced this problem today while setting up ssh between name node and data node in fully distributed mode between two VMs in CentOS.

The problem was faced because I ran the below command from data node instead of name node ssh-copy-id -i /home/hduser/.ssh/id_ras.pub hduser@HadoopBox2

Since the public key file did not exist in data node it threw the error.

How do I declare an array of undefined or no initial size?

One way I can imagine is to use a linked list to implement such a scenario, if you need all the numbers entered before the user enters something which indicates the loop termination. (posting as the first option, because have never done this for user input, it just seemed to be interesting. Wasteful but artistic)

Another way is to do buffered input. Allocate a buffer, fill it, re-allocate, if the loop continues (not elegant, but the most rational for the given use-case).

I don't consider the described to be elegant though. Probably, I would change the use-case (the most rational).

What is the difference between CSS and SCSS?

Variable definitions right:

$      => SCSS, SASS
--     => CSS
@      => LESS

All answers is good but question a little different than answers

"about Sass. How is SCSS different from CSS" : scss is well formed CSS3 syntax. uses sass preprocessor to create that.

and if I use SCSS instead of CSS will it work the same? yes. if your ide supports sass preprocessor. than it will work same.

Sass has two syntaxes. The most commonly used syntax is known as “SCSS” (for “Sassy CSS”), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension .scss.

The second, older syntax is known as the indented syntax (or just “.sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Files in the indented syntax use the extension .sass.


  • Furher Information About:

What Is A CSS Preprocessor?

CSS in itself is devoid of complex logic and functionality which is required to write reusable and organized code. As a result, a developer is bound by limitations and would face extreme difficulty in code maintenance and scalability, especially when working on large projects involving extensive code and multiple CSS stylesheets. This is where CSS Preprocessors come to the rescue.

A CSS Preprocessor is a tool used to extend the basic functionality of default vanilla CSS through its own scripting language. It helps us to use complex logical syntax like – variables, functions, mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS. By using CSS Preprocessors, you can seamlessly automate menial tasks, build reusable code snippets, avoid code repetition and bloating and write nested code blocks that are well organized and easy to read. However, browsers can only understand native vanilla CSS code and will be unable to interpret the CSS Preprocessor syntax. Therefore, the complex and advanced Preprocessor syntax needs to be first compiled into native CSS syntax which can then be interpreted by the browsers to avoid cross browser compatibility issues. While different Preprocessors have their own unique syntaxes, eventually all of them are compiled to the same native CSS code.

Moving forward in the article, we will take a look at the 3 most popular CSS Preprocessors currently being used by developers around the world i.e Sass, LESS, and Stylus. Before you decide the winner between Sass vs LESS vs Stylus, let us get to know them in detail first.

Sass – Syntactically Awesome Style Sheets

Sass is the acronym for “Syntactically Awesome Style Sheets”. Sass is not only the most popular CSS Preprocessor in the world but also one of the oldest, launched in 2006 by Hampton Catlin and later developed by Natalie Weizenbaum. Although Sass is written in Ruby language, a Precompiler LibSass allows Sass to be parsed in other languages and decouple it from Ruby. Sass has a massive active community and extensive learning resources available on the net for beginners. Thanks to its maturity, stability and powerful logical prowess, Sass has established itself to the forefront of CSS Preprocessor ahead of its rival peers.

Sass can be written in 2 syntaxes either using Sass or SCSS. What is the difference between the two? Let’s find out.

Syntax Declaration: Sass vs SCSS

  • SCSS stands for Sassy CSS. Unlike Sass, SCSS is not based on indentation.
  • .sass extension is used as original syntax for Sass, while SCSS offers a newer syntax with .scss extension.
  • Unlike Sass, SCSS has curly braces and semicolons, just like CSS.
  • Contrary to SCSS, Sass is difficult to read as it is quite deviant from CSS. Which is why SCSS it the more recommended Sass syntax as it is easier to read and closely resembles Native CSS while at the same time enjoying with power of Sass.

Consider the example below with Sass vs SCSS syntax along with Compiled CSS code.

Sass SYNTAX
    $font-color: #fff
    $bg-color: #00f

    #box
      color: $font-color
      background: $bg-color

SCSS SYNTAX
    $font-color: #fff;
    $bg-color: #00f;

    #box{
      color: $font-color;
      background: $bg-color;
    }

In both cases, be it Sass or SCSS, the compiled CSS code will be the same –

#box {
      color: #fff;
      background: #00f;

Usage of Sass

Arguably the most Popular front end framework Bootstrap is written in Sass. Up until version 3, Bootstrap was written in LESS but bootstrap 4 adopted Sass and boosted its popularity. A few of the big companies using Sass are – Zapier, Uber, Airbnb and Kickstarter.

LESS – Leaner Style Sheets

LESS is an acronym for “Leaner Stylesheets”. It was released in 2009 by Alexis Sellier, 3 years after the initial launch of Sass in 2006. While Sass is written in Ruby, LESS is written JavaScript. In fact, LESS is a JavaScript library that extends the functionality of native vanilla CSS with mixins, variables, nesting and rule set loop. Sass vs LESS has been a heated debate. It is no surprise that LESS is the strongest competitor to Sass and has the second-largest user base. However, When bootstrap dumped LESS in favor of Sass with the launch of Bootstrap 4, LESS has waned in popularity. One of the few disadvantages of LESS over Sass is that it does not support functions. Unlike Sass, LESS uses @ to declare variables which might cause confusion with @media and @keyframes. However, One key advantage of LESS over Sass and Stylus or any other preprocessors, is the ease of adding it in your project. You can do that either by using NPM or by incorporating Less.js file. Syntax Declaration: LESS Uses .less extension. Syntax of LESS is quite similar to SCSS with the exception that for declaring variables, instead of $ sign, LESS uses @.

@font-color: #fff;
    @bg-color: #00f

    #box{
      color: @font-color;
      background: @bg-color;
    }

COMPILED CSS
    #box {
        color: #fff;
        background: #00f;
      }

Usage Of LESS The popular Bootstrap framework until the launch of version 4 was written in LESS. However, another popular framework called SEMANTIC UI is still written in LESS. Among the big companies using Sass are – Indiegogo, Patreon, and WeChat

Stylus

The stylus was launched in 2010 by former Node JS developer TJ Holowaychuk, nearly 4 years after the release of Sass and 1 year after the release of LESS. The stylus is written Node JS and fits perfectly with JS stack. The stylus was heavily influenced by the logical prowess of the Sass and simplicity of LESS. Even though Stylus is still popular with Node JS developers, it hasn’t managed to carve out a sizeable share for itself. One advantage of Stylus over Sass or LESS, is that it is armed with extremely powerful built-in functions and is capable of handling heavy computing.

Syntax Declaration: Stylus Uses .styl extension. Stylus offers a great deal of flexibility in writing syntax, supports native CSS as well as allows omission of brackets colons and semicolons. Also, note that Stylus does not use @ or $ symbols for defining variables. Instead, Stylus uses the assignment operators to indicate a variable declaration.

STYLUS SYNTAX WRITTEN LIKE NATIVE CSS

font-color = #fff;
bg-color = #00f;

#box {
    color: font-color;
    background: bg-color;
}

OR

STYLUS SYNTAX WITHOUT CURLY BRACES

font-color = #fff;
bg-color = #00f;

#box 
    color: font-color;
    background: bg-color;

OR

STYLUS SYNTAX WITHOUT COLONS AND SEMICOLONS

font-color = #fff
bg-color = #00f

#box 
    color font-color
    background bg-color

Shall we always use [unowned self] inside closure in Swift

No, there are definitely times where you would not want to use [unowned self]. Sometimes you want the closure to capture self in order to make sure that it is still around by the time the closure is called.

Example: Making an asynchronous network request

If you are making an asynchronous network request you do want the closure to retain self for when the request finishes. That object may have otherwise been deallocated but you still want to be able to handle the request finishing.

When to use unowned self or weak self

The only time where you really want to use [unowned self] or [weak self] is when you would create a strong reference cycle. A strong reference cycle is when there is a loop of ownership where objects end up owning each other (maybe through a third party) and therefore they will never be deallocated because they are both ensuring that each other stick around.

In the specific case of a closure, you just need to realize that any variable that is referenced inside of it, gets "owned" by the closure. As long as the closure is around, those objects are guaranteed to be around. The only way to stop that ownership, is to do the [unowned self] or [weak self]. So if a class owns a closure, and that closure captures a strong reference to that class, then you have a strong reference cycle between the closure and the class. This also includes if the class owns something that owns the closure.

Specifically in the example from the video

In the example on the slide, TempNotifier owns the closure through the onChange member variable. If they did not declare self as unowned, the closure would also own self creating a strong reference cycle.

Difference between unowned and weak

The difference between unowned and weak is that weak is declared as an Optional while unowned is not. By declaring it weak you get to handle the case that it might be nil inside the closure at some point. If you try to access an unowned variable that happens to be nil, it will crash the whole program. So only use unowned when you are positive that variable will always be around while the closure is around

Display images in asp.net mvc

Make sure you image is a relative path such as:

@Url.Content("~/Content/images/myimage.png")

MVC4

<img src="~/Content/images/myimage.png" />

You could convert the byte[] into a Base64 string on the fly.

string base64String = Convert.ToBase64String(imageBytes);

<img src="@String.Format("data:image/png;base64,{0}", base64string)" />

Include files from parent or other directory

Had same issue earlier solved like this :

include('/../includes/config.php'); //note '/' appearing before '../includes/config.php'

How to save a git commit message from windows cmd?

I believe the REAL answer to this question is an explanation as to how you configure what editor to use by default, if you are not comfortable with Vim.

This is how to configure Notepad for example, useful in Windows:

git config --global core.editor "notepad"

Gedit, more Linux friendly:

git config --global core.editor "gedit"

You can read the current configuration like this:

git config core.editor

Algorithm to randomly generate an aesthetically-pleasing color palette

I'd strongly recommend using a CG HSVtoRGB shader function, they are awesome... it gives you natural color control like a painter instead of control like a crt monitor, which you arent presumably!

This is a way to make 1 float value. i.e. Grey, into 1000 ds of combinations of color and brightness and saturation etc:

int rand = a global color randomizer that you can control by script/ by a crossfader etc.
float h = perlin(grey,23.3*rand)
float s = perlin(grey,54,4*rand)
float v = perlin(grey,12.6*rand)

Return float4 HSVtoRGB(h,s,v);

result is AWESOME COLOR RANDOMIZATION! it's not natural but it uses natural color gradients and it looks organic and controlleably irridescent / pastel parameters.

For perlin, you can use this function, it is a fast zig zag version of perlin.

function  zig ( xx : float ): float{    //lfo nz -1,1
    xx= xx+32;
    var x0 = Mathf.Floor(xx);
    var x1 = x0+1;
    var v0 = (Mathf.Sin (x0*.014686)*31718.927)%1;
    var v1 = (Mathf.Sin  (x1*.014686)*31718.927)%1;
    return Mathf.Lerp( v0 , v1 , (xx)%1 )*2-1;
}

Escape Character in SQL Server

You could use the **\** character before the value you want to escape e.g insert into msglog(recipient) values('Mr. O\'riely') select * from msglog where recipient = 'Mr. O\'riely'

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I faced this issue:

(node:1131004) UnhandledPromiseRejectionWarning: Unhandled promise rejection (re jection id: 1): TypeError: res.json is not a function (node:1131004) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.j s process with a non-zero exit code.

It was my mistake, I was replacing res object in then(function(res), so changed res to result and now it is working.

Wrong

module.exports.update = function(req, res){
        return Services.User.update(req.body)
                .then(function(res){//issue was here, res overwrite
                    return res.json(res);
                }, function(error){
                    return res.json({error:error.message});
                }).catch(function () {
                   console.log("Promise Rejected");
              });

Correction

module.exports.update = function(req, res){
        return Services.User.update(req.body)
                .then(function(result){//res replaced with result
                    return res.json(result);
                }, function(error){
                    return res.json({error:error.message});
                }).catch(function () {
                   console.log("Promise Rejected");
              });

Service code:

function update(data){
   var id = new require('mongodb').ObjectID(data._id);
        userData = {
                    name:data.name,
                    email:data.email,
                    phone: data.phone
                };
 return collection.findAndModify(
          {_id:id}, // query
          [['_id','asc']],  // sort order
          {$set: userData}, // replacement
          { "new": true }
          ).then(function(doc) {
                if(!doc)
                    throw new Error('Record not updated.');
                return doc.value;   
          });
    }

module.exports = {
        update:update
}

Adb over wireless without usb cable at all for not rooted phones

This might help:

If the adb connection is ever lost:

Make sure that your host is still connected to the same Wi-Fi network your Android device is. Reconnect by executing the "adb connect IP" step. (IP is obviously different when you change location.) Or if that doesn't work, reset your adb host: adb kill-server and then start over from the beginning.

Change windows hostname from command line

The previously mentioned wmic command is the way to go, as it is installed by default in recent versions of Windows.

Here is my small improvement to generalize it, by retrieving the current name from the environment:

wmic computersystem where name="%COMPUTERNAME%" 
     call rename name="NEW-NAME"

NOTE: The command must be given in one line, but I've broken it into two to make scrolling unnecessary. As @rbeede mentions you'll have to reboot to complete the update.

how to get right offset of an element? - jQuery

Actually these only work when the window isn't scrolled at all from the top left position.
You have to subtract the window scroll values to get an offset that's useful for repositioning elements so they stay on the page:

var offset = $('#whatever').offset();

offset.right = ($(window).width() + $(window).scrollLeft()) - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = ($(window).height() + $(window).scrollTop()) - (offset.top + $('#whatever').outerHeight(true));

How to bind Close command to a button

In the beginning I was also having a bit of trouble figuring out how this works so I wanted to post a better explanation of what is actually going on.

According to my research the best way to handle things like this is using the Command Bindings. What happens is a "Message" is broadcast to everything in the program. So what you have to do is use the CommandBinding. What this essentially does is say "When you hear this Message do this".

So in the Question the User is trying to Close the Window. The first thing we need to do is setup our Functions that will be called when the SystemCommand.CloseWindowCommand is broadcast. Optionally you can assign a Function that determines if the Command should be executed. An example would be closing a Form and checking if the User has saved.

MainWindow.xaml.cs (Or other Code-Behind)

void CloseApp( object target, ExecutedRoutedEventArgs e ) {
    /*** Code to check for State before Closing ***/
    this.Close();
}

void CloseAppCanExecute( object sender, CanExecuteRoutedEventArgs e ) {
    /*** Logic to Determine if it is safe to Close the Window ***/
    e.CanExecute = true;
}

Now we need to setup the "Connection" between the SystemCommands.CloseWindowCommand and the CloseApp and CloseAppCanExecute

MainWindow.xaml (Or anything that implements CommandBindings)

<Window.CommandBindings>
    <CommandBinding Command="SystemCommands.CloseWindowCommand"
                    Executed="CloseApp"
                    CanExecute="CloseAppCanExecute"/>
</Window.CommandBindings>

You can omit the CanExecute if you know that the Command should be able to always be executed Save might be a good example depending on the Application. Here is a Example:

<Window.CommandBindings>
    <CommandBinding Command="SystemCommands.CloseWindowCommand"
                    Executed="CloseApp"/>
</Window.CommandBindings>

Finally you need to tell the UIElement to send out the CloseWindowCommand.

<Button Command="SystemCommands.CloseWindowCommand">

Its actually a very simple thing to do, just setup the link between the Command and the actual Function to Execute then tell the Control to send out the Command to the rest of your program saying "Ok everyone run your Functions for the Command CloseWindowCommand".

This is actually a very nice way of handing this because, you can reuse the Executed Function all over without having a wrapper like you would with say WinForms (using a ClickEvent and calling a function within the Event Function) like:

protected override void OnClick(EventArgs e){
    /*** Function to Execute ***/
}

In WPF you attach the Function to a Command and tell the UIElement to execute the Function attached to the Command instead.

I hope this clears things up...

How to write into a file in PHP?

In order to write to a file in PHP you need to go through the following steps:

  1. Open the file

  2. Write to the file

  3. Close the file

    $select = "data what we trying to store in a file";
    $file = fopen("/var/www/htdocs/folder/test.txt", "a");
    fwrite($file  , $select->__toString());
         fclose($file );
    

How do I find the last column with data?

Lots of ways to do this. The most reliable is find.

Dim rLastCell As Range

Set rLastCell = ws.Cells.Find(What:="*", After:=ws.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False)

MsgBox ("The last used column is: " & rLastCell.Column)

If you want to find the last column used in a particular row you can use:

Dim lColumn As Long

lColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column

Using used range (less reliable):

Dim lColumn As Long

lColumn = ws.UsedRange.Columns.Count

Using used range wont work if you have no data in column A. See here for another issue with used range:

See Here regarding resetting used range.

How can I get the behavior of GNU's readlink -f on a Mac?

MacPorts and Homebrew provide a coreutils package containing greadlink (GNU readlink). Credit to Michael Kallweitt post in mackb.com.

brew install coreutils

greadlink -f file.txt

Python regex to match dates

Well, from my understanding, simply for matching this format in a given string, I prefer this regular expression:

pattern='[0-9|/]+'

to match the format in a more strict way, the following works:

pattern='(?:[0-9]{2}/){2}[0-9]{2}'

Personally, I cannot agree with unutbu's answer since sometimes we use regular expression for "finding" and "extract", not only "validating".

set date in input type date

For me the shortest way to get locale date and in correct format for input type="date" is this :

var d = new Date(); 
var today = d.getFullYear()+"-"+("0"+(d.getMonth()+1)).slice(-2)+"-"+("0"+d.getDate()).slice(-2);

Or this :

var d = new Date().toLocaleDateString().split('/');
var today = d[2]+"-"+("0"+d[0]).slice(-2)+"-"+("0"+d[1]).slice(-2);

Then just set the date input value :

$('#datePicker').val(today);

Extracting extension from filename in Python

A true one-liner, if you like regex. And it doesn't matter even if you have additional "." in the middle

import re

file_ext = re.search(r"\.([^.]+)$", filename).group(1)

See here for the result: Click Here

Java, How to add values to Array List used as value in HashMap

You could either use the Google Guava library, which has implementations for Multi-Value-Maps (Apache Commons Collections has also implementations, but without generics).

However, if you don't want to use an external lib, then you would do something like this:

if (map.get(id) == null) { //gets the value for an id)
    map.put(id, new ArrayList<String>()); //no ArrayList assigned, create new ArrayList

map.get(id).add(value); //adds value to list.

Find object in list that has attribute equal to some value (that meets any condition)

next((x for x in test_list if x.value == value), None)

This gets the first item from the list that matches the condition, and returns None if no item matches. It's my preferred single-expression form.

However,

for x in test_list:
    if x.value == value:
        print("i found it!")
        break

The naive loop-break version, is perfectly Pythonic -- it's concise, clear, and efficient. To make it match the behavior of the one-liner:

for x in test_list:
    if x.value == value:
        print("i found it!")
        break
else:
    x = None

This will assign None to x if you don't break out of the loop.

Android: How to handle right to left swipe gestures

If you want to display some buttons with actions when an list item is swipe are a lot of libraries on the internet that have this behavior. I implemented the library that I found on the internet and I am very satisfied. It is very simple to use and very quick. I improved the original library and I added a new click listener for item click. Also I added font awesome library (http://fortawesome.github.io/Font-Awesome/) and now you can simply add a new item title and specify the icon name from font awesome.

Here is the github link

format a number with commas and decimals in C# (asp.net MVC3)

Maybe you simply want the standard format string "N", as in

number.ToString("N")

It will use thousand separators, and a fixed number of fractional decimals. The symbol for thousands separators and the symbol for the decimal point depend on the format provider (typically CultureInfo) you use, as does the number of decimals (which will normally by 2, as you require).

If the format provider specifies a different number of decimals, and if you don't want to change the format provider, you can give the number of decimals after the N, as in .ToString("N2").

Edit: The sizes of the groups between the commas are governed by the

CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes

array, given that you don't specify a special format provider.

Node.js – events js 72 throw er unhandled 'error' event

Well, your script throws an error and you just need to catch it (and/or prevent it from happening). I had the same error, for me it was an already used port (EADDRINUSE).

Easiest way to split a string on newlines in .NET?

Very easy, actually.

VB.NET:

Private Function SplitOnNewLine(input as String) As String
    Return input.Split(Environment.NewLine)
End Function

C#:

string splitOnNewLine(string input)
{
    return input.split(environment.newline);
}

ORA-01861: literal does not match format string

A simple view like this was giving me the ORA-01861 error when executed from Entity Framework:

create view myview as 
select * from x where x.initialDate >= '01FEB2021'

Just did something like this to fix it:

create view myview as 
select * from x where x.initialDate >= TO_DATE('2021-02-01', 'YYYY-MM-DD')

I think the problem is EF date configuration is not the same as Oracle's.

Scroll back to the top of scrollable div

I tried the existing answers to this question, and none of them worked on Chrome for me. What did work was slightly different:

$('body, html, #containerDiv').scrollTop(0);

How to find a value in an excel column by vba code Cells.Find

Just for sake of completeness, you can also use the same technique above with excel tables.

In the example below, I'm looking of a text in any cell of a Excel Table named "tblConfig", place in the sheet named Config that normally is set to be hidden. I'm accepting the defaults of the Find method.

Dim list As ListObject
Dim config As Worksheet
Dim cell as Range


Set config = Sheets("Config")
Set list = config.ListObjects("tblConfig")

'search in any cell of the data range of excel table
Set cell = list.DataBodyRange.Find(searchTerm)

If cell Is Nothing Then
    'when information is not found
Else
    'when information is found
End If

How do I make the text box bigger in HTML/CSS?

.textbox {
    height: 40px;
}

<div id=signin>  
    <input type="text" class="textbox" size="25%" height="50"/></br>
<input type="text" class="textbox" size="25%" height="50"/>

Make the font size larger and add height (or line height to the input boxes) I would not recommend adding those size and height attributes in the HTML as that can be handled by CSS. I have made a class text-box that can be used for multiple input boxes

How to remove an element from a list by index

Use the following code to remove element from the list:

list = [1, 2, 3, 4]
list.remove(1)
print(list)

output = [2, 3, 4]

If you want to remove index element data from the list use:

list = [1, 2, 3, 4]
list.remove(list[2])
print(list)
output : [1, 2, 4]

Combining two lists and removing duplicates, without removing duplicates in original list

    first_list = [1, 2, 2, 5]
    second_list = [2, 5, 7, 9]

    newList=[]
    for i in first_list:
        newList.append(i)
    for z in second_list:
        if z not in newList:
            newList.append(z)
    newList.sort()
    print newList

[1, 2, 2, 5, 7, 9]

Invalid date in safari

I had the same issue.Then I used moment.Js.Problem has vanished.

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, then fall back to new Date(string) if a known format is not found.

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

e.g.

var date= moment(String);

TensorFlow, "'module' object has no attribute 'placeholder'"

Solution: Do not use "tensorflow" as your filename.

Notice that you use tensorflow.py as your filename. And I guess you write code like:

import tensorflow as tf

Then you are actually importing the script file "tensorflow.py" that is under your current working directory, rather than the "real" tensorflow module from Google.

Here is the order in which a module will be searched when importing:

  1. The directory containing the input script (or the current directory when no file is specified).

  2. PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

  3. The installation-dependent default.

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

If you are using an eclipse ide, download the mysql jdbc connector jar and point that jar to the build path. Project Java Build Path --> Libraries --> Add external jars. Connector can be obtained from http://dev.mysql.com/downloads/connector/j/

How to return 2 values from a Java method?

You could implement a generic Pair if you are sure that you just need to return two values:

public class Pair<U, V> {

 /**
     * The first element of this <code>Pair</code>
     */
    private U first;

    /**
     * The second element of this <code>Pair</code>
     */
    private V second;

    /**
     * Constructs a new <code>Pair</code> with the given values.
     * 
     * @param first  the first element
     * @param second the second element
     */
    public Pair(U first, V second) {

        this.first = first;
        this.second = second;
    }

//getter for first and second

and then have the method return that Pair:

public Pair<Object, Object> getSomePair();

Use Expect in a Bash script to provide a password to an SSH command

Mixing Bash and Expect is not a good way to achieve the desired effect. I'd try to use only Expect:

#!/usr/bin/expect
eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com

# Use the correct prompt
set prompt ":|#|\\\$"
interact -o -nobuffer -re $prompt return
send "my_password\r"
interact -o -nobuffer -re $prompt return
send "my_command1\r"
interact -o -nobuffer -re $prompt return
send "my_command2\r"
interact

Sample solution for bash could be:

#!/bin/bash
/usr/bin/expect -c 'expect "\n" { eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com; interact }'

This will wait for Enter and then return to (for a moment) the interactive session.

What is the right way to populate a DropDownList from a database?

public void getClientNameDropDowndata()
{
    getConnection = Connection.SetConnection(); // to connect with data base Configure manager
    string ClientName = "Select  ClientName from Client ";
    SqlCommand ClientNameCommand = new SqlCommand(ClientName, getConnection);
    ClientNameCommand.CommandType = CommandType.Text;
    SqlDataReader ClientNameData;
    ClientNameData = ClientNameCommand.ExecuteReader();
    if (ClientNameData.HasRows)
    {
        DropDownList_ClientName.DataSource = ClientNameData;
        DropDownList_ClientName.DataValueField = "ClientName";
        DropDownList_ClientName.DataTextField="ClientName";
        DropDownList_ClientName.DataBind();
    }
    else
    {
        MessageBox.Show("No is found");
        CloseConnection = new Connection();
        CloseConnection.closeConnection(); // close the connection 
    }
}

How do you get total amount of RAM the computer has?

Add a reference to Microsoft.VisualBasic and a using Microsoft.VisualBasic.Devices;.

The ComputerInfo class has all the information that you need.

How to use QTimer

mytimer.h:

    #ifndef MYTIMER_H
    #define MYTIMER_H

    #include <QTimer>

    class MyTimer : public QObject
    {
        Q_OBJECT
    public:
        MyTimer();
        QTimer *timer;

    public slots:
        void MyTimerSlot();
    };

    #endif // MYTIME

mytimer.cpp:

#include "mytimer.h"
#include <QDebug>

MyTimer::MyTimer()
{
    // create a timer
    timer = new QTimer(this);

    // setup signal and slot
    connect(timer, SIGNAL(timeout()),
          this, SLOT(MyTimerSlot()));

    // msec
    timer->start(1000);
}

void MyTimer::MyTimerSlot()
{
    qDebug() << "Timer...";
}

main.cpp:

#include <QCoreApplication>
#include "mytimer.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Create MyTimer instance
    // QTimer object will be created in the MyTimer constructor
    MyTimer timer;

    return a.exec();
}

If we run the code:

Timer...
Timer...
Timer...
Timer...
Timer...
...

resources

Reset MySQL root password using ALTER USER statement after install on Mac

Mysql 5.7.24 get root first login

step 1: get password from log

 grep root@localhost /var/log/mysqld.log
    Output
        2019-01-17T09:58:34.459520Z 1 [Note] A temporary password is generated for root@localhost: wHkJHUxeR4)w

step 2: login with him to mysql

mysql -uroot -p'wHkJHUxeR4)w'

step 3: you put new root password

SET PASSWORD = PASSWORD('xxxxx');

you get ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

how fix it?

run this SET GLOBAL validate_password_policy=LOW;

Try Again SET PASSWORD = PASSWORD('xxxxx');

syntax error when using command line in python

Looks like your problem is that you are trying to run python test.py from within the Python interpreter, which is why you're seeing that traceback.

Make sure you're out of the interpreter, then run the python test.py command from bash or command prompt or whatever.

Convert int to string?

or:

string s = Convert.ToString(num);

Removing duplicates from a SQL query (not just "use distinct")

Your question is kind of confusing; do you want to show only one row per user, or do you want to show a row per picture but suppress repeating values in the U.NAME field? I think you want the second; if not there are plenty of answers for the first.

Whether to display repeating values is display logic, which SQL wasn't really designed for. You can use a cursor in a loop to process the results row-by-row, but you will lose a lot of performance. If you have a "smart" frontend language like a .NET language or Java, whatever construction you put this data into can be cheaply manipulated to suppress repeating values before finally displaying it in the UI.

If you're using Microsoft SQL Server, and the transformation HAS to be done at the data layer, you may consider using a CTE (Computed Table Expression) to hold the initial query, then select values from each row of the CTE based on whether the columns in the previous row hold the same data. It'll be more performant than the cursor, but it'll be kinda messy either way. Observe:

USING CTE (Row, Name, PicID)
AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY U.NAME, P.PIC_ID),
       U.NAME, P.PIC_ID
    FROM USERS U
        INNER JOIN POSTINGS P1
            ON U.EMAIL_ID = P1.EMAIL_ID
        INNER JOIN PICTURES P
            ON P1.PIC_ID = P.PIC_ID
    WHERE P.CAPTION LIKE '%car%'
    ORDER BY U.NAME, P.PIC_ID 
)
SELECT
    CASE WHEN current.Name == previous.Name THEN '' ELSE current.Name END,
    current.PicID
FROM CTE current
LEFT OUTER JOIN CTE previous
   ON current.Row = previous.Row + 1
ORDER BY current.Row

The above sample is TSQL-specific; it is not guaranteed to work in any other DBPL like PL/SQL, but I think most of the enterprise-level SQL engines have something similar.

Android - Start service on boot

Your Service may be getting shut down before it completes due to the device going to sleep after booting. You need to obtain a wake lock first. Luckily, the Support library gives us a class to do this:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

then, in your Service, make sure to release the wake lock:

    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.

...
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

Don't forget to add the WAKE_LOCK permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Passing a Bundle on startActivity()?

Write this is the activity you are in:

Intent intent = new Intent(CurrentActivity.this,NextActivity.class);
intent.putExtras("string_name","string_to_pass");
startActivity(intent);

In the NextActivity.java

Intent getIntent = getIntent();
//call a TextView object to set the string to
TextView text = (TextView)findViewById(R.id.textview_id);
text.setText(getIntent.getStringExtra("string_name"));

This works for me, you can try it.

Source:https://www.c-sharpcorner.com/article/how-to-send-the-data-one-activity-to-another-activity-in-android-application/

Cannot kill Python script with Ctrl-C

KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python

sendKeys() in Selenium web driver

Try this code:

WebElement userName = pathfinderdriver.switchTo().activeElement();
userName.sendKeys(Keys.TAB);

Python dictionary : TypeError: unhashable type: 'list'

This is indeed rather odd.

If aSourceDictionary were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.

This leads to two hypotheses:

  1. The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)

  2. aSourceDictionary is in fact not a dictionary, but is some other structure (for example, a list).

Proper MIME type for OTF fonts

As from March 2013 IANA.ORG recommends for .otf:
application/font-sfnt

Other fonts:

.eot  ->  application/vnd.ms-fontobject (as from December 2005)
.otf  ->  application/font-sfnt         (as from March 2013)
.svg  ->  image/svg+xml                 (as from August 2011)
.ttf  ->  application/font-sfnt         (as from March 2013)
.woff ->  application/font-woff         (as from January 2013)

See more...

Jenkins Host key verification failed

Try

ssh-keygen -R hostname

-R hostname Removes all keys belonging to hostname from a known_hosts file. This option is useful to delete hashed hosts

Alternate output format for psql

pspg is a simple tool that offers advanced table formatting, horizontal scrolling, search and many more features.

git clone https://github.com/okbob/pspg.git
cd pspg
./configure
make
make install

then make sure to update PAGER variable e.g. in your ~/.bashrc

export PAGER="pspg -s 6" 

where -s stands for color scheme (1-14). If you're using pgdg repositories simply install a package (on Debian-like distribution):

sudo apt install pspg

pspg example

Creating a ZIP archive in memory using System.IO.Compression

       private void button6_Click(object sender, EventArgs e)
    {

        //create With Input FileNames
        AddFileToArchive_InputByte(new ZipItem[]{ new ZipItem( @"E:\b\1.jpg",@"images\1.jpg"),
            new ZipItem(@"E:\b\2.txt",@"text\2.txt")}, @"C:\test.zip");

        //create with input stream
        AddFileToArchive_InputByte(new ZipItem[]{ new ZipItem(File.ReadAllBytes( @"E:\b\1.jpg"),@"images\1.jpg"),
            new ZipItem(File.ReadAllBytes(@"E:\b\2.txt"),@"text\2.txt")}, @"C:\test.zip");

        //Create Archive And Return StreamZipFile
        MemoryStream GetStreamZipFile = AddFileToArchive(new ZipItem[]{ new ZipItem( @"E:\b\1.jpg",@"images\1.jpg"),
            new ZipItem(@"E:\b\2.txt",@"text\2.txt")});


        //Extract in memory
        ZipItem[] ListitemsWithBytes = ExtractItems(@"C:\test.zip");

        //Choese Files For Extract To memory
        List<string> ListFileNameForExtract = new List<string>(new string[] { @"images\1.jpg", @"text\2.txt" });
        ListitemsWithBytes = ExtractItems(@"C:\test.zip", ListFileNameForExtract);


        // Choese Files For Extract To Directory
        ExtractItems(@"C:\test.zip", ListFileNameForExtract, "c:\\extractFiles");

    }

    public struct ZipItem
    {
        string _FileNameSource;
        string _PathinArchive;
        byte[] _Bytes;
        public ZipItem(string __FileNameSource, string __PathinArchive)
        {
            _Bytes=null ;
            _FileNameSource = __FileNameSource;
            _PathinArchive = __PathinArchive;
        }
        public ZipItem(byte[] __Bytes, string __PathinArchive)
        {
            _Bytes = __Bytes;
            _FileNameSource = "";
            _PathinArchive = __PathinArchive;

        }
        public string FileNameSource
        {
            set
            {
                FileNameSource = value;
            }
            get
            {
                return _FileNameSource;
            }
        }
        public string PathinArchive
        {
            set
            {
                _PathinArchive = value;
            }
            get
            {
                return _PathinArchive;
            }
        }
        public byte[] Bytes
        {
            set
            {
                _Bytes = value;
            }
            get
            {
                return _Bytes;
            }
        }
    }


     public void AddFileToArchive(ZipItem[] ZipItems, string SeveToFile)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
            FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 0;
            while (fsReader.Position != fsReader.Length)
            {
                //Read Bytes
                ReadByte = fsReader.Read(ReadAllbytes, 0, ReadAllbytes.Length);

                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
            }
            fsReader.Dispose();
            OpenFileInArchive.Close();


        }
        archive.Dispose();

        using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
        {
            memoryStream.Seek(0, SeekOrigin.Begin);
            memoryStream.CopyTo(fileStream);
        }





    }
     public MemoryStream  AddFileToArchive(ZipItem[] ZipItems)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
            FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 0;
            while (fsReader.Position != fsReader.Length)
            {
                //Read Bytes
                ReadByte = fsReader.Read(ReadAllbytes, 0, ReadAllbytes.Length);

                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
            }
            fsReader.Dispose();
            OpenFileInArchive.Close();


        }
        archive.Dispose();




        return memoryStream;


    }

     public void AddFileToArchive_InputByte(ZipItem[] ZipItems, string SeveToFile)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
          //  FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 4096 ;int  TotalWrite=0;
            while (TotalWrite != item.Bytes.Length)
            {

                if(TotalWrite+4096>item.Bytes.Length)
                 ReadByte=item.Bytes.Length-TotalWrite;



                Array.Copy(item.Bytes, TotalWrite, ReadAllbytes, 0, ReadByte);




                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
                TotalWrite += ReadByte;
            }

            OpenFileInArchive.Close();


        }
        archive.Dispose();

        using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
        {
            memoryStream.Seek(0, SeekOrigin.Begin);
            memoryStream.CopyTo(fileStream);
        }


    }
     public MemoryStream  AddFileToArchive_InputByte(ZipItem[] ZipItems)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
          //  FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 4096 ;int  TotalWrite=0;
            while (TotalWrite != item.Bytes.Length)
            {

                if(TotalWrite+4096>item.Bytes.Length)
                 ReadByte=item.Bytes.Length-TotalWrite;



                Array.Copy(item.Bytes, TotalWrite, ReadAllbytes, 0, ReadByte);




                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
                TotalWrite += ReadByte;
            }

            OpenFileInArchive.Close();


        }
        archive.Dispose();



        return memoryStream;
    }

     public void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName)
     {
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {
             if (Directory.Exists(destinationDirectoryName)==false )
                 Directory.CreateDirectory(destinationDirectoryName);

             //Loops through each file in the zip file
             archive.ExtractToDirectory(destinationDirectoryName);

         }
     }  
     public void   ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive, string destinationDirectoryName)
     {

         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {


             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 int PosResult = _PathFilesinArchive.IndexOf(file.FullName);
                 if (PosResult != -1)
                 {
                     //Create Folder
                     if (Directory.Exists( destinationDirectoryName + "\\" +Path.GetDirectoryName( _PathFilesinArchive[PosResult])) == false)
                         Directory.CreateDirectory(destinationDirectoryName + "\\" + Path.GetDirectoryName(_PathFilesinArchive[PosResult]));

                     Stream OpenFileGetBytes = file.Open();

                     FileStream   FileStreamOutput = new FileStream(destinationDirectoryName + "\\" + _PathFilesinArchive[PosResult], FileMode.Create);

                     byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                     int ReadByte = 0; int TotalRead = 0; 
                     while (TotalRead != file.Length)
                     {
                         //Read Bytes
                         ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                         TotalRead += ReadByte;

                         //Write Bytes
                         FileStreamOutput.Write(ReadAllbytes, 0, ReadByte);
                     }

                     FileStreamOutput.Close();
                     OpenFileGetBytes.Close();



                     _PathFilesinArchive.RemoveAt(PosResult);
                 }

                 if (_PathFilesinArchive.Count == 0)
                     break;
             }
         }


     }

     public ZipItem[] ExtractItems(string sourceArchiveFileName)
     {
       List<  ZipItem> ZipItemsReading = new List<ZipItem>();
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {


             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 Stream OpenFileGetBytes = file.Open();

                 MemoryStream memstreams = new MemoryStream();
                 byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                 int ReadByte = 0; int TotalRead = 0;
                 while (TotalRead != file.Length)
                 {
                     //Read Bytes
                     ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                     TotalRead += ReadByte;

                     //Write Bytes
                     memstreams.Write(ReadAllbytes, 0, ReadByte);
                 }

                 memstreams.Position = 0;
                 OpenFileGetBytes.Close();
                 memstreams.Dispose();

                 ZipItemsReading.Add(new ZipItem(memstreams.ToArray(),file.FullName));


             }
         }

         return ZipItemsReading.ToArray();
     }
     public ZipItem[] ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive)
     {
       List<  ZipItem> ZipItemsReading = new List<ZipItem>();
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {

             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 int PosResult = _PathFilesinArchive.IndexOf(file.FullName); 
                 if (PosResult!= -1)
                 {
                     Stream OpenFileGetBytes = file.Open();

                     MemoryStream memstreams = new MemoryStream();
                     byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                     int ReadByte = 0; int TotalRead = 0;  
                     while (TotalRead != file.Length)
                     {
                         //Read Bytes
                         ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                         TotalRead += ReadByte;

                         //Write Bytes
                         memstreams.Write(ReadAllbytes, 0, ReadByte);
                     }

                     //Create item
                     ZipItemsReading.Add(new ZipItem(memstreams.ToArray(),file.FullName));

                     OpenFileGetBytes.Close();
                     memstreams.Dispose();



                     _PathFilesinArchive.RemoveAt(PosResult);
                 }

                 if (_PathFilesinArchive.Count == 0)
                     break;


             }
         }

         return ZipItemsReading.ToArray();
     }

Unable to add window -- token null is not valid; is your activity running?

In my case, I was inflating a PopupMenu at the very beginning of the activity i.e on onCreate()... I fixed it by putting it in a Handler

  new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                PopupMenu popuMenu=new PopupMenu(SplashScreen.this,binding.progressBar);
                popuMenu.inflate(R.menu.bottom_nav_menu);
                popuMenu.show();
            }
        },100);

How to extend / inherit components?

just use inheritance,Extend parent class in child class and declare constructor with parent class parameter and this parameter use in super().

1.parent class
@Component({
    selector: 'teams-players-box',
    templateUrl: '/maxweb/app/app/teams-players-box.component.html'
})
export class TeamsPlayersBoxComponent {
    public _userProfile:UserProfile;
    public _user_img:any;
    public _box_class:string="about-team teams-blockbox";
    public fullname:string;
    public _index:any;
    public _isView:string;
    indexnumber:number;
    constructor(
        public _userProfilesSvc: UserProfiles,
        public _router:Router,
    ){}
2.child class
@Component({

    selector: '[teams-players-eligibility]',
    templateUrl: '/maxweb/app/app/teams-players-eligibility.component.html'
})
export class TeamsPlayersEligibilityComponent extends TeamsPlayersBoxComponent{

    constructor (public _userProfilesSvc: UserProfiles,
            public _router:Router) {
            super(_userProfilesSvc,_router);
        }
}

what's data-reactid attribute in html?

That's the HTML data attribute. See this for more detail: http://html5doctor.com/html5-custom-data-attributes/

Basically it's just a container of your custom data while still making the HTML valid. It's data- plus some unique identifier.

JSON Stringify changes time of date because of UTC

All boils down to if your server backend is timezone-agnostic or not. If it is not, then you need to assume that timezone of server is the same as client, or transfer information about client's timezone and include that also into calculations.

a PostgreSQL backend based example:

select '2009-09-28T08:00:00Z'::timestamp -> '2009-09-28 08:00:00' (wrong for 10am)
select '2009-09-28T08:00:00Z'::timestamptz -> '2009-09-28 10:00:00+02'
select '2009-09-28T08:00:00Z'::timestamptz::timestamp -> '2009-09-28 10:00:00'

The last one is probably what you want to use in database, if you are not willing properly implement timezone logic.

Laravel - Form Input - Multiple select for a one to many relationship

Just single if conditions

<select name="category_type[]" id="category_type" class="select2 m-b-10 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose" tooltip="Select Category Type">
 @foreach ($categoryTypes as $categoryType)
  <option value="{{ $categoryType->id }}"
    **@if(in_array($categoryType->id,
     request()->get('category_type')??[]))selected="selected"
    @endif**>
     {{ ucfirst($categoryType->title) }}</option>
     @endforeach
 </select>

Google Maps JS API v3 - Simple Multiple Marker Example

From Google Map API samples:

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(-33.9, 151.2),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
                                myOptions);

  setMarkers(map, beaches);
}

/**
 * Data for the markers consisting of a name, a LatLng and a zIndex for
 * the order in which these markers should display on top of each
 * other.
 */
var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

function setMarkers(map, locations) {
  // Add markers to the map

  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.

  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in
  // the Y direction down.
  var image = new google.maps.MarkerImage('images/beachflag.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(20, 32),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));
  var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(37, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML &lt;area&gt; element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.
  var shape = {
      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });
  }
}

Escaping HTML strings with jQuery

I realize how late I am to this party, but I have a very easy solution that does not require jQuery.

escaped = new Option(unescaped).innerHTML;

Edit: This does not escape quotes. The only case where quotes would need to be escaped is if the content is going to be pasted inline to an attribute within an HTML string. It is hard for me to imagine a case where doing this would be good design.

Edit 3: For the fastest solution, check the answer above from Saram. This one is the shortest.

Getting Python error "from: can't read /var/mail/Bio"

for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

If the extra entries in the log bother you but an extra second of start-up time doesn't, just add this to your logging.properties and forget about it:

org.apache.jasper.servlet.TldScanner.level = WARNING

How to create bitmap from byte array?

You'll need to get those bytes into a MemoryStream:

Bitmap bmp;
using (var ms = new MemoryStream(imageData))
{
    bmp = new Bitmap(ms);
}

That uses the Bitmap(Stream stream) constructor overload.

UPDATE: keep in mind that according to the documentation, and the source code I've been reading through, an ArgumentException will be thrown on these conditions:

stream does not contain image data or is null.
-or-
stream contains a PNG image file with a single dimension greater than 65,535 pixels.

Determine whether a key is present in a dictionary

In the same vein as martineau's response, the best solution is often not to check. For example, the code

if x in d:
    foo = d[x]
else:
    foo = bar

is normally written

foo = d.get(x, bar)

which is shorter and more directly speaks to what you mean.

Another common case is something like

if x not in d:
    d[x] = []

d[x].append(foo)

which can be rewritten

d.setdefault(x, []).append(foo)

or rewritten even better by using a collections.defaultdict(list) for d and writing

d[x].append(foo)

Opening Chrome From Command Line

open command prompt and type

cd\ (enter)

then type

start chrome "www.google.com"(any website you require)

css with background image without repeating the image

Try this

padding:8px;
overflow: hidden;
zoom: 1;
text-align: left;
font-size: 13px;
font-family: "Trebuchet MS",Arial,Sans;
line-height: 24px;
color: black;
border-bottom: solid 1px #BBB;
background:url('images/checked.gif') white no-repeat;

This is full css.. Why you use padding:0 8px, then override it with paddings? This is what you need...

No module named Image

It is changed to : from PIL.Image import core as image for new versions.

Read from file in eclipse

You are searching/reading the file "fiel.txt" in the execution directory (where the class are stored, i think).

If you whish to read the file in a given directory, you have to says so :

File file = new File(System.getProperty("user.dir")+"/"+"file.txt");

You could also give the directory with a relative path, eg "./images/photo.gif) for a subdirecory for example.

Note that there is also a property for the separator (hard-coded to "/" in my exemple)

regards Guillaume

Iterating through a range of dates in Python

This function has some extra features:

  • can pass a string matching the DATE_FORMAT for start or end and it is converted to a date object
  • can pass a date object for start or end
  • error checking in case the end is older than the start

    import datetime
    from datetime import timedelta
    
    
    DATE_FORMAT = '%Y/%m/%d'
    
    def daterange(start, end):
          def convert(date):
                try:
                      date = datetime.datetime.strptime(date, DATE_FORMAT)
                      return date.date()
                except TypeError:
                      return date
    
          def get_date(n):
                return datetime.datetime.strftime(convert(start) + timedelta(days=n), DATE_FORMAT)
    
          days = (convert(end) - convert(start)).days
          if days <= 0:
                raise ValueError('The start date must be before the end date.')
          for n in range(0, days):
                yield get_date(n)
    
    
    start = '2014/12/1'
    end = '2014/12/31'
    print list(daterange(start, end))
    
    start_ = datetime.date.today()
    end = '2015/12/1'
    print list(daterange(start, end))
    

How to format LocalDate to string?

Could be short as:

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

Fix for Android N & above: I had similar issue and mange to solve it by following steps described in https://developer.android.com/training/articles/security-config

But the config changes, without any complicated code logic, would only work on Android version 24 & above.

Fix for all version, including version < N: So for android lower then N (version 24) the solution is to via code changes as mentioned above. If you are using OkHttp, then follow the customTrust: https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java

How to define the css :hover state in a jQuery selector?

I know this has an accepted answer but if anyone comes upon this, my solution may help.

I found this question because I have a use-case where I wanted to turn off the :hover state for elements individually. Since there is no way to do this in the DOM, another good way to do it is to define a class in CSS that overrides the hover state.

For instance, the css:

.nohover:hover {
    color: black !important;
}

Then with jQuery:

$("#elm").addClass("nohover");

With this method, you can override as many DOM elements as you would like without binding tons of onHover events.

How can I handle the warning of file_get_contents() function in PHP?

Step 1: check the return code: if($content === FALSE) { // handle error here... }

Step 2: suppress the warning by putting an error control operator (i.e. @) in front of the call to file_get_contents(): $content = @file_get_contents($site);

JQuery Event for user pressing enter in a textbox?

   $('#textbox').on('keypress', function (e) {
         if(e.which === 13){

            //Disable textbox to prevent multiple submit
            $(this).attr("disabled", "disabled");

            //Do Stuff, submit, etc..

            //Enable the textbox again if needed.
            $(this).removeAttr("disabled");
         }
   });

MongoDB relationships: embed or reference?

If I want to edit a specified comment, how to get its content and its question?

You can query by sub-document: db.question.find({'comments.content' : 'xxx'}).

This will return the whole Question document. To edit the specified comment, you then have to find the comment on the client, make the edit and save that back to the DB.

In general, if your document contains an array of objects, you'll find that those sub-objects will need to be modified client side.

Display all dataframe columns in a Jupyter Python Notebook

I recommend setting the display options inside a context manager so that it only affects a single output. I usually prefer "pretty" html-output, and define a function force_show_all(df) for displaying the DataFrame df:

from IPython.core.display import display, HTML

def force_show_all(df):
    with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None):
        display(HTML(df.to_html()))

# ... now when you're ready to fully display df:
force_show_all(df)

As others have mentioned, please be cautious to only call this on a reasonably-sized dataframe.

How do you run a command as an administrator from the Windows command line?

A batch/WSH hybrid is able to call ShellExecute to display the UAC elevation dialog...

@if (1==1) @if(1==0) @ELSE
@echo off&SETLOCAL ENABLEEXTENSIONS
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"||(
    cscript //E:JScript //nologo "%~f0"
    @goto :EOF
)
echo.Performing admin tasks...
REM call foo.exe
@goto :EOF
@end @ELSE
ShA=new ActiveXObject("Shell.Application")
ShA.ShellExecute("cmd.exe","/c \""+WScript.ScriptFullName+"\"","","runas",5);
@end

Oracle SQL Developer - tables cannot be seen

SQL Developer 3.1 fixes this issue. Its an early adopter release at the moment though.

Get class list for element with jQuery

Here you go, just tweaked readsquare's answer to return an array of all classes:

function classList(elem){
   var classList = elem.attr('class').split(/\s+/);
    var classes = new Array(classList.length);
    $.each( classList, function(index, item){
        classes[index] = item;
    });

    return classes;
}

Pass a jQuery element to the function, so that a sample call will be:

var myClasses = classList($('#myElement'));

Git removing upstream from local repository

In git version 2.14.3,

You can remove upstream using

git branch --unset-upstream

The above command will also remove the tracking stream branch, hence if you want to rebase from repository you have use

git rebase origin master 

instead of git pull --rebase

How to pipe list of files returned by find command to cat to view all the files

Sounds like a job for a shell script to me:

for file in 'find -name *.xml'
do
   grep 'hello' file
done

or something like that

Perl read line by line

you need to use ++$counter, not $++counter, hence the reason it isn't working..

Change background color of iframe issue

Put the Iframe between aside tags

<aside style="background-color:#FFF"> your IFRAME </aside>

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

if You use spring boot , you should add origin link in the @CrossOrigin annotation

@CrossOrigin(origins = "http://localhost:4200")
@GetMapping("/yourPath")

You can find detailed instruction in the https://spring.io/guides/gs/rest-service-cors/

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

grep find the lines and output the line numbers, but does not let you "program" other things. If you want to include arbitrary text and do other "programming", you can use awk,

$ awk '/null/{c++;print $0," - Line number: "NR}END{print "Total null count: "c}' file
example two null,  - Line number: 2
example four null,  - Line number: 4
Total null count: 2

Or only using the shell(bash/ksh)

c=0
while read -r line
do
  case "$line" in
   *null* )  (
    ((c++))
    echo "$line - Line number $c"
    ;;
  esac
done < "file"
echo "total count: $c"

How do I handle newlines in JSON?

JSON.stringify

JSON.stringify(`{ 
  a:"a"
}`)

would convert the above string to

"{ \n      a:\"a\"\n    }"

as mentioned here

json stringify

This function adds double quotes at the beginning and end of the input string and escapes special JSON characters. In particular, a newline is replaced by the \n character, a tab is replaced by the \t character, a backslash is replaced by two backslashes \, and a backslash is placed before each quotation mark.

how to count the total number of lines in a text file using python

You can use sum() with a generator expression here. The generator expression will be [1, 1, ...] up to the length of the file. Then we call sum() to add them all together, to get the total count.

with open('text.txt') as myfile:
    count = sum(1 for line in myfile)

It seems by what you have tried that you don't want to include empty lines. You can then do:

with open('text.txt') as myfile:
    count = sum(1 for line in myfile if line.rstrip('\n'))

How do you Hover in ReactJS? - onMouseLeave not registered during fast hover over

I had a similar issue when onMouseEnter was called but sometimes the corresponding onMouseLeave event wasn't fired, here is a workaround that works well for me (it partially relies on jQuery):

var Hover = React.createClass({
    getInitialState: function() {
        return {
            hover: false
        };
    },
    onMouseEnterHandler: function(e) {
        this.setState({
            hover: true
        });
        console.log('enter');

        $(e.currentTarget).one("mouseleave", function (e) {
            this.onMouseLeaveHandler();
        }.bind(this));

    },
    onMouseLeaveHandler: function() {
        this.setState({
            hover: false
        });
        console.log('leave');
    },
    render: function() {
        var inner = normal;
        if(this.state.hover) {
            inner = hover;
        }

        return (
            <div style={outer}>
                <div style={inner}
                    onMouseEnter={this.onMouseEnterHandler} >
                    {this.props.children}
                </div>
            </div>
        );
    }
});

See on jsfiddle: http://jsfiddle.net/qtbr5cg6/1/


Why was it happening (in my case): I am running a jQuery scrolling animation (through $('#item').animate({ scrollTop: 0 })) when clicking on the item. So the cursor doesn't leave the item "naturally", but during a the JavaScript-driven animation ... and in this case the onMouseLeave was not fired properly by React (React 15.3.0, Chrome 51, Desktop)

TypeScript and React - children type?

These answers appear to be outdated - React now has a built in type PropsWithChildren<{}>. It is defined similarly to some of the correct answers on this page:

type PropsWithChildren<P> = P & { children?: ReactNode };

What are projection and selection?

Simply PROJECTION deals with elimination or selection of columns, while SELECTION deals with elimination or selection of rows.

What Regex would capture everything from ' mark to the end of a line?

https://regex101.com/r/Jjc2xR/1

/(\w*\(Hex\): w*)(.*?)(?= |$)/gm

I'm sure this one works, it will capture de hexa serial in the badly structured text multilined bellow

     Space Reservation: disabled
         Serial Number: wCVt1]IlvQWv
   Serial Number (Hex): 77435674315d496c76515776
               Comment: new comment

I'm a eternal newbie in regex but I'll try explain this one

(\w*(Hex): w*) : Find text in line where string contains "Hex: "

(.*?) This is the second captured text and means everything after

(?= |$) create a limit that is the space between = and the |

So with the second group, you will have the value

writing a batch file that opens a chrome URL

assuming chrome is his default browser: start http://url.site.you.com/path/to/joke should open that url in his browser.

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

Parsing date string in Go

Use the exact layout numbers described here and a nice blogpost here.

so:

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC

I know. Mind boggling. Also caught me first time. Go just doesn't use an abstract syntax for datetime components (YYYY-MM-DD), but these exact numbers (I think the time of the first commit of go Nope, according to this. Does anyone know?).

Create a file from a ByteArrayOutputStream

You can use a FileOutputStream for this.

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(new File("myFile")); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Put data in your baos

    baos.writeTo(fos);
} catch(IOException ioe) {
    // Handle exception here
    ioe.printStackTrace();
} finally {
    fos.close();
}

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

For those who work with AX 2012 AIF services and try to call there C# or VB project inside AX (x++) and suffer from such errors of "could not find default endpoint"... or "no contract found" ... go back to your visual studio (c#) project and add these lines before defining your service client, then deploy the project and restart AX client and retry: Note, the example is for NetTcp adapter, you could easily use any other adapter instead according to your need.

 Uri Address = new Uri("net.tcp://your-server:Port>/DynamicsAx/Services/your-port-name");
 NetTcpBinding Binding = new NetTcpBinding();
 EndpointAddress EndPointAddr = new EndpointAddress(Address);
 SalesOrderServiceClient Client = new SalesOrderServiceClient(Binding, EndPointAddr);

Correct way to pass multiple values for same parameter name in GET request

I would suggest looking at how browsers handle forms by default. For example take a look at the form element <select multiple> and how it handles multiple values from this example at w3schools.

<form action="/action_page.php">
<select name="cars" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<input type="submit">
</form>

For PHP use:

<select name="cars[]" multiple>

Live example from above at w3schools.com

From above if you click "saab, opel" and click submit, it will generate a result of cars=saab&cars=opel. Then depending on the back-end server, the parameter cars should come across as an array that you can further process.

Hope this helps anyone looking for a more 'standard' way of handling this issue.

How do I use Join-Path to combine more than two strings into a file path?

You can use the .NET Path class:

[IO.Path]::Combine('C:\', 'Foo', 'Bar')

How do I parse an ISO 8601-formatted date?

Note in Python 2.6+ and Py3K, the %f character catches microseconds.

>>> datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")

See issue here

What is the difference between IEnumerator and IEnumerable?

IEnumerable and IEnumerator are both interfaces. IEnumerable has just one method called GetEnumerator. This method returns (as all methods return something including void) another type which is an interface and that interface is IEnumerator. When you implement enumerator logic in any of your collection class, you implement IEnumerable (either generic or non generic). IEnumerable has just one method whereas IEnumerator has 2 methods (MoveNext and Reset) and a property Current. For easy understanding consider IEnumerable as a box that contains IEnumerator inside it (though not through inheritance or containment). See the code for better understanding:

class Test : IEnumerable, IEnumerator
{
    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    public object Current
    {
        get { throw new NotImplementedException(); }
    }

    public bool MoveNext()
    {
        throw new NotImplementedException();
    }

    public void Reset()
    {
        throw new NotImplementedException();
    }
}

Show pop-ups the most elegant way

Angular-ui comes with dialog directive.Use it and set templateurl to whatever page you want to include.That is the most elegant way and i have used it in my project as well. You can pass several other parameters for dialog as per need.

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    ORDER BY RAND()
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.

WooCommerce: Finding the products in database

I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta table. You can find the corresponding products within wp_posts table.

Angular expression if array contains

You can accomplish this with a slightly different syntax:

ng-class="{'approved': selectedForApproval.indexOf(jobSet) === -1}"

Plnkr

Read XML Attribute using XmlDocument

You can migrate to XDocument instead of XmlDocument and then use Linq if you prefer that syntax. Something like:

var q = (from myConfig in xDoc.Elements("MyConfiguration")
         select myConfig.Attribute("SuperString").Value)
         .First();

ORA-01843 not a valid month- Comparing Dates

Just in case this helps, I solved this by checking the server date format:

SELECT * FROM nls_session_parameters WHERE parameter = 'NLS_DATE_FORMAT';

then by using the following comparison (the left field is a date+time):

AND EV_DTTM >= ('01-DEC-16')

I was trying this with TO_DATE but kept getting an error. But when I matched my string with the NLS_DATE_FORMAT and removed TO_DATE, it worked...

PHP: How to check if image file exists?

If the file is on your local domain, you don't need to put the full URL. Only the path to the file. If the file is in a different directory, then you need to preface the path with "."

$file = './images/image.jpg';
if (file_exists($file)) {}

Often times the "." is left off which will cause the file to be shown as not existing, when it in fact does.

How to create a dump with Oracle PL/SQL Developer?

There are some easy steps to make Dump file of your Tables,Users and Procedures:

Goto sqlplus or any sql*plus connect by your username or password

  1. Now type host it looks like SQL>host.
  2. Now type "exp" means export.
  3. It ask u for username and password give the username and password of that user of which you want to make a dump file.
  4. Now press Enter.
  5. Now option blinks for Export file: EXPDAT.DMP>_ (Give a path and file name to where you want to make a dump file e.g e:\FILENAME.dmp) and the press enter
  6. Select the option "Entire Database" or "Tables" or "Users" then press Enter
  7. Again press Enter 2 more times table data and compress extent
  8. Enter the name of table like i want to make dmp file of table student existing so type student and press Enter
  9. Enter to quit now your file at your given path is dump file now import that dmp file to get all the table data.

Running ASP.Net on a Linux based server

It depends what specific .NET technologies you're using. The Mono Project provides an Apache module (mod_mono) for running ASP.NET sites, and from what I gather it works well.

Mono doesn't support all the .NET APIs, though - notably WPF (and possibly WCF too, I can't remember) - but it does provide good support for much else of the framework.

If you're starting from scratch and particularly want to target non-Windows servers, then ensuring your project works with Mono would be a good goal to aim for. However, if you need particular APIs or language features that are not supported by Mono, then you will need to use a Windows server for deployment. It's a design-time/architectural choice that should make up front.

Populate nested array in mongoose

That works for me:

 Project.find(query)
  .lean()
  .populate({ path: 'pages' })
  .exec(function(err, docs) {

    var options = {
      path: 'pages.components',
      model: 'Component'
    };

    if (err) return res.json(500);
    Project.populate(docs, options, function (err, projects) {
      res.json(projects);
    });
  });

Documentation: Model.populate

Bootstrap css hides portion of container below navbar navbar-fixed-top

Just define an empty navbar prior to the fixed one, it will create the space needed.

<nav class="navbar navbar-default ">
</nav>
<nav class="navbar  navbar-default navbar-fixed-top ">
     <div class="container-fluid">
// Your menu code 
     </div>
</nav>

How to read file from res/raw by name

With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

To get it as a InputStream

InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));

How to remove text from a string?

Using match() and Number() to return a number variable:

Number(("data-123").match(/\d+$/));

// strNum = 123

Here's what the statement above does...working middle-out:

  1. str.match(/\d+$/) - returns an array containing matches to any length of numbers at the end of str. In this case it returns an array containing a single string item ['123'].
  2. Number() - converts it to a number type. Because the array returned from .match() contains a single element Number() will return the number.

PowerShell: Format-Table without headers

Try the -HideTableHeaders parameter to Format-Table:

gci | ft -HideTableHeaders

(I'm using PowerShell v2. I don't know if this was in v1.)

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I solved this error

A connection attempt failed with "ECONNREFUSED - Connection refused by server"

by changing my port to 22 that was successful

Define the selected option with the old input in Laravel / Blade

this will help you , just compare with old if exist , if not then compare with the default value

<select name="select_name">
    @foreach($options as $key => $text)
       <option {{ ($key == old('select_name',$default))?'selected':'' }}> {{ $text }} </option>
    @endforeach
</select>

the $default is the value that injected from the controller to the view

Python constructor and default value

Let's illustrate what's happening here:

Python 3.1.2 (r312:79147, Sep 27 2010, 09:45:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def __init__(self, x=[]):
...         x.append(1)
... 
>>> Foo.__init__.__defaults__
([],)
>>> f = Foo()
>>> Foo.__init__.__defaults__
([1],)
>>> f2 = Foo()
>>> Foo.__init__.__defaults__
([1, 1],)

You can see that the default arguments are stored in a tuple which is an attribute of the function in question. This actually has nothing to do with the class in question and goes for any function. In python 2, the attribute will be func.func_defaults.

As other posters have pointed out, you probably want to use None as a sentinel value and give each instance it's own list.

Resize on div element

You can change your text or Content or Attribute depend on Screen size: HTML:

<p class="change">Frequently Asked Questions (FAQ)</p>
<p class="change">Frequently Asked Questions </p>

Javascript:

<script>
const changeText = document.querySelector('.change');
function resize() {
  if((window.innerWidth<500)&&(changeText.textContent="Frequently Asked Questions (FAQ)")){
    changeText.textContent="FAQ";
  } else {
    changeText.textContent="Frequently Asked Questions (FAQ)";
  }
}
window.onresize = resize;
</script>

Powershell remoting with ip-address as target

On your machine* run 'Set-Item WSMan:\localhost\Client\TrustedHosts -Value "$ipaddress"

*Machine from where you are running PSSession

How to get main window handle from process id?

Just to make sure you are not confusing the tid (thread id) and the pid (process id):

DWORD pid;
DWORD tid = GetWindowThreadProcessId( this->m_hWnd, &pid);

Cannot install node modules that require compilation on Windows 7 x64/VS2012

on windows 8, it worked for me using :

npm install -g node-gyp -msvs_version=2012

then

npm install -g restify

getResourceAsStream returns null

What worked for me was to add the file under My Project/Java Resources/src and then use

this.getClass().getClassLoader().getResourceAsStream("myfile.txt");

I didn't need to explicitly add this file to the path (adding it to /src does that apparently)

jQuery select child element by class with unknown path

According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector) is the fastest and most efficient way to do this.

Find if value in column A contains value from column B?

You can try this. :) simple solution!

=IF(ISNUMBER(MATCH(I1,E:E,0)),"TRUE","")

importing a CSV into phpmyadmin

In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :

enter image description here

Virtualbox "port forward" from Guest to Host

That's not possible. localhost always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.

If you want to access it e.g. in a browser, connect to it using the local IP instead:

http://192.168.180.1:8000

This is just an example of course, you can find out the actual IP by issuing an ifconfig command on a shell in the guest operating system.

Eloquent Collection: Counting and Detect Empty

------SOLVED------

in this case you want to check two type of count for two cace

case 1:

if result contain only one record other word select single row from database using ->first()

 if(count($result)){
     
       ...record is exist true...
  }

case 2:

if result contain set of multiple row other word using ->get() or ->all()

  if($result->count()) {
    
         ...record is exist true...
  }