SoftwareDistribution folder is huge on small drive

Windows cleans SoftwareDistribution directory automatically after updates are installed.
The directory was 1GB big after updates on 20GB partition and the reason was \softwaredistribution\datastore\datastore.edb file.
Forums says just delete the whole folder. Don't do it!
datastore.edb is Extensible Storage Engine (ESE) database and you can shrink it.
Launch cmd.exe as as administrator and execute

net stop wuauserv
esentutl /d %windir%\softwaredistribution\datastore\datastore.edb
net start wuauserv

After defragmentation the file was reduced upto 10MB. Wow! I got free space on the disk.
Enjoy!

Certificate Credentials - Generate Proxy Class

Below you will find my workaround for proxy class generation if remote web service is old-fashioned and protected with certificate credentials.
Often is enough svcutil.exe to generate proxy class. But not in my case because web service was ancient and does not provide MEX, WS or netTcp binding. Please advise whether is possible to use svcutil for archaic service like https://remote.com/service?wsdl
Another way to create proxy class is wsdl.exe utility, but wsdl.exe does not support certificates at all.

Solution: I have installed locally http NGINX revers proxy with following config

    server {
        listen       8080;
        server_name  localhost;

        location / {
     #repace urls in response     
     sub_filter 'https://remote.com:8080/' 'http://$host:8080/';
     sub_filter_types *; # enable all type
     sub_filter_once off;
            proxy_pass https://remote.com:8080/;
            proxy_ssl_certificate  cert.pem;
            proxy_ssl_certificate_key cert.pem;
        }
    }

to convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM file execute
openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes

start Nginx and execute wsdl.exe command
wsdl.exe http://localhost:8080/service?wsdl

Enjoy!


How to REALLY destroy stored data

I have written already about SDelete and bootable DiskWipe, but what if you have to rely on the result?
In that case you have only once option - physical destruction!

First you have to disassemble your hard drive disk and extract each single platter.

As next step use blow torch (blowlamp) till surface of disk will be red, look at the photo.

After that all your data are really demolished.


CAUTION! That is truly very dangerous! Fire hazard! 

bulk convert to u-law or a-law audio format


The telephone system requires often audio prompts in u-law or a-law format.
To convert all your wav files you can execute following command in the directory with wav files,
it will convert file and save it with the same file name and new extension

# for a in *.wav; do sox "$a" -t raw -r 8000 -c 1 -e u-law ${a/.wav/.ulaw} ; done

or 

# for a in *.wav; do sox "$a" -t raw -r 8000 -c 1 -e a-law ${a/.wav/.alaw} ; done

Enjoy!

Connecting to Ubuntu using UltraVNC


first enable Desktop Sharing on Ubuntu 16.04 host

and protect it with password.


Ubuntu is running Vino VNC Server and UltraVNC does not support Vino encryption. You have to execute without restart and sudo(!) the followinf command

$ gsettings set org.gnome.Vino require-encryption false

Enjoy!

PS: I did not test the settings with TightVNC or RealVNC, but expecting also  to be working solution

Aspose.Cells change style of cell

It was possible in previous versions of Aspose Cells to apply changes directly to cell.
Starting from version 7.0 you have to call first GetStyle() method and then call SetStyle(s) method.

You can use simple extension method to mimic old behavior.


public static class AsposeCellsExt
    {
        public static void ChangeStyle(this Cell cell, Action<Style> applyChangesTo)
        {
            Style s = cell.GetStyle();
            applyChangesTo(s);
            cell.SetStyle(s);
        }
    }

and now to fill A1 cell with green background you can execute just single line

cells[0, 0].ChangeStyle(s => { s.ForegroundColor = GREEN; s.Pattern = Aspose.Cells.BackgroundType.Solid; });


Enjoy!

[SOLVED]: mysqldump: Got error: 1045: Access denied for user 'ODBC'@'localhost'

