text:
Homosexuality in China

Homosexuality has been documented in China since ancient times. According to one study by Bret Hinsch, for some time after the fall of the Han dynasty, homosexuality was widely accepted in China but this has been disputed. Several early Chinese emperors are speculated to have had homosexual relationships accompanied by heterosexual ones. Opposition to homosexuality, according to the study by Hinsch, did not become firmly established in China until the 19th and 20th centuries through the Westernization efforts of the late Qing dynasty and early Republic of China. On the other hand, Gulik's study argued that the Mongol Yuan dynasty introduced a more ascetic attitude to sexuality in general.

For most of the 20th century homosexuality in China had been legal, except for a period between 1979 and 1997 where male anal sex was punishable as "hooliganism".

In a survey by the organization WorkForLGBT of 18,650 lesbians, gay, bisexual and transgender (LGBT) people, 3% of males and 6% of females surveyed described themselves as "completely out". A third of the men surveyed, as well as 9% of the women surveyed said they were in the closet about their sexuality. 18% of men surveyed answered they had come out to their families, while around 80% were reluctant due to family pressure.

There was a step forward for the China LGBT community after the Weibo incident in April 2018, where the public outcry over the platform for banning homosexual content led the platform to withdraw the decision. Yet, in 2021 Weibo and WeChat censored the accounts of numerous LGBT student organizations without any prior warning.

Terminology
Traditional terms for homosexuality included "the passion of the cut sleeve", and "the divided peach". An example of the latter term appears in a 6th-century poem by Liu Xiaozhuo: "— She dawdles, not daring to move closer, / Afraid he might compare her with leftover peach."

Other, less literary, terms have included "male trend", "allied brothers" , and "the passion of Longyang" , referencing a homoerotic anecdote about Lord Long Yang in the Warring States period. The formal modern word for "homosexuality/homosexual(s)" is tongxinglian or tongxinglian zhe (, homosexual people). Instead of that formal word, "tongzhi", simply a head rhyme word, is more commonly used in the gay community. Tongzhi (sometimes along with nü tongzhi, ), which was first adopted by Hong Kong researchers in Gender Studies, is used as slang in Mandarin Chinese to refer to homosexuals. Such usage is seen in Taiwan. However, in mainland China, tongzhi is used both in the context of the traditional "comrade" sense (e.g., used in speeches by Chinese Communist Party officials) and to refer to homosexuals. In Cantonese, gei1 (基), adopted from English gay, is used. "Gay" is sometimes considered to be offensive when used by heterosexuals or even by homosexuals in certain situations. Another slang term is boli, which is not so commonly used. Among gay university students, the acronym "datong", which also refers to utopia, in Chinese is becoming popular. Datong is short for daxuesheng tongzhi (university students [that are] homosexuals).

Lesbians usually call themselves lazi or lala (拉拉, ). These two terms are abbreviations of the transliteration of the English term "lesbian". These slang terms are also commonly used in mainland China now.

History
The story of Dong Xian, which details the same-sex relationship between Emperor Ai of Han and one of his male concubines, has been cited by Hinsch as evidence of the historical tolerance of homosexuality within the Chinese empire. However, critics have cited the fact that the relationship ended in tragedy and violence to argue that the story was therefore critical rather than supportive of homosexual relationships.

Ming dynasty literature, such as Bian Er Chai (弁而釵/弁而钗), portrays homosexual relationships between men as enjoyable relationships. Writings from the Liu Song dynasty claimed that homosexuality was as common as heterosexuality in the late 3rd century: "All the gentlemen and officials esteemed it. All men in the realm followed this fashion to the extent that husbands and wives were estranged. Resentful unmarried women became jealous."

Some scholars argue that Confucianism, being primarily a social and political philosophy, focused little on sexuality, whether homosexual or heterosexual. Critics have argued that under Confucian teachings, not having children was one of the greatest sins against filial piety, contending that while procreational bisexuality was tolerated, exclusive homosexuality was not. Emperors were still obligated to marry women and raise heirs, and same-sex sexual activities and relationships were merely tolerated as secondary practices. Confucian ideology did emphasize male friendships, and Louis Crompton has argued that the "closeness of the master-disciple bond it fostered may have subtly facilitated homosexuality".

Although Taoist alchemy regarded heterosexual sex, without ejaculation, as a way of maintaining a male's "life essence", homosexual intercourse was seen as "neutral", because the act has no detrimental or beneficial effect on a person's life essence.

In a similar way to Buddhism, Taoist schools sought throughout history to define what would be sexual misconduct. Broadly speaking, the precept against "sexual misconduct" in Taoism relates to extramarital sex. The term for a married couple (夫婦) usually in Chinese suggests a male with a female, though Taoist scripture itself does not explicitly say anything against same-sex relations. Many sorts of precepts mentioned in the Yunji Qiqian (雲笈七籤), The Mini Daoist Canon, does not say anything against same-sex relations, maintaining neutrality.

Opposition to homosexuality in China rose in the medieval Tang dynasty, but did not become fully established until the late Qing dynasty and the Chinese Republic. There exists a dispute among sinologists as to when negative views of homosexual relationships became prevalent among the general Chinese population, with some scholars arguing that it was common by the time of the Ming dynasty, established in the 14th century, and others arguing that anti-gay attitudes became entrenched during the Westernization efforts of the late Qing dynasty and the early Republic of China in the 19th and 20th centuries.

In Ancient Fujian, the region had developed a sexual culture isolated from that of the rest of the Chinese empire. During the Qing dynasty, the local population began worshipping a Taoist deity known as Tu Er Shen, who served as the guardian of same-sex love. The deity was originally a human by the name of Hu Tianbao. Hu was executed after having been caught peeping on a nobleman he had become attracted to. He was originally destined to go to hell, but the guardians of the spirit realm took pity on him, as his crime was committed out of love. He was then appointed as the guardian of same-sex love.

The Central Qing government of Beijing labeled followers of Tu Er Shen "cultists" and demanded for their persecution and elimination. It was during this dynasty that China's very first law against non-commercial same-sex sexual conduct was enacted. However, the newly created offense of homosexuality carried the most lenient penalty possible in the Qing legal system. Today, the Wei-ming temple dedicated to Tu Er Shen, located in New Taipei, serves as the world's only religious temple dedicated exclusively to same-sex love.

The earliest law against a homosexual act dates from the Song dynasty, punishing "young males who act as prostitutes". The first statute specifically banning homosexual intercourse was enacted in the Jiajing era of the Ming dynasty.

Ming dynasty China banned homosexual sodomy (anal sex) in the Ming Code since the Jiajing emperor's reign and continued into the Qing dynasty until 1907, when western influence led to the law being repealed. The Chinese mocked and insulted Puyi and the Japanese as homosexuals and presented it as proof of their perversion and being uncivilized. The only time homosexual sodomy has been banned in Japan was for short time for 8 years in 1872-1880 due to western influence.

Lu Tonglin, author of Misogyny, Cultural Nihilism & Oppositional Politics: Contemporary Chinese Experimental Fiction, said "a clear-cut dichotomy between heterosexuality and homosexuality did not exist in traditional China."

Male prostitution was forbidden during the Yuan dynasty (descended from the Mongol Empire) and the following Ming dynasty, and evidence suggests that there was a crackdown on homosexuality during this period as a continuation of the Mongol Empire's hostility to homosexuality.

Same-sex relationships in literature
Same-sex love can sometimes be difficult to differentiate in Classical Chinese because the pronouns he and she were not distinguished. And like many East and Southeast Asian languages, Chinese sometime does not have grammatical gender. Thus, poems such as Tang dynasty poems and other Chinese poetry may be read as either heterosexual or homosexual, neutral in that regard, depending on the context.

Another complication in trying to separate heterosexual and homosexual themes in Chinese literature is that for most of Chinese history, writing was restricted to a cultivated elite, amongst whom blatant discussion of sex was considered vulgar. Until adopting European values late in their history, the Chinese did not even have nouns to describe a heterosexual or homosexual person per se. Rather, people who might be directly labeled as such in other traditions would be described by veiled allusions to the actions they enjoyed, or, more often, by referring to a famous example from the past. The most common of these references to homosexuality referenced Dong Xian and Mizi Xia.

