Programs & Examples On #Linq to entities

This tag is for questions about LINQ to Entities, which means LINQ queries using the ADO.NET Entity Framework. Note that this is different than LINQ to SQL or other LINQ providers.

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

I use this method:

var results = this.Database.SqlQuery<yourEntity>("EXEC [ent].[GetNextExportJob] {0}", ProcessorID);

I like it because I just drop in Guids and Datetimes and SqlQuery performs all the formatting for me.

Entity framework left join

For 2 and more left joins (left joining creatorUser and initiatorUser )

IQueryable<CreateRequestModel> queryResult = from r in authContext.Requests
                                             join candidateUser in authContext.AuthUsers
                                             on r.CandidateId equals candidateUser.Id
                                             join creatorUser in authContext.AuthUsers
                                             on r.CreatorId equals creatorUser.Id into gj
                                             from x in gj.DefaultIfEmpty()
                                             join initiatorUser in authContext.AuthUsers
                                             on r.InitiatorId equals initiatorUser.Id into init
                                             from x1 in init.DefaultIfEmpty()

                                             where candidateUser.UserName.Equals(candidateUsername)
                                             select new CreateRequestModel
                                             {
                                                 UserName = candidateUser.UserName,
                                                 CreatorId = (x == null ? String.Empty : x.UserName),
                                                 InitiatorId = (x1 == null ? String.Empty : x1.UserName),
                                                 CandidateId = candidateUser.UserName
                                             };

The cast to value type 'Int32' failed because the materialized value is null

You are using aggregate function which not getting the items to perform action , you must verify linq query is giving some result as below:

var maxOrderLevel =sdv.Any()? sdv.Max(s => s.nOrderLevel):0

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

Upgraded from EF5 to EF6 nuget a while back and kept encountering this issue. I'd temp fix it by updating the generated code to reference System.Data.Entity.Core.Objects, but after generation it would be changed back again (as expected since its generated).

This solved the problem for good:

http://msdn.microsoft.com/en-us/data/upgradeef6

If you have any models created with the EF Designer, you will need to update the code generation templates to generate EF6 compatible code. Note: There are currently only EF 6.x DbContext Generator templates available for Visual Studio 2012 and 2013.

  1. Delete existing code-generation templates. These files will typically be named <edmx_file_name>.tt and <edmx_file_name>.Context.tt and be nested under your edmx file in Solution Explorer. You can select the templates in Solution Explorer and press the Del key to delete them.
    Note: In Web Site projects the templates will not be nested under your edmx file, but listed alongside it in Solution Explorer.
    Note: In VB.NET projects you will need to enable 'Show All Files' to be able to see the nested template files.
  2. Add the appropriate EF 6.x code generation template. Open your model in the EF Designer, right-click on the design surface and select Add Code Generation Item...
    • If you are using the DbContext API (recommended) then EF 6.x DbContext Generator will be available under the Data tab.
      Note: If you are using Visual Studio 2012, you will need to install the EF 6 Tools to have this template. See Get Entity Framework for details.
    • If you are using the ObjectContext API then you will need to select the Online tab and search for EF 6.x EntityObject Generator.
  3. If you applied any customizations to the code generation templates you will need to re-apply them to the updated templates.

How to compare only date components from DateTime in EF?

NOTE: at the time of writing this answer, the EF-relation was unclear (that was edited into the question after this was written). For correct approach with EF, check Mandeeps answer.


You can use the DateTime.Date property to perform a date-only comparison.

DateTime a = GetFirstDate();
DateTime b = GetSecondDate();

if (a.Date.Equals(b.Date))
{
    // the dates are equal
}

How to do SQL Like % in Linq?

.NET core now has EF.Functions.Like

  var isMatch = EF.Functions.Like(stringThatMightMatch, pattern);

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

In my case, I was getting this error message only in Production but not when run locally, even though my application's binaries were identical.

In my application, I'm using a custom DbModelStore so that the runtime-generated EDMX is saved to disk and loaded from disk on startup (instead of regenerating it from scratch) to reduce application startup time - and due to a bug in my code I wasn't invalidating the EDMX file on-disk - so Production was using an older version of the EDMX file from disk that referenced an older version of my application's types from before I renamed the type-name in the exception error message.

Deleting the cache file and restarting the application fixed it.

LEFT JOIN in LINQ to entities?

Ah, got it myselfs.
The quirks and quarks of LINQ-2-entities.
This looks most understandable:

var query2 = (
    from users in Repo.T_Benutzer
    from mappings in Repo.T_Benutzer_Benutzergruppen
        .Where(mapping => mapping.BEBG_BE == users.BE_ID).DefaultIfEmpty()
    from groups in Repo.T_Benutzergruppen
        .Where(gruppe => gruppe.ID == mappings.BEBG_BG).DefaultIfEmpty()
    //where users.BE_Name.Contains(keyword)
    // //|| mappings.BEBG_BE.Equals(666)  
    //|| mappings.BEBG_BE == 666 
    //|| groups.Name.Contains(keyword)

    select new
    {
         UserId = users.BE_ID
        ,UserName = users.BE_User
        ,UserGroupId = mappings.BEBG_BG
        ,GroupName = groups.Name
    }

);


var xy = (query2).ToList();

Remove the .DefaultIfEmpty(), and you get an inner join.
That was what I was looking for.

"NOT IN" clause in LINQ to Entities

I have the following extension methods:

    public static bool IsIn<T>(this T keyObject, params T[] collection)
    {
        return collection.Contains(keyObject);
    }

    public static bool IsIn<T>(this T keyObject, IEnumerable<T> collection)
    {
        return collection.Contains(keyObject);
    }

    public static bool IsNotIn<T>(this T keyObject, params T[] collection)
    {
        return keyObject.IsIn(collection) == false;
    }

    public static bool IsNotIn<T>(this T keyObject, IEnumerable<T> collection)
    {
        return keyObject.IsIn(collection) == false;
    }

Usage:

var inclusionList = new List<string> { "inclusion1", "inclusion2" };
var query = myEntities.MyEntity
                     .Select(e => e.Name)
                     .Where(e => e.IsIn(inclusionList));

var exceptionList = new List<string> { "exception1", "exception2" };
var query = myEntities.MyEntity
                     .Select(e => e.Name)
                     .Where(e => e.IsNotIn(exceptionList));

Very useful as well when passing values directly:

var query = myEntities.MyEntity
                     .Select(e => e.Name)
                     .Where(e => e.IsIn("inclusion1", "inclusion2"));

var query = myEntities.MyEntity
                     .Select(e => e.Name)
                     .Where(e => e.IsNotIn("exception1", "exception2"));

inner join in linq to entities

public IList<Splitting> get(Guid companyId, long customrId) {    
    var res=from c in Customers_data_source
            where c.CustomerId = customrId && c.CompanyID == companyId
            from s in Splittings_data_srouce
            where s.CustomerID = c.CustomerID
            select s;

    return res.ToList();
}

Like Operator in Entity Framework?

You can use a real like in Link to Entities quite easily

Add

    <Function Name="String_Like" ReturnType="Edm.Boolean">
      <Parameter Name="searchingIn" Type="Edm.String" />
      <Parameter Name="lookingFor" Type="Edm.String" />
      <DefiningExpression>
        searchingIn LIKE lookingFor
      </DefiningExpression>
    </Function>

to your EDMX in this tag:

edmx:Edmx/edmx:Runtime/edmx:ConceptualModels/Schema

Also remember the namespace in the <schema namespace="" /> attribute

Then add an extension class in the above namespace:

public static class Extensions
{
    [EdmFunction("DocTrails3.Net.Database.Models", "String_Like")]
    public static Boolean Like(this String searchingIn, String lookingFor)
    {
        throw new Exception("Not implemented");
    }
}

This extension method will now map to the EDMX function.

More info here: http://jendaperl.blogspot.be/2011/02/like-in-linq-to-entities.html

Linq to Entities join vs groupjoin

Behaviour

Suppose you have two lists:

Id  Value
1   A
2   B
3   C

Id  ChildValue
1   a1
1   a2
1   a3
2   b1
2   b2

When you Join the two lists on the Id field the result will be:

Value ChildValue
A     a1
A     a2
A     a3
B     b1
B     b2

When you GroupJoin the two lists on the Id field the result will be:

Value  ChildValues
A      [a1, a2, a3]
B      [b1, b2]
C      []

So Join produces a flat (tabular) result of parent and child values.
GroupJoin produces a list of entries in the first list, each with a group of joined entries in the second list.

That's why Join is the equivalent of INNER JOIN in SQL: there are no entries for C. While GroupJoin is the equivalent of OUTER JOIN: C is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null).

Syntax

So let the two lists be IEnumerable<Parent> and IEnumerable<Child> respectively. (In case of Linq to Entities: IQueryable<T>).

Join syntax would be

from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }

returning an IEnumerable<X> where X is an anonymous type with two properties, Value and ChildValue. This query syntax uses the Join method under the hood.

GroupJoin syntax would be

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

returning an IEnumerable<Y> where Y is an anonymous type consisting of one property of type Parent and a property of type IEnumerable<Child>. This query syntax uses the GroupJoin method under the hood.

We could just do select g in the latter query, which would select an IEnumerable<IEnumerable<Child>>, say a list of lists. In many cases the select with the parent included is more useful.

Some use cases

1. Producing a flat outer join.

As said, the statement ...

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:

from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty()               // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }

The result is similar to

Value Child
A     a1
A     a2
A     a3
B     b1
B     b2
C     (null)

Note that the range variable c is reused in the above statement. Doing this, any join statement can simply be converted to an outer join by adding the equivalent of into g from c in g.DefaultIfEmpty() to an existing join statement.

This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:

parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
       .SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )

So a flat outer join in LINQ is a GroupJoin, flattened by SelectMany.

2. Preserving order

Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id values in a fixed order. Let's use:

var ids = new[] { 3,7,2,4 };

Now the selected parents must be filtered from the parents list in this exact order.

If we do ...

var result = parents.Where(p => ids.Contains(p.Id));

... the order of parents will determine the result. If the parents are ordered by Id, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join to filter the list. And by using ids as first list, the order will be preserved:

from id in ids
join p in parents on id equals p.Id
select p

The result is parents 3, 7, 2, 4.

SQL to Entity Framework Count Group-By

Here is a simple example of group by in .net core 2.1

var query = this.DbContext.Notifications.
            Where(n=> n.Sent == false).
            GroupBy(n => new { n.AppUserId })
            .Select(g => new { AppUserId = g.Key, Count =  g.Count() });

var query2 = from n in this.DbContext.Notifications
            where n.Sent == false
            group n by n.AppUserId into g
            select new { id = g.Key,  Count = g.Count()};

Which translates to:

SELECT [n].[AppUserId], COUNT(*) AS [Count]
FROM [Notifications] AS [n]
WHERE [n].[Sent] = 0
GROUP BY [n].[AppUserId]

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

I would like to add a solution, that have helpt me to solve this problem in entity framework:

var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
                .Where(x =>  x.DateTimeStart.Year == currentDateTime.Year &&
                             x.DateTimeStart.Month== currentDateTime.Month &&
                             x.DateTimeStart.Day == currentDateTime.Day
    );

I hope that it helps.

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

your question is basically O/RM's vs hand writing SQL

Using an ORM or plain SQL?

Take a look at some of the other O/RM solutions out there, L2S isn't the only one (NHibernate, ActiveRecord)

http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software

to address the specific questions:

  1. Depends on the quality of the O/RM solution, L2S is pretty good at generating SQL
  2. This is normally much faster using an O/RM once you grok the process
  3. Code is also usually much neater and more maintainable
  4. Straight SQL will of course get you more flexibility, but most O/RM's can do all but the most complicated queries
  5. Overall I would suggest going with an O/RM, the flexibility loss is negligable

How to get first record in each group using Linq

    var res = from element in list
              group element by element.F1
                  into groups
                  select groups.OrderBy(p => p.F2).First();

"A lambda expression with a statement body cannot be converted to an expression tree"

You can use statement body in lamba expression for IEnumerable collections. try this one:

Obj[] myArray = objects.AsEnumerable().Select(o =>
{
    var someLocalVar = o.someVar;

    return new Obj() 
    { 
        Var1 = someLocalVar,
        Var2 = o.var2 
    };
}).ToArray();

Notice:
Think carefully when using this method, because this way, you will have all query result in memory, that may have unwanted side effects on the rest of your code.

How to add a default "Select" option to this ASP.NET DropDownList control?

The reason it is not working is because you are adding an item to the list and then overriding the whole list with a new DataSource which will clear and re-populate your list, losing the first manually added item.

So, you need to do this in reverse like this:

Status status = new Status();
DropDownList1.DataSource = status.getData();
DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Description";
DropDownList1.DataBind();

// Then add your first item
DropDownList1.Items.Insert(0, "Select");

How do I get the max ID with Linq to Entity?

var max = db.Users.DefaultIfEmpty().Max(r => r == null ? 0 : r.ModelID);

when there are no records in db it would return 0 with no exception.

LINQ to Entities how to update a record

Just modify one of the returned entities:

Customer c = (from x in dataBase.Customers
             where x.Name == "Test"
             select x).First();
c.Name = "New Name";
dataBase.SaveChanges();