I would like to execute mysqldump using .mylogin.cnf file and --login-path option to make it more secure as it can be with plain text password. It appears the error
mysqldump: Got error: 1045: Access denied for user 'ODBC'@'localhost' (using password: NO) when trying connect.
It was really strange because I have never created any ODBC user.


The solution: you have to export MYSQL_TEST_LOGIN_FILE variable and point to correct CNF file, e.g.
SET MYSQL_TEST_LOGIN_FILE=C:\secret\.mylogin.cnf
 - or -
export MYSQL_TEST_LOGIN_FILE=/var/mysql/.mylogin.cnf

Don't forget to restrict access permission to the file!

Enjoy!

OTRS: add new statistics takes too long

Does it take an enternity to create new statistics in OTRS?
Check an option CustomerIDAsMultiSelect in SysConfig and set it to No,
You can't select mutiple customers anymore, try to revert the option back and edit existing report.

Enjoy!

[SOLVED] ERROR 1290 (HY000) The MySQL server is running with the --secure-file-priv


if appears the error
ERROR 1290 (HY000) The MySQL server is running with the --secure-file-priv

you have to check
1.  execute show variables and find secure_file_priv variable value (e.g. c:/uploads/)
2. use full path in SELECT .. INTO OUTFILE  or LOAD DATA statements (e.g. 'c:/uploads/some_file.cvs')
3. grant file priviledge to the user (e.g. GRANT FILE ON *.* TO 'someuser'@'localhost';)


You can always change the path in my.ini file, search for secure_file_priv 


Enjoy!

[SOLVED] crond[PID]: (root) FAILED to authorize user with PAM (Permission denied)


I have disabled root login in /etc/security/access.conf and it appears  the error message in /var/cron/log

crond[PID]: (root) FAILED to authorize user with PAM (Permission denied)

The fixed access.conf file looks like

#Allow root only from localhost and cron daemon
+ : root  : 127.0.0.1 ::1
+ : root : cron crond :0 tty1 tty2 tty3 tty4 tty5 tty6
- : root  : ALL


Enjoy!

ARDUINO: control your gate, pump just with single power button

It is often necessary to control remotely two-state devices like entrance gate, water pump, RF switch or IR switch. My idea was to keep just single on/off button and keep smallest possible leakage current.
You can see my idea on schematic below.

Windows Server - make network private

You can mark your network location on windows host as private just in three steps

1. Launch PowerShell as administrator
2. Get list of network interfaces (NICs) with command
Get-NetConnectionProfile

3. Change network category for selected network interface
Set-NetConnectionProfile -InterfaceIndex 15 -NetworkCategory Private


Enjoy!

Arduino - Easter Egg Dyeing

You know that modern eastern egg dyes requires about 5 minutes to make super bright eggs. It also takes about 5 minutes and 10 lines of code to create the countdown timer with left minute display on arduino.
The schematic diagram is more than simple. Just connect 5 or more green LEDs on ports 0-7 and one red LED on port 8.

Here is photo of my assembled board.

Is it possible to make the code shorter?!
/*
  Arduino - count down timer
*/

int MAX_LEDS = 5; // max_leds = maximun minutes
int counter = 60 * MAX_LEDS; 
bool flip_flop = LOW;

void setup() {
  
   DDRB = DDRC = DDRD = 255; // set all ports to output
   PORTD = (((unsigned int)1 << MAX_LEDS) - 1); // ON first N LEDs

   while(counter--){
    delay(1000);  // wait for a second
    flip_flop = flip_flop == LOW ? HIGH : LOW;
    digitalWrite((int)(counter/60), flip_flop); // blink current minute LED
   }

   while(true){
    delay(1000);  // wait for a second
    flip_flop = flip_flop == LOW ? HIGH : LOW;
    digitalWrite(8, flip_flop); // blink red light
   }
}

void loop() {

}

and video

Enjoy!

[SOLVED]: rhythmbox does not play mp3 file