The Chen dynasty's Book of Chen, records the relationship between Emperor Wen of Chen and his favorite male lover, Han Zigao. Chen famously said to Han: "people say I am destined to be an Emperor, if it comes true, you will become my queen." Chen did become an Emperor in 559, but he was unable to keep his promise to Han and instead, he made him a general. Han spent all his time with Chen until the latter died in 566. Outside the tomb of Chen, discovered in 2013, two statues of pixiu were found, different from the usual male and female design, since both of them are male, and are believed to represent Emperor Chen and Han Zigao.

The Tang dynasty "Poetical Essay on the Supreme Joy" is another good example of the allusive nature of Chinese writing on sexuality. This manuscript sought to present the "supreme joy" (sex) in every form known to the author; the chapter on homosexuality comes between chapters on sex in Buddhist monasteries and sex between peasants. It is the earliest surviving manuscript to mention homosexuality, but it does so through phrases such as "cut sleeves in the imperial palace", "countenances of linked jade", and "they were like Lord Long Yang", phrases which would not be recognizable as speaking of sexuality of any kind to someone who was not familiar with the literary tradition.

While these conventions make explicit mentions of homosexuality rare in Chinese literature in comparison to the Greek or Japanese traditions, the allusions which do exist are given an exalted air by their frequent comparison to former Golden Ages and imperial favorites. A Han dynasty scholar describes in Garden of Stories the official Zhuang Xin making a nervous pass at his lord, Xiang Cheng of Chu. The ruler is nonplussed at first, but Zhuang justifies his suggestion through allusion to a chancellor who received the confessions of a fisherman by singing a song. At that, "Lord Xiang Cheng also received Zhuang Xin's hand and promoted him." A remarkable aspect of traditional Chinese literature is the prominence of same-sex friendship. Bai Juyi is one of many writers who wrote dreamy, lyrical poems to male friends about shared experiences. He and fellow scholar-bureaucrat Yuan Zhen made plans to retire together as Taoist recluses once they had saved enough funds, but Yuan's death kept that dream from being fulfilled.

Other works depict less platonic relationships. A Ming dynasty rewriting of a very early Zhou dynasty legend recounts a passionate male relationship between Pan Zhang & Wang Zhongxian which is equated to heterosexual marriage, and which continues even beyond death. The daring 17th century author Li Yu combined tales of passionate love between men with brutal violence and cosmic revenge. Dream of the Red Chamber, one of China's Four Great Classical Novels from the Qing dynasty, has scenes that depict men engaging in both same-sex and opposite-sex acts.

There is a tradition of clearly erotic literature, which is less known. It is supposed that most such works have been purged in the periodic book burnings that have been a feature of Chinese history. However, isolated manuscripts have survived. Chief among these is the anthology "Bian er chai", a series of four short stories in five chapters each, of passion and seduction. The first short story, Chronicle of a Loyal Love, involves a twenty-year-old academician chasing a fifteen-year-old scholar and a bevy of adolescent valets. In another, "Qing Xia Ji", the protagonist, Zhang, a valiant soldier with two warrior wives, is seduced by his younger friend Zhong, a remarkable arrangement as it is stereotypically the older man who takes the initiative with a boy. The work appeared in a single edition some time between 1630 and 1640.

More recently, Ding Ling, an author of the 1920s in China, was a prominent and controversial feminist author, and it is generally agreed that she had lesbian (or at least bisexual) content in her stories. Her most famous piece is "Miss Sophia's Diary", a seminal work in the development of a voice for women's sexuality and sexual desire. Additionally, a contemporary author, Wong Bik-Wan, writes from the lesbian perspective in her story "She's a Young Woman and So Am I". Author Pai Hsien-yung created a sensation by coming out of the closet in Taiwan, and by writing about gay life in Taipei in the 1960s and 70s.

Same-sex love was also celebrated in Chinese art, many examples of which have survived the various traumatic political events in recent Chinese history. Though no large statues are known to still exist, many hand scrolls and paintings on silk can be found in private collections.

Gay, lesbian and queer culture in contemporary mainland China
Gay identities and communities have expanded in China since the 1980s as a result of resurfacing dialogue about and engagement with queer identities in the public domain. Since the 1990s, the preferred term for people of diverse sexuality, sex and gender is tongzhi. While lesbian, gay, bisexual and transgender (LGBT) culture remains largely underground, there are a plethora of gay cruising zones and often unadvertised gay bars, restaurants and discos spread across the country. The recent and escalating proliferation of gay identity in mainland China is most significantly signaled by its recognition in mainstream media despite China's media censorship. There are also many gay websites and LGBT organisations which help organise gay rights' campaigns, AIDS prevention efforts, film festivals and pride parades. Yet public discourse on the issue remains fraught - a product of competing ideologies surrounding the body; the morality of its agency in the public and private arena.

Like most modern societies, public sentiment on homosexuality in China sits within a liminal space. While it is not outright condemned, neither is it fully accepted as being part of the social norm. In many instances, those who associate with the queer community also associate with another marginalised group, such as rural-to-urban migrants and sex workers, and therefore the stigma that is attached to aspects of queer identity is often a manifestation of perceived social disobedience against different intersecting vectors of 'moral rights'. As Elaine Jeffreys and Haiqing Yu note in their book, Sex in China, individuals who interact within the queer community do not necessarily identify as being homosexual. 'Money boys', men who provide commercial sexual services to other men, but do not identify as being homosexual, are an example of such a social group. Their minority status is imbued with aspects of criminality and poverty. This suggests that the 'perverseness' attached to homosexuality in mainland China is not purely informed by a biological discourse, but, depending on the circumstances, can also be informed by accepted notions of cultural and social legitimacy.

The influence of Western gay and lesbian culture on China's culture is complex. While Western ideas and conceptions of gayness have begun to permeate the Chinese gay and lesbian identity, some Chinese gay and lesbian activists have pushed back against the mainstream politics of asserting one's own identity and pushing for social change due to its disruption of "family ties and social harmony". Most of the exposure to Western gay and lesbian culture is through the internet or the media, but this exposure is limited—mainstream symbols of gay and lesbian culture (such as the rainbow flag) are not widely recognisable in China.

Justice Anthony Kennedy quoted Confucius in his majority ruling in Obergefell v. Hodges leading to discussion of the ruling on Sina Weibo. Chinese microblogging services also facilitate discourse on things like coming out to parents and articles in the People's Daily on gay men.

Later occurrences
In 2009, a male couple held a symbolic wedding in public and China Daily took the photo of the two men in a passionate embrace across its pages. Other symbolic gay and lesbian weddings have been held across the country and have been covered positively by the Chinese media. In 2012, Luo Hongling, a university professor, committed suicide because she knew her husband was a gay man. She alleged their marriage was just a lie since the man could not admit he was gay to his parents. Luo was considered a "tongqi", local slang for a woman married to a homosexual male akin to the English term "beard".

In 2016, the State Administration of Press, Publication, Radio, Film and Television banned images of homosexuals on television.

On April 13, 2018, Sina Weibo, one of China's largest and most popular microblogging platforms, announced a new policy to ban all pieces of contents related to pornography, violence, and homosexuality. According to Weibo, this act was requested by the "Network(Cyber) Security Law." However, it is unclear which "Network Security Law" Weibo was referring to. In the newest edition of "People's Republic of China Network(Cyber) Security Law" put into effect on June 1, 2017, by the government, media related to pornography is banned, yet the issue of homosexuality is not mentioned. It remains unclear if Weibo's decision reflects its company's own discrimination against the LGBTQ community, or if it foreshadows the government's future policy against this group.

Weibo's announcement led to the anger of China's LGBTQ community as well as many other Chinese citizens. A Weibo user called "Zhu Ding Zhen 竹顶针" made a post, saying, "I am gay, what about you? 我是同性恋，你呢？" This post was read more than 2.4 billion times and shared by about 3 million users, commented by 1.5 million users, and liked by 9.5 million users in less than 3 days. On April 16, Weibo posted another announcement to reverse its previous decision, stating that Weibo would stop banning pieces of contents related to homosexuality and expressed thanks to its users' "discussions" and "suggestions".

In 2021, China's government began to crack down on the presence of what it called "sissy men" and "effeminate men" in television, making many in the country's LGBTQ community feel "deeply uneasy". Films with gay characters like "Call Me By Your Name" and "Bohemian Rhapsody" have also been curbed in the country.

