Joseph  Murray

Joseph Murray

1660096020

Svelte Action Sortable: Way to Add Drag and Drop Sorting To A List

svelte-action-sortable

Minimal Svelte action to add drag and drop sorting to a list.

<script lang="ts">
    import { writable } from 'svelte/store';
    import { flip } from 'svelte/animate';
    import createSortable from '$lib/actions/sortable';

    const list = writable(['a', 'b', 'c', 'd', 'e', 'f', 'g']);
    const [sortable, target] = createSortable(list);
</script>

<div use:sortable>
    {#each $list as item (item)}
        <div animate:flip use:target={item}>
            {item}
        </div>
    {/each}
</div>

Why?

Existing libraries such as svelte-sortable-list use extra dom nodes and require resturcturing your markup. svelte-action-sortable only uses 1 single dom node to indicate where the item will be moved to and does not require you to change your markup at all.

Download details:

Author: JacobZwang
Source code: https://github.com/JacobZwang/svelte-action-sortable

#svelte #javascript

What is GEEK

Buddha Community

Svelte Action Sortable: Way to Add Drag and Drop Sorting To A List

I am Developer

1597487472

Country State City Dropdown list in PHP MySQL PHP

Here, i will show you how to populate country state city in dropdown list in php mysql using ajax.

Country State City Dropdown List in PHP using Ajax

You can use the below given steps to retrieve and display country, state and city in dropdown list in PHP MySQL database using jQuery ajax onchange:

  • Step 1: Create Country State City Table
  • Step 2: Insert Data Into Country State City Table
  • Step 3: Create DB Connection PHP File
  • Step 4: Create Html Form For Display Country, State and City Dropdown
  • Step 5: Get States by Selected Country from MySQL Database in Dropdown List using PHP script
  • Step 6: Get Cities by Selected State from MySQL Database in DropDown List using PHP script

https://www.tutsmake.com/country-state-city-database-in-mysql-php-ajax/

#country state city drop down list in php mysql #country state city database in mysql php #country state city drop down list using ajax in php #country state city drop down list using ajax in php demo #country state city drop down list using ajax php example #country state city drop down list in php mysql ajax

Duong Tran

Duong Tran

1646796864

Sắp Xếp Danh Sách Trong Python Với Python.sort ()

Trong bài viết này, bạn sẽ học cách sử dụng phương pháp danh sách của Python sort().

Bạn cũng sẽ tìm hiểu một cách khác để thực hiện sắp xếp trong Python bằng cách sử dụng sorted()hàm để bạn có thể thấy nó khác với nó như thế nào sort().

Cuối cùng, bạn sẽ biết những điều cơ bản về sắp xếp danh sách bằng Python và biết cách tùy chỉnh việc sắp xếp để phù hợp với nhu cầu của bạn.

Phương pháp sort() - Tổng quan về cú pháp

Phương pháp sort() này là một trong những cách bạn có thể sắp xếp danh sách trong Python.

Khi sử dụng sort(), bạn sắp xếp một danh sách tại chỗ . Điều này có nghĩa là danh sách ban đầu được sửa đổi trực tiếp. Cụ thể, thứ tự ban đầu của các phần tử bị thay đổi.

Cú pháp chung cho phương thức sort() này trông giống như sau:

list_name.sort(reverse=..., key=... )

Hãy chia nhỏ nó:

  • list_name là tên của danh sách bạn đang làm việc.
  • sort()là một trong những phương pháp danh sách của Python để sắp xếp và thay đổi danh sách. Nó sắp xếp các phần tử danh sách theo thứ tự tăng dần hoặc giảm dần .
  • sort()chấp nhận hai tham số tùy chọn .
  • reverse là tham số tùy chọn đầu tiên. Nó chỉ định liệu danh sách sẽ được sắp xếp theo thứ tự tăng dần hay giảm dần. Nó nhận một giá trị Boolean, nghĩa là giá trị đó là True hoặc False. Giá trị mặc định là False , nghĩa là danh sách được sắp xếp theo thứ tự tăng dần. Đặt nó thành True sẽ sắp xếp danh sách ngược lại, theo thứ tự giảm dần.
  • key là tham số tùy chọn thứ hai. Nó có một hàm hoặc phương pháp được sử dụng để chỉ định bất kỳ tiêu chí sắp xếp chi tiết nào mà bạn có thể có.

Phương sort()thức trả về None, có nghĩa là không có giá trị trả về vì nó chỉ sửa đổi danh sách ban đầu. Nó không trả về một danh sách mới.

Cách sắp xếp các mục trong danh sách theo thứ tự tăng dần bằng phương pháp sort()

Như đã đề cập trước đó, theo mặc định, sort()sắp xếp các mục trong danh sách theo thứ tự tăng dần.

Thứ tự tăng dần (hoặc tăng dần) có nghĩa là các mặt hàng được sắp xếp từ giá trị thấp nhất đến cao nhất.

Giá trị thấp nhất ở bên trái và giá trị cao nhất ở bên phải.

Cú pháp chung để thực hiện việc này sẽ giống như sau:

list_name.sort()

Hãy xem ví dụ sau đây cho thấy cách sắp xếp danh sách các số nguyên:

# a list of numbers
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]