Yes, it should play and you have already double checked  that gstreamer was installed with all possible plugins. Also was installed apt://ubuntu-restricted-extras on Ubuntu or ugly on fedora

# yum install gstreamer gstreamer-ffmpeg gstreamer-plugins-bad gstreamer-plugins-bad-free gstreamer-plugins-bad-free-extras gstreamer-plugins bad-nonfree gstreamer-plugins-base gstreamer-plugins-good gstreamer-plugins-ugly install faad2 faac libdca wget compat-libstdc++-33 compat-libstdc++-296  xine-lib-extras-freeworld
just execute following command, which helped me a lot

# cd ~/Music
# find . -exec touch '{}' \;


Enjoy with mp3 on rhythmbox!

HOWTO: RDP from linux to windows with audio support

what you need to hear sounds on linux box connected to Windows Remote Desktop using RDP (Remote Desktop Protocol) connection?

You need linux machine with
1. Xorg
2. ALSA support (e.g. alsa-plugins-pulseaudio installed)
3. FreeRDP client

start RDP client with following command line parameters
# xfreerdp /sound:sys:alsa /u:<USERNAME> /v:<WINDOWS_HOST>


Enjoy your remote sound!

Control Kodi on Raspberry Pi with TV Remote

You don't have to buy IR receiver and remote to control your OSMC on Raspberry Pi. Yes, it's true.
Because Raspberry Pi supports HDMI-CEC and most of TVs support too.
HDMI-CEC means Consumer Electronics Control and allows to control attached devices just with single TV remote. It has also different names (please check recent revision)
AOC - E-link
LG - SimpLink
Loewe - Digital Link or Digital Link Plus
Mitsubishi - NetCommand for HDMI
Onkyo - RIHD (Remote Interactive over HDMI)
Panasonic - VIERA Link or HDAVI Control or EZ-Sync
Philips - EasyLink
Pioneer - Kuro Link
Runco International - RuncoLink
Samsung - Anynet+
Sharp - Aquos Link
Sony - BRAVIA Link or BRAVIA Sync
Toshiba - Regza Link or CE-Link

Also you need good HDMI CEC compatible cable. Cheap one transfers no signal sometimes.

Also I recommend to install Kore - Kodi/XBMC remote for Android if you own android smartphone.
Kore Main Features:

  • Control your media center with an easy to use remote
  • See what’s currently playing, including relevant information about it (movies, TV shows, music, pictures, files and addons)
  • View and manage the current playlist
  • Change and sync subtitles and audiostreams
  • View your media library, with details about movies, TV shows, music and addons
  • Control Kodi's volume with the hardware keys


Enjoy!

HOWTO: fix "Forbidden" from '"Anonymous"

If you need to outdial anonymously the call received from SIP trunk on Avaya CM you can see the error message on SIP server
"Forbidden" from '"Anonymous" <sip:anonymous@anonymous.invalid>

First you should fix From: field, because Avaya will accept only registered domain, it should sound like
From: "unknown" <sip:unknown@YOUR.SIP.DOMAIN>

Next step to make call anonymous, Avaya respects SIP header Privacy (see RFC 3325). So you need to send header
Privacy: id

Enjoy!

HOWTO: debug the AppPool crashing

get latest WinDbg here
make dir c:\MySymbols

Alt+1 in WInDBG and execute
.sympath cache*c:\MySymbols;srv*https://msdl.microsoft.com/download/symbols
.reload

after that
!clrstack

if appears error message, do
.cordll -ve -u -l

If you see message ERROR: Unable to load DLL mscordacwks, take mscordacwks from original system and copy it into \mscorwks.dll\53A121FA5ae000\mscordacwks.dll

and repeat
.cordll -ve -u -l
!clrstack -p

It returns function calls with arguments. To dump the object's value use !do with HEX address, e.g.
!do 0x09fd0618 

Enjoy!

LINQ Aggregate algorithm explained

Question

This might sound lame, but I have not been able to find a really good explanation of Aggregate. Good means short, descriptive, comprehensive with a small and clear example.