This restrictions also come as social media star Zhou Peng committed suicide just a few months later saying that he was bullied and called a "sissy". "Boys are supposed to be naughty, fight, and swear, and boys who are too quiet and polite are effeminate," he wrote in a suicide letter. "I was called 'sissy' at school. I might somewhat appear like a girl when I was younger, but I dressed 'normally' and didn't attempt to imitate girls."

Legal status
Adult, consensual and non-commercial homosexuality has been legal in China since 1997, when the national penal code was revised. Homosexuality was removed from the Chinese Society of Psychiatry's list of mental illnesses in 2001 and the public health campaign against HIV/AIDS pandemic does include education for men who have sex with men. Officially, overt police enforcement against gay people is restricted to gay people engaging in sex acts in public or prostitution, which are also illegal for heterosexuals. In addition, the declassification in 2001 was never officially recognised by the Ministry of Health (Now National Health Commission).

However, despite these changes, no civil rights law exists to address discrimination or harassment on the basis of sexual orientation or gender identity. Households headed by same-sex couples are not permitted to adopt children and do not have the same privileges as heterosexual married couples.

On January 5, 2016, a court in Changsha, southern Hunan province, agreed to hear the lawsuit of 26-year-old Sun Wenlin filed in December 2015 against the Furong district civil affairs bureau for its June 2015 refusal of the right to register to marry his 36-year-old male partner, Hu Mingliang. On April 13, 2016, with hundreds of gay marriage supporters outside, the Changsha court ruled against Sun, who vowed to appeal, citing the importance of his case for LGBT progress in China. On May 17, 2016, Sun and Hu were married in a private ceremony in Changsha, expressing their intention to organize another 99 LGBT weddings across the country to normalize gay marriage in China.

In 2014, a Beijing court issued an unanticipated ruling against the practice of gay conversion therapy. This ruling, however, did not apply nationwide and different district courts have issued various conflicting rulings. In 2016, a Henan court awarded civil damages to a victim of gay conversion therapy who had been physically and psychologically traumatized as a result of the procedure. However, the Court did not expressly prohibit the practice. In parallel to the previous decision, the Henan's court's decision also did not apply nationwide. At the national level, no action has been taken against gay conversion therapy and the practice continues to be promoted on a national level. LGBT activists have been pressuring the central government for a complete nationwide ban.

Sham marriages in contemporary mainland China
Due to social pressure, gay men and women sometimes enter into heterosexual-presenting relationships for appearances. When a straight woman marries a gay man, the woman is known as tongqi; when a straight man marries a lesbian woman, they are known as tongfu. When a lesbian woman and a gay man marry each other, the resulting marriage is known as xinghun, or cooperative marriage.

Much more research has been done on tongqi than tongfu, although neither has been extensive. Researchers at the Harbin Institute of Technology conducted a study on tongqi and tongfu in China. In their research, they were able to find over 200 tongqi to interview but only about 10 tongfu. They hypothesized this was because men are less likely to take their complaints online, and are less likely to be aware they are married to a queer person than their female counterparts, so they are less likely to be represented in self-help groups. They also hypothesized that men are more likely to be pressured into marriage than women, due to the social pressure to produce an heir. It is estimated that over 80% of bisexual and gay men in China marry straight women but the percentage of lesbian and bisexual women who marry straight men is unknown.

Xinghun, or formality marriage, is a tradition among Chinese queers that has seen uptake in recent years. Due to the rise of the internet, and specifically, online dating sites, Chinese entrepreneurs have created services to expedite the marriages of gay men and women to each other. Some examples of these services are the Queers app created to facilitate lavender marriage and Chinagayles.com, a service created in 2005 with over 380,000 registered accounts that has claimed to facilitate over 20,000 sham marriages.

The practice of Xinghun has become more accessible with the rise of the internet, but has also come under more scrutiny in recent years. Most people opposed to the practice were born in the late 1980s and early 1990s when Deng Xiaoping was the chairman of China. Xiaoping's economic policy of "reform and re-opening up" opened up China to foreign imports but also foreign ideas, such as acceptance of homosexuality and autonomy in marriage choices. Xiaoping's policies led to a more market-based economy in China and a populace that was more willing to express their ideas. Young Chinese people raise issues about the complications that could arise from sham marriages, such as male violence through rape or assault towards an unwilling wife, or the issues that come from raising a child who does not know the full extent of their parents' identities and relationship.

"出柜" (Coming out)
Coming out (出柜) is a crucial component of the experience of homosexuality in China, as it requires navigating complex cultural, social, and political factors. Coming out involves revealing one's sexual orientation or gender identity to others, and it can pose significant challenges and risks for LGBTQ+ individuals in Chinese society. The act of coming out can have a profound impact on the lives and well-being of members of the LGBTQ+ community, particularly in a country like China, where strong traditions and family values are deeply ingrained in the fabric of society. These strong traditions and family values often emphasize the importance of maintaining a harmonious family structure and fulfilling filial duties. One of these duties is to marry and have children, ensuring the continuation of the family line. In this context, coming out as LGBTQ+ may be perceived as a betrayal of these expectations, causing tension and conflict within the family unit. This can lead to social isolation, strained relationships, and even disownment, as family members may feel ashamed or dishonored by an LGBTQ+ relative's disclosure. Additionally, traditional Chinese values place great importance on preserving social harmony, which can manifest in a preference for conformity and adherence to social norms. As a result, LGBTQ+ individuals who come out may face ostracism, discrimination, and harassment from their communities, as their sexual orientation or gender identity may be considered disruptive to the social order. These challenges can make the coming-out process incredibly difficult and emotionally taxing for LGBTQ+ individuals in China. Historically, homosexuality was largely taboo in Chinese society, and individuals who identified as LGBTQ+ faced significant social and legal consequences for their sexual orientation or gender identity, examples range from when the People's Republic of China was just established, being an LGBTQ+ individual was criminalized under "hooliganism" laws, which led to the arrest, imprisonment, and sentenced to re-education through the labor, to homosexuality has been listed as a mental disorder in the Chinese Classification of Mental Disorders before it was taken out of the list in 2001.

In recent years, there has been a notable shift in China towards greater awareness and acceptance of LGBTQ+ individuals, particularly among younger generations who are more exposed to global perspectives on sexual diversity. This progress is evidenced by the growing visibility of LGBTQ+ communities, increased media representation, and the emergence of support networks and advocacy organizations. Despite these positive developments, coming out remains a challenging and often daunting process in China, as LGBTQ+ individuals must navigate a myriad of diverse and complex concerns. They may fear rejection or discrimination from their families, who might struggle to reconcile traditional values with their loved one's sexual orientation or gender identity. Additionally, LGBTQ+ individuals could face ostracism from their peers, colleagues, or employers, further complicating the decision to come out. Legal protections for LGBTQ+ individuals in China remain limited. Same-sex marriage is not recognized, and there are no comprehensive anti-discrimination laws that specifically protect LGBTQ+ individuals. Consequently, many LGBTQ+ people may choose to conceal their identities to avoid discrimination or persecution in various aspects of their lives.

Despite these challenges, coming out can be a powerful and transformative experience for LGBTQ+ individuals in China. Sharing their experiences and identities not only enables personal growth and self-acceptance but also helps to promote greater understanding and acceptance of sexual diversity in Chinese society. As more people come out, the visibility of the LGBTQ+ community increases, fostering conversations and challenging misconceptions and stereotypes. Moreover, the growing support for LGBTQ+ rights in China has led to the formation of advocacy groups, non-governmental organizations, and community-based initiatives that provide crucial resources, safe spaces, and support networks for LGBTQ+ individuals. These efforts contribute to a more inclusive and supportive environment for sexual minorities, which can, in turn, improve their health and well-being.