Note, you can only update an entity (something that extends EntityObject, not something that you have projected using something like select new CustomObject{Name = x.Name}

Linq to Entities - SQL "IN" clause

This should suffice your purpose. It compares two collections and checks if one collection has the values matching those in the other collection

fea_Features.Where(s => selectedFeatures.Contains(s.feaId))

Linq where clause compare only date value without time value

There is also EntityFunctions.TruncateTime or DbFunctions.TruncateTime in EF 6.0

Best way to check if object exists in Entity Framework?

From a performance point of view, I guess that a direct SQL query using the EXISTS command would be appropriate. See here for how to execute SQL directly in Entity Framework: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/25/execute-t-sql-statements-in-entity-framework-4.aspx

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

SonarQube reported Return an empty collection instead of null. and I had a problem with the error with casting as in the title of this question. I was able to get rid of both only using return XYZ.ToList().AsQueryable(); in a method with IQueryable like so:

public IQueryable<SomeType> MethodName (...) {
  IQueryable<SomeType> XYZ;
  ...
  return XYZ.ToList().AsQueryable();
}

Hope so it helps for those in a similar scenario(s).

Problem with converting int to string in Linq to entities

Brian Cauthon's answer is excellent! Just a little update, for EF 6, the class got moved to another namespace. So, before EF 6, you should include:

System.Data.Objects.SqlClient

If you update to EF 6, or simply are using this version, include:

System.Data.Entity.SqlServer

By including the incorrect namespace with EF6, the code will compile just fine but will throw a runtime error. I hope this note helps to avoid some confusion.

LINQ to Entities does not recognize the method

As you've figured out, Entity Framework can't actually run your C# code as part of its query. It has to be able to convert the query to an actual SQL statement. In order for that to work, you will have to restructure your query expression into an expression that Entity Framework can handle.

public System.Linq.Expressions.Expression<Func<Charity, bool>> IsSatisfied()
{
    string name = this.charityName;
    string referenceNumber = this.referenceNumber;
    return p => 
        (string.IsNullOrEmpty(name) || 
            p.registeredName.ToLower().Contains(name.ToLower()) ||
            p.alias.ToLower().Contains(name.ToLower()) ||
            p.charityId.ToLower().Contains(name.ToLower())) &&
        (string.IsNullOrEmpty(referenceNumber) ||
            p.charityReference.ToLower().Contains(referenceNumber.ToLower()));
}

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

Many SQL databases allow a table to contain a subtable as a component. The usual method is to allow the domain of one of the columns to be a table. This is in addition to using some convention like CSV to encode the substructure in ways unknown to the DBMS.

When Ed Codd was developing the relational model in 1969-1970, he specifically defined a normal form that would disallow this kind of nesting of tables. Normal form was later called First Normal Form. He then went on to show that for every database, there is a database in first normal form that expresses the same information.

Why bother with this? Well, databases in first normal form permit keyed access to all data. If you provide a table name, a key value into that table, and a column name, the database will contain at most one cell containing one item of data.

If you allow a cell to contain a list or a table or any other collection, now you can't provide keyed access to the sub items, without completely reworking the idea of a key.

Keyed access to all data is fundamental to the relational model. Without this concept, the model isn't relational. As to why the relational model is a good idea, and what might be the limitations of that good idea, you have to look at the 50 years worth of accumulated experience with the relational model.

Print newline in PHP in single quotes

You can use this:

echo 'Hello World' . "\n";

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

One solution for this can be found with find.

$ mkdir foo bar
$ touch foo/a.txt foo/Music.txt
$ find foo -type f ! -name '*Music*' -exec cp {} bar \;
$ ls bar
a.txt

Find has quite a few options, you can get pretty specific on what you include and exclude.

Edit: Adam in the comments noted that this is recursive. find options mindepth and maxdepth can be useful in controlling this.

No grammar constraints (DTD or XML schema) detected for the document

For me it was a Problem with character encoding and unix filemode running eclipse on Windows:

Just marked the complete code, cutted and pasted it back (in short: CtrlA-CtrlX-CtrlV) and everything was fine - no more "No grammar constraints..." warnings

Anaconda site-packages

I installed miniconda and found all the installed packages in /miniconda3/pkgs

How can I make a program wait for a variable change in javascript?

No you would have to create your own solution. Like using the Observer design pattern or something.

If you have no control over the variable or who is using it, I'm afraid you're doomed. EDIT: Or use Skilldrick's solution!

Mike

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

When you use @DataJpaTest you need to load classes using @Import explicitly. It wouldn't load you for auto.

How to delete items from a dictionary while iterating over it?

You can't modify a collection while iterating it. That way lies madness - most notably, if you were allowed to delete and deleted the current item, the iterator would have to move on (+1) and the next call to next would take you beyond that (+2), so you'd end up skipping one element (the one right behind the one you deleted). You have two options:

  • Copy all keys (or values, or both, depending on what you need), then iterate over those. You can use .keys() et al for this (in Python 3, pass the resulting iterator to list). Could be highly wasteful space-wise though.
  • Iterate over mydict as usual, saving the keys to delete in a seperate collection to_delete. When you're done iterating mydict, delete all items in to_delete from mydict. Saves some (depending on how many keys are deleted and how many stay) space over the first approach, but also requires a few more lines.

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Oracle will try to recompile invalid objects as they are referred to. Here the trigger is invalid, and every time you try to insert a row it will try to recompile the trigger, and fail, which leads to the ORA-04098 error.

You can select * from user_errors where type = 'TRIGGER' and name = 'NEWALERT' to see what error(s) the trigger actually gets and why it won't compile. In this case it appears you're missing a semicolon at the end of the insert line:

INSERT INTO Users (userID, firstName, lastName, password)
VALUES ('how', 'im', 'testing', 'this trigger')

So make it:

CREATE OR REPLACE TRIGGER newAlert
AFTER INSERT OR UPDATE ON Alerts
  BEGIN
        INSERT INTO Users (userID, firstName, lastName, password)
        VALUES ('how', 'im', 'testing', 'this trigger');
  END;           
/

If you get a compilation warning when you do that you can do show errors if you're in SQL*Plus or SQL Developer, or query user_errors again.

Of course, this assumes your Users tables does have those column names, and they are all varchar2... but presumably you'll be doing something more interesting with the trigger really.

How do you beta test an iphone app?

In 2014 along with iOS 8 and XCode 6 apple introduced Beta Testing of iOS App using iTunes Connect.

You can upload your build to iTunes connect and invite testers using their mail id's. You can invite up to 2000 external testers using just their email address. And they can install the beta app through TestFlight

Binding select element to object in Angular

You Can Select the Id using a Function

<option *ngFor="#c of countries" (change)="onchange(c.id)">{{c.name}}</option>

How to center align the cells of a UICollectionView?

Put this into your collection view delegate. It considers more of the the basic flow layout settings than the other answers and is thereby more generic.

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    NSInteger cellCount = [collectionView.dataSource collectionView:collectionView numberOfItemsInSection:section];
    if( cellCount >0 )
    {
        CGFloat cellWidth = ((UICollectionViewFlowLayout*)collectionViewLayout).itemSize.width+((UICollectionViewFlowLayout*)collectionViewLayout).minimumInteritemSpacing;
        CGFloat totalCellWidth = cellWidth*cellCount + spacing*(cellCount-1);
        CGFloat contentWidth = collectionView.frame.size.width-collectionView.contentInset.left-collectionView.contentInset.right;
        if( totalCellWidth<contentWidth )
        {
            CGFloat padding = (contentWidth - totalCellWidth) / 2.0;
            return UIEdgeInsetsMake(0, padding, 0, padding);
        }
    }
    return UIEdgeInsetsZero;
}

swift version (thanks g0ld2k):

extension CommunityConnectViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {

    // Translated from Objective-C version at: http://stackoverflow.com/a/27656363/309736

        let cellCount = CGFloat(viewModel.getNumOfItemsInSection(0))

        if cellCount > 0 {
            let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
            let cellWidth = flowLayout.itemSize.width + flowLayout.minimumInteritemSpacing
            let totalCellWidth = cellWidth*cellCount + spacing*(cellCount-1)
            let contentWidth = collectionView.frame.size.width - collectionView.contentInset.left - collectionView.contentInset.right

            if (totalCellWidth < contentWidth) {
                let padding = (contentWidth - totalCellWidth) / 2.0
                return UIEdgeInsetsMake(0, padding, 0, padding)
            }
        }

        return UIEdgeInsetsZero
    }
}

how to add script src inside a View when using Layout

Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.

_Layout

<!DOCTYPE html>
<html>
  <head>
    <title>...</title>
    <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
    @RenderSection("Scripts",false/*required*/)
  </head>
  <body>
    @RenderBody()
  </body>
</html>

View

@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
  <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}

Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script> declaration within the view.

Post order traversal of binary tree without recursion

I have not added the node class as its not particularly relevant or any test cases, leaving those as an excercise for the reader etc.

void postOrderTraversal(node* root)
{
    if(root == NULL)
        return;

    stack<node*> st;
    st.push(root);

    //store most recent 'visited' node
    node* prev=root;

    while(st.size() > 0)
    {
        node* top = st.top();
        if((top->left == NULL && top->right == NULL))
        {
            prev = top;
            cerr<<top->val<<" ";
            st.pop();
            continue;
        }
        else
        {
            //we can check if we are going back up the tree if the current
            //node has a left or right child that was previously outputted
            if((top->left == prev) || (top->right== prev))
            {
                prev = top;
                cerr<<top->val<<" ";
                st.pop();
                continue;
            }

            if(top->right != NULL)
                st.push(top->right);

            if(top->left != NULL)
                st.push(top->left);
        }
    }
    cerr<<endl;
}

running time O(n) - all nodes need to be visited AND space O(n) - for the stack, worst case tree is a single line linked list

CSS disable text selection

instead of body type a list of elements you want.

if checkbox is checked, do this

Optimal implementation

$('#checkbox').on('change', function(){
    $('p').css('color', this.checked ? '#09f' : '');
});

Demo