Answer

The easiest to understand definition of Aggregate is that it performs an operation on each element of the list taking into account the operations that have gone before. That is to say it performs the action on the first and second element and carries the result forward. Then it operates on the previous result and the third element and carries forward. etc. Example 1. Summing numbers
var nums = new[]{1,2,3,4};
var sum = nums.Aggregate( (a,b) => a + b);
Console.WriteLine(sum); // output: 10 (1+2+3+4)
This adds 1 and 2 to make 3. Then adds 3 (result of previous) and 3 (next element in sequence) to make 6. Then adds 6 and 4 to make 10. Example 2. create a csv from an array of strings
var chars = new []{"a","b","c", "d"};
var csv = chars.Aggregate( (a,b) => a + ',' + b);
Console.WriteLine(csv); // Output a,b,c,d
This works in much the same way. Concatenate a a comma and b to make a,b. Then concatenates a,b with a comma and c to make a,b,c. and so on. Example 3. Multiplying numbers using a seed For completeness, there is an overload of Aggregate which takes a seed value.
var multipliers = new []{10,20,30,40};
var multiplied = multipliers.Aggregate(5, (a,b) => a * b);
Console.WriteLine(multiplied); //Output 1200000 ((((5*10)*20)*30)*40)
Much like the above examples, this starts with a value of 5 and multiplies it by the first element of the sequence 10 giving a result of 50. This result is carried forward and multiplied by the next number in the sequence 20 to give a result of 1000. This continues through the remaining 2 element of the sequence. Live examples: http://rextester.com/ZXZ64749 Docs: http://msdn.microsoft.com/en-us/library/bb548651.aspx Addendum Example 2, above, uses string concatenation to create a list of values separated by a comma. This is a simplistic way to explain the use of Aggregate which was the intention of this answer. However, if using this technique to actually create a large amount of comma separated data, it would be more appropriate to use a StringBuilder, and this is entirely compatible with Aggregate using the seeded overload to initiate the StringBuilder.
var chars = new []{"a","b","c", "d"};
var csv = chars.Aggregate(new StringBuilder(), (a,b) => {
    if(a.Length>0)
        a.Append(",");
    a.Append(b);
    return a;
});
Console.WriteLine(csv);
Updated example: http://rextester.com/YZCVXV6464 Source

Using LINQ to remove elements from a List

Question

Say that I have LINQ query such as:
var authors = from x in authorsList
              where x.firstname == "Bob"
              select x;
Given that authorsList is of type List, how can I delete the Author elements from authorsList that are returned by the query into authors? Or, put another way, how can I delete all of the Bob's from authorsList? Note: This is a simplified example for the purposes of the question.

Answer

Well, it would be easier to exclude them in the first place:
authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();
However, that would just change the value of authorsList instead of removing the authors from the previous collection. Alternatively, you can use RemoveAll:
authorsList.RemoveAll(x => x.FirstName == "Bob");
If you really need to do it based on another collection, I'd use a HashSet, RemoveAll and Contains:
var setToRemove = new HashSet(authors);
authorsList.RemoveAll(x => setToRemove.Contains(x));
Source

When to use .First and when to use .FirstOrDefault

Question

I've searched around and haven't really found a clear answer as to when you'd want to use .First and when you'd want to use .FirstOrDefault with LINQ. When would you want to use .First? Only when you'd want to catch the exception if no results where returned?
var result = List.Where(x => x == "foo").First();
And when would you want to use .FirstOrDefault? When you'd always want the default type if no result?
var result = List.Where(x => x == "foo").FirstOrDefault();
And for that matter, what about Take?
var result = List.Where(x => x == "foo").Take(1);

Answer

I would use First() when I know or expect the sequence to have at least one element. In other words, when it is an exceptional occurrence when the sequence is empty. Use FirstOrDefault() when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check. (It is bad practice and might hurt performance). Finally, the difference between First() and Take() is that First() returns the element itself, while Take() returns a sequence of elements that contains exactly one element. (If you pass 1 as the parameter). Source