Family and societal expectations
One significant factor influencing the coming out process in China is the deeply ingrained cultural concept of filial piety. The notion of filial piety, originating from Confucianism and Chinese traditions, promotes a collection of ethical principles, ideals, and behaviors that emphasize reverence and compassion towards one's parents. Filial piety also places great emphasis on continuing the family line through procreation. A famous saying in Chinese, "不孝有三，无后为大", suggests that among the three major ways to be disrespectful to your parents and ancestors, the most severe one is not having offspring. This saying reifies the Chinese individual's natural obligation to contribute more children to the family, a hallmark of filial culture that fundamentally focuses on collective and familial flourishing. Filial piety, deeply ingrained in Chinese culture, is seen as a moral obligation. It is believed in the Chinese culture that, by fulfilling this duty, one can bring honor to their family and ancestors. Failing to fulfill the moral obligation would be considered unfilial, bringing shame to the entire family. As such, this cultural expectation often discourages LGBTQ+ individuals from coming out, for fear that they will disappoint their families or fail to fulfill their apparent duties. In order to continue the family line in a society where same-sex marriage is the norm - legally and socially - two situations arise. The first situation concerns those who would like to come out before reaching marriageable age which is 22 for the man and 20 for the woman. For them, the most difficult situation is that coming out will lead their parents to strongly oppose their children's self-selection in fear that it contradicts the notion of filial piety to continue the bloodline and the traditional gender concepts. One such example is the story of Ying Xin. Ying Xin was born in the small city of Xiangyang in Hubei Province, she has been the executive director at the Beijing LGBT Center for seven years and has helped transform the Beijing LGBT Center into the biggest queer community safe space in China. Ying Xin shared her coming out story, and her mother thought she was joking at first and became angry and said, "I didn't think I would have a daughter like this kind of freak." Then, she asked, "Don't you feel ashamed to do that kind of thing with girls?". Addressing the second problem that arises for individuals who wish to come out, for individuals who come to realize their sexual orientation or gender identity after they have already married and established a family, the situation can be particularly challenging. These individuals may have been deeply influenced by traditional gender concepts and societal expectations, which may have prevented them from recognizing or acknowledging their true identity earlier in life. They usually face the daunting challenge of potentially jeopardizing their marital or family bonds due to the fear associated with coming out.

Conversion therapy
Despite being extensively discredited by mental health professionals around the world, conversion therapy—a set of practices aimed at changing an individual's sexual orientation or gender identity—continues to be practiced in China. Unfortunately, many LGBTQ+ people are coerced into undergoing conversion therapy by family members who, see it as a way to "cure" their loved ones' homosexuality. the family usually uses verbal threats and emotional manipulation to force the child into this so-called conversion therapy. These conversion therapy practices can take various forms, including electroconvulsive therapy, aversion techniques, and prescription of inappropriate medications without informing the individuals about its purpose and side-effect, examples like giving unknown pills and injecting "colorless liquid". All of these methods have been proven to be not only ineffective but also harmful to the individuals subjected to them. The lasting effects of conversion therapy on individuals' mental health are profoundly negative, often leading to severe depression, anxiety, and even suicidal thoughts. Furthermore, the trauma inflicted by these practices can cause feelings of isolation, self-loathing, and difficulty forming healthy relationships. The consequences of conversion therapy extend beyond the immediate psychological impact, affecting individuals' overall well-being and their ability to lead fulfilling lives.

Workplace discrimination and career implications
Examining the impact of prejudice in the labor market, taste-based discrimination (TBD) is an economic model that sheds light on how personal biases against specific cultures or communities can lead employers to discriminate against minority groups, including the LGBTQ community, in the workplace. This model posits that some employers, driven by personal biases or prejudices against particular cultures or communities, may discriminate against minority groups. In an effort to avoid engaging with minority applicants, including transgender individuals, companies may display bias, even though it can have a detrimental effect on their financial performance. In the workplace, many LGBTQ employees face challenges due to stigma and a lack of supportive policies that protect them from harassment and discrimination. The Chinese Labor Law explicitly provides protection against discrimination based on ethnicity, religion, and gender, it does not include provisions addressing discrimination related to sexual orientation or gender identity. In the same vein, the Employment Promotion Law prohibits discriminatory practices in recruitment and employment but fails to explicitly reference issues concerning sexuality or gender identity. Since many companies lack protective policies and guidelines for LGBTQ employees, a majority of these individuals do not disclose their sexual orientation or self-identification in the workplace. A previous study carried out by grassroots organizations in 2013 identified various motives behind LGBTQ+ employees hiding their identity: 60.9 percent were concerned about being marginalized, 51.7 percent believed it might hinder their chances of promotion, and 22.5 percent were apprehensive about losing their jobs. These career-related anxieties are supported by evidence, as another survey discovered that approximately one-fourth of individuals whose sexual orientation was disclosed were either terminated from their jobs or forced to resign. These fear of revealing sexual orientation and negative experiences related to that can contribute to reduced job satisfaction, decreased productivity, and mental health issues such as anxiety and depression. It is crucial for companies to establish inclusive policies and offer training that fosters a safe and supportive environment for all employees. However. By addressing these issues and promoting a more inclusive work climate, companies can create a healthier, more productive environment for all employees.

Slang in contemporary Chinese gay culture
The following terms are not standard usage; rather, they are colloquial and used within the gay community in mainland China, Hong Kong, and Taiwan.

Modern people
The following are prominent mainland Chinese and Hong Kong people who have come out to the public or are actively working to improve gay rights in mainland China and Taiwan:

 * Wan Yanhai (signatory on The Yogyakarta Principles and participant of 2009 World Outgames)
 * Leslie Cheung (singer and actor from Hong Kong - died 2003)
 * Li Yinhe (the well known scholar on sexology in China)
 * Cui Zi'en (film director, producer, film scholar, screenwriter, novelist, and associate professor at the Film Research Institute of the Beijing Film Academy)
 * Raymond Chan Chi-chuen (Hong Kong legislator)
 * Denise Ho (Hong Kong Celebrity/Actor/Singer)
 * Anthony Wong (Hong Kong Singer/Activist)
 * Suzie Wong (Hong Kong TV Host)
 * Elaine Jin (Hong Kong Actor)
 * Gigi Chao (Hong Kong Activist/Heiress to Cheuk Nang Holdings)
 * Dr Chow Yiu Fai (Hong Kong Lyricist/Activist/Associate Professor of Humanities in Hong Kong Baptist University)
 * Winnie Yu (Hong Kong Radio Host/Ex-CEO of Commercial Radio Hong Kong)
 * Edward Lam (Lam Yik Wah) (Hong Kong Playwright)
 * Chet Lam (Hong Kong Indie Singer/Song Writer)

Movies, TV and web series
Many gay movies, TV series and web series have been made in Hong Kong and mainland China, including:
 * Addicted (web series) (China, 2016 web series)
 * All About Love (HK)
 * Alternative Love (China, 2016 movie)
 * Amphetamine (HK)
 * Be Here for You (China, 2015 web series)
 * Bishonen (HK)
 * Buffering... (HK)
 * Butterfly (HK)
 * Butterfly Lovers (2005 Stage Act by Denise Ho)
 * CEO and His Man / The Same Kind of Love (China, 2015)
 * Counter Attack: Falling in Love with a Rival (China, 2015 web series)
 * East Palace, West Palace (China)
 * Farewell My Concubine (China)
 * Ghost Boyfriend (China, 2016 movie)
 * Happy Together (HK)
 * He Can (China, 2016 movie)
 * Homosexuality in China (China, 2009 documentary)
 * I Am Not What You Want (HK)
 * Lanyu (China)
 * Like Love (China, 2014 web series)
 * Lost (China, 2013 short film)
 * Love Actually... Sucks! (HK)
 * Love Is More Than A Word (China, 2016 movie)
 * Mama Rainbow (China, 2012 documentary)
 * My Lover and I (China, 2015 web series)
 * No. 10 YanDaiXie Street (China, 2016 web series)
 * Nobody Knows But Me: sequel to Like Love (China, 2015 web series)
 * Oppressive Love/Queer Beauty (China, 2016 movie)
 * Permanent Residence (HK)
 * Portland Street Blues (HK)
 * The Raccoon (China, 2016 movie)
 * Rainbow Family (2015)
 * Revive: Reincarnation of a Superstar (China, 2016 web series)
 * A Round Trip to Love (China, 2016 movie)
 * Stay With Me (China, 2023 web series)
 * Speechless (China)
 * Spring Fever (2009)
 * (The Scarlet Dreams of) This Summer (China, 2015 short film)
 * ''The Untamed (China, 2019 TV series)
 * Till Death Tear Us Apart: sequel to Love Is More Than A Word (China, 2016 movie)
 * Tongzhi in Love (documentary film, China/US, 2008)
 * To You, For Me (Macao, 2015 short film)
 * Uncontrolled Love / Force Majeure (China, 2016 movie)
 * Word of Honor (China, 2021 TV series)
 * Yóuyuán Jīngmèng