_x000D_
_x000D_
$('#checkbox').on('change', function(){_x000D_
    $('p').css('color', this.checked ? '#09f' : '');_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>_x000D_
<input id="checkbox" type="checkbox" /> _x000D_
<p>_x000D_
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do_x000D_
    eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
</p>_x000D_
<p>_x000D_
    Ut enim ad minim veniam, quis nostrud exercitation ullamco_x000D_
    laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
    dolor in reprehenderit in voluptate velit esse cillum dolore eu_x000D_
    fugiat nulla pariatur. Excepteur sint occaecat cupidatat non_x000D_
    proident, sunt in culpa qui officia deserunt mollit anim id est_x000D_
    laborum._x000D_
</p>
_x000D_
_x000D_
_x000D_

JS: Uncaught TypeError: object is not a function (onclick)

I was able to figure it out by following the answer in this thread: https://stackoverflow.com/a/8968495/1543447

Basically, I renamed all values, function names, and element names to different values so they wouldn't conflict - and it worked!

Java check to see if a variable has been initialized

Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {
    box.removeFromCanvas();
}

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:

if (box != null) {
    box.removeFromCanvas();
    // Forget about the box - we don't want to try to remove it again
    box = null;
}

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile
String x;
System.out.println(x);

// Will compile, prints null
String y = null;
System.out.println(y);

Create a date time with month and day only, no year

Well, you can create your own type - but a DateTime always has a full date and time. You can't even have "just a date" using DateTime - the closest you can come is to have a DateTime at midnight.

You could always ignore the year though - or take the current year:

// Consider whether you want DateTime.UtcNow.Year instead
DateTime value = new DateTime(DateTime.Now.Year, month, day);

To create your own type, you could always just embed a DateTime within a struct, and proxy on calls like AddDays etc:

public struct MonthDay : IEquatable<MonthDay>
{
    private readonly DateTime dateTime;

    public MonthDay(int month, int day)
    {
        dateTime = new DateTime(2000, month, day);
    }

    public MonthDay AddDays(int days)
    {
        DateTime added = dateTime.AddDays(days);
        return new MonthDay(added.Month, added.Day);
    }

    // TODO: Implement interfaces, equality etc
}

Note that the year you choose affects the behaviour of the type - should Feb 29th be a valid month/day value or not? It depends on the year...

Personally I don't think I would create a type for this - instead I'd have a method to return "the next time the program should be run".

jdk7 32 bit windows version to download

As detailed in the Oracle Java SE Support Roadmap

After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive

Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe (64-bit is named jdk-7u80-windows-x64.exe.

Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget to grab the file without signing in.

wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

If it's important you really need to benchmark both options!

Having said that, I have always used the exception method, the reasoning being it's better to only hit the database once.

Android: How to overlay a bitmap and draw over a bitmap?

I think this example will definitely help you overlay a transparent image on top of another image. This is made possible by drawing both the images on canvas and returning a bitmap image.

Read more or download demo here

private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){

        Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(firstImage, 0f, 0f, null);
        canvas.drawBitmap(secondImage, 10, 10, null);
        return result;
    }

and call the above function on button click and pass the two images to our function as shown below

public void buttonMerge(View view) {

        Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
        Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
        Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);

        img.setImageBitmap(mergedImages);
    }

For more than two images, you can follow this link, how to merge multiple images programmatically on android

jQuery - Appending a div to body, the body is the object?

$('</div>').attr('id', 'holdy').appendTo('body');

Apache shows PHP code instead of executing it

Alright if you've tried what you've been told above or earlier(which are possible reasons) and it still displays the code instead of executing it then there is one thing which you are doing wrong that hasn't been addressed. The url you used to access your php code; some people try to execute their php code by just dragging the .php file into the web browser. this is wrong practice and could lead to this kind of problem. if you have saved a file as "test.php" in the C://wamp/www folder then you must access this file this way: localhost://test.php. this kind of mistake will arise when you access it this way: localhost://wamp/www/test.php

Hope I helped someone out there. o/ ~Daniel

NodeJS - Error installing with NPM

gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT HON env variable.

This means the Python env. variable should point to the executable python file, in my case: SET PYTHON=C:\work\_env\Python27\python.exe

Changing route doesn't scroll to top in the new page

All of the answers above break expected browser behavior. What most people want is something that will scroll to the top if it's a "new" page, but return to the previous position if you're getting there through the Back (or Forward) button.

If you assume HTML5 mode, this turns out to be easy (although I'm sure some bright folks out there can figure out how to make this more elegant!):

// Called when browser back/forward used
window.onpopstate = function() { 
    $timeout.cancel(doc_scrolling); 
};

// Called after ui-router changes state (but sadly before onpopstate)
$scope.$on('$stateChangeSuccess', function() {
    doc_scrolling = $timeout( scroll_top, 50 );

// Moves entire browser window to top
scroll_top = function() {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
}

The way it works is that the router assumes it is going to scroll to the top, but delays a bit to give the browser a chance to finish up. If the browser then notifies us that the change was due to a Back/Forward navigation, it cancels the timeout, and the scroll never occurs.

I used raw document commands to scroll because I want to move to the entire top of the window. If you just want your ui-view to scroll, then set autoscroll="my_var" where you control my_var using the techniques above. But I think most people will want to scroll the entire page if you are going to the page as "new".

The above uses ui-router, though you could use ng-route instead by swapping $routeChangeSuccess for$stateChangeSuccess.

Cannot create SSPI context

It sounds like your PC hasn't contacted an authenticating domain controller for a little while. (I used to have this happen on my laptop a few times.)

It can also happen if your password expires.

How to fill color in a cell in VBA?

  1. Use conditional formatting instead of VBA to highlight errors.

  2. Using a VBA loop like the one you posted will take a long time to process

  3. the statement If cell.Value = "#N/A" Then will never work. If you insist on using VBA to highlight errors, try this instead.

    Sub ColorCells()

    Dim Data As Range
    Dim cell As Range
    Set currentsheet = ActiveWorkbook.Sheets("Comparison")
    Set Data = currentsheet.Range("A2:AW1048576")
    
    For Each cell In Data
    
    If IsError(cell.Value) Then
       cell.Interior.ColorIndex = 3
    End If
    Next
    
    End Sub
    
  4. Be prepared for a long wait, since the procedure loops through 51 million cells

  5. There are more efficient ways to achieve what you want to do. Update your question if you have a change of mind.

How to get the last char of a string in PHP?

Siemano, get only php files from selected directory:

$dir    = '/home/zetdoa/ftp/domeny/MY_DOMAIN/projekty/project';
$files = scandir($dir, 1);


foreach($files as $file){
  $n = substr($file, -3);
  if($n == 'php'){
    echo $file.'<br />';
  }
}

How do I properly compare strings in C?

Whenever you are trying to compare the strings, compare them with respect to each character. For this you can use built in string function called strcmp(input1,input2); and you should use the header file called #include<string.h>

Try this code:

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h>  

int main() 
{ 
    char s[]="STACKOVERFLOW";
    char s1[200];
    printf("Enter the string to be checked\n");//enter the input string
    scanf("%s",s1);
    if(strcmp(s,s1)==0)//compare both the strings  
    {
        printf("Both the Strings match\n"); 
    } 
    else
    {
        printf("Entered String does not match\n");  
    } 
    system("pause");  
} 

MySQL - how to front pad zip code with "0"?

It would still make sense to create your zip code field as a zerofilled unsigned integer field.

CREATE TABLE xxx ( zipcode INT(5) ZEROFILL UNSIGNED, ... )

That way mysql takes care of the padding for you.

How to know/change current directory in Python shell?

The easiest way to change the current working directory in python is using the 'os' package. Below there is an example for windows computer:

# Import the os package
import os

# Confirm the current working directory 
os.getcwd()

# Use '\\' while changing the directory 
os.chdir("C:\\user\\foldername")

How to markdown nested list items in Bitbucket?

Even a single space works

...Just open this answer for edit to see it.

Nested lists, deeper levels: ---- leave here an empty row * first level A item - no space in front the bullet character * second level Aa item - 1 space is enough * third level Aaa item - 5 spaces min * second level Ab item - 4 spaces possible too * first level B item

Nested lists, deeper levels:

  • first level A item - no space in front the bullet character
    • second level Aa item - 1 space is enough
      • third level Aaa item - 5 spaces min
    • second level Ab item - 4 spaces possible too
  • first level B item

    Nested lists, deeper levels:
     ...Skip a line and indent eight spaces. (as said in the editor-help, just on this page)
    * first level A item - no space in front the bullet character
     * second level Aa item - 1 space is enough
         * third level Aaa item - 5 spaces min
        * second level Ab item - 4 spaces possible too
    * first level B item
    

How to iterate over associative arrays in Bash

Use this higher order function to prevent the pyramid of doom

foreach(){ 
  arr="$(declare -p $1)" ; eval "declare -A f="${arr#*=}; 
  for i in ${!f[@]}; do $2 "$i" "${f[$i]}"; done
}

example:

$ bar(){ echo "$1 -> $2"; }
$ declare -A foo["flap"]="three four" foo["flop"]="one two"
$ foreach foo bar
flap -> three four
flop -> one two

Clear form after submission with jQuery

You can reset your form with:

$("#myform")[0].reset();

How to disable textbox from editing?

        textBox1.Enabled = false;

"false" property will make the text box disable. and "true" will make it in regular form. Thanks.

Split string into strings by length?

My solution

   st =' abs de fdgh  1234 556 shg shshh'
   print st

   def splitStringMax( si, limit):
    ls = si.split()
    lo=[]
    st=''
    ln=len(ls)
    if ln==1:
        return [si]
    i=0
    for l in ls:
        st+=l
        i+=1
        if i <ln:
            lk=len(ls[i])
            if (len(st))+1+lk < limit:
                st+=' '
                continue
        lo.append(st);st=''
    return lo

   ############################

   print  splitStringMax(st,7)
   # ['abs de', 'fdgh', '1234', '556', 'shg', 'shshh']
    print  splitStringMax(st,12)

   # ['abs de fdgh', '1234 556', 'shg shshh']

Pandas timeseries plot setting x-axis major and minor ticks and labels

Both pandas and matplotlib.dates use matplotlib.units for locating the ticks.

But while matplotlib.dates has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).

So for the moment it seems more reasonable to use matplotlib.dates (as mentioned by @BrenBarn in his comment).

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt 
import matplotlib.dates as dates

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

pandas_like_date_fomatting

(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])

Excel - match data from one range to another and get the value from the cell to the right of the matched data

Here is how I used the formula from chuffs' solution:

In Sheet1, column C5, I have first names from one list and answers to a survey, but no email address. In sheet two, column A1 and C1, I have first names and email addresses, but no answers to the survey. I need email addresses and answers to the survey for my project.

With this formula I was able to get the solution as follows, putting the matched email addresses in column A1 of sheet 1.

=IFERROR(VLOOKUP(C5,Sheet1!$A$2:$C$654,3,0),"")

How to test Spring Data repositories?

tl;dr

To make it short - there's no way to unit test Spring Data JPA repositories reasonably for a simple reason: it's way to cumbersome to mock all the parts of the JPA API we invoke to bootstrap the repositories. Unit tests don't make too much sense here anyway, as you're usually not writing any implementation code yourself (see the below paragraph on custom implementations) so that integration testing is the most reasonable approach.

Details

We do quite a lot of upfront validation and setup to make sure you can only bootstrap an app that has no invalid derived queries etc.

  • We create and cache CriteriaQuery instances for derived queries to make sure the query methods do not contain any typos. This requires working with the Criteria API as well as the meta.model.
  • We verify manually defined queries by asking the EntityManager to create a Query instance for those (which effectively triggers query syntax validation).
  • We inspect the Metamodel for meta-data about the domain types handled to prepare is-new checks etc.

All stuff that you'd probably defer in a hand-written repository which might cause the application to break at runtime (due to invalid queries etc.).

If you think about it, there's no code you write for your repositories, so there's no need to write any unittests. There's simply no need to as you can rely on our test base to catch basic bugs (if you still happen to run into one, feel free to raise a ticket). However, there's definitely need for integration tests to test two aspects of your persistence layer as they are the aspects that related to your domain:

  • entity mappings
  • query semantics (syntax is verified on each bootstrap attempt anyway).

Integration tests

This is usually done by using an in-memory database and test cases that bootstrap a Spring ApplicationContext usually through the test context framework (as you already do), pre-populate the database (by inserting object instances through the EntityManager or repo, or via a plain SQL file) and then execute the query methods to verify the outcome of them.

Testing custom implementations

Custom implementation parts of the repository are written in a way that they don't have to know about Spring Data JPA. They are plain Spring beans that get an EntityManager injected. You might of course wanna try to mock the interactions with it but to be honest, unit-testing the JPA has not been a too pleasant experience for us as well as it works with quite a lot of indirections (EntityManager -> CriteriaBuilder, CriteriaQuery etc.) so that you end up with mocks returning mocks and so on.

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

CAUSE: "Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app." In this case, "ACCESS_FINE_LOCATION" is a "dangerous permission and for that reason, you get this 'java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.' error (https://developer.android.com/training/permissions/requesting.html).

SOLUTION: Implementing the code provided at https://developer.android.com/training/permissions/requesting.html under the "Request the permissions you need" and "Handle the permissions request response" headings.

When do you use the "this" keyword?

1 - Common Java setter idiom:

 public void setFoo(int foo) {
     this.foo = foo;
 }

2 - When calling a function with this object as a parameter

notifier.addListener(this);

Select multiple columns in data.table by their numeric indices

From v1.10.2 onwards, you can also use ..

dt <- data.table(a=1:2, b=2:3, c=3:4)

keep_cols = c("a", "c")

dt[, ..keep_cols]

How to properly validate input values with React.JS?

Sometimes you can have multiple fields with similar validation in your application. In such a case I recommend to create common component field where you keep this validation.

For instance, let's assume that you have mandatory text input in a few places in your application. You can create a TextInput component:

constructor(props) {
    super(props); 
    this.state = {
        touched: false, error: '', class: '', value: ''
    }
}

onValueChanged = (event) => {
    let [error, validClass, value] = ["", "", event.target.value];

    [error, validClass] = (!value && this.props.required) ? 
        ["Value cannot be empty", "is-invalid"] : ["", "is-valid"]

    this.props.onChange({value: value, error: error});

    this.setState({
        touched: true,
        error: error,
        class: validClass,
        value: value
    })
}

render() {
    return (
        <div>
            <input type="text"
                value={this.props.value}
                onChange={this.onValueChanged}
                className={"form-control " + this.state.class}
                id="{this.props.id}"
                placeholder={this.props.placeholder} />
            {this.state.error ?
                <div className="invalid-feedback">
                    {this.state.error}
                </div> : null
            }
        </div>
    )
}

And then you can use such a component anywhere in your application:

constructor(props) {
    super(props);
    this.state = {
        user: {firstName: '', lastName: ''},
        formState: {
            firstName: { error: '' },
            lastName: { error: '' }
        }
    }
}

onFirstNameChange = (model) => {
    let user = this.state.user;
    user.firstName = model.value;

    this.setState({
        user: user,
        formState: {...this.state.formState, firstName: { error: model.error }}
    })
}

onLastNameChange = (model) => {
    let user = this.state.user;
    user.lastName = model.value;

    this.setState({
        user: user,
        formState: {...this.state.formState, lastName: { error: model.error }}
    })
}


onSubmit = (e) => {
   // submit logic
}


render() {
    return (
        <form onSubmit={this.onSubmit}>
            <TextInput id="input_firstName"
                value={this.state.user.firstName}
                onChange={this.onFirstNameChange}
                required = {true}
                placeholder="First name" />

            <TextInput id="input_lastName"
                value={this.state.user.lastName}
                onChange={this.onLastNameChange}
                required = {true}
                placeholder="Last name" />

            {this.state.formState.firstName.error || this.state.formState.lastName.error ?
                <button type="submit" disabled className="btn btn-primary margin-left disabled">Save</button>
                : <button type="submit" className="btn btn-primary margin-left">Save</button>
            }

        </form>
    )
}

Benefits:

  • You don't repeat your validation logic
  • Less code in your forms - it is more readable
  • Other common input logic can be kept in component
  • You follow React rule that component should be as dumb as possible

Ref. https://webfellas.tech/#/article/5

Develop Android app using C#

There are indeed C# compilers for Android available. Even though I prefer developing Android Apps in Java, I can recommend MonoForAndroid. You find more information on http://xamarin.com/monoforandroid

Advantages of SQL Server 2008 over SQL Server 2005?

The new features are really great and its meets the very important factors of current age. For .net people it’s always be a boon to use SQL Server, I hope using the latest version we will have better security and better performance as well as the introduction of compression the size of the database. The backup encryption utility is also phenomenon.

Once again thanks to Microsoft for their great thoughts in form of software :)

How to check whether an object has certain method/property?

You could write something like that :

public static bool HasMethod(this object objectToCheck, string methodName)
{
    var type = objectToCheck.GetType();
    return type.GetMethod(methodName) != null;
} 

Edit : you can even do an extension method and use it like this

myObject.HasMethod("SomeMethod");

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

Excel add one hour

This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.

=IF((Sheet1!C4)="",DATE(1999,1,1),Sheet1!C4-TIME(1,0,0))

You can also substitute TIME with DATE to add or subtract a date or time.

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

Its supported in notepad++ 5.0+ but not enabled by default. You can enable it from settings -> preferences

Create a global variable in TypeScript

Inside a .d.ts definition file

type MyGlobalFunctionType = (name: string) => void

If you work in the browser, you add members to the browser's window context:

interface Window {
  myGlobalFunction: MyGlobalFunctionType
}

Same idea for NodeJS:

declare module NodeJS {
  interface Global {
    myGlobalFunction: MyGlobalFunctionType
  }
}

Now you declare the root variable (that will actually live on window or global)

declare const myGlobalFunction: MyGlobalFunctionType;

Then in a regular .ts file, but imported as side-effect, you actually implement it:

global/* or window */.myGlobalFunction = function (name: string) {
  console.log("Hey !", name);
};

And finally use it elsewhere in the codebase, with either:

global/* or window */.myGlobalFunction("Kevin");

myGlobalFunction("Kevin");

PHP/MySQL insert row then get 'id'

The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.

The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().

Getting Current date, time , day in laravel

FOR LARAVEL 5.x

I think you were looking for this

$errorLog->timestamps = false;
$errorLog->created_at = date("Y-m-d H:i:s");

Why does .json() return a promise?

Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then method will be resolved differently depending on what the handler fn returns:

if the handler function:

  • returns a value, the promise returned by then gets resolved with the returned value as its value;
  • throws an error, the promise returned by then gets rejected with the thrown error as its value;
  • returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
  • returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
  • returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.

Assigning variables with dynamic names in Java

Dynamic Variable Names in Java
There is no such thing.

In your case you can use array:

int[] n = new int[3];
for() {
 n[i] = 5;
}

For more general (name, value) pairs, use Map<>

Remove characters except digits from string using Python?

Not a one liner but very simple:

buffer = ""
some_str = "aas30dsa20"

for char in some_str:
    if not char.isdigit():
        buffer += char

print( buffer )

How do I concatenate text in a query in sql server?

You might want to consider NULL values as well. In your example, if the column notes has a null value, then the resulting value will be NULL. If you want the null values to behave as empty strings (so that the answer comes out 'SomeText'), then use the IsNull function:

Select IsNull(Cast(notes as nvarchar(4000)),'') + 'SomeText' From NotesTable a

How should I choose an authentication library for CodeIgniter?

Update (May 14, 2010):

It turns out, the russian developer Ilya Konyukhov picked up the gauntlet after reading this and created a new auth library for CI based on DX Auth, following the recommendations and requirements below.

And the resulting Tank Auth is looking like the answer to the OP's question. I'm going to go out on a limb here and call Tank Auth the best authentication library for CodeIgniter available today. It's a rock-solid library that has all the features you need and none of the bloat you don't:

Tank Auth

Pros

  • Full featured
  • Lean footprint (20 files) considering the feature set
  • Very good documentation
  • Simple and elegant database design (just 4 DB tables)
  • Most features are optional and easily configured
  • Language file support
  • reCAPTCHA supported
  • Hooks into CI's validation system
  • Activation emails
  • Login with email, username or both (configurable)
  • Unactivated accounts auto-expire
  • Simple yet effective error handling
  • Uses phpass for hashing (and also hashes autologin codes in the DB)
  • Does not use security questions
  • Separation of user and profile data is very nice
  • Very reasonable security model around failed login attempts (good protection against bots and DoS attacks)

(Minor) Cons

  • Lost password codes are not hashed in DB
  • Includes a native (poor) CAPTCHA, which is nice for those who don't want to depend on the (Google-owned) reCAPTCHA service, but it really isn't secure enough
  • Very sparse online documentation (minor issue here, since the code is nicely documented and intuitive)

Download Tank Auth here


Original answer:

I've implemented my own as well (currently about 80% done after a few weeks of work). I tried all of the others first; FreakAuth Light, DX Auth, Redux, SimpleLogin, SimpleLoginSecure, pc_user, Fresh Powered, and a few more. None of them were up to par, IMO, either they were lacking basic features, inherently INsecure, or too bloated for my taste.

Actually, I did a detailed roundup of all the authentication libraries for CodeIgniter when I was testing them out (just after New Year's). FWIW, I'll share it with you:

DX Auth

Pros

  • Very full featured
  • Medium footprint (25+ files), but manages to feel quite slim
  • Excellent documentation, although some is in slightly broken English
  • Language file support
  • reCAPTCHA supported
  • Hooks into CI's validation system
  • Activation emails
  • Unactivated accounts auto-expire
  • Suggests grc.com for salts (not bad for a PRNG)
  • Banning with stored 'reason' strings
  • Simple yet effective error handling

Cons

  • Only lets users 'reset' a lost password (rather than letting them pick a new one upon reactivation)
  • Homebrew pseudo-event model - good intention, but misses the mark
  • Two password fields in the user table, bad style
  • Uses two separate user tables (one for 'temp' users - ambiguous and redundant)
  • Uses potentially unsafe md5 hashing
  • Failed login attempts only stored by IP, not by username - unsafe!
  • Autologin key not hashed in the database - practically as unsafe as storing passwords in cleartext!
  • Role system is a complete mess: is_admin function with hard-coded role names, is_role a complete mess, check_uri_permissions is a mess, the whole permissions table is a bad idea (a URI can change and render pages unprotected; permissions should always be stored exactly where the sensitive logic is). Dealbreaker!
  • Includes a native (poor) CAPTCHA
  • reCAPTCHA function interface is messy

FreakAuth Light

Pros

  • Very full featured
  • Mostly quite well documented code
  • Separation of user and profile data is a nice touch
  • Hooks into CI's validation system
  • Activation emails
  • Language file support
  • Actively developed

Cons

  • Feels a bit bloated (50+ files)
  • And yet it lacks automatic cookie login (!)
  • Doesn't support logins with both username and email
  • Seems to have issues with UTF-8 characters
  • Requires a lot of autoloading (impeding performance)
  • Badly micromanaged config file
  • Terrible View-Controller separation, with lots of program logic in views and output hard-coded into controllers. Dealbreaker!
  • Poor HTML code in the included views
  • Includes substandard CAPTCHA
  • Commented debug echoes everywhere
  • Forces a specific folder structure
  • Forces a specific Ajax library (can be switched, but shouldn't be there in the first place)
  • No max limit on login attempts - VERY unsafe! Dealbreaker!
  • Hijacks form validation
  • Uses potentially unsafe md5 hashing

pc_user

Pros

  • Good feature set for its tiny footprint
  • Lightweight, no bloat (3 files)
  • Elegant automatic cookie login
  • Comes with optional test implementation (nice touch)

Cons

  • Uses the old CI database syntax (less safe)
  • Doesn't hook into CI's validation system
  • Kinda unintuitive status (role) system (indexes upside down - impractical)
  • Uses potentially unsafe sha1 hashing

Fresh Powered

Pros

  • Small footprint (6 files)

Cons

  • Lacks a lot of essential features. Dealbreaker!
  • Everything is hard-coded. Dealbreaker!

Redux / Ion Auth

According to the CodeIgniter wiki, Redux has been discontinued, but the Ion Auth fork is going strong: https://github.com/benedmunds/CodeIgniter-Ion-Auth

Ion Auth is a well featured library without it being overly heavy or under advanced. In most cases its feature set will more than cater for a project's requirements.

Pros

  • Lightweight and simple to integrate with CodeIgniter
  • Supports sending emails directly from the library
  • Well documented online and good active dev/user community
  • Simple to implement into a project

Cons

  • More complex DB schema than some others
  • Documentation lacks detail in some areas

SimpleLoginSecure

Pros

  • Tiny footprint (4 files)
  • Minimalistic, absolutely no bloat
  • Uses phpass for hashing (excellent)

Cons

  • Only login, logout, create and delete
  • Lacks a lot of essential features. Dealbreaker!
  • More of a starting point than a library

Don't get me wrong: I don't mean to disrespect any of the above libraries; I am very impressed with what their developers have accomplished and how far each of them have come, and I'm not above reusing some of their code to build my own. What I'm saying is, sometimes in these projects, the focus shifts from the essential 'need-to-haves' (such as hard security practices) over to softer 'nice-to-haves', and that's what I hope to remedy.

Therefore: back to basics.

Authentication for CodeIgniter done right

Here's my MINIMAL required list of features from an authentication library. It also happens to be a subset of my own library's feature list ;)

  1. Tiny footprint with optional test implementation
  2. Full documentation
  3. No autoloading required. Just-in-time loading of libraries for performance
  4. Language file support; no hard-coded strings
  5. reCAPTCHA supported but optional
  6. Recommended TRUE random salt generation (e.g. using random.org or random.irb.hr)
  7. Optional add-ons to support 3rd party login (OpenID, Facebook Connect, Google Account, etc.)
  8. Login using either username or email
  9. Separation of user and profile data
  10. Emails for activation and lost passwords
  11. Automatic cookie login feature
  12. Configurable phpass for hashing (properly salted of course!)
  13. Hashing of passwords
  14. Hashing of autologin codes
  15. Hashing of lost password codes
  16. Hooks into CI's validation system
  17. NO security questions!
  18. Enforced strong password policy server-side, with optional client-side (Javascript) validator
  19. Enforced maximum number of failed login attempts with BEST PRACTICES countermeasures against both dictionary and DoS attacks!
  20. All database access done through prepared (bound) statements!

Note: those last few points are not super-high-security overkill that you don't need for your web application. If an authentication library doesn't meet these security standards 100%, DO NOT USE IT!

Recent high-profile examples of irresponsible coders who left them out of their software: #17 is how Sarah Palin's AOL email was hacked during the Presidential campaign; a nasty combination of #18 and #19 were the culprit recently when the Twitter accounts of Britney Spears, Barack Obama, Fox News and others were hacked; and #20 alone is how Chinese hackers managed to steal 9 million items of personal information from more than 70.000 Korean web sites in one automated hack in 2008.

These attacks are not brain surgery. If you leave your back doors wide open, you shouldn't delude yourself into a false sense of security by bolting the front. Moreover, if you're serious enough about coding to choose a best-practices framework like CodeIgniter, you owe it to yourself to at least get the most basic security measures done right.


<rant>

Basically, here's how it is: I don't care if an auth library offers a bunch of features, advanced role management, PHP4 compatibility, pretty CAPTCHA fonts, country tables, complete admin panels, bells and whistles -- if the library actually makes my site less secure by not following best practices. It's an authentication package; it needs to do ONE thing right: Authentication. If it fails to do that, it's actually doing more harm than good.

</rant>

/Jens Roland

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

There's some sort of bogus character at the end of that source. Try deleting the last line and adding it back.

I can't figure out exactly what's there, yet ...

edit — I think it's a zero-width space, Unicode 200B. Seems pretty weird and I can't be sure of course that it's not a Stackoverflow artifact, but when I copy/paste that last function including the complete last line into the Chrome console, I get your error.

A notorious source of such characters are websites like jsfiddle. I'm not saying that there's anything wrong with them — it's just a side-effect of something, maybe the use of content-editable input widgets.

If you suspect you've got a case of this ailment, and you're on MacOS or Linux/Unix, the od command line tool can show you (albeit in a fairly ugly way) the numeric values in the characters of the source code file. Some IDEs and editors can show "funny" characters as well. Note that such characters aren't always a problem. It's perfectly OK (in most reasonable programming languages, anyway) for there to be embedded Unicode characters in string constants, for example. The problems start happening when the language parser encounters the characters when it doesn't expect them.

Simulate low network connectivity for Android

Easy way to test your application with low/bad connection in emulator:

Go Run > Run configurations, select your Android Application, and there go to Target tab. Look Emulator launch parameters. Here, you can easy modify Network Speed and Network Latency.

Java Replace Character At Specific Position Of String?

If you need to re-use a string, then use StringBuffer:

String str = "hi";
StringBuffer sb = new StringBuffer(str);
while (...) {
    sb.setCharAt(1, 'k');
}

EDIT:

Note that StringBuffer is thread-safe, while using StringBuilder is faster, but not thread-safe.

How to create a new instance from a class object in Python

Just call the "type" built in using three parameters, like this:

ClassName = type("ClassName", (Base1, Base2,...), classdictionary)

update as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.

To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:

instance = ClassObject()

The mechanism for instantiation is thus:

Python does not use the new keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable:

Its class' __call__ method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in type). The normal behavior of this call is to invoke the (pseudo) static __new__ method on the class being instantiated, followed by its __init__. The __new__ method is responsible for allocating memory and such, and normally is done by the __new__ of object which is the class hierarchy root.

So calling ClassObject() invokes ClassObject.__class__.call() (which normally will be type.__call__) this __call__ method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations)

class type:
    ...
    def __call__(cls, *args, **kw):
          constructor = getattr(cls, "__new__")
          instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)
          instance.__init__(cls, *args, **kw)
          return instance

(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__ and passing it to other classes - but it is what happen "in real life" - if object.__new__ is called with any extra parameters it raises a type error - however, any custom implementation of a __new__ will get the extra parameters normally)

"FATAL: Module not found error" using modprobe

The best thing is to actually use the kernel makefile to install the module:

Here is are snippets to add to your Makefile

around the top add:

PWD=$(shell pwd)
VER=$(shell uname -r)
KERNEL_BUILD=/lib/modules/$(VER)/build
# Later if you want to package the module binary you can provide an INSTALL_ROOT
# INSTALL_ROOT=/tmp/install-root

around the end add:

install:
        $(MAKE) -C $(KERNEL_BUILD) M=$(PWD) \
           INSTALL_MOD_PATH=$(INSTALL_ROOT) modules_install

and then you can issue

    sudo make install

this will put it either in /lib/modules/$(uname -r)/extra/

or /lib/modules/$(uname -r)/misc/

and run depmod appropriately

Javascript replace with reference to matched group?

"hello _there_".replace(/_(.*?)_/, function(a, b){
    return '<div>' + b + '</div>';
})

Oh, or you could also:

"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")