#sort list in-place in ascending order
my_numbers.sort()

#print modified list
print(my_numbers)

#output

#[3, 7, 8, 10, 11, 22, 33, 54, 100]

Trong ví dụ trên, các số được sắp xếp từ nhỏ nhất đến lớn nhất.

Bạn cũng có thể đạt được điều tương tự khi làm việc với danh sách các chuỗi:

# a list of strings
programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]

#sort list in-place in alphabetical order
programming_languages.sort()

#print modified list
print(programming_languages)

#output

#['C++', 'Go', 'Java', 'Python', 'Rust', 'Swift']

Trong trường hợp này, mỗi chuỗi có trong danh sách được sắp xếp theo thứ tự không tuân theo.

Như bạn đã thấy trong cả hai ví dụ, danh sách ban đầu đã được thay đổi trực tiếp.

Cách sắp xếp các mục trong danh sách theo thứ tự giảm dần bằng phương pháp sort()

Thứ tự giảm dần (hoặc giảm dần) ngược lại với thứ tự tăng dần - các phần tử được sắp xếp từ giá trị cao nhất đến thấp nhất.

Để sắp xếp các mục trong danh sách theo thứ tự giảm dần, bạn cần sử dụng reverse tham số tùy chọn với phương thức sort() và đặt giá trị của nó thành True.

Cú pháp chung để thực hiện việc này sẽ giống như sau:

list_name.sort(reverse=True)

Hãy sử dụng lại cùng một ví dụ từ phần trước, nhưng lần này làm cho nó để các số được sắp xếp theo thứ tự ngược lại:

# a list of numbers
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]

#sort list in-place in descending order
my_numbers.sort(reverse=True)

#print modified list
print(my_numbers)

#output

#[100, 54, 33, 22, 11, 10, 8, 7, 3]

Bây giờ tất cả các số được sắp xếp ngược lại, với giá trị lớn nhất ở bên tay trái và giá trị nhỏ nhất ở bên phải.

Bạn cũng có thể đạt được điều tương tự khi làm việc với danh sách các chuỗi.

# a list of strings
programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]

#sort list in-place in  reverse alphabetical order
programming_languages.sort(reverse=True)

#print modified list
print(programming_languages)

#output

#['Swift', 'Rust', 'Python', 'Java', 'Go', 'C++']

Các mục danh sách hiện được sắp xếp theo thứ tự bảng chữ cái ngược lại.

Cách sắp xếp các mục trong danh sách bằng cách sử dụng key tham số với phương thức sort()

Bạn có thể sử dụng key tham số để thực hiện các thao tác sắp xếp tùy chỉnh hơn.

Giá trị được gán cho key tham số cần phải là thứ có thể gọi được.

Callable là thứ có thể được gọi, có nghĩa là nó có thể được gọi và tham chiếu.

Một số ví dụ về các đối tượng có thể gọi là các phương thức và hàm.

Phương thức hoặc hàm được gán cho key này sẽ được áp dụng cho tất cả các phần tử trong danh sách trước khi bất kỳ quá trình sắp xếp nào xảy ra và sẽ chỉ định logic cho tiêu chí sắp xếp.

Giả sử bạn muốn sắp xếp danh sách các chuỗi dựa trên độ dài của chúng.

Đối với điều đó, bạn chỉ định len()hàm tích hợp cho key tham số.

Hàm len()sẽ đếm độ dài của từng phần tử được lưu trong danh sách bằng cách đếm các ký tự có trong phần tử đó.

programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]

programming_languages.sort(key=len)

print(programming_languages)

#output

#['Go', 'C++', 'Java', 'Rust', 'Swift', 'Python']