In 2015, film-maker Fan Popo sued government censors for pulling his gay documentary Mama Rainbow from online sites. The lawsuit concluded in December 2015 with a finding by Beijing No.1 Intermediate People's Court that the State Administration of Press, Publication, Radio, Film and Television (SAPPRFT) had not requested that hosting sites pull the documentary. Despite this ruling, which Fan felt was a victory because it effectively limited state involvement, "the film is still unavailable to see online on Chinese hosting sites."

On December 31, 2015, the China Television Drama Production Industry Association posted new guidelines, including a ban on showing queer relationships on TV. The regulations stated: "No television drama shall show abnormal sexual relationships and behaviors, such as incest, same-sex relationships, sexual perversion, sexual assault, sexual abuse, sexual violence, and so on." These new regulations have begun to affect web dramas, which have historically had fewer restrictions:

"Chinese Web dramas are commonly deemed as enjoying looser censorship compared with content on TV and the silver screen. They often feature more sexual, violent and other content that is deemed by traditional broadcasters to fall in the no-no area."

In February 2016 the popular Chinese gay web series Addicted (Heroin) was banned from being broadcast online 12 episodes into a 15-episode season. Makers of the series uploaded the remaining episodes on YouTube, and production of a planned second season remains in doubt.

title: Homosexuality in China


text:
Närke and Värmland County

Närke and Värmland County (Närkes och Värmlands län) was the earlier name of Örebro County in Sweden, between 1634 and 1779. In that year Värmland ceded to form Värmland County. Since Närke only corresponded the southern part of the remaining territory and the name was changed to reflect the city where the Governor resided, namely Örebro.

See also about Sweden

 * Counties of Sweden
 * Provinces of Sweden
 * List of Örebro Governors

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: Närke and Värmland County


text:
Abstract structure

An abstract structure is an abstraction that might be of the geometric spaces or a set structure, or a hypostatic abstraction that is defined by a set of mathematical theorems and laws, properties and relationships in a way that is logically if not always historically independent of the structure of contingent experiences, for example, those involving physical objects. Abstract structures are studied not only in logic and mathematics but in the fields that apply them, as computer science and computer graphics, and in the studies that reflect on them, such as philosophy (especially the philosophy of mathematics). Indeed, modern mathematics has been defined in a very general sense as the study of abstract structures (by the Bourbaki group: see discussion there, at algebraic structure and also structure).

An abstract structure may be represented (perhaps with some degree of approximation) by one or more physical objects – this is called an implementation or instantiation of the abstract structure. But the abstract structure itself is defined in a way that is not dependent on the properties of any particular implementation.

An abstract structure has a richer structure than a concept or an idea. An abstract structure must include precise rules of behaviour which can be used to determine whether a candidate implementation actually matches the abstract structure in question, and it must be free from contradictions. Thus we may debate how well a particular government fits the concept of democracy, but there is no room for debate over whether a given sequence of moves is or is not a valid game of chess (for example Kasparovian approaches).

Examples

 * A sorting algorithm is an abstract structure, but a recipe is not, because it depends on the properties and quantities of its ingredients.
 * A simple melody is an abstract structure, but an orchestration is not, because it depends on the properties of particular instruments.
 * Euclidean geometry is an abstract structure, but the theory of continental drift is not, because it depends on the geology of the Earth.
 * A formal language is an abstract structure, but a natural language is not, because its rules of grammar and syntax are open to debate and interpretation.

title: Abstract structure


text:
User talk:Flyducky

Hello, and welcome to Wikipedia! We welcome contributions, but please do not add dates or persons that are not famous. Bear in mind that this is an encyclopedia. Pages and editions will be deleted. Cheers, Muriel Gottrop 17:47, 7 Nov 2003 (UTC)

title: User talk:Flyducky


text:
Lempel–Ziv–Markov chain algorithm

The Lempel–Ziv–Markov chain algorithm (LZMA) is an algorithm used to perform lossless data compression. It has been under development since either 1996 or 1998 by Igor Pavlov and was first used in the 7z format of the 7-Zip archiver. This algorithm uses a dictionary compression scheme somewhat similar to the LZ77 algorithm published by Abraham Lempel and Jacob Ziv in 1977 and features a high compression ratio (generally higher than bzip2) and a variable compression-dictionary size (up to 4 GB), while still maintaining decompression speed similar to other commonly used compression algorithms.

LZMA2 is a simple container format that can include both uncompressed data and LZMA data, possibly with multiple different LZMA encoding parameters. LZMA2 supports arbitrarily scalable multithreaded compression and decompression and efficient compression of data which is partially incompressible.

Overview
LZMA uses a dictionary compression algorithm (a variant of LZ77 with huge dictionary sizes and special support for repeatedly used match distances), whose output is then encoded with a range encoder, using a complex model to make a probability prediction of each bit. The dictionary compressor finds matches using sophisticated dictionary data structures, and produces a stream of literal symbols and phrase references, which is encoded one bit at a time by the range encoder: many encodings are possible, and a dynamic programming algorithm is used to select an optimal one under certain approximations.

Prior to LZMA, most encoder models were purely byte-based (i.e. they coded each bit using only a cascade of contexts to represent the dependencies on previous bits from the same byte). The main innovation of LZMA is that instead of a generic byte-based model, LZMA's model uses contexts specific to the bitfields in each representation of a literal or phrase: this is nearly as simple as a generic byte-based model, but gives much better compression because it avoids mixing unrelated bits together in the same context. Furthermore, compared to classic dictionary compression (such as the one used in zip and gzip formats), the dictionary sizes can be and usually are much larger, taking advantage of the large amount of memory available on modern systems.

Compressed format overview
In LZMA compression, the compressed stream is a stream of bits, encoded using an adaptive binary range coder. The stream is divided into packets, each packet describing either a single byte, or an LZ77 sequence with its length and distance implicitly or explicitly encoded. Each part of each packet is modeled with independent contexts, so the probability predictions for each bit are correlated with the values of that bit (and related bits from the same field) in previous packets of the same type. Both the lzip and the LZMA SDK documentation describes this stream format.

There are 7 types of packets:

LONGREP[*] refers to LONGREP[0–3] packets, *REP refers to both LONGREP and SHORTREP, and *MATCH refers to both MATCH and *REP.

LONGREP[n] packets remove the distance used from the list of the most recent distances and reinsert it at the front, to avoid useless repeated entry, while MATCH just adds the distance to the front even if already present in the list and SHORTREP and LONGREP[0] don't alter the list.

The length is encoded as follows:

As in LZ77, the length is not limited by the distance, because copying from the dictionary is defined as if the copy was performed byte by byte, keeping the distance constant.

Distances are logically 32-bit and distance 0 points to the most recently added byte in the dictionary.

The distance encoding starts with a 6-bit "distance slot", which determines how many further bits are needed. Distances are decoded as a binary concatenation of, from most to least significant, two bits depending on the distance slot, some bits encoded with fixed 0.5 probability, and some context encoded bits, according to the following table (distance slots 0−3 directly encode distances 0−3).

Decompression algorithm details
No complete natural language specification of the compressed format seems to exist, other than the one attempted in the following text.

The description below is based on the compact XZ Embedded decoder by Lasse Collin included in the Linux kernel source from which the LZMA and LZMA2 algorithm details can be relatively easily deduced: thus, while citing source code as reference is not ideal, any programmer should be able to check the claims below with a few hours of work.

Range coding of bits
LZMA data is at the lowest level decoded one bit at a time by the range decoder, at the direction of the LZMA decoder.

Context-based range decoding is invoked by the LZMA algorithm passing it a reference to the "context", which consists of the unsigned 11-bit variable prob (typically implemented using a 16-bit data type) representing the predicted probability of the bit being 0, which is read and updated by the range decoder (and should be initialized to $2^{10}$, representing 0.5 probability).

Fixed probability range decoding instead assumes a 0.5 probability, but operates slightly differently from context-based range decoding.

The range decoder state consists of two unsigned 32-bit variables, range (representing the range size), and code (representing the encoded point within the range).

Initialization of the range decoder consists of setting range to $2^{32} − 1$, and code to the 32-bit value starting at the second byte in the stream interpreted as big-endian; the first byte in the stream is completely ignored.

Normalization proceeds in this way:
 * 1) Shift both range and code left by 8 bits
 * 2) Read a byte from the compressed stream
 * 3) Set the least significant 8 bits of code to the byte value read