EDIT by Liran H: For six other people including myself, $1 did not work, whereas \1 did.

for-in statement

TypeScript isn't giving you a gun to shoot yourself in the foot with.

The iterator variable is a string because it is a string, full stop. Observe:

var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';

for(var key in obj) {
    console.log('Type: ' + typeof key);
    console.log(key + ' => ' + obj[key]);
}

How many key/value pairs are in obj now? 6, more or less? No, 3, and all of the keys are strings:

Type: string
0 => zero point zero
Type: string
[object Object] => this obj; 
Type: string
undefined => the literal string "undefined" 

How to print current date on python3?

I always use this code, which print the year to second in a tuple

import datetime

now = datetime.datetime.now()

time_now = (now.year, now.month, now.day, now.hour, now.minute, now.second)

print(time_now)

What is the difference between `sorted(list)` vs `list.sort()`?

The .sort() function stores the value of new list directly in the list variable; so answer for your third question would be NO. Also if you do this using sorted(list), then you can get it use because it is not stored in the list variable. Also sometimes .sort() method acts as function, or say that it takes arguments in it.

You have to store the value of sorted(list) in a variable explicitly.

Also for short data processing the speed will have no difference; but for long lists; you should directly use .sort() method for fast work; but again you will face irreversible actions.

How to dynamically add and remove form fields in Angular 2

This is a few months late but I thought I'd provide my solution based on this here tutorial. The gist of it is that it's a lot easier to manage once you change the way you approach forms.

First, use ReactiveFormsModule instead of or in addition to the normal FormsModule. With reactive forms you create your forms in your components/services and then plug them into your page instead of your page generating the form itself. It's a bit more code but it's a lot more testable, a lot more flexible, and as far as I can tell the best way to make a lot of non-trivial forms.

The end result will look a little like this, conceptually:

  • You have one base FormGroup with whatever FormControl instances you need for the entirety of the form. For example, as in the tutorial I linked to, lets say you want a form where a user can input their name once and then any number of addresses. All of the one-time field inputs would be in this base form group.

  • Inside that FormGroup instance there will be one or more FormArray instances. A FormArray is basically a way to group multiple controls together and iterate over them. You can also put multiple FormGroup instances in your array and use those as essentially "mini-forms" nested within your larger form.

  • By nesting multiple FormGroup and/or FormControl instances within a dynamic FormArray, you can control validity and manage the form as one, big, reactive piece made up of several dynamic parts. For example, if you want to check if every single input is valid before allowing the user to submit, the validity of one sub-form will "bubble up" to the top-level form and the entire form becomes invalid, making it easy to manage dynamic inputs.

  • As a FormArray is, essentially, a wrapper around an array interface but for form pieces, you can push, pop, insert, and remove controls at any time without recreating the form or doing complex interactions.

In case the tutorial I linked to goes down, here some sample code you can implement yourself (my examples use TypeScript) that illustrate the basic ideas:

Base Component code:

import { Component, Input, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-form-component',
  templateUrl: './my-form.component.html'
})
export class MyFormComponent implements OnInit {
    @Input() inputArray: ArrayType[];
    myForm: FormGroup;

    constructor(private fb: FormBuilder) {}
    ngOnInit(): void {
        let newForm = this.fb.group({
            appearsOnce: ['InitialValue', [Validators.required, Validators.maxLength(25)]],
            formArray: this.fb.array([])
        });

        const arrayControl = <FormArray>newForm.controls['formArray'];
        this.inputArray.forEach(item => {
            let newGroup = this.fb.group({
                itemPropertyOne: ['InitialValue', [Validators.required]],
                itemPropertyTwo: ['InitialValue', [Validators.minLength(5), Validators.maxLength(20)]]
            });
            arrayControl.push(newGroup);
        });

        this.myForm = newForm;
    }
    addInput(): void {
        const arrayControl = <FormArray>this.myForm.controls['formArray'];
        let newGroup = this.fb.group({

            /* Fill this in identically to the one in ngOnInit */

        });
        arrayControl.push(newGroup);
    }
    delInput(index: number): void {
        const arrayControl = <FormArray>this.myForm.controls['formArray'];
        arrayControl.removeAt(index);
    }
    onSubmit(): void {
        console.log(this.myForm.value);
        // Your form value is outputted as a JavaScript object.
        // Parse it as JSON or take the values necessary to use as you like
    }
}

Sub-Component Code: (one for each new input field, to keep things clean)

import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Component({
    selector: 'my-form-sub-component',
    templateUrl: './my-form-sub-component.html'
})
export class MyFormSubComponent {
    @Input() myForm: FormGroup; // This component is passed a FormGroup from the base component template
}

Base Component HTML

<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
    <label>Appears Once:</label>
    <input type="text" formControlName="appearsOnce" />

    <div formArrayName="formArray">
        <div *ngFor="let control of myForm.controls['formArray'].controls; let i = index">
            <button type="button" (click)="delInput(i)">Delete</button>
            <my-form-sub-component [myForm]="myForm.controls.formArray.controls[i]"></my-form-sub-component>
        </div>
    </div>
    <button type="button" (click)="addInput()">Add</button>
    <button type="submit" [disabled]="!myForm.valid">Save</button>
</form>

Sub-Component HTML

<div [formGroup]="form">
    <label>Property One: </label>
    <input type="text" formControlName="propertyOne"/>

    <label >Property Two: </label>
    <input type="number" formControlName="propertyTwo"/>
</div>

In the above code I basically have a component that represents the base of the form and then each sub-component manages its own FormGroup instance within the FormArray situated inside the base FormGroup. The base template passes along the sub-group to the sub-component and then you can handle validation for the entire form dynamically.

Also, this makes it trivial to re-order component by strategically inserting and removing them from the form. It works with (seemingly) any number of inputs as they don't conflict with names (a big downside of template-driven forms as far as I'm aware) and you still retain pretty much automatic validation. The only "downside" of this approach is, besides writing a little more code, you do have to relearn how forms work. However, this will open up possibilities for much larger and more dynamic forms as you go on.

If you have any questions or want to point out some errors, go ahead. I just typed up the above code based on something I did myself this past week with the names changed and other misc. properties left out, but it should be straightforward. The only major difference between the above code and my own is that I moved all of the form-building to a separate service that's called from the component so it's a bit less messy.

Replace substring with another substring C++

Boost String Algorithms Library way:

#include <boost/algorithm/string/replace.hpp>

{ // 1. 
  string test = "abc def abc def";
  boost::replace_all(test, "abc", "hij");
  boost::replace_all(test, "def", "klm");
}


{ // 2.
  string test = boost::replace_all_copy
  (  boost::replace_all_copy<string>("abc def abc def", "abc", "hij")
  ,  "def"
  ,  "klm"
  );
}

Using jQuery to test if an input has focus

An alternative to using classes to mark the state of an element is the internal data store functionality.

P.S.: You are able to store booleans and whatever you desire using the data() function. It's not just about strings :)

$("...").mouseover(function ()
{
    // store state on element
}).mouseout(function ()
{
    // remove stored state on element
});

And then it's just a matter of accessing the state of elements.

Initializing a list to a known number of elements in Python

Without knowing more about the problem domain, it's hard to answer your question. Unless you are certain that you need to do something more, the pythonic way to initialize a list is:

verts = []

Are you actually seeing a performance problem? If so, what is the performance bottleneck? Don't try to solve a problem that you don't have. It's likely that performance cost to dynamically fill an array to 1000 elements is completely irrelevant to the program that you're really trying to write.

The array class is useful if the things in your list are always going to be a specific primitive fixed-length type (e.g. char, int, float). But, it doesn't require pre-initialization either.

How do I set up HttpContent for my HttpClient PostAsync second parameter?

To add to Preston's answer, here's the complete list of the HttpContent derived classes available in the standard library:

Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

Credit: https://pfelix.wordpress.com/2012/01/16/the-new-system-net-http-classes-message-content/

There's also a supposed ObjectContent but I was unable to find it in ASP.NET Core.