Trong ví dụ trên, các chuỗi được sắp xếp theo thứ tự tăng dần mặc định, nhưng lần này việc sắp xếp xảy ra dựa trên độ dài của chúng.

Chuỗi ngắn nhất ở bên trái và dài nhất ở bên phải.

Các keyreverse tham số cũng có thể được kết hợp.

Ví dụ: bạn có thể sắp xếp các mục trong danh sách dựa trên độ dài của chúng nhưng theo thứ tự giảm dần.

programming_languages = ["Python", "Swift","Java", "C++", "Go", "Rust"]

programming_languages.sort(key=len, reverse=True)

print(programming_languages)

#output

#['Python', 'Swift', 'Java', 'Rust', 'C++', 'Go']

Trong ví dụ trên, các chuỗi đi từ dài nhất đến ngắn nhất.

Một điều cần lưu ý nữa là bạn có thể tạo một chức năng sắp xếp tùy chỉnh của riêng mình, để tạo các tiêu chí sắp xếp rõ ràng hơn.

Ví dụ: bạn có thể tạo một hàm cụ thể và sau đó sắp xếp danh sách theo giá trị trả về của hàm đó.

Giả sử bạn có một danh sách các từ điển với các ngôn ngữ lập trình và năm mà mỗi ngôn ngữ lập trình được tạo ra.

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]

Bạn có thể xác định một hàm tùy chỉnh nhận giá trị của một khóa cụ thể từ từ điển.

💡 Hãy nhớ rằng khóa từ điển và key tham số sort()chấp nhận là hai thứ khác nhau!

Cụ thể, hàm sẽ lấy và trả về giá trị của year khóa trong danh sách từ điển, chỉ định năm mà mọi ngôn ngữ trong từ điển được tạo.

Giá trị trả về sau đó sẽ được áp dụng làm tiêu chí sắp xếp cho danh sách.

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]

def get_year(element):
    return element['year']

Sau đó, bạn có thể sắp xếp theo giá trị trả về của hàm bạn đã tạo trước đó bằng cách gán nó cho key tham số và sắp xếp theo thứ tự thời gian tăng dần mặc định:

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]

def get_year(element):
    return element['year']

programming_languages.sort(key=get_year)

print(programming_languages)

Đầu ra:

[{'language': 'C++', 'year': 1985}, {'language': 'Python', 'year': 1991}, {'language': 'Java', 'year': 1995}, {'language': 'Go', 'year': 2007}, {'language': 'Rust', 'year': 2010}, {'language': 'Swift', 'year': 2014}]

Nếu bạn muốn sắp xếp từ ngôn ngữ được tạo gần đây nhất đến ngôn ngữ cũ nhất hoặc theo thứ tự giảm dần, thì bạn sử dụng reverse=Truetham số:

programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]

def get_year(element):
    return element['year']

programming_languages.sort(key=get_year, reverse=True)

print(programming_languages)

Đầu ra:

[{'language': 'Swift', 'year': 2014}, {'language': 'Rust', 'year': 2010}, {'language': 'Go', 'year': 2007}, {'language': 'Java', 'year': 1995}, {'language': 'Python', 'year': 1991}, {'language': 'C++', 'year': 1985}]

Để đạt được kết quả chính xác, bạn có thể tạo một hàm lambda.

Thay vì sử dụng hàm tùy chỉnh thông thường mà bạn đã xác định bằng def từ khóa, bạn có thể:

  • tạo một biểu thức ngắn gọn một dòng,
  • và không xác định tên hàm như bạn đã làm với def hàm. Các hàm lambda còn được gọi là các hàm ẩn danh .
programming_languages = [{'language':'Python','year':1991},
{'language':'Swift','year':2014},
{'language':'Java', 'year':1995},
{'language':'C++','year':1985},
{'language':'Go','year':2007},
{'language':'Rust','year':2010},
]

programming_languages.sort(key=lambda element: element['year'])

print(programming_languages)

Hàm lambda được chỉ định với dòng key=lambda element: element['year']sắp xếp các ngôn ngữ lập trình này từ cũ nhất đến mới nhất.

Sự khác biệt giữa sort()sorted()

Phương sort()thức hoạt động theo cách tương tự như sorted()hàm.

Cú pháp chung của sorted()hàm trông như sau:

sorted(list_name,reverse=...,key=...)