What is the Java equivalent for LINQ?

Question

see subj

Answer

LINQ to Objects - JAVA 8 has added the Stream API which adds support for functional-style operations on streams of values: Package java.util.stream Java 8 Explained: Applying Lambdas to Java Collections Source

Multiple Order By

Question

I have two tables, movies and categories, and I get an ordered list by categoryID first and then by Name. The movie table has three columns, ID, Name, and CategoryID. The category table two has columns, ID, and Name. I tried something like the following, but it didn't work.
var movies = _db.Movies.OrderBy( m => { m.CategoryID, m.Name })

Answer

This should work for you:
Var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name)
Source

LINQ query on a DataTable

Question

I'm trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example:
var results = from myRow in myDataTable
where results.Field("RowNo") == 1
select results;
This is not allowed. How do I get something like this working?

Answer

You can't query against the DataTable's Rows collection, since DataRowCollection doesn't implement IEnumerable. You need to use the AsEnumerable() extension for DataTable. Like so:
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field("RowNo") == 1
select myRow;
If you need to convert IEnumerable to a DataTable, use the CopyToDataTable() extension. Source

Group By Multiple Columns and Sum

Question

How can I do GroupBy Multiple Columns in LINQ Something similar to this in SQL:
SELECT * FROM  GROUP BY ,
How can I convert this to LINQ:
QuantityBreakdown
(
    MaterialID int,
    ProductID int,
    Quantity float
)

INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity)
SELECT MaterialID, ProductID, SUM(Quantity)
FROM @Transactions
GROUP BY MaterialID, ProductID

Answer

Use an anonymous type like group x by new { x.Column1, x.Column2 }
var query = (from t in Transactions
             group t by new {t.MaterialID, t.ProductID}
             into grp
                    select new
                    {
                        grp.Key.MaterialID,
                        grp.Key.ProductID,
                        Quantity = grp.Sum(t => t.Quantity)
                    }).ToList();
Source

Sublists with Group by

Question

Let's suppose if we have a class like
class Person { 
    internal int PersonID; 
    internal string car  ; 
}
Now I have a list of this class: List persons; Now this list can have instances multiple same PersonIDs, for ex.
persons[0] = new Person { PersonID = 1, car = "Ferrari" }; 
persons[1] = new Person { PersonID = 1, car = "BMW"     }; 
persons[2] = new Person { PersonID = 2, car = "Audi"    }; 
Is there a way I can group by personID and get the list of all the cars he has? For ex. expected result would be
class Result { 
   int PersonID;
   List cars; 
}
Could someone please point me in the right direction?

Answer

Absolutely - you basically want:
var results = from p in persons
              group p.car by p.PersonId into g
              select new { PersonID = g.Key, Cars = g.ToList() };
Or as a non-query expression:
var results = persons.GroupBy( p => p.PersonId, 
                               p => p.car,
                               (key, g) => new { 
                                                 PersonId = key, 
                                                 Cars = g.ToList() 
                                                }
                              );
Basically the contents of the group (when view as an IEnumerable) is a sequence of whatever values were in the projection (p.car in this case) present for the given key Source

Returning IEnumerable vs IQueryable

Question

What is the difference between returning IQueryable vs IEnumerable? Will both be deferred execution and when should one be preferred over the other?
IQueryable custs = from c in db.Customers
where c.City == ""
select c;

IEnumerable custs = from c in db.Customers
where c.City == ""
select c;

Answer