Context-based range decoding of a bit using the prob probability variable proceeds in this way:
 * 1) If range is less than $2^{24}$, perform normalization
 * 2) Set bound to $\lfloor range / 2^{11} \rfloor \times prob$
 * 3) If code is less than bound:
 * 4) Set range to bound
 * 5) Set prob to prob + $\lfloor 2^{11} - prob \rfloor / 2^5$
 * 6) Return bit 0
 * 7) Otherwise (if code is greater than or equal to the bound):
 * 8) Set range to range − bound
 * 9) Set code to code − bound
 * 10) Set prob to $prob - \lfloor prob / 2^5 \rfloor$
 * 11) Return bit 1

Fixed-probability range decoding of a bit proceeds in this way:
 * 1) If range is less than $2^{24}$, perform normalization
 * 2) Set range to $\lfloor range / 2 \rfloor$
 * 3) If code is less than range:
 * 4) Return bit 0
 * 5) Otherwise (if code is greater or equal than range):
 * 6) Set code to code − range
 * 7) Return bit 1

The Linux kernel implementation of fixed-probability decoding in, for performance reasons, does not include a conditional branch, but instead subtracts range from code unconditionally. The resulting sign bit is used to both decide the bit to return and to generate a mask that is combined with code and added to range.

Note that:
 * 1) The division by $2^{11}$ when computing bound and floor operation is done before the multiplication, not after (apparently to avoid requiring fast hardware support for 32-bit multiplication with a 64-bit result)
 * 2) Fixed probability decoding is not strictly equivalent to context-based range decoding with any prob value, due to the fact that context-based range decoding discards the lower 11 bits of range before multiplying by prob as just described, while fixed probability decoding only discards the last bit

Range coding of integers
The range decoder also provides the bit-tree, reverse bit-tree and fixed probability integer decoding facilities, which are used to decode integers, and generalize the single-bit decoding described above. To decode unsigned integers less than limit, an array of $(limit − 1)$ 11-bit probability variables is provided, which are conceptually arranged as the internal nodes of a complete binary tree with limit leaves.

Non-reverse bit-tree decoding works by keeping a pointer to the tree of variables, which starts at the root. As long as the pointer does not point to a leaf, a bit is decoded using the variable indicated by the pointer, and the pointer is moved to either the left or right children depending on whether the bit is 0 or 1; when the pointer points to a leaf, the number associated with the leaf is returned.

Non-reverse bit-tree decoding thus happens from most significant to least significant bit, stopping when only one value in the valid range is possible (this conceptually allows to have range sizes that are not powers of two, even though LZMA does not make use of this).

Reverse bit-tree decoding instead decodes from least significant bit to most significant bits, and thus only supports ranges that are powers of two, and always decodes the same number of bits. It is equivalent to performing non-reverse bittree decoding with a power of two limit, and reversing the last $log2(limit)$ bits of the result.

In the rc_bittree function in the Linux kernel, integers are actually returned in the $[limit, 2 × limit)$ range (with limit added to the conceptual value), and the variable at index 0 in the array is unused, while the one at index 1 is the root, and the left and right children indices are computed as 2i and 2i + 1. The rc_bittree_reverse function instead adds integers in the $[0, limit)$ range to a caller-provided variable, where limit is implicitly represented by its logarithm, and has its own independent implementation for efficiency reasons.

Fixed probability integer decoding simply performs fixed probability bit decoding repeatedly, reading bits from the most to the least significant.

LZMA configuration
The LZMA decoder is configured by an lclppb "properties" byte and a dictionary size. The value of the lclppb byte is $lc + lp × 9 + pb × 9 × 5$, where:
 * lc is the number of high bits of the previous byte to use as a context for literal encoding (the default value used by the LZMA SDK is 3)
 * lp is the number of low bits of the dictionary position to include in literal_pos_state (the default value used by the LZMA SDK is 0)
 * pb is the number of low bits of the dictionary position to include in pos_state (the default value used by the LZMA SDK is 2)

In non-LZMA2 streams, lc must not be greater than 8, and lp and pb must not be greater than 4. In LZMA2 streams, $(lc + lp)$ and pb must not be greater than 4.

In the 7-zip LZMA file format, configuration is performed by a header containing the "properties" byte followed by the 32-bit little-endian dictionary size in bytes. In LZMA2, the properties byte can optionally be changed at the start of LZMA2 LZMA packets, while the dictionary size is specified in the LZMA2 header as later described.

LZMA coding contexts
The LZMA packet format has already been described, and this section specifies how LZMA statistically models the LZ-encoded streams, or in other words which probability variables are passed to the range decoder to decode each bit.

Those probability variables are implemented as multi-dimensional arrays; before introducing them, a few values that are used as indices in these multidimensional arrays are defined.

The state value is conceptually based on which of the patterns in the following table match the latest 2–4 packet types seen, and is implemented as a state machine state updated according to the transition table listed in the table every time a packet is output.

The initial state is 0, and thus packets before the beginning are assumed to be LIT packets.

The pos_state and literal_pos_state values consist of respectively the pb and lp (up to 4, from the LZMA header or LZMA2 properties packet) least significant bits of the dictionary position (the number of bytes coded since the last dictionary reset modulo the dictionary size). Note that the dictionary size is normally the multiple of a large power of 2, so these values are equivalently described as the least significant bits of the number of uncompressed bytes seen since the last dictionary reset.

The prev_byte_lc_msbs value is set to the lc (up to 4, from the LZMA header or LZMA2 properties packet) most significant bits of the previous uncompressed byte.

The is_REP value denotes whether a packet that includes a length is a LONGREP rather than a MATCH.

The match_byte value is the byte that would have been decoded if a SHORTREP packet had been used (in other words, the byte found at the dictionary at the last used distance); it is only used just after a *MATCH packet.

literal_bit_mode is an array of 8 values in the 0–2 range, one for each bit position in a byte, which are 1 or 2 if the previous packet was a *MATCH and it is either the most significant bit position or all the more significant bits in the literal to encode/decode are equal to the bits in the corresponding positions in match_byte, while otherwise it is 0; the choice between the 1 or 2 values depends on the value of the bit at the same position in match_byte.

The literal/Literal set of variables can be seen as a "pseudo-bit-tree" similar to a bit-tree but with 3 variables instead of 1 in every node, chosen depending on the literal_bit_mode value at the bit position of the next bit to decode after the bit-tree context denoted by the node.

The claim, found in some sources, that literals after a *MATCH are coded as the XOR of the byte value with match_byte is incorrect; they are instead coded simply as their byte value, but using the pseudo-bit-tree just described and the additional context listed in the table below.

The probability variable groups used in LZMA are those:

LZMA2 format
The LZMA2 container supports multiple runs of compressed LZMA data and uncompressed data. Each LZMA compressed run can have a different LZMA configuration and dictionary. This improves the compression of partially or completely incompressible files and allows multithreaded compression and multithreaded decompression by breaking the file into runs that can be compressed or decompressed independently in parallel. Criticism of LZMA2's changes over LZMA include header fields not being covered by CRCs, and parallel decompression not being possible in practice.

The LZMA2 header consists of a byte indicating the dictionary size:
 * 40 indicates a 4 GB − 1 dictionary size
 * Even values less than 40 indicate a 2v/2 + 12 bytes dictionary size
 * Odd values less than 40 indicate a 3×2(v − 1)/2 + 11 bytes dictionary size
 * Values higher than 40 are invalid

LZMA2 data consists of packets starting with a control byte, with the following values:
 * 0 denotes the end of the file
 * 1 denotes a dictionary reset followed by an uncompressed chunk
 * 2 denotes an uncompressed chunk without a dictionary reset
 * 3–0x7f are invalid values
 * 0x80–0xff denotes an LZMA chunk, where the lowest 5 bits are used as bit 16–20 of the uncompressed size minus one, and bit 5–6 indicates what should be reset

Bits 5–6 for LZMA chunks can be:
 * 0: nothing reset
 * 1: state reset
 * 2: state reset, properties reset using properties byte
 * 3: state reset, properties reset using properties byte, dictionary reset

LZMA state resets cause a reset of all LZMA state except the dictionary, and specifically:
 * The range coder
 * The state value
 * The last distances for repeated matches
 * All LZMA probabilities

Uncompressed chunks consist of:
 * A 16-bit big-endian value encoding the data size minus one
 * The data to be copied verbatim into the dictionary and the output