Hãy chia nhỏ nó:

  • sorted()là một hàm tích hợp chấp nhận một có thể lặp lại. Sau đó, nó sắp xếp nó theo thứ tự tăng dần hoặc giảm dần.
  • sorted()chấp nhận ba tham số. Một tham số là bắt buộc và hai tham số còn lại là tùy chọn.
  • list_name là tham số bắt buộc . Trong trường hợp này, tham số là danh sách, nhưng sorted()chấp nhận bất kỳ đối tượng có thể lặp lại nào khác.
  • sorted()cũng chấp nhận các tham số tùy chọn reversekey, đó là các tham số tùy chọn tương tự mà phương thức sort() chấp nhận.

Sự khác biệt chính giữa sort()sorted()sorted()hàm nhận một danh sách và trả về một bản sao được sắp xếp mới của nó.

Bản sao mới chứa các phần tử của danh sách ban đầu theo thứ tự được sắp xếp.

Các phần tử trong danh sách ban đầu không bị ảnh hưởng và không thay đổi.

Vì vậy, để tóm tắt sự khác biệt:

  • Phương sort()thức không có giá trị trả về và trực tiếp sửa đổi danh sách ban đầu, thay đổi thứ tự của các phần tử chứa trong nó.
  • Mặt khác, sorted()hàm có giá trị trả về, là một bản sao đã được sắp xếp của danh sách ban đầu. Bản sao đó chứa các mục danh sách của danh sách ban đầu theo thứ tự được sắp xếp. Cuối cùng, danh sách ban đầu vẫn còn nguyên vẹn.

Hãy xem ví dụ sau để xem nó hoạt động như thế nào:

#original list of numbers
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]

#sort original list in default ascending order
my_numbers_sorted = sorted(my_numbers)

#print original list
print(my_numbers)

#print the copy of the original list that was created
print(my_numbers_sorted)

#output

#[10, 8, 3, 22, 33, 7, 11, 100, 54]
#[3, 7, 8, 10, 11, 22, 33, 54, 100]

Vì không có đối số bổ sung nào được cung cấp sorted(), nó đã sắp xếp bản sao của danh sách ban đầu theo thứ tự tăng dần mặc định, từ giá trị nhỏ nhất đến giá trị lớn nhất.

Và khi in danh sách ban đầu, bạn thấy rằng nó vẫn được giữ nguyên và các mục có thứ tự ban đầu.

Như bạn đã thấy trong ví dụ trên, bản sao của danh sách đã được gán cho một biến mới my_numbers_sorted,.

Một cái gì đó như vậy không thể được thực hiện với sort().

Hãy xem ví dụ sau để xem điều gì sẽ xảy ra nếu điều đó được thực hiện với phương thức sort().

my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]

my_numbers_sorted = my_numbers.sort()

print(my_numbers)
print(my_numbers_sorted)

#output

#[3, 7, 8, 10, 11, 22, 33, 54, 100]
#None

Bạn thấy rằng giá trị trả về của sort()None.

Cuối cùng, một điều khác cần lưu ý là các reversekey tham số mà sorted()hàm chấp nhận hoạt động giống hệt như cách chúng thực hiện với phương thức sort() bạn đã thấy trong các phần trước.

Khi nào sử dụng sort()sorted()

Dưới đây là một số điều bạn có thể muốn xem xét khi quyết định có nên sử dụng sort()vs. sorted()

Trước tiên, hãy xem xét loại dữ liệu bạn đang làm việc:

  • Nếu bạn đang làm việc nghiêm ngặt với một danh sách ngay từ đầu, thì bạn sẽ cần phải sử dụng sort()phương pháp này vì sort()chỉ được gọi trong danh sách.
  • Mặt khác, nếu bạn muốn linh hoạt hơn và chưa làm việc với danh sách, thì bạn có thể sử dụng sorted(). Hàm sorted()chấp nhận và sắp xếp mọi thứ có thể lặp lại (như từ điển, bộ giá trị và bộ) chứ không chỉ danh sách.

Tiếp theo, một điều khác cần xem xét là liệu bạn có giữ được thứ tự ban đầu của danh sách mà bạn đang làm việc hay không:

  • Khi gọi sort(), danh sách ban đầu sẽ bị thay đổi và mất thứ tự ban đầu. Bạn sẽ không thể truy xuất vị trí ban đầu của các phần tử danh sách. Sử dụng sort()khi bạn chắc chắn muốn thay đổi danh sách đang làm việc và chắc chắn rằng bạn không muốn giữ lại thứ tự đã có.
  • Mặt khác, sorted()nó hữu ích khi bạn muốn tạo một danh sách mới nhưng bạn vẫn muốn giữ lại danh sách bạn đang làm việc. Hàm sorted()sẽ tạo một danh sách được sắp xếp mới với các phần tử danh sách được sắp xếp theo thứ tự mong muốn.