Of course, you could skip the whole HttpContent thing all together with Microsoft.AspNet.WebApi.Client extensions (you'll have to do an import to get it to work in ASP.NET Core for now: https://github.com/aspnet/Home/issues/1558) and then you can do things like:

var response = await client.PostAsJsonAsync("AddNewArticle", new Article
{
    Title = "New Article Title",
    Body = "New Article Body"
});

How to generate a random int in C?

My minimalistic solution should work for random numbers in range [min, max). Use srand(time(NULL)) before invoking the function.

int range_rand(int min_num, int max_num) {
    if (min_num >= max_num) {
        fprintf(stderr, "min_num is greater or equal than max_num!\n"); 
    }
    return min_num + (rand() % (max_num - min_num));
} 

MySQL - count total number of rows in php

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

if ($result=mysqli_query($con,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  echo "number of rows: ",$rowcount;
  // Free result set
  mysqli_free_result($result);
  }

mysqli_close($con);
?>

it is best way (I think) to get the number of special row in mysql with php.

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

I had the exact same issue. The following thread helped me solve it. Just set your Compile SDK version to Android P.

https://stackoverflow.com/a/49172361/1542720

I fixed this issue by selecting:

API 27+: Android API 27, P preview (Preview)

in the project structure settings. the following image shows my settings. The 13 errors that were coming while building the app, have disappeared.

Gradle settings

Google Map API v3 — set bounds and center

My suggestion for google maps api v3 would be(don't think it can be done more effeciently):

gmap : {
    fitBounds: function(bounds, mapId)
    {
        //incoming: bounds - bounds object/array; mapid - map id if it was initialized in global variable before "var maps = [];"
        if (bounds==null) return false;
        maps[mapId].fitBounds(bounds);
    }
}

In the result u will fit all points in bounds in your map window.

Example works perfectly and u freely can check it here www.zemelapis.lt

How to format a date using ng-model?

Use custom validation of forms http://docs.angularjs.org/guide/forms Demo: http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=preview

Directive using formaters and parsers and MomentJS )

angModule.directive('moDateInput', function ($window) {
    return {
        require:'^ngModel',
        restrict:'A',
        link:function (scope, elm, attrs, ctrl) {
            var moment = $window.moment;
            var dateFormat = attrs.moDateInput;
            attrs.$observe('moDateInput', function (newValue) {
                if (dateFormat == newValue || !ctrl.$modelValue) return;
                dateFormat = newValue;
                ctrl.$modelValue = new Date(ctrl.$setViewValue);
            });

            ctrl.$formatters.unshift(function (modelValue) {
                if (!dateFormat || !modelValue) return "";
                var retVal = moment(modelValue).format(dateFormat);
                return retVal;
            });

            ctrl.$parsers.unshift(function (viewValue) {
                var date = moment(viewValue, dateFormat);
                return (date && date.isValid() && date.year() > 1950 ) ? date.toDate() : "";
            });
        }
    };
});

Sort array of objects by single key with date value

var months = [
    {
        "updated_at" : "2012-01-01T06:25:24Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-09T11:25:13Z",
        "foo" : "bar"
    },
    {
        "updated_at" : "2012-01-05T04:13:24Z",
        "foo" : "bar"
    }];
months.sort((a, b)=>{
    var keyA = new Date(a.updated_at),
        keyB = new Date(b.updated_at);
    // Compare the 2 dates
    if(keyA < keyB) return -1;
    if(keyA > keyB) return 1;
    return 0;
});
console.log(months);

Retrieving Data from SQL Using pyodbc

import pyodbc
conn = pyodbc.connect('Driver={SQL Server};'
                  'Server=db-server;'
                  'Database=db;'
                  'Trusted_Connection=yes;')
sql = "SELECT * FROM [mytable] "
cursor.execute(sql)
for r in cursor:
    print(r)

How can I search for a multiline pattern in a file?

Using ex/vi editor and globstar option (syntax similar to awk and sed):

ex +"/string1/,/string3/p" -R -scq! file.txt

where aaa is your starting point, and bbb is your ending text.

To search recursively, try:

ex +"/aaa/,/bbb/p" -scq! **/*.py

Note: To enable ** syntax, run shopt -s globstar (Bash 4 or zsh).

Checking if an Android application is running in the background

There are few ways to detect whether your application is running in the background, but only one of them is completely reliable:

  1. The right solution (credits go to Dan, CommonsWare and NeTeInStEiN)
    Track visibility of your application by yourself using Activity.onPause, Activity.onResume methods. Store "visibility" status in some other class. Good choices are your own implementation of the Application or a Service (there are also a few variations of this solution if you'd like to check activity visibility from the service).
     
    Example
    Implement custom Application class (note the isActivityVisible() static method):

    public class MyApplication extends Application {
    
      public static boolean isActivityVisible() {
        return activityVisible;
      }  
    
      public static void activityResumed() {
        activityVisible = true;
      }
    
      public static void activityPaused() {
        activityVisible = false;
      }
    
      private static boolean activityVisible;
    }
    

    Register your application class in AndroidManifest.xml:

    <application
        android:name="your.app.package.MyApplication"
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
    

    Add onPause and onResume to every Activity in the project (you may create a common ancestor for your Activities if you'd like to, but if your activity is already extended from MapActivity/ListActivity etc. you still need to write the following by hand):

    @Override
    protected void onResume() {
      super.onResume();
      MyApplication.activityResumed();
    }
    
    @Override
    protected void onPause() {
      super.onPause();
      MyApplication.activityPaused();
    }
    

     
    Update
    ActivityLifecycleCallbacks were added in API level 14 (Android 4.0). You can use them to track whether an activity of your application is currently visible to the user. Check Cornstalks' answer below for the details.

  2. The wrong one
    I used to suggest the following solution:

    You can detect currently foreground/background application with ActivityManager.getRunningAppProcesses() which returns a list of RunningAppProcessInfo records. To determine if your application is on the foreground check RunningAppProcessInfo.importance field for equality to RunningAppProcessInfo.IMPORTANCE_FOREGROUND while RunningAppProcessInfo.processName is equal to your application package name.

    Also if you call ActivityManager.getRunningAppProcesses() from your application UI thread it will return importance IMPORTANCE_FOREGROUND for your task no matter whether it is actually in the foreground or not. Call it in the background thread (for example via AsyncTask) and it will return correct results.

    While this solution may work (and it indeed works most of the time) I strongly recommend to refrain from using it. And here's why. As Dianne Hackborn wrote:

    These APIs are not there for applications to base their UI flow on, but to do things like show the user the running apps, or a task manager, or such.

    Yes there is a list kept in memory for these things. However, it is off in another process, managed by threads running separately from yours, and not something you can count on (a) seeing in time to make the correct decision or (b) have a consistent picture by the time you return. Plus the decision about what the "next" activity to go to is always done at the point where the switch is to happen, and it is not until that exact point (where the activity state is briefly locked down to do the switch) that we actually know for sure what the next thing will be.

    And the implementation and global behavior here is not guaranteed to remain the same in the future.

    I wish I had read this before I posted an answer on the SO, but hopefully it's not too late to admit my error.

  3. Another wrong solution
    Droid-Fu library mentioned in one of the answers uses ActivityManager.getRunningTasks for its isApplicationBroughtToBackground method. See Dianne's comment above and don't use that method either.

Variable number of arguments in C++?

In C++11 there is a way to do variable argument templates which lead to a really elegant and type safe way to have variable argument functions. Bjarne himself gives a nice example of printf using variable argument templates in the C++11FAQ.

Personally, I consider this so elegant that I wouldn't even bother with a variable argument function in C++ until that compiler has support for C++11 variable argument templates.

How to select date from datetime column?

You can format the datetime to the Y-M-D portion:

DATE_FORMAT(datetime, '%Y-%m-%d')

What is the largest Safe UDP Packet Size on the Internet

The maximum safe UDP payload is 508 bytes. This is a packet size of 576 (the "minimum maximum reassembly buffer size"), minus the maximum 60-byte IP header and the 8-byte UDP header.

Any UDP payload this size or smaller is guaranteed to be deliverable over IP (though not guaranteed to be delivered). Anything larger is allowed to be outright dropped by any router for any reason. Except on an IPv6-only route, where the maximum payload is 1,212 bytes. As others have mentioned, additional protocol headers could be added in some circumstances. A more conservative value of around 300-400 bytes may be preferred instead.

The maximum possible UDP payload is 67 KB, split into 45 IP packets, adding an additional 900 bytes of overhead (IPv4, MTU 1500, minimal 20-byte IP headers).

Any UDP packet may be fragmented. But this isn't too important, because losing a fragment has the same effect as losing an unfragmented packet: the entire packet is dropped. With UDP, this is going to happen either way.

IP packets include a fragment offset field, which indicates the byte offset of the UDP fragment in relation to its UDP packet. This field is 13-bit, allowing 8,192 values, which are in 8-byte units. So the range of such offsets an IP packet can refer to is 0...65,528 bytes. Being an offset, we add 1,480 for the last UDP fragment to get 67,008. Minus the UDP header in the first fragment gives us a nice, round 67 KB.

Sources: RFC 791, RFC 1122, RFC 2460

What is the best way to auto-generate INSERT statements for a SQL Server table?

I'm using SSMS 2008 version 10.0.5500.0. In this version as part of the Generate Scripts wizard, instead of an Advanced button, there is the screen below. In this case, I wanted just the data inserted and no create statements, so I had to change the two circled propertiesScript Options

Create a directory if it does not exist and then create the files in that directory as well

I would suggest the following for Java8+.

/**
 * Creates a File if the file does not exist, or returns a
 * reference to the File if it already exists.
 */
private File createOrRetrieve(final String target) throws IOException{

    final Path path = Paths.get(target);

    if(Files.notExists(path)){
        LOG.info("Target file \"" + target + "\" will be created.");
        return Files.createFile(Files.createDirectories(path)).toFile();
    }
    LOG.info("Target file \"" + target + "\" will be retrieved.");
    return path.toFile();
}

/**
 * Deletes the target if it exists then creates a new empty file.
 */
private File createOrReplaceFileAndDirectories(final String target) throws IOException{

    final Path path = Paths.get(target);
    // Create only if it does not exist already
    Files.walk(path)
        .filter(p -> Files.exists(p))
        .sorted(Comparator.reverseOrder())
        .peek(p -> LOG.info("Deleted existing file or directory \"" + p + "\"."))
        .forEach(p -> {
            try{
                Files.createFile(Files.createDirectories(p));
            }
            catch(IOException e){
                throw new IllegalStateException(e);
            }
        });

    LOG.info("Target file \"" + target + "\" will be created.");

    return Files.createFile(
        Files.createDirectories(path)
    ).toFile();
}

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The route engine uses the same sequence as you add rules into it. Once it gets the first matched rule, it will stop checking other rules and take this to search for controller and action.

So, you should:

  1. Put your specific rules ahead of your general rules(like default), which means use RouteTable.Routes.MapHttpRoute to map "WithActionApi" first, then "DefaultApi".

  2. Remove the defaults: new { id = System.Web.Http.RouteParameter.Optional } parameter of your "WithActionApi" rule because once id is optional, url like "/api/{part1}/{part2}" will never goes into "DefaultApi".

  3. Add an named action to your "DefaultApi" to tell the route engine which action to enter. Otherwise once you have more than one actions in your controller, the engine won't know which one to use and throws "Multiple actions were found that match the request: ...". Then to make it matches your Get method, use an ActionNameAttribute.

So your route should like this:

// Map this rule first
RouteTable.Routes.MapRoute(
     "WithActionApi",
     "api/{controller}/{action}/{id}"
 );

RouteTable.Routes.MapRoute(
    "DefaultApi",
    "api/{controller}/{id}",
    new { action="DefaultAction", id = System.Web.Http.RouteParameter.Optional }
);

And your controller:

[ActionName("DefaultAction")] //Map Action and you can name your method with any text
public string Get(int id)
{
    return "object of id id";
}        

[HttpGet]
public IEnumerable<string> ByCategoryId(int id)
{
    return new string[] { "byCategory1", "byCategory2" };
}

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

The way to do it without projection:

StudentsGrades.OrderBy(student => student.Name).
ThenBy(student => student.Grade);

Trying Gradle build - "Task 'build' not found in root project"

You didn't do what you're being asked to do.

What is asked:

I have to execute ../gradlew build

What you do

cd ..
gradlew build

That's not the same thing.

The first one will use the gradlew command found in the .. directory (mdeinum...), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore.

The second one will execute the gradlew command found in the current directory (mdeinum...), and look for the build file to execute in the current directory, which is mdeinum....

So the build file executed is not the same.

CSS3 scrollbar styling on a div

.scroll {
   width: 200px; height: 400px;
   overflow: auto;
}

Focus Next Element In Tab Index

i use this code, which relies on the library "JQuery":

    $(document).on('change', 'select', function () {
    let next_select = $(this);
// console.log(next_select.toArray())
    if (!next_select.parent().parent().next().find('select').length) {
        next_select.parent().parent().parent().next().find('input[type="text"]').click()
        console.log(next_select.parent().parent().parent().next());
    } else if (next_select.parent().parent().next().find('select').prop("disabled")) {
        setTimeout(function () {
            next_select.parent().parent().next().find('select').select2('open')
        }, 1000)
        console.log('b');
    } else if (next_select.parent().parent().next().find('select').length) {
        next_select.parent().parent().next().find('select').select2('open')
        console.log('c');
    }
});

jquery - Check for file extension before uploading

 $("#file-upload").change(function () {

    var validExtensions = ["jpg","pdf","jpeg","gif","png"]
    var file = $(this).val().split('.').pop();
    if (validExtensions.indexOf(file) == -1) {
        alert("Only formats are allowed : "+validExtensions.join(', '));
    }

});

Unable to find velocity template resources

I faced a similar issue. I was copying the velocity engine mail templates in wrong folder. Since JavaMailSender and VelocityEngine are declared as resources under MailService, its required to add the templates under resource folder declared for the project.

I made the changes and it worked. Put the templates as

src/main/resources/templates/<package>/sampleMail.vm

Remove Rows From Data Frame where a Row matches a String

if you wish to using dplyr, for to remove row "Foo":

df %>%
 filter(!C=="Foo")

SSIS Text was truncated with status value 4

I suspect the or one or more characters had no match in the target code page part of the error.

If you remove the rows with values in that column, does it load? Can you identify, in other words, the rows which cause the package to fail? It could be the data is too long, or it could be that there's some funky character in there SQL Server doesn't like.

PHP PDO returning single row

You could try this for a database SELECT query based on user input using PDO:

$param = $_GET['username'];

$query=$dbh->prepare("SELECT secret FROM users WHERE username=:param");
$query->bindParam(':param', $param);
$query->execute();

$result = $query -> fetch();

print_r($result);

Distinct() with lambda?

All solutions I've seen here rely on selecting an already comparable field. If one needs to compare in a different way, though, this solution here seems to work generally, for something like:

somedoubles.Distinct(new LambdaComparer<double>((x, y) => Math.Abs(x - y) < double.Epsilon)).Count()

How to pass parameter to a promise function

Try this:

function someFunction(username, password) {
      return new Promise((resolve, reject) => {
        // Do something with the params username and password...
        if ( /* everything turned out fine */ ) {
          resolve("Stuff worked!");
        } else {
          reject(Error("It didn't work!"));
        }
      });
    }
    
    someFunction(username, password)
      .then((result) => {
        // Do something...
      })
      .catch((err) => {
        // Handle the error...
      });

How to download image from url

It is not necessary to use System.Drawing to find the image format in a URI. System.Drawing is not available for .NET Core unless you download the System.Drawing.Common NuGet package and therefore I don't see any good cross-platform answers to this question.

Also, my example does not use System.Net.WebClient since Microsoft explicitly discourage the use of System.Net.WebClient.

We don't recommend that you use the WebClient class for new development. Instead, use the System.Net.Http.HttpClient class.

Download an image from a URL and write it to a file (cross platform)*

*Without old System.Net.WebClient and System.Drawing.

This method will asynchronously download an image (or any file as long as the URI has a file extension) using the System.Net.Http.HttpClient and then write it to a file, using the same file extension as the image had in the URI.

Getting the file extension

First part of getting the file extension is removing all the unnecessary parts from the URI.
We use Uri.GetLeftPart() with UriPartial.Path to get everything from the Scheme up to the Path.
In other words, https://www.example.com/image.png?query&with.dots becomes https://www.example.com/image.png.

After that, we use Path.GetExtension() to get only the extension (in my previous example, .png).

var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
var fileExtension = Path.GetExtension(uriWithoutQuery);

Downloading the image

From here it should be straight forward. Download the image with HttpClient.GetByteArrayAsync, create the path, ensure the directory exists and then write the bytes to the path with File.WriteAllBytesAsync() (or File.WriteAllBytes if you are on .NET Framework)

private async Task DownloadImageAsync(string directoryPath, string fileName, Uri uri)
{
    using var httpClient = new HttpClient();

    // Get the file extension
    var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path);
    var fileExtension = Path.GetExtension(uriWithoutQuery);

    // Create file path and ensure directory exists
    var path = Path.Combine(directoryPath, $"{fileName}{fileExtension}");
    Directory.CreateDirectory(directoryPath);

    // Download the image and write to the file
    var imageBytes = await _httpClient.GetByteArrayAsync(uri);
    await File.WriteAllBytesAsync(path, imageBytes);
}

Note that you need the following using directives.

using System;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http;

Example usage

var folder = "images";
var fileName = "test";
var url = "https://cdn.discordapp.com/attachments/458291463663386646/592779619212460054/Screenshot_20190624-201411.jpg?query&with.dots";

await DownloadImageAsync(folder, fileName, new Uri(url));

Notes

  • It's bad practice to create a new HttpClient for every method call. It is supposed to be reused throughout the application. I wrote a short example of an ImageDownloader(50 lines) with more documentation that correctly reuses the HttpClient and properly disposes of it that you can find here.

How do you access the matched groups in a JavaScript regular expression?

There is no need to invoke the exec method! You can use "match" method directly on the string. Just don't forget the parentheses.

var str = "This is cool";
var matches = str.match(/(This is)( cool)$/);
console.log( JSON.stringify(matches) ); // will print ["This is cool","This is"," cool"] or something like that...

Position 0 has a string with all the results. Position 1 has the first match represented by parentheses, and position 2 has the second match isolated in your parentheses. Nested parentheses are tricky, so beware!

How to convert a SVG to a PNG with ImageMagick?

On Linux with Inkscape 1.0 to convert from svg to png need to use

inkscape -w 1024 -h 1024 input.svg --export-file output.png

not

inkscape -w 1024 -h 1024 input.svg --export-filename output.png

a = open("file", "r"); a.readline() output without \n

That would be:

b.rstrip('\n')

If you want to strip space from each and every line, you might consider instead:

a.read().splitlines()

This will give you a list of lines, without the line end characters.

Java: Calling a super method which calls an overridden method

You can only access overridden methods in the overriding methods (or in other methods of the overriding class).

So: either don't override method2() or call super.method2() inside the overridden version.

I have filtered my Excel data and now I want to number the rows. How do I do that?

Okay I found the correct answer to this issue here

Here are the steps:

  1. Filter your data.
  2. Select the cells you want to add the numbering to.
  3. Press F5.
  4. Select Special.
  5. Choose "Visible Cells Only" and press OK.
  6. Now in the top row of your filtered data (just below the header) enter the following code:

    =MAX($"Your Column Letter"$1:"Your Column Letter"$"The current row for the filter - 1") + 1

    Ex:

    =MAX($A$1:A26)+1

    Which would be applied starting at cell A27.

  7. Hold Ctrl and press enter.

Note this only works in a range, not in a table!

Jquery how to find an Object by attribute in an Array

The error was that you cannot use this in the grep, but you must use a reference to the element. This works:

function findPurpose(purposeName){
    return $.grep(purposeObjects, function(n, i){
      return n.purpose == purposeName;
    });
};

findPurpose("daily");

returns:

[Object { purpose="daily"}]

Check whether a table contains rows or not sql server 2005

Can't you just count the rows using select count(*) from table (or an indexed column instead of * if speed is important)?

If not then maybe this article can point you in the right direction.

Removing MySQL 5.7 Completely

You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo rm -rf /var/lib/mysql

I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

Convert string to Boolean in javascript

you can also use JSON.parse() function

JSON.parse("true") returns true (Boolean)

JSON.parse("false") return false (Boolean)

Datatables Select All Checkbox

This should work for you:

let example = $('#example').DataTable({
    columnDefs: [{
        orderable: false,
        className: 'select-checkbox',
        targets: 0
    }],
    select: {
        style: 'os',
        selector: 'td:first-child'
    },
    order: [
        [1, 'asc']
    ]
});
example.on("click", "th.select-checkbox", function() {
    if ($("th.select-checkbox").hasClass("selected")) {
        example.rows().deselect();
        $("th.select-checkbox").removeClass("selected");
    } else {
        example.rows().select();
        $("th.select-checkbox").addClass("selected");
    }
}).on("select deselect", function() {
    ("Some selection or deselection going on")
    if (example.rows({
            selected: true
        }).count() !== example.rows().count()) {
        $("th.select-checkbox").removeClass("selected");
    } else {
        $("th.select-checkbox").addClass("selected");
    }
});

I've added to the CSS though:

table.dataTable tr th.select-checkbox.selected::after {
    content: "?";
    margin-top: -11px;
    margin-left: -4px;
    text-align: center;
    text-shadow: rgb(176, 190, 217) 1px 1px, rgb(176, 190, 217) -1px -1px, rgb(176, 190, 217) 1px -1px, rgb(176, 190, 217) -1px 1px;
}

Working JSFiddle, hope that helps.

Floating Point Exception C++ Why and what is it?

Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.

for (i>0; i--;){
c= input%i;

Thats division by zero at some point since you are decrementing i.

Negative regex for Perl string pattern match

What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:

if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }

if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
        && $string !~ /Bush/i) {
    print "$string\n"
}