Yes, both will give you deferred execution. The difference is that IQueryable is the interface that allows LINQ-to-SQL (LINQ.-to-anything really) to work. So if you further refine your query on an IQueryable, that query will be executed in the database, if possible. For the IEnumerable case, it will be LINQ-to-object, meaning that all objects matching the original query will have to be loaded into memory from the database. Code:
IQueryable custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
That code will execute SQL to only select gold customers. The following code, on the other hand, will execute the original query in the database, then filtering out the non-gold customers in the memory:
IEnumerable custs = ...;
// Later on...
var goldCustomers = custs.Where(c => c.IsGold);
This is quite an important difference, and working on IQueryable can in many cases save you from returning too many rows from the database. Another prime example is doing paging: If you use Take and Skip on IQueryable, you will only get the number of rows requested; doing that on an IEnumerable will cause all of your rows to be loaded in memory. Source

Linq Distinct on a particular Property

Question

I am playing with Linq to learn about it but I can't figure out how to use Distinct when I do not have a simple list (a simple list of integers is pretty easy to do, this is not the question). What if want to use Distinct on a list of an Object on ONE or MORE Properties of the object? Example: If an object is Person, with Property Id. How can I get all Person and use Distinct on them with the property Id of the object?
Person1: Id=1, Name="Test1"
Person2: Id=1, Name="Test1"
Person3: Id=2, Name="Test2"
How can I get just Person1 and Person3? Is that possible? If it's not possible with Linq, what would be the best way to have a list of Person depending on some of its Properties in .Net 3.5?

Answer