Cuối cùng, một điều khác mà bạn có thể muốn xem xét khi làm việc với các tập dữ liệu lớn hơn, đó là hiệu quả về thời gian và bộ nhớ:

  • Phương sort()pháp này chiếm dụng và tiêu tốn ít bộ nhớ hơn vì nó chỉ sắp xếp danh sách tại chỗ và không tạo ra danh sách mới không cần thiết mà bạn không cần. Vì lý do tương tự, nó cũng nhanh hơn một chút vì nó không tạo ra một bản sao. Điều này có thể hữu ích khi bạn đang làm việc với danh sách lớn hơn chứa nhiều phần tử hơn.

Phần kết luận

Và bạn có nó rồi đấy! Bây giờ bạn đã biết cách sắp xếp một danh sách trong Python bằng sort()phương pháp này.

Bạn cũng đã xem xét sự khác biệt chính giữa sắp xếp danh sách bằng cách sử dụng sort()sorted().

Tôi hy vọng bạn thấy bài viết này hữu ích.

Để tìm hiểu thêm về ngôn ngữ lập trình Python, hãy xem Chứng chỉ Máy tính Khoa học với Python của freeCodeCamp .

Bạn sẽ bắt đầu từ những điều cơ bản và học theo cách tương tác và thân thiện với người mới bắt đầu. Bạn cũng sẽ xây dựng năm dự án vào cuối để áp dụng vào thực tế và giúp củng cố những gì bạn đã học được.

Nguồn: https://www.freecodecamp.org/news/python-sort-how-to-sort-a-list-in-python/

#python 

Joseph  Murray

Joseph Murray

1660096020

Svelte Action Sortable: Way to Add Drag and Drop Sorting To A List

svelte-action-sortable

Minimal Svelte action to add drag and drop sorting to a list.

<script lang="ts">
    import { writable } from 'svelte/store';
    import { flip } from 'svelte/animate';
    import createSortable from '$lib/actions/sortable';

    const list = writable(['a', 'b', 'c', 'd', 'e', 'f', 'g']);
    const [sortable, target] = createSortable(list);
</script>