git still shows files as modified after adding to .gitignore

The solutions offered here and in other places didn't work for me, so I'll add to the discussion for future readers. I admittedly don't fully understand the procedure yet, but have finally solved my (similar) problem and want to share.

I had accidentally cached some doc-directories with several hundred files when working with git in IntelliJ IDEA on Windows 10, and after adding them to .gitignore (and PROBABLY moving them around a bit) I couldn't get them removed from the Default Changelist.

I first commited the actual changes I had made, then went about solving this - took me far too long. I tried git rm -r --cached . but would always get path-spec ERRORS, with different variations of the path-spec as well as with the -f and -r flags.

git status would still show the filenames, so I tried using some of those verbatim with git rm -cached, but no luck. Stashing and unstashing the changes seemed to work, but they got queued again after a time (I'm a bity hazy on the exact timeframe). I have finally removed these entries for good using

git reset

I assume this is only a GOOD IDEA when you have no changes staged/cached that you actually want to commit.

Convert timestamp in milliseconds to string formatted time in Java

It is possible to use apache commons (commons-lang3) and its DurationFormatUtils class.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.1</version>
</dependency>

For example:

String formattedDuration = DurationFormatUtils.formatDurationHMS(12313152);
// formattedDuration value is "3:25:13.152"
String otherFormattedDuration = DurationFormatUtils.formatDuration(12313152, DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN);
// otherFormattedDuration value is "P0000Y0M0DT3H25M13.152S"

Hope it can help ...

How to clear textarea on click?

<textarea onClick="javascript: this.value='';">Please describe why</textarea>

Is a new line = \n OR \r\n?

The given answer is far from complete. In fact, it is so far from complete that it tends to lead the reader to believe that this answer is OS dependent when it isn't. It also isn't something which is programming language dependent (as some commentators have suggested). I'm going to add more information in order to make this more clear. First, lets give the list of current new line variations (as in, what they've been since 1999):

  • \r\n is only used on Windows Notepad, the DOS command line, most of the Windows API and in some (older) Windows apps.
  • \n is used for all other systems, applications and the Internet.

You'll notice that I've put most Windows apps in the \n group which may be slightly controversial but before you disagree with this statement, please grab a UNIX formatted text file and try it in 10 web friendly Windows applications of your choice (which aren't listed in my exceptions above). What percentage of them handled it just fine? You'll find that they (practically) all implement auto detection of line endings or just use \n because, while Windows may use \r\n, the Internet uses \n. Therefore, it is best practice for applications to use \n alone if you want your output to be Internet friendly.

PHP also defines a newline character called PHP_EOL. This constant is set to the OS specific newline string for the machine PHP is running on (\r\n for Windows and \n for everything else). This constant is not very useful for webpages and should be avoided for HTML output or for writing most text to files. It becomes VERY useful when we move to command line output from PHP applications because it will allow your application to output to a terminal Window in a consistent manner across all supported OSes.

If you want your PHP applications to work from any server they are placed on, the two biggest things to remember are that you should always just use \n unless it is terminal output (in which case you use PHP_EOL) and you should also ALWAYS use / for your path separator (not \).

The even longer explanation:

An application may choose to use whatever line endings it likes regardless of the default OS line ending style. If I want my text editor to print a newline every time it encounters a period that is no harder than using the \n to represent a newline because I'm interpreting the text as I display it anyway. IOW, I'm fiddling around with measuring the width of each character so it knows where to display the next so it is very simple to add a statement saying that if the current char is a period then perform a newline action (or if it is a \n then display a period).

Aside from the null terminator, no character code is sacred and when you write a text editor or viewer you are in charge of translating the bits in your file into glyphs (or carriage returns) on the screen. The only thing that distinguishes a control character such as the newline from other characters is that most font sets don't include them (meaning they don't have a visual representation available).

That being said, if you are working at a higher level of abstraction then you probably aren't making your own textbox controls. If this is the case then you're stuck with whatever line ending that control makes available to you. Even in this case it is a simple matter to automatically detect the line ending style of any string and make the conversion before you load your text into the control and then undo it when you read from that control. Meaning, that if you're a desktop application dev and your application doesn't recognize \n as a newline then it isn't a very friendly application and you really have no excuse because it isn't hard to make it the right way. It also means that whomever wrote Notepad should be ashamed of himself because it really is very easy to do much better and so many people suffer through using it every day.

How to get the selected row values of DevExpress XtraGrid?

I found the solution as follows:

private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
{
    TBGRNo.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "GRNo").ToString();
    TBSName.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "SName").ToString();
    TBFName.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FName").ToString();            
}

enter image description here

How do I use Join-Path to combine more than two strings into a file path?

Here's something that will do what you'd want when using a string array for the ChildPath.

$path = "C:"
@( "Program Files", "Microsoft Office" ) | %{ $path = Join-Path $path $_ }
Write-Host $path

Which outputs

C:\Program Files\Microsoft Office

The only caveat I found is that the initial value for $path must have a value (cannot be null or empty).

Connection to SQL Server Works Sometimes

Solved this problem by blocking/ blacklisting IP address that were trying to brute force user accounts. Check your SQL access logs for large numbers of failed login attempts (usually for the 'sa' account).

How do we download a blob url video

The process can differ depending on where and how the video is being hosted. Knowing that can help to answer the question in more detail.

As an example; this is how you can download videos with blob links on Vimeo.

  1. View the source code of the video player iframe
  2. Search for mp4
  3. Copy link with token query
  4. Download before token expires

Source & step-by-step instructions here.

enter image description here

Left join only selected columns in R with the merge() function

I think it's a little simpler to use the dplyr functions select and left_join ; at least it's easier for me to understand. The join function from dplyr are made to mimic sql arguments.

 library(tidyverse)

 DF2 <- DF2 %>%
   select(client, LO)

 joined_data <- left_join(DF1, DF2, by = "Client")

You don't actually need to use the "by" argument in this case because the columns have the same name.

Is it possible to display inline images from html in an Android TextView?

I have implemented in my app ,taken referece from the pskink.thanx a lot

package com.example.htmltagimg;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity implements ImageGetter {
private final static String TAG = "TestImageGetter";
private TextView mTv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String source = "this is a test of <b>ImageGetter</b> it contains " +
            "two images: <br/>" +
            "<img src=\"http://developer.android.com/assets/images/dac_logo.png\"><br/>and<br/>" +
            "<img src=\"http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg\">";
    String imgs="<p><img alt=\"\" src=\"http://images.visitcanberra.com.au/images/canberra_hero_image.jpg\" style=\"height:50px; width:100px\" />Test Article, Test Article, Test Article, Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,v</p>";
    String src="<p><img alt=\"\" src=\"http://stylonica.com/wp-content/uploads/2014/02/Beauty-of-nature-random-4884759-1280-800.jpg\" />Test Attractions Test Attractions Test Attractions Test Attractions</p>";
    String img="<p><img alt=\"\" src=\"/site_media/photos/gallery/75b3fb14-3be6-4d14-88fd-1b9d979e716f.jpg\" style=\"height:508px; width:640px\" />Test Article, Test Article, Test Article, Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,Test Article,v</p>";
    Spanned spanned = Html.fromHtml(imgs, this, null);
    mTv = (TextView) findViewById(R.id.text);
    mTv.setText(spanned);
}

@Override
public Drawable getDrawable(String source) {
    LevelListDrawable d = new LevelListDrawable();
    Drawable empty = getResources().getDrawable(R.drawable.ic_launcher);
    d.addLevel(0, 0, empty);
    d.setBounds(0, 0, empty.getIntrinsicWidth(), empty.getIntrinsicHeight());

    new LoadImage().execute(source, d);

    return d;
}

class LoadImage extends AsyncTask<Object, Void, Bitmap> {

    private LevelListDrawable mDrawable;

    @Override
    protected Bitmap doInBackground(Object... params) {
        String source = (String) params[0];
        mDrawable = (LevelListDrawable) params[1];
        Log.d(TAG, "doInBackground " + source);
        try {
            InputStream is = new URL(source).openStream();
            return BitmapFactory.decodeStream(is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        Log.d(TAG, "onPostExecute drawable " + mDrawable);
        Log.d(TAG, "onPostExecute bitmap " + bitmap);
        if (bitmap != null) {
            BitmapDrawable d = new BitmapDrawable(bitmap);
            mDrawable.addLevel(1, 1, d);
            mDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
            mDrawable.setLevel(1);
            // i don't know yet a better way to refresh TextView
            // mTv.invalidate() doesn't work as expected
            CharSequence t = mTv.getText();
            mTv.setText(t);
        }
    }
}
}

As per below @rpgmaker comment i added this answer

yes you can do using ResolveInfo class

check your file is supported with already installed apps or not

using below code:

private boolean isSupportedFile(File file) throws PackageManager.NameNotFoundException {
    PackageManager pm = mContext.getPackageManager();
    java.io.File mFile = new java.io.File(file.getFileName());
    Uri data = Uri.fromFile(mFile);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(data, file.getMimeType());
    List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);

    if (resolveInfos != null && resolveInfos.size() > 0) {
        Drawable icon = mContext.getPackageManager().getApplicationIcon(resolveInfos.get(0).activityInfo.packageName);
        Glide.with(mContext).load("").placeholder(icon).into(binding.fileAvatar);
        return true;
    } else {
        Glide.with(mContext).load("").placeholder(R.drawable.avatar_defaultworkspace).into(binding.fileAvatar);
        return false;
    }
}

How to save public key from a certificate in .pem format

if it is a RSA key

openssl rsa  -pubout -in my_rsa_key.pem

if you need it in a format for openssh , please see Use RSA private key to generate public key?

Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.

What's the difference between "static" and "static inline" function?

One difference that's not at the language level but the popular implementation level: certain versions of gcc will remove unreferenced static inline functions from output by default, but will keep plain static functions even if unreferenced. I'm not sure which versions this applies to, but from a practical standpoint it means it may be a good idea to always use inline for static functions in headers.

Phonegap Cordova installation Windows

I faced this same error too. And i even tried downloading the PhoneGap master from GitHub,but i found out that what i got was Phonegap 2.9. I eventually had to download the Cordova 3 Source

Follow this steps to get it.

  1. Download and unzip the Cordova 3 Source
  2. Run the template.bat in the cordova-wp8 folder
  3. Copy the generated Zip files to your Visual studio template folder