What you need is a "distinct-by" effectively. I don't believe it's part of LINQ as it stands, although it's fairly easy to write:
public static IEnumerable DistinctBy
    (this IEnumerable source, Func keySelector)
{
    HashSet seenKeys = new HashSet();
    foreach (TSource element in source)
    {
        if (seenKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}
So to find the distinct values using just the Id property, you could use:
var query = people.DistinctBy(p => p.Id);
And to use multiple properties, you can use anonymous types, which implement equality appropriately:
var query = people.DistinctBy(p => new { p.Id, p.Name });
Source

MoreLINQ - enhances LINQ with a lot of methods

This project enhances LINQ to Objects with the following methods: Acquire, AssertCount, Batch, Concat, Consume, DistinctBy, EquiZip, ExceptBy, Fold, ForEach, Generate, GenerateByIndex, GroupAdjacent, Index, MaxBy, MinBy, OrderedMerge, Pad, Pairwise, Pipe, Prepend, PreScan, Scan, SingleOrFallback, SkipUntil, Split, TakeEvery, TakeLast, TakeUntil, ToDataTable, ToDelimitedString, ToHashSet, Trace, Zip, ZipLongest. To install MoreLINQ, run the following command in the Package Manager Console PM> Install-Package morelinq source

LEFT OUTER JOIN in LINQ

Question

How to perform left outer join in C# LINQ to objects without using join-on-equals-into clauses? Is there any way to do that with where clause? Correct problem: For inner join is easy and I have a solution like this
List innerFinal = (from l in lefts from r in rights where l.Key == r.Key
                             select new JoinPair { LeftId = l.Id, RightId = r.Id})
but for left outer join I need a solution. Mine is something like this but it's not working
List< JoinPair> leftFinal = (from l in lefts from r in rights
                             select new JoinPair { 
                                            LeftId = l.Id, 
                                            RightId = ((l.Key==r.Key) ? r.Id : 0
                                        })
where JoinPair is a class:
public class JoinPair { long leftId; long rightId; }

Answer

As stated on: 101 LINQ Samples - Left outer join
var q =
    from c in categories
    join p in products on c equals p.Category into ps
    from p in ps.DefaultIfEmpty()
    select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };
Source

LINQ equivalent of foreach for IEnumerable

Question

I'd like to do the equivalent of the following in LINQ, but I can't figure out how:
IEnumerable items = GetItems();
items.ForEach(i => i.DoStuff());
What is the real syntax?

Answer

1. LINQ is all about query data, while ForEach method is about manipulation (cause side effects)! 2. There is no ForEach extension for IEnumerable; only for List. So you could do
items.ToList().ForEach(i => i.DoStuff());
Alternatively, write your own ForEach extension method:
public static void ForEach(this IEnumerable enumeration, Action action)
{
    foreach(T item in enumeration)
    {
        action(item);
    }
}
Source

Retrieving Property name from lambda expression

Question

Is there a better way to get the Property name when passed in via a lambda expression?

Answer

Here's an update to method proposed by Cameron. The first parameter is not required.
public PropertyInfo GetPropertyInfo(
    Expression> propertyLambda)
{
    Type type = typeof(TSource);

    MemberExpression member = propertyLambda.Body as MemberExpression;
    if (member == null)
        throw new ArgumentException(string.Format(
            "Expression '{0}' refers to a method, not a property.",
            propertyLambda.ToString()));

    PropertyInfo propInfo = member.Member as PropertyInfo;
    if (propInfo == null)
        throw new ArgumentException(string.Format(
            "Expression '{0}' refers to a field, not a property.",
            propertyLambda.ToString()));

    if (type != propInfo.ReflectedType &&
        !type.IsSubclassOf(propInfo.ReflectedType))
        throw new ArgumentException(string.Format(
            "Expresion '{0}' refers to a property that is not from type {1}.",
            propertyLambda.ToString(),
            type));

    return propInfo;
}
Usage
var propertyInfo = GetPropertyInfo(u => u.UserID);
Source

Split List into Sublists

Question

: I believe this is another easy one for you LINQ masters out there. Is there any way I can separe a List into several separate lists of SomeObject, using the item index as the delimiter of each split? Let me exemplify: I have a List and I need a List<List> or List[], so that each of these resulting lists will contain a group of 3 items of the original list (sequentially). eg.: Original List: [a, g, e, w, p, s, q, f, x, y, i, m, c] Resulting lists: [a, g, e], [w, p, s], [q, f, x], [y, i, m], [c] I'd also need the resulting lists size to be a parameter of this function. Is it possible??

Answer

: completely lazy: works on infinite enumerables no intermediate copying/buffering O(n) execution time works also when child sequences are only partially consumed
public static IEnumerable Chunks(this IEnumerable enumerable,
                                                    int chunkSize)
{
    if (chunkSize < 1) throw new ArgumentException("chunkSize must be positive");

    using (var e = enumerable.GetEnumerator())
    while (e.MoveNext())
    {
        var remaining = chunkSize;    // elements remaining in the current chunk
        var innerMoveNext = new Func(() => --remaining > 0 && e.MoveNext());

        yield return e.GetChunk(innerMoveNext);
        while (innerMoveNext()) {/* discard elements skipped by inner iterator */}
    }
}

private static IEnumerable GetChunk(this IEnumerator e,
                                          Func innerMoveNext)
{
    do yield return e.Current;
    while (innerMoveNext());
}
Example Usage
var src = new [] {1, 2, 3, 4, 5, 6}; 

var c3 = src.Chunks(3);      // {{1, 2, 3}, {4, 5, 6}}; 
var c4 = src.Chunks(4);      // {{1, 2, 3, 4}, {5, 6}}; 

var sum   = c3.Select(c => c.Sum());    // {6, 15}
var count = c3.Count();                 // 2
var take2 = c3.Select(c => c.Take(2));  // {{1, 2}, {4, 5}}
Explanations The code works by nesting two yield based iterators. The outer iterator must keep track of how many elements have been effectively consumed by the inner (chunk) iterator. This is done by a closing over remaining with innerMoveNext(). Unconsumed elements of a chunk are discarded before the next chunk is yielded by the outer iterator. This is necessary because otherwise you get inconsistent results, when the inner enumerables are not (completely) consumed (e.g. c3.Count() would return 6). stackoverflow.com/q/419019#20953521

HOWTO: access an administrative share on a computer


If you cannot access an administrative share on a computer, apply EnableAdminShares.reg file and restart "Server" windows service.

Enjoy!

HOWTO: Repair Logitech M325 Mouse

FixIt says that you will find single screw under CE label. It isn't always true.