<div use:sortable>
    {#each $list as item (item)}
        <div animate:flip use:target={item}>
            {item}
        </div>
    {/each}
</div>

Why?

Existing libraries such as svelte-sortable-list use extra dom nodes and require resturcturing your markup. svelte-action-sortable only uses 1 single dom node to indicate where the item will be moved to and does not require you to change your markup at all.

Download details:

Author: JacobZwang
Source code: https://github.com/JacobZwang/svelte-action-sortable

#svelte #javascript

Brook  Legros

Brook Legros

1659226440

Efficient, Immutable, Thread-Safe Collection Classes for Ruby

Hamster

Efficient, immutable, and thread-safe collection classes for Ruby.

Hamster provides 6 Persistent Data Structures: Hash, Vector, Set, SortedSet, List, and Deque (which works as an immutable queue or stack).

Hamster collections are immutable. Whenever you modify a Hamster collection, the original is preserved and a modified copy is returned. This makes them inherently thread-safe and shareable. At the same time, they remain CPU and memory-efficient by sharing between copies.

While Hamster collections are immutable, you can still mutate objects stored in them. We recommend that you don't do this, unless you are sure you know what you are doing. Hamster collections are thread-safe and can be freely shared between threads, but you are responsible for making sure that the objects stored in them are used in a thread-safe manner.

Hamster collections are almost always closed under a given operation. That is, whereas Ruby's collection methods always return arrays, Hamster collections will return an instance of the same class wherever possible.

Where possible, Hamster collections offer an interface compatible with Ruby's built-in Hash, Array, and Enumerable, to ease code migration. Also, Hamster methods accept regular Ruby collections as arguments, so code which uses Hamster can easily interoperate with your other Ruby code.

And lastly, Hamster lists are lazy, making it possible to (among other things) process "infinitely large" lists.

Using

To make the collection classes available in your code:

require "hamster"

Or if you prefer to only pull in certain collection types:

require "hamster/hash"
require "hamster/vector"
require "hamster/set"
require "hamster/sorted_set"
require "hamster/list"
require "hamster/deque"

Hash (API Documentation)

Constructing a Hamster Hash is almost as simple as a regular one:

person = Hamster::Hash[name: "Simon", gender: :male]
# => Hamster::Hash[:name => "Simon", :gender => :male]

Accessing the contents will be familiar to you:

person[:name]                       # => "Simon"
person.get(:gender)                 # => :male

Updating the contents is a little different than you are used to:

friend = person.put(:name, "James") # => Hamster::Hash[:name => "James", :gender => :male]
person                              # => Hamster::Hash[:name => "Simon", :gender => :male]
friend[:name]                       # => "James"
person[:name]                       # => "Simon"

As you can see, updating the hash returned a copy leaving the original intact. Similarly, deleting a key returns yet another copy:

male = person.delete(:name)         # => Hamster::Hash[:gender => :male]
person                              # => Hamster::Hash[:name => "Simon", :gender => :male]
male.key?(:name)                    # => false
person.key?(:name)                  # => true

Since it is immutable, Hamster's Hash doesn't provide an assignment (Hash#[]=) method. However, Hash#put can accept a block which transforms the value associated with a given key:

counters = Hamster::Hash[evens: 0, odds: 0]  # => Hamster::Hash[:evens => 0, :odds => 0]
counters.put(:odds) { |value| value + 1 }    # => Hamster::Hash[:odds => 1, :evens => 0]

Or more succinctly:

counters.put(:odds, &:next)         # => {:odds => 1, :evens => 0}

This is just the beginning; see the API documentation for details on all Hash methods.

Vector (API Documentation)

A Vector is an integer-indexed collection much like an immutable Array. Examples:

vector = Hamster::Vector[1, 2, 3, 4] # => Hamster::Vector[1, 2, 3, 4]
vector[0]                            # => 1
vector[-1]                           # => 4
vector.put(1, :a)                    # => Hamster::Vector[1, :a, 3, 4]
vector.add(:b)                       # => Hamster::Vector[1, 2, 3, 4, :b]
vector.insert(2, :a, :b)             # => Hamster::Vector[1, 2, :a, :b, 3, 4]
vector.delete_at(0)                  # => Hamster::Vector[2, 3, 4]

Other Array-like methods like #select, #map, #shuffle, #uniq, #reverse, #rotate, #flatten, #sort, #sort_by, #take, #drop, #take_while, #drop_while, #fill, #product, and #transpose are also supported. See the API documentation for details on all Vector methods.

Set (API Documentation)

A Set is an unordered collection of values with no duplicates. It is much like the Ruby standard library's Set, but immutable. Examples:

set = Hamster::Set[:red, :blue, :yellow] # => Hamster::Set[:red, :blue, :yellow]
set.include? :red                        # => true
set.add :green                           # => Hamster::Set[:red, :blue, :yellow, :green]
set.delete :blue                         # => Hamster::Set[:red, :yellow]
set.superset? Hamster::Set[:red, :blue]  # => true
set.union([:red, :blue, :pink])          # => Hamster::Set[:red, :blue, :yellow, :pink]
set.intersection([:red, :blue, :pink])   # => Hamster::Set[:red, :blue]

Like most Hamster methods, the set-theoretic methods #union, #intersection, #difference, and #exclusion (aliased as #|, #&, #-, and #^) all work with regular Ruby collections, or indeed any Enumerable object. So just like all the other Hamster collections, Hamster::Set can easily be used in combination with "ordinary" Ruby code.

See the API documentation for details on all Set methods.

SortedSet (API Documentation)

A SortedSet is like a Set, but ordered. You can do everything with it that you can do with a Set. Additionally, you can get the #first and #last item, or retrieve an item using an integral index:

set = Hamster::SortedSet['toast', 'jam', 'bacon'] # => Hamster::SortedSet["bacon", "jam", "toast"]
set.first                                         # => "bacon"
set.last                                          # => "toast"
set[1]                                            # => "jam"

You can also specify the sort order using a block:

Hamster::SortedSet.new(['toast', 'jam', 'bacon']) { |a,b| b <=> a } Hamster::SortedSet.new(['toast', 'jam', 'bacon']) { |str| str.chars.last }

See the API documentation for details on all SortedSet methods.

List (API Documentation)

Hamster Lists have a head (the value at the front of the list), and a tail (a list of the remaining items):

list = Hamster::List[1, 2, 3]
list.head                    # => 1
list.tail                    # => Hamster::List[2, 3]

Add to a list with List#add:

original = Hamster::List[1, 2, 3]
copy = original.add(0)      # => Hamster::List[0, 1, 2, 3]

Notice how modifying a list actually returns a new list. That's because Hamster Lists are immutable.

Laziness

List is lazy where possible. It tries to defer processing items until absolutely necessary. For example, the following code will only call Prime.prime? as many times as necessary to generate the first 3 prime numbers between 10,000 and 1,000,000:

require 'prime'

Hamster.interval(10_000, 1_000_000).select do |number|
  Prime.prime?(number)
end.take(3)
  # => 0.0009s

Compare that to the conventional equivalent which needs to calculate all possible values in the range before taking the first three:

(10000..1000000).select do |number|
  Prime.prime?(number)
end.take(3)
  # => 10s

Construction

Besides Hamster::List[] there are other ways to construct lists:

Hamster.interval(from, to) creates a lazy list equivalent to a list containing all the values between from and to without actually creating a list that big.

Hamster.stream { ... } allows you to creates infinite lists. Each time a new value is required, the supplied block is called. To generate a list of integers you could do:

count = 0
Hamster.stream { count += 1 }

Hamster.repeat(x) creates an infinite list with x the value for every element.

Hamster.replicate(n, x) creates a list of size n with x the value for every element.

Hamster.iterate(x) { |x| ... } creates an infinite list where the first item is calculated by applying the block on the initial argument, the second item by applying the function on the previous result and so on. For example, a simpler way to generate a list of integers would be:

Hamster.iterate(1) { |i| i + 1 }

or even more succinctly:

Hamster.iterate(1, &:next)

Hamster::List.empty returns an empty list, which you can build up using repeated calls to #add or other List methods.

Core Extensions

Enumerable#to_list will convert any existing Enumerable to a list, so you can slowly transition from built-in collection classes to Hamster.

IO#to_list enables lazy processing of huge files. For example, imagine the following code to process a 100MB file:

require 'hamster/core_ext'

File.open("my_100_mb_file.txt") do |file|
  lines = []
  file.each_line do |line|
    break if lines.size == 10
    lines << line.chomp.downcase.reverse
  end
end

Compare to the following more functional version:

File.open("my_100_mb_file.txt") do |file|
  file.map(&:chomp).map(&:downcase).map(&:reverse).take(10)
end

Unfortunately, though the second example reads nicely it takes many seconds to run (compared with milliseconds for the first) even though we're only interested in the first ten lines. Using #to_list we can get the running time back comparable to the imperative version.

File.open("my_100_mb_file.txt") do |file|
  file.to_list.map(&:chomp).map(&:downcase).map(&:reverse).take(10)
end

This is possible because IO#to_list creates a lazy list whereby each line is only ever read and processed as needed, in effect converting it to the first example.

See the API documentation for details on all List methods.

Deque (API Documentation)

A Deque (or "double-ended queue") is an ordered collection, which allows you to push and pop items from both front and back. This makes it perfect as an immutable stack or queue. Examples:

deque = Hamster::Deque[1, 2, 3] # => Hamster::Deque[1, 2, 3]
deque.first                     # 1
deque.last                      # 3
deque.pop                       # => Hamster::Deque[1, 2]
deque.push(:a)                  # => Hamster::Deque[1, 2, 3, :a]
deque.shift                     # => Hamster::Deque[2, 3]
deque.unshift(:a)               # => Hamster::Deque[:a, 1, 2, 3]

Of course, you can do the same thing with a Vector, but a Deque is more efficient. See the API documentation for details on all Deque methods.

Transformations

Hamster arrays, hashes, and nested structures of arrays and hashes may be transformed with the update_in method.

c = Hamster.from({
  people: [{name: 'Chris', city: 'Lagos'}, {name: 'Pat', city: 'Madrid'}],
  places: [{name: 'Lagos', population: 1}, {name: 'Madrid', population: 1}]})
c2 = c.update_in(:people, 1, :city) { |old_city| 'Lagos' }
c3 = c2.update_in(:places, 1, :population) { |old_population| old_population - 1 }
c4 = c3.update_in(:places, 0, :population) { |old_population| old_population + 1 }
Hamster.to_ruby(c4)
# => {:places=>[{:population=>2, :name=>"Lagos"}, {:population=>0, :name=>"Madrid"}], :people=>[{:name=>"Chris", :city=>"Lagos"}, {:name=>"Pat", :city=>"Lagos"}]}

Naturally, update_in never mutates your collections.

See Hamster::Hash#update_in, Hamster::Vector#update_in, and Hamster::Associable#update_in for details.

Installing

Add this line to your application's Gemfile:

gem "hamster"

And then execute:

$ bundle

Or install it yourself as:

$ gem install hamster

Contributing

  1. Read the Code of Conduct
  2. Fork it
  3. Create your feature branch (git checkout -b my-new-feature)
  4. Commit your changes (git commit -am "Add some feature")
  5. Push to the branch (git push origin my-new-feature)
  6. Create new Pull Request

Other Reading

Licensing

Copyright (c) 2009-2015 Simon Harris

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Author: hamstergem
Source code: https://github.com/hamstergem/hamster
License: View license

#ruby  #ruby-on-rails 

Nina Diana

Nina Diana

1578050760

10 Best Vue Drag and Drop Component For Your App

Vue Drag and drop is a feature of many interactive web apps. It provides an intuitive way for users to manipulate their data. Adding drag and drop feature is easy to add to Vue.js apps.

Here are 10 vue drop components that contribute to the flexibility of your vue application.

1. Vue.Draggable

Vue component (Vue.js 2.0) or directive (Vue.js 1.0) allowing drag-and-drop and synchronization with view model array.

Based on and offering all features of Sortable.js

Vue.Draggable

Demo: https://sortablejs.github.io/Vue.Draggable/#/simple

Download: https://github.com/SortableJS/Vue.Draggable/archive/master.zip

2. realtime-kanban-vue

Real-time kanban board built with Vue.js and powered by Hamoni Sync.

realtime-kanban-vue

Demo: https://dev.to/pmbanugo/real-time-kanban-board-with-vuejs-and-hamoni-sync-52kg

Download: https://github.com/pmbanugo/realtime-kanban-vue/archive/master.zip

3. vue-nestable

Drag & drop hierarchical list made as a vue component.

Goals

  • A simple vue component to create a draggable list to customizable items
  • Reorder items by dragging them above an other item
  • Intuitively nest items by dragging right
  • Fully customizable, ships with no css
  • Everything is configurable: item identifier, max nesting level, threshold for nesting

vue-nestable

Demo: https://rhwilr.github.io/vue-nestable/

Download: https://github.com/rhwilr/vue-nestable/archive/master.zip

4. VueDraggable

VueJS directive for drag and drop.

Native HTML5 drag and drop implementation made for VueJS.

VueDraggable

Demo: https://vivify-ideas.github.io/vue-draggable/

Download: https://github.com/Vivify-Ideas/vue-draggable/archive/master.zip

5. vue-grid-layout

vue-grid-layout is a grid layout system, like Gridster, for Vue.js. Heavily inspired in React-Grid-Layout

vue-grid-layout

Demo: https://jbaysolutions.github.io/vue-grid-layout/examples/01-basic.html

Download: https://github.com/jbaysolutions/vue-grid-layout/archive/master.zip

6. vue-drag-tree

It’s a tree components(Vue2.x) that allow you to drag and drop the node to exchange their data .

Feature

  • Double click on an node to turn it into a folder
  • Drag and Drop the tree node, even between two different levels
  • Controls whether a particular node can be dragged and whether the node can be plugged into other nodes
  • Append/Remove Node in any level (#TODO)

vue-drag-tree

Demo: https://vigilant-curran-d6fec6.netlify.com/#/

Download: https://github.com/shuiRong/vue-drag-tree/archive/master.zip

7. VueDragDrop

A Simple Drag & Drop example created in Vue.js.

VueDragDrop

Demo: https://seregpie.github.io/VueDragDrop/

Download: https://github.com/SeregPie/VueDragDrop/archive/master.zip

8. Vue-drag-resize

Vue Component for resize and drag elements.

Vue-drag-resize

Demo: http://kirillmurashov.com/vue-drag-resize/

Download: https://github.com/kirillmurashov/vue-drag-resize/archive/master.zip

9. vue-smooth-dnd

A fast and lightweight drag&drop, sortable library for Vue.js with many configuration options covering many d&d scenarios.

This library consists wrapper Vue.js components over smooth-dnd library.

Show, don’t tell !

vue-smooth-dnd

Demo: https://kutlugsahin.github.io/vue-smooth-dnd/#/cards

Download: https://github.com/kutlugsahin/vue-smooth-dnd/archive/master.zip

10. vue-dragula

Drag and drop so simple it hurts

vue-dragula

Demo: http://astray-git.github.io/vue-dragula/

Download: https://github.com/Astray-git/vue-dragula/archive/master.zip

#vue #vue-drag #vue-drop #drag-and-drop #vue-drag-and-drop