Installing PIL with pip

  1. Install Xcode and Xcode Command Line Tools as mentioned.
  2. Use Pillow instead, as PIL is basically dead. Pillow is a maintained fork of PIL.

https://pypi.org/project/Pillow/

pip install Pillow

If you have both Pythons installed and want to install this for Python3:

python3 -m pip install Pillow

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

How do I install imagemagick with homebrew?

Answering old thread here (and a bit off-topic) because it's what I found when I was searching how to install Image Magick on Mac OS to run on the local webserver. It's not enough to brew install Imagemagick. You have to also PECL install it so the PHP module is loaded.

From this SO answer:

brew install php
brew install imagemagick
brew install pkg-config
pecl install imagick

And you may need to sudo apachectl restart. Then check your phpinfo() within a simple php script running on your web server.

If it's still not there, you probably have an issue with running multiple versions of PHP on the same Mac (one through the command line, one through your web server). It's beyond the scope of this answer to resolve that issue, but there are some good options out there.

Find a file by name in Visual Studio Code

I believe the action name is "workbench.action.quickOpen".

Getting value from JQUERY datepicker

If you want to get the date when the user selects it, you can do this:

$("#datepicker").datepicker({
    onSelect: function() { 
        var dateObject = $(this).datepicker('getDate'); 
    }
});

I am not sure about the second part of your question. But, have you tried using style sheets and relative positioning?

Default values in a C Struct

One pattern gobject uses is a variadic function, and enumerated values for each property. The interface looks something like:

update (ID, 1,
        BACKUP_ROUTE, 4,
        -1); /* -1 terminates the parameter list */

Writing a varargs function is easy -- see http://www.eskimo.com/~scs/cclass/int/sx11b.html. Just match up key -> value pairs and set the appropriate structure attributes.

How to drop all user tables?

begin
  for i in (select 'drop table '||table_name||' cascade constraints' tbl from user_tables) 
  loop
     execute immediate i.tbl;
  end loop;
end;

How to open up a form from another form in VB.NET?

You can also use showdialog

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                      Handles Button3.Click

     dim mydialogbox as new aboutbox1
     aboutbox1.showdialog()

End Sub

How to convert a string to lower case in Bash?

If using v4, this is baked-in. If not, here is a simple, widely applicable solution. Other answers (and comments) on this thread were quite helpful in creating the code below.

# Like echo, but converts to lowercase
echolcase () {
    tr [:upper:] [:lower:] <<< "${*}"
}

# Takes one arg by reference (var name) and makes it lowercase
lcase () { 
    eval "${1}"=\'$(echo ${!1//\'/"'\''"} | tr [:upper:] [:lower:] )\'
}

Notes:

  • Doing: a="Hi All" and then: lcase a will do the same thing as: a=$( echolcase "Hi All" )
  • In the lcase function, using ${!1//\'/"'\''"} instead of ${!1} allows this to work even when the string has quotes.

How does Java resolve a relative path in new File()?

There is a concept of a working directory.
This directory is represented by a . (dot).
In relative paths, everything else is relative to it.

Simply put the . (the working directory) is where you run your program.
In some cases the working directory can be changed but in general this is
what the dot represents. I think this is C:\JavaForTesters\ in your case.

So test\..\test.txt means: the sub-directory test
in my working directory, then one level up, then the
file test.txt. This is basically the same as just test.txt.

For more details check here.

http://docs.oracle.com/javase/7/docs/api/java/io/File.html

http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

How do I quickly rename a MySQL database (change schema name)?

I posted this How do I change the database name using MySQL? today after days of head scratching and hair pulling. The solution is quite simple export a schema to a .sql file and open the file and change the database/schema name in the sql CREAT TABLE section at the top. There are three instances or more and may not be at the top of the page if multible schemas are saved to the file. It is posible to edit the entire database this way but I expect that in large databases it could be quite a pain following all instances of a table property or index.

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Rename multiple files in a folder, add a prefix (Windows)

I was tearing my hair out because for some items, the renamed item would get renamed again (repeatedly, unless max file name length was reached). This was happening both for Get-ChildItem and piping the output of dir. I guess that the renamed files got picked up because of a change in the alphabetical ordering. I solved this problem in the following way:

Get-ChildItem -Path . -OutVariable dirs
foreach ($i in $dirs) { Rename-Item $i.name ("<MY_PREFIX>"+$i.name) }

This "locks" the results returned by Get-ChildItem in the variable $dirs and you can iterate over it without fear that ordering will change or other funny business will happen.

Dave.Gugg's tip for using -Exclude should also solve this problem, but this is a different approach; perhaps if the files being renamed already contain the pattern used in the prefix.

(Disclaimer: I'm very much a PowerShell n00b.)

Algorithm to randomly generate an aesthetically-pleasing color palette

In php:

function pastelColors() {
    $r = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127);
    $g = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127);
    $b = dechex(round(((float) rand() / (float) getrandmax()) * 127) + 127);

    return "#" . $r . $g . $b;
}

source: https://stackoverflow.com/a/12266311/2875783

How to get document height and width without using jquery

You can try also:

document.body.offsetHeight
document.body.offsetWidth

How can I add an item to a IEnumerable<T> collection?

you can do this.

//Create IEnumerable    
IEnumerable<T> items = new T[]{new T("msg")};

//Convert to list.
List<T> list = items.ToList();

//Add new item to list.
list.add(new T("msg2"));

//Cast list to IEnumerable
items = (IEnumerable<T>)items;

How can I make sticky headers in RecyclerView? (Without external lib)

Easiest way is to just create an Item Decoration for your RecyclerView.

import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class RecyclerSectionItemDecoration extends RecyclerView.ItemDecoration {

private final int             headerOffset;
private final boolean         sticky;
private final SectionCallback sectionCallback;

private View     headerView;
private TextView header;

public RecyclerSectionItemDecoration(int headerHeight, boolean sticky, @NonNull SectionCallback sectionCallback) {
    headerOffset = headerHeight;
    this.sticky = sticky;
    this.sectionCallback = sectionCallback;
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    super.getItemOffsets(outRect, view, parent, state);

    int pos = parent.getChildAdapterPosition(view);
    if (sectionCallback.isSection(pos)) {
        outRect.top = headerOffset;
    }
}

@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
    super.onDrawOver(c,
                     parent,
                     state);

    if (headerView == null) {
        headerView = inflateHeaderView(parent);
        header = (TextView) headerView.findViewById(R.id.list_item_section_text);
        fixLayoutSize(headerView,
                      parent);
    }

    CharSequence previousHeader = "";
    for (int i = 0; i < parent.getChildCount(); i++) {
        View child = parent.getChildAt(i);
        final int position = parent.getChildAdapterPosition(child);

        CharSequence title = sectionCallback.getSectionHeader(position);
        header.setText(title);
        if (!previousHeader.equals(title) || sectionCallback.isSection(position)) {
            drawHeader(c,
                       child,
                       headerView);
            previousHeader = title;
        }
    }
}

private void drawHeader(Canvas c, View child, View headerView) {
    c.save();
    if (sticky) {
        c.translate(0,
                    Math.max(0,
                             child.getTop() - headerView.getHeight()));
    } else {
        c.translate(0,
                    child.getTop() - headerView.getHeight());
    }
    headerView.draw(c);
    c.restore();
}

private View inflateHeaderView(RecyclerView parent) {
    return LayoutInflater.from(parent.getContext())
                         .inflate(R.layout.recycler_section_header,
                                  parent,
                                  false);
}

/**
 * Measures the header view to make sure its size is greater than 0 and will be drawn
 * https://yoda.entelect.co.za/view/9627/how-to-android-recyclerview-item-decorations
 */
private void fixLayoutSize(View view, ViewGroup parent) {
    int widthSpec = View.MeasureSpec.makeMeasureSpec(parent.getWidth(),
                                                     View.MeasureSpec.EXACTLY);
    int heightSpec = View.MeasureSpec.makeMeasureSpec(parent.getHeight(),
                                                      View.MeasureSpec.UNSPECIFIED);

    int childWidth = ViewGroup.getChildMeasureSpec(widthSpec,
                                                   parent.getPaddingLeft() + parent.getPaddingRight(),
                                                   view.getLayoutParams().width);
    int childHeight = ViewGroup.getChildMeasureSpec(heightSpec,
                                                    parent.getPaddingTop() + parent.getPaddingBottom(),
                                                    view.getLayoutParams().height);

    view.measure(childWidth,
                 childHeight);

    view.layout(0,
                0,
                view.getMeasuredWidth(),
                view.getMeasuredHeight());
}

public interface SectionCallback {

    boolean isSection(int position);

    CharSequence getSectionHeader(int position);
}

}

XML for your header in recycler_section_header.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_item_section_text"
    android:layout_width="match_parent"
    android:layout_height="@dimen/recycler_section_header_height"
    android:background="@android:color/black"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:textColor="@android:color/white"
    android:textSize="14sp"
/>

And finally to add the Item Decoration to your RecyclerView:

RecyclerSectionItemDecoration sectionItemDecoration =
        new RecyclerSectionItemDecoration(getResources().getDimensionPixelSize(R.dimen.recycler_section_header_height),
                                          true, // true for sticky, false for not
                                          new RecyclerSectionItemDecoration.SectionCallback() {
                                              @Override
                                              public boolean isSection(int position) {
                                                  return position == 0
                                                      || people.get(position)
                                                               .getLastName()
                                                               .charAt(0) != people.get(position - 1)
                                                                                   .getLastName()
                                                                                   .charAt(0);
                                              }

                                              @Override
                                              public CharSequence getSectionHeader(int position) {
                                                  return people.get(position)
                                                               .getLastName()
                                                               .subSequence(0,
                                                                            1);
                                              }
                                          });
    recyclerView.addItemDecoration(sectionItemDecoration);

With this Item Decoration you can either make the header pinned/sticky or not with just a boolean when creating the Item Decoration.

You can find a complete working example on github: https://github.com/paetztm/recycler_view_headers

Adding hours to JavaScript Date object?

SPRBRN is correct. In order to account for the beginning/end of the month and year, you need to convert to Epoch and back.

Here's how you do that:

var milliseconds = 0;          //amount of time from current date/time
var sec = 0;                   //(+): future
var min = 0;                   //(-): past
var hours = 2;
var days = 0;

var startDate = new Date();     //start date in local time (we'll use current time as an example)

var time = startDate.getTime(); //convert to milliseconds since epoch

//add time difference
var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);

var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now