LZMA chunks consist of:
 * A 16-bit big-endian value encoding the low 16 bits of the uncompressed size minus one
 * A 16-bit big-endian value encoding the compressed size minus one
 * A properties/lclppb byte if bit 6 in the control byte is set
 * The LZMA compressed data, starting with the 5 bytes (of which the first is ignored) used to initialize the range coder (which are included in the compressed size)

xz and 7z formats
The .xz format, which can contain LZMA2 data, is documented at tukaani.org, while the .7z file format, which can contain either LZMA or LZMA2 data, is documented in the 7zformat.txt file contained in the LZMA SDK.

Compression algorithm details
Similar to the decompression format situation, no complete natural language specification of the encoding techniques in 7-zip or xz seems to exist, other than the one attempted in the following text.

The description below is based on the XZ for Java encoder by Lasse Collin, which appears to be the most readable among several rewrites of the original 7-zip using the same algorithms: again, while citing source code as reference is not ideal, any programmer should be able to check the claims below with a few hours of work.

Range encoder
The range encoder cannot make any interesting choices, and can be readily constructed based on the decoder description.

Initialization and termination are not fully determined; the xz encoder outputs 0 as the first byte which is ignored by the decompressor, and encodes the lower bound of the range (which matters for the final bytes).

The xz encoder uses an unsigned 33-bit variable called low (typically implemented as a 64-bit integer, initialized to 0), an unsigned 32-bit variable called range (initialized to $2^{32} − 1$), an unsigned 8-bit variable called cache (initialized to 0), and an unsigned variable called cache_size which needs to be large enough to store the uncompressed size (initialized to 1, typically implemented as a 64-bit integer).

The cache/cache_size variables are used to properly handle carries, and represent a number defined by a big-endian sequence starting with the cache value, and followed by cache_size 0xff bytes, which has been shifted out of the low register, but has not been written yet, because it could be incremented by one due to a carry.

Note that the first byte output will always be 0 due to the fact that cache and low are initialized to 0, and the encoder implementation; the xz decoder ignores this byte.

Normalization proceeds in this way:
 * 1) If low is less than ($2^{32} - 2^{24}$):
 * 2) Output the byte stored in cache to the compressed stream
 * 3) Output cache_size − 1 bytes with 0xff value
 * 4) Set cache to bits 24–31 of low
 * 5) Set cache_size to 0
 * 6) If low is greater or equal than $2^{32}$:
 * 7) Output the byte stored in cache plus one to the compressed stream
 * 8) Output cache_size − 1 bytes with 0 value
 * 9) Set cache to bits 24–31 of low
 * 10) Set cache_size to 0
 * 11) Increment cache_size
 * 12) Set low to the lowest 24 bits of low shifted left by 8 bits
 * 13) Set range to range shifted left by 8 bits

Context-based range encoding of a bit using the prob probability variable proceeds in this way:
 * 1) If range is less than $2^{24}$, perform normalization
 * 2) Set bound to $\lfloor range / 2^{11} \rfloor \times prob$
 * 3) If encoding a 0 bit:
 * 4) Set range to bound
 * 5) Set prob to $prob + \lfloor 2^{11} - prob \rfloor / 2^5$
 * 6) Otherwise (if encoding a 1 bit):
 * 7) Set range to range − bound
 * 8) Set low to low + bound
 * 9) Set prob to $prob - \lfloor prob / 2^5 \rfloor$

Fixed-probability range encoding of a bit proceeds in this way:
 * 1) If range is less than $2^{24}$, perform normalization
 * 2) Set range to $\lfloor range / 2 \rfloor$
 * 3) If encoding a 1 bit:
 * 4) Set low to low + range

Termination proceeds this way:
 * 1) Perform normalization 5 times

Bit-tree encoding is performed like decoding, except that bit values are taken from the input integer to be encoded rather than from the result of the bit decoding functions.

For algorithms that try to compute the encoding with the shortest post-range-encoding size, the encoder also needs to provide an estimate of that.

Dictionary search data structures
The encoder needs to be able to quickly locate matches in the dictionary. Since LZMA uses very large dictionaries (potentially on the order of gigabytes) to improve compression, simply scanning the whole dictionary would result in an encoder too slow to be practically usable, so sophisticated data structures are needed to support fast match searches.

Hash chains
The simplest approach, called "hash chains", is parameterized by a constant N which can be either 2, 3 or 4, which is typically chosen so that $28×N$ is greater than or equal to the dictionary size.

It consists of creating, for each k less than or equal to N, a hash table indexed by tuples of k bytes, where each of the buckets contains the last position where the first k bytes hashed to the hash value associated with that hash table bucket.

Chaining is achieved by an additional array which stores, for every dictionary position, the last seen previous position whose first N bytes hash to the same value of the first N bytes of the position in question.

To find matches of length N or higher, a search is started using the N-sized hash table, and continued using the hash chain array; the search stop after a pre-defined number of hash chain nodes has been traversed, or when the hash chains "wraps around", indicating that the portion of the input that has been overwritten in the dictionary has been reached.

Matches of size less than N are instead found by simply looking at the corresponding hash table, which either contains the latest such match, if any, or a string that hashes to the same value; in the latter case, the encoder will not be able to find the match. This issue is mitigated by the fact that for distant short matches using multiple literals might require less bits, and having hash conflicts in nearby strings is relatively unlikely; using larger hash tables or even direct lookup tables can reduce the problem at the cost of higher cache miss rate and thus lower performance.

Note that all matches need to be validated to check that the actual bytes match currently at that specific dictionary position match, since the hashing mechanism only guarantees that at some past time there were characters hashing to the hash table bucket index (some implementations may not even guarantee that, because they do not initialize the data structures).

Binary trees
The binary tree approach follows the hash chain approach, except that it logically uses a binary tree instead of a linked list for chaining.

The binary tree is maintained so that it is always both a search tree relative to the suffix lexicographic ordering, and a max-heap for the dictionary position (in other words, the root is always the most recent string, and a child cannot have been added more recently than its parent): assuming all strings are lexicographically ordered, these conditions clearly uniquely determine the binary tree (this is trivially provable by induction on the size of the tree).

Since the string to search for and the string to insert are the same, it is possible to perform both dictionary search and insertion (which requires to rotate the tree) in a single tree traversal.

Patricia tries
Some old LZMA encoders also supported a data structure based on Patricia tries, but such support has since been dropped since it was deemed inferior to the other options.

LZMA encoder
LZMA encoders can freely decide which match to output, or whether to ignore the presence of matches and output literals anyway.

The ability to recall the 4 most recently used distances means that, in principle, using a match with a distance that will be needed again later may be globally optimal even if it is not locally optimal, and as a result of this, optimal LZMA compression probably requires knowledge of the whole input and might require algorithms too slow to be usable in practice.

Due to this, practical implementations tend to employ non-global heuristics.

The xz encoders use a value called nice_len (the default is 64): when any match of length at least nice_len is found, the encoder stops the search and outputs it, with the maximum matching length.

Fast encoder
The XZ fast encoder (derived from the 7-zip fast encoder) is the shortest LZMA encoder in the xz source tree.

It works like this:
 * 1) Perform combined search and insertion in the dictionary data structure
 * 2) If any repeated distance matches with length at least nice_len:
 * 3) * Output the most frequently used such distance with a REP packet
 * 4) If a match was found of length at least nice_len:
 * 5) * Output it with a MATCH packet
 * 6) Set the main match to the longest match
 * 7) Look at the nearest match of every length in decreasing length order, and until no replacement can be made:
 * 8) * Replace the main match with a match which is one character shorter, but whose distance is less than 1/128 the current main match distance
 * 9) Set the main match length to 1 if the current main match is of length 2 and distance at least 128
 * 10) If a repeated match was found, and it is shorter by at most 1 character than the main match:
 * 11) * Output the repeated match with a REP packet
 * 12) If a repeated match was found, and it is shorter by at most 2 characters than the main match, and the main match distance is at least 512:
 * 13) * Output the repeated match with a REP packet
 * 14) If a repeated match was found, and it is shorter by at most 3 characters than the main match, and the main match distance is at least 32768:
 * 15) * Output the repeated match with a REP packet
 * 16) If the main match size is less than 2 (or there is not any match):
 * 17) * Output a LIT packet
 * 18) Perform a dictionary search for the next byte
 * 19) If the next byte is shorter by at most 1 character than the main match, with distance less than 1/128 times the main match distance, and if the main match length is at least 3:
 * 20) * Output a LIT packet
 * 21) If the next byte has a match at least as long as the main match, and with less distance than the main match:
 * 22) * Output a LIT packet
 * 23) If the next byte has a match at least one character longer than the main match, and such that 1/128 of its distance is less or equal than the main match distance:
 * 24) * Output a LIT packet
 * 25) If the next byte has a match more than one character longer than the main match:
 * 26) * Output a LIT packet
 * 27) If any repeated match is shorter by at most 1 character than the main match:
 * 28) * Output the most frequently used such distance with a REP packet
 * 29) Output the main match with a MATCH packet