or do it in one line (where variable names are the same as above:
var newDate = 
    new Date(startDate.getTime() + millisecond + 
        1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

If you want to use the non-SSL source, try removing the HTTPS source first, and then adding the HTTP one:

sudo gem sources -r https://rubygems.org
sudo gem sources -a http://rubygems.org  

UPDATE:

As mpapis states, this should be used only as a temporary workaround. There could be some security concerns if you're accessing RubyGems through the non-SSL source.

Once the workaround is not needed anymore, you should restore the SSL-source:

sudo gem sources -r http://rubygems.org
sudo gem sources -a https://rubygems.org

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

I use this method:

var results = this.Database.SqlQuery<yourEntity>("EXEC [ent].[GetNextExportJob] {0}", ProcessorID);

I like it because I just drop in Guids and Datetimes and SqlQuery performs all the formatting for me.

python list in sql query as parameter

a simpler solution:

lst = [1,2,3,a,b,c]

query = f"""SELECT * FROM table WHERE IN {str(lst)[1:-1}"""

How to add `style=display:"block"` to an element using jQuery?

$("#YourElementID").css("display","block");

Edit: or as dave thieben points out in his comment below, you can do this as well:

$("#YourElementID").css({ display: "block" });

How to Get XML Node from XDocument

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>
  <Node>
    <ID>123</ID>
    <Name>ABC</Name>
  </Node>
  <Node>
    <ID>124</ID>
    <Name>DEF</Name>
  </Node>
</Contacts>

Select a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected

XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();

Console.WriteLine(Contact.ToString());

Delete a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";

var Contact = (from xml2 in XMLDoc.Descendants("Node")
               where xml2.Element("ID").Value == id
               select xml2).FirstOrDefault();

Contact.Remove();
XMLDoc.Save("test.xml");

Add new node:

XDocument XMLDoc = XDocument.Load("test.xml");

XElement newNode = new XElement("Node",
    new XElement("ID", "500"),
    new XElement("Name", "Whatever")
);

XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");

Best way to deploy Visual Studio application that can run without installing

It is possible and is deceptively easy:

  1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
  2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
  3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

Calculating the position of points in a circle

Using one of the above answers as a base, here's the Java/Android example:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    RectF bounds = new RectF(canvas.getClipBounds());
    float centerX = bounds.centerX();
    float centerY = bounds.centerY();

    float angleDeg = 90f;
    float radius = 20f

    float xPos = radius * (float)Math.cos(Math.toRadians(angleDeg)) + centerX;
    float yPos = radius * (float)Math.sin(Math.toRadians(angleDeg)) + centerY;

    //draw my point at xPos/yPos
}

Best approach to remove time part of datetime in SQL Server

See this question:
How can I truncate a datetime in SQL Server?

Whatever you do, don't use the string method. That's about the worst way you could do it.

SQL Server 2008 - Case / If statements in SELECT Clause

The most obvious solutions are already listed. Depending on where the query is sat (i.e. in application code) you can't always use IF statements and the inline CASE statements can get painful where lots of columns become conditional. Assuming Col1 + Col3 + Col7 are the same type, and likewise Col2, Col4 + Col8 you can do this:

SELECT Col1, Col2 FROM tbl WHERE @Var LIKE 'xyz'
UNION ALL
SELECT Col3, Col4 FROM tbl WHERE @Var LIKE 'zyx'
UNION ALL
SELECT Col7, Col8 FROM tbl WHERE @Var NOT LIKE 'xyz' AND @Var NOT LIKE 'zyx'

As this is a single command there are several performance benefits with regard to plan caching. Also the Query Optimiser will quickly eliminate those statements where @Var doesn't match the appropriate value without touching the storage engine.

Django error - matching query does not exist

You can use this:

comment = Comment.objects.filter(pk=comment_id)

TypeError: tuple indices must be integers, not str

Like the error says, row is a tuple, so you can't do row["pool_number"]. You need to use the index: row[0].

How I can check whether a page is loaded completely or not in web driver?

Simple ready2use snippet, working perfectly for me

static void waitForPageLoad(WebDriver wdriver) {
    WebDriverWait wait = new WebDriverWait(wdriver, 60);

    Predicate<WebDriver> pageLoaded = new Predicate<WebDriver>() {

        @Override
        public boolean apply(WebDriver input) {
            return ((JavascriptExecutor) input).executeScript("return document.readyState").equals("complete");
        }

    };
    wait.until(pageLoaded);
}

Finding the type of an object in C++

You are looking for dynamic_cast<B*>(pointer)

What's sizeof(size_t) on 32-bit vs the various 64-bit data models?

size_t is 64 bit normally on 64 bit machine

What is the difference between React Native and React?

In a simple sense, React and React native follows the same design principles except in the case of designing user interface.

  1. React native has a separate set of tags for defining user interface for mobile, but both use JSX for defining components.
  2. Both systems main intention is to develop re-usable UI-components and reduce development effort by its compositions.
  3. If you plan & structure code properly you can use the same business logic for mobile and web

Anyway, it's an excellent library to build user interface for mobile and web.

How do I dynamically set HTML5 data- attributes using react?

You should not wrap JavaScript expressions in quotes.

<option data-img-src={this.props.imageUrl} value="1">{this.props.title}</option>

Take a look at the JavaScript Expressions docs for more info.

How to get database structure in MySQL via query

To get the whole database structure as a set of CREATE TABLE statements, use mysqldump:

mysqldump database_name --compact --no-data

For single tables, add the table name after db name in mysqldump. You get the same results with SQL and SHOW CREATE TABLE:

SHOW CREATE TABLE table;

Or DESCRIBE if you prefer a column listing:

DESCRIBE table;

Create normal zip file programmatically

You should look into Zip Packages

They are a more structured version of normal ZIP archives, requiring some meta stuff in the root. So other ZIP tools can open a package, but the Sysytem.IO.Packaging API can not open all ZIP files.

CodeIgniter: How to use WHERE clause and OR clause

You can use or_where() for that - example from the CI docs:

$this->db->where('name !=', $name);

$this->db->or_where('id >', $id); 

// Produces: WHERE name != 'Joe' OR id > 50

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I had same problem regarding that i.e A network-related or instance-specific error occurred while establishing a connection to SQL Server.

I was using SQL Server 2005 (.\sqlexpress)` and worked fine but suddenly services stopped and gave me error.

I solved it like this,

Start -> Search Box - > Sql Configuration Manager -> SQL Server 2005 Services >and just Change Your SQL Server (SQLEXPRESS) State to Running by right clicking that service Sate.

Is Google Play Store supported in avd emulators?

It's not officially supported yet.

Edit: It's now supported in modern versions of Android Studio, at least on some platforms.

Old workarounds

If you're using an old version of Android Studio which doesn't support the Google Play Store, and you refuse to upgrade, here are two possible workarounds:

  1. Ask your favorite app's maintainers to upload a copy of their app into the Amazon Appstore. Next, install the Appstore onto your Android device. Finally, use the Appstore to install your favorite app.

  2. Or: Do a Web search to find a .apk file for the software you want. For example, if you want to install SleepBot in your Android emulator, you can do a Google Web search for [ SleepBot apk ]. Then use adb install to install the .apk file.

Currency formatting in Python

A lambda for calculating it inside a function, with help from @Nate's answer

converter = lambda amount, currency: "%s%s%s" %(
    "-" if amount < 0 else "", 
    currency, 
    ('{:%d,.2f}'%(len(str(amount))+3)).format(abs(amount)).lstrip())

and then,

>>> converter(123132132.13, "$")
'$123,132,132.13'

>>> converter(-123132132.13, "$")
'-$123,132,132.13'

jQuery if div contains this text, replace that part of the text

var d = $('.text_div');
d.text(d.text().trim().replace(/contains/i, "hello everyone"));

do-while loop in R

Noticing that user 42-'s perfect approach {
* "do while" = "repeat until not"
* The code equivalence:

do while (condition) # in other language
..statements..
endo

repeat{ # in R
  ..statements..
  if(! condition){ break } # Negation is crucial here!
}

} did not receive enough attention from the others, I'll emphasize and bring forward his approach via a concrete example. If one does not negate the condition in do-while (via ! or by taking negation), then distorted situations (1. value persistence 2. infinite loop) exist depending on the course of the code.

In Gauss:

proc(0)=printvalues(y);
DO WHILE y < 5;    
y+1;
 y=y+1;
ENDO;
ENDP;
printvalues(0); @ run selected code via F4 to get the following @
       1.0000000 
       2.0000000 
       3.0000000 
       4.0000000 
       5.0000000 

In R:

printvalues <- function(y) {
repeat {
 y=y+1;
print(y)
if (! (y < 5) ) {break}   # Negation is crucial here!
}
}
printvalues(0)
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5

I still insist that without the negation of the condition in do-while, Salcedo's answer is wrong. One can check this via removing negation symbol in the above code.

wget: unable to resolve host address `http'

The DNS server seems out of order. You can use another DNS server such as 8.8.8.8. Put nameserver 8.8.8.8 to the first line of /etc/resolv.conf.

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Sleeping in a batch file

In Notepad, write:

@echo off
set /a WAITTIME=%1+1
PING 127.0.0.1 -n %WAITTIME% > nul
goto:eof

Now save as wait.bat in the folder C:\WINDOWS\System32, then whenever you want to wait, use:

CALL WAIT.bat <whole number of seconds without quotes>

Saving data to a file in C#

One liner:

System.IO.File.WriteAllText(@"D:\file.txt", content);

It creates the file if it doesn't exist and overwrites it if it exists. Make sure you have appropriate privileges to write to the location, otherwise you will get an exception.

https://msdn.microsoft.com/en-us/library/ms143375%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

Write string to text file and ensure it always overwrites the existing content.

Is it possible to print a variable's type in standard C++?

#include <iostream>
#include <typeinfo>
using namespace std;
#define show_type_name(_t) \
    system(("echo " + string(typeid(_t).name()) + " | c++filt -t").c_str())

int main() {
    auto a = {"one", "two", "three"};
    cout << "Type of a: " << typeid(a).name() << endl;
    cout << "Real type of a:\n";
    show_type_name(a);
    for (auto s : a) {
        if (string(s) == "one") {
            cout << "Type of s: " << typeid(s).name() << endl;
            cout << "Real type of s:\n";
            show_type_name(s);
        }
        cout << s << endl;
    }

    int i = 5;
    cout << "Type of i: " << typeid(i).name() << endl;
    cout << "Real type of i:\n";
    show_type_name(i);
    return 0;
}

Output:

Type of a: St16initializer_listIPKcE
Real type of a:
std::initializer_list<char const*>
Type of s: PKc
Real type of s:
char const*
one
two
three
Type of i: i
Real type of i:
int

When to Redis? When to MongoDB?

Maybe this resource is useful helping decide between both. It also discusses several other NoSQL databases, and offers a short list of characteristics, along with a "what I would use it for" explanation for each of them.

http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis

Accessing variables from other functions without using global variables

I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:

var MyApp = {}; // Globally scoped object

function foo(){
    MyApp.color = 'green';
}

function bar(){
    alert(MyApp.color); // Alerts 'green'
} 

No one should yell at you for doing something like the above.

What is the meaning of ToString("X2")?

It formats the string as two uppercase hexadecimal characters.

In more depth, the argument "X2" is a "format string" that tells the ToString() method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.

byte.ToString() without any arguments returns the number in its natural decimal representation, with no padding.

Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString() methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString().

Python ImportError: No module named wx

Just open your terminal and run this command thats for windows users pip install -U wxPython

for Ubuntu user you can use this

pip install -U \
-f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-16.04 \
wxPython

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

I tried make a telnet over remote server on port 3306. The error message is clear

Host 'x.x.x.x' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'Connection closed by foreign host.

As root at server mysqladmin flush-hosts worked at all!

How do I find out my root MySQL password?

MySQL 5.5 on Ubuntu 14.04 required slightly different commands as recommended here. In a nutshell:

sudo /etc/init.d/mysql stop
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
mysql -u root

And then from the MySQL prompt

FLUSH PRIVILEGES;
SET PASSWORD FOR root@'localhost' = PASSWORD('password');
UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
FLUSH PRIVILEGES;

And the cited source offers an alternate method as well.

Objective-C: Reading a file line by line

Use this script, it works great:

NSString *path = @"/Users/xxx/Desktop/names.txt";
NSError *error;
NSString *stringFromFileAtPath = [NSString stringWithContentsOfFile: path
                                                           encoding: NSUTF8StringEncoding
                                                              error: &error];
if (stringFromFileAtPath == nil) {
    NSLog(@"Error reading file at %@\n%@", path, [error localizedFailureReason]);
}
NSLog(@"Contents:%@", stringFromFileAtPath);

Using :focus to style outer div?

focus-within

.box:focus-within {
  background: cyan;
}

read more here

Git keeps asking me for my ssh key passphrase

Another possible solution that is not mentioned above is to check your remote with the following command:

git remote -v

If the remote does not start with git but starts with https you might want to change it to git by following the example below.

git remote -v // origin is https://github.com/user/myrepo.git
git remote set-url origin [email protected]:user/myrepo.git
git remote -v // check if remote is changed

Apache: The requested URL / was not found on this server. Apache

I had the same problem, but believe it or not is was a case of case sensitivity.

This on localhost: http://localhost/.../getdata.php?id=3

Did not behave the same as this on the server: http://server/.../getdata.php?id=3

Changing the server url to this (notice the capital D in getData) solved my issue. http://localhost/.../getData.php?id=3

Checking on a thread / remove from list

The answer has been covered, but for simplicity...

# To filter out finished threads
threads = [t for t in threads if t.is_alive()]

# Same thing but for QThreads (if you are using PyQt)
threads = [t for t in threads if t.isRunning()]

How to search by key=>value in a multidimensional array in PHP

function findKey($tab, $key){
    foreach($tab as $k => $value){ 
        if($k==$key) return $value; 
        if(is_array($value)){ 
            $find = findKey($value, $key);
            if($find) return $find;
        }
    }
    return null;
}

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

I ran into similar problems when accessing the project files from different computers via a shared folder. In my case clean + reabuild did not help. Had to delete the bin and objects folders from the output directory.

How to use the COLLATE in a JOIN in SQL Server?

As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server

SELECT *
  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p
  ON (p.vTreasuryId = f.RFC) COLLATE Database_Default 

Why does Java's hashCode() in String use 31 as a multiplier?

According to Joshua Bloch's Effective Java (a book that can't be recommended enough, and which I bought thanks to continual mentions on stackoverflow):

The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically.

(from Chapter 3, Item 9: Always override hashcode when you override equals, page 48)

Javascript to sort contents of select element

Yes DOK has the right answer ... either pre-sort the results before you write the HTML (assuming it's dynamic and you are responsible for the output), or you write javascript.

The Javascript Sort method will be your friend here. Simply pull the values out of the select list, then sort it, and put them back :-)

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.

The HttpSession#setMaxInactiveInterval() doesn't change much here by the way. It does exactly the same as <session-timeout> in web.xml, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static method).


To play around and experience this yourself, try to set <session-timeout> to 1 minute and create a HttpSessionListener like follows:

@WebListener
public class HttpSessionChecker implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
    }

}

(if you're not on Servlet 3.0 yet and thus can't use @WebListener, then register in web.xml as follows):

<listener>
    <listener-class>com.example.HttpSessionChecker</listener-class>
</listener>

Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.

See also:

How do I enable TODO/FIXME/XXX task tags in Eclipse?

There are apparently distributions or custom builds in which the ability to set Task Tags for non-Java files is not present. This post mentions that ColdFusion Builder (built on Eclipse) does not let you set non-Java Task Tags, but the beta version of CF Builder 2 does. (I know the OP wasn't using CF Builder, but I am, and I was wondering about this question myself ... because he didn't see the ability to set non-Java tags, I thought others might be in the same position.)

How can I throw a general exception in Java?

You could create your own Exception class:

public class InvalidSpeedException extends Exception {

  public InvalidSpeedException(String message){
     super(message);
  }

}

In your code:

throw new InvalidSpeedException("TOO HIGH");

MySQL Creating tables with Foreign Keys giving errno: 150

I encountered the same problem, but I check find that I hadn't the parent table. So I just edit the parent migration in front of the child migration. Just do it.

Opacity CSS not working in IE8

You can also add a polyfil to enable native opacity usage in IE6-8.

https://github.com/bladeSk/internet-explorer-opacity-polyfill

This is a stand alone polyfil that does not require jQuery or other libraries. There are several small caveats it does not operate on in-line styles and for any style sheets that need opacity polyfil'd they must adhere to the same-origin security policy.

Usage is dead simple

<!--[if lte IE 8]>
    <script src="jquery.ie-opacity-polyfill.js"></script>
<![endif]-->

<style>
    a.transparentLink { opacity: 0.5; }
</style>

<a class="transparentLink" href="#"> foo </a>

Shorthand if/else statement Javascript

var x = y !== undefined ? y : 1;

Note that var x = y || 1; would assign 1 for any case where y is falsy (e.g. false, 0, ""), which may be why it "didn't work" for you. Also, if y is a global variable, if it's truly not defined you may run into an error unless you access it as window.y.


As vol7ron suggests in the comments, you can also use typeof to avoid the need to refer to global vars as window.<name>:

var x = typeof y != "undefined" ? y : 1;

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

This can be done using GroupBy and SelectMany in LINQ lamda expression

var groupByMax = list.GroupBy(x=>x.item1).SelectMany(y=>y.Where(z=>z.item2 == y.Max(i=>i.item2)));

Git remote branch deleted, but still it appears in 'branch -a'

Use:

git remote prune <remote>

Where <remote> is a remote source name like origin or upstream.

Example: git remote prune origin

Recommended way to embed PDF in HTML?

Our problem is that for legal reasons we are not allowed to temporarily store a PDF on the hard disk. In addition, the entire page should not be reloaded when displaying a PDF as Preview in the Browser.

First we tried PDF.jS. It worked with Base64 in the viewer for Firefox and Chrome. However, it was unacceptably slow for our PDF. IE/Edge didn't work at all.

We therefore tried it with a Base64 string in an HTML object tag. This again didn't work for IE/Edge (maybe the same problem as with PDF.js). In Chrome/Firefox/Safari again no problem. That's why we chose a hybrid solution. IE/Edge we use an IFrame and for all other browsers the object-tag.

The IFrame solution would of course also work for Chrome and co. The reason why we didn't use this solution for Chrome is that although the PDF is displayed correctly, Chrome makes a new request to the server as soon as you click on "download" in the preview. The required hidden-field pdfHelperTransferData (for sending our form data needed for PDF generation) is no longer set because the PDF is displayed in an IFrame. For this feature/bug see Chrome sends two requests when downloading a PDF (and cancels one of them).

Now the problem children IE9 and IE10 remain. For these we gave up a preview solution and simply send the document by clicking the preview button as a download to the user (instead of the preview). We have tried a lot but even if we had found a solution the extra effort for this tiny part of users would not have been worth the effort. You can find our solution for the download here: Download PDF without refresh with IFrame.

Our Javascript:

var transferData = getFormAsJson()
if (isMicrosoftBrowser()) {
        // Case IE / Edge (because doesn't recoginzie Pdf-Base64 use Iframe)
        var form = document.getElementById('pdf-helper-form');
        $("#pdfHelperTransferData").val(transferData);
        form.target = "iframe-pdf-shower";
        form.action = "serverSideFunctonWhichWritesPdfinResponse";
        form.submit();
 } else {
        // Case non IE use Object tag instead of iframe
        $.ajax({
            url: "serverSideFunctonWhichRetrivesPdfAsBase64",
            type: "post",
            data: { downloadHelperTransferData: transferData },
            success: function (result) {
                $("#object-pdf-shower").attr("data", result);
            }
        })
 }

Our HTML:

<div id="pdf-helper-hidden-container" style="display:none">
   <form id="pdf-helper-form" method="post">
        <input type="hidden" name="pdfHelperTransferData" id="pdfHelperTransferData" />
   </form>
</div>

<div id="pdf-wrapper" class="modal-content">
    <iframe id="iframe-pdf-shower" name="iframe-pdf-shower"></iframe>
    <object id="object-pdf-shower" type="application/pdf"></object>
</div>

To check the browser type for IE/Edge see here: How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript? I hope these findings will save someone else the time.

How to fix the session_register() deprecated issue?

Don't use it. The description says:

Register one or more global variables with the current session.

Two things that came to my mind:

  1. Using global variables is not good anyway, find a way to avoid them.
  2. You can still set variables with $_SESSION['var'] = "value".

See also the warnings from the manual:

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

This is pretty important, because the register_globals directive is set to False by default!

Further:

This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below.

and

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered(), and session_unregister().

CHECK constraint in MySQL is not working

Update to MySQL 8.0.16 to use checks:

As of MySQL 8.0.16, CREATE TABLE permits the core features of table and column CHECK constraints, for all storage engines. CREATE TABLE permits the following CHECK constraint syntax, for both table constraints and column constraints

MySQL Checks Documentation