Normal encoder
The XZ normal encoder (derived from the 7-zip normal encoder) is the other LZMA encoder in the xz source tree, which adopts a more sophisticated approach that tries to minimize the post-range-encoding size of the generated packets.

Specifically, it encodes portions of the input using the result of a dynamic programming algorithm, where the subproblems are finding the approximately optimal encoding (the one with minimal post-range-encoding size) of the substring of length L starting at the byte being compressed.

The size of the portion of the input processed in the dynamic programming algorithm is determined to be the maximum between the longest dictionary match and the longest repeated match found at the start position (which is capped by the maximum LZMA match length, 273); furthermore, if a match longer than nice_len is found at any point in the range just defined, the dynamic programming algorithm stops, the solution for the subproblem up to that point is output, the nice_len-sized match is output, and a new dynamic programming problem instance is started at the byte after the match is output.

Subproblem candidate solutions are incrementally updated with candidate encodings, constructed taking the solution for a shorter substring of length L', extended with all possible "tails", or sets of 1–3 packets with certain constraints that encode the input at the L' position. Once the final solution of a subproblem is found, the LZMA state and least used distances for it are computed, and are then used to appropriately compute post-range-encoding sizes of its extensions.

At the end of the dynamic programming optimization, the whole optimal encoding of the longest substring considered is output, and encoding continues at the first uncompressed byte not already encoded, after updating the LZMA state and least used distances.

Each subproblem is extended by a packet sequence which we call "tail", which must match one of the following patterns:

The reason for not only extending with single packets is that subproblems only have the substring length as the parameter for performance and algorithmic complexity reasons, while an optimal dynamic programming approach would also require to have the last used distances and LZMA state as parameter; thus, extending with multiple packets allows to better approximate the optimal solution, and specifically to make better use of LONGREP[0] packets.

The following data is stored for each subproblem (of course, the values stored are for the candidate solution with minimum price), where by "tail" we refer to the packets extending the solution of the smaller subproblem, which are described directly in the following structure:

Note that in the XZ for Java implementation, the optPrev and backPrev members are reused to store a forward single-linked list of packets as part of outputting the final solution.

LZMA2 encoder
The XZ LZMA2 encoder processes the input in chunks (of up to 2 MB uncompressed size or 64 KB compressed size, whichever is lower), handing each chunk to the LZMA encoder, and then deciding whether to output an LZMA2 LZMA chunk including the encoded data, or to output an LZMA2 uncompressed chunk, depending on which is shorter (LZMA, like any other compressor, will necessarily expand rather than compress some kinds of data).

The LZMA state is reset only in the first block, if the caller requests a change of properties and every time a compressed chunk is output. The LZMA properties are changed only in the first block, or if the caller requests a change of properties. The dictionary is only reset in the first block.

Upper encoding layers
Before LZMA2 encoding, depending on the options provided, xz can apply the BCJ filter, which filters executable code to replace relative offsets with absolute ones that are more repetitive, or the delta filter, which replaces each byte with the difference between it and the byte N bytes before it.

Parallel encoding is performed by dividing the file in chunks which are distributed to threads, and ultimately each encoded (using, for instance, xz block encoding) separately, resulting in a dictionary reset between chunks in the output file.

7-Zip reference implementation
The LZMA implementation extracted from 7-Zip is available as LZMA SDK. It was originally dual-licensed under both the GNU LGPL and Common Public License, with an additional special exception for linked binaries, but was placed by Igor Pavlov in the public domain on December 2, 2008, with the release of version 4.62.

LZMA2 compression, which is an improved version of LZMA, is now the default compression method for the .7z format, starting with version 9.30 on October 26, 2012.

The reference open source LZMA compression library was originally written in C++ but has been ported to ANSI C, C#, and Java. There are also third-party Python bindings for the C++ library, as well as ports of LZMA to Pascal, Go and Ada.

The 7-Zip implementation uses several variants of hash chains, binary trees and Patricia trees as the basis for its dictionary search algorithm.

In addition to LZMA, the SDK and 7-Zip also implements multiple preprocessing filters intended to improve compression, ranging from simple delta encoding (for images) and BCJ for executable code. It also provides some other compression algorithms used in 7z.

Decompression-only code for LZMA generally compiles to around 5 KB, and the amount of RAM required during decompression is principally determined by the size of the sliding window used during compression. Small code size and relatively low memory overhead, particularly with smaller dictionary lengths, and free source code make the LZMA decompression algorithm well-suited to embedded applications.

Other implementations
In addition to the 7-Zip reference implementation, the following support the LZMA format.
 * xz: a streaming implementation that contains a gzip-like command line tool, supporting both LZMA and LZMA2 in its xz file format. It made its way into several software of the Unix-like world with its high performance (compared to bzip2) and small size (compared to gzip). The Linux kernel, dpkg and RPM systems contains xz code, and many software distributors like kernel.org, Debian and Fedora now use xz for compressing their releases.
 * lzip: another LZMA implementation mostly for Unix-like systems to be directly competing with xz. It mainly features a simpler file format and therefore easier error recovery.
 * ZIPX: an extension to the ZIP compressions format that was created by WinZip starting with version 12.1. It also can use various other compression methods such as BZip and PPMd.

LZHAM
LZHAM (LZ, Huffman, Arithmetic, Markov), is an LZMA-like implementation that trades compression throughput for very high ratios and higher decompression throughput. It was placed by its author in the public domain on 15 September 2020.

title: Lempel–Ziv–Markov chain algorithm


text:
User:Cogibyte

I created the following articles:

 * Delicatessen
 * Hero sandwich
 * Club sandwich
 * Phillip J. Fry
 * Turanga Leela
 * Professor Hubert Farnsworth
 * Zapp Brannigan
 * Butterfly stroke

I have contributed substantially to the following:

 * American dream
 * Futurama
 * The Adventures of Pete & Pete

I'd like to start a page that lists the most controversial movies. I'll start the list on this page, feel free to add any missing entries. Once the list becomes long enough, I'll make it a page. Eventually, I'd like to create different categories of controversy, such as authenticity, offensive content, explicit content, etc. Someone please tell me if this list is redundant in Wikipedia.

 * Irreversible (2003) - Criticized for explicit violence and rape scenes.
 * The Passion of Christ (2004) - Allegedly anti-semitic in its depiction of Christ's crucifixion.

Stamm -- Good idea for the list. I'll add the following:
 * The Last Temptation of Christ (1988) - Criticized for its depiction of the Christ as an ordinary man.
 * A Clockwork Orange (1971) - Kubrick banned it in UK when people started to act as violently as the protagonist.
 * Empire of the Senses (1976) - Explicit sex in a mainstream japanese movie.

Thank god somebody added to this, I'd forgotten about it. A few more, and I think its ready for the prime time.
 * Birth of a Nation -- Panned as racist
 * The Godfather III -- for being bad, whereas the previous two are widely considered among the best ever made (?)
 * Lolita -- I don't know, I'm sure the book was controversial, someone will have to let me know on the movie
 * American Pie -- A landmark in terms of gross-out humour, probably helped to establish it as a genre
 * Farenheit 9/11 -- thank god, one i'm sure about... Very critical of the Bush administration, borderline conspiracy theory-ing
 * Jungle Fever -- Truly, pretty much anything by Spike Lee, but I think this one was a good example
 * Bowling for Columbine -- Again, Moore. Dealt with gun laws in the wake of the Columbine massacre.  Unsavory editing and filmaking techniques employed to further its agenda.
 * Battle Royale -- A brutal Japanese film featuring extreme violence between adolescents
 * City of God -- I'm not too sure if this was controversial, but it was recognized as extremely violent

title: User:Cogibyte