ทดสอบที่กำหนดเอง

Rust SQLx Persist by strosekd

use super::IdempotencyKey;
use actix_web::body::to_bytes;
use actix_web::http::StatusCode;
use actix_web::HttpResponse;
use sqlx::{Executor, PgPool};
use sqlx::{Postgres, Transaction};
use uuid::Uuid;

#[derive(Debug, sqlx::Type)]
#[sqlx(type_name = "header_pair")]
struct HeaderPairRecord {
name: String,
value: Vec<u8>,
}

pub async fn get_saved_response(
pool: &PgPool,
idempotency_key: &IdempotencyKey,
user_id: Uuid,
) -> Result<Option<HttpResponse>, anyhow::Error> {
let saved_response = sqlx::query!(
r#"
SELECT
response_status_code as "response_status_code!",
response_headers as "response_headers!: Vec<HeaderPairRecord>",
response_body as "response_body!"
FROM idempotency
WHERE
user_id = $1 AND
idempotency_key = $2
"#,
user_id,
idempotency_key.as_ref()
)
.fetch_optional(pool)
.await?;
if let Some(r) = saved_response {
let status_code = StatusCode::from_u16(r.response_status_code.try_into()?)?;
let mut response = HttpResponse::build(status_code);
for HeaderPairRecord { name, value } in r.response_headers {
response.append_header((name, value));
}
Ok(Some(response.body(r.response_body)))
} else {
Ok(None)
}
}

pub async fn save_response(
mut transaction: Transaction<'static, Postgres>,
idempotency_key: &IdempotencyKey,
user_id: Uuid,
http_response: HttpResponse,
) -> Result<HttpResponse, anyhow::Error> {
let (response_head, body) = http_response.into_parts();
let body = to_bytes(body).await.map_err(|e| anyhow::anyhow!("{}", e))?;
let status_code = response_head.status().as_u16() as i16;
let headers = {
let mut h = Vec::with_capacity(response_head.headers().len());
for (name, value) in response_head.headers().iter() {
let name = name.as_str().to_owned();
let value = value.as_bytes().to_owned();
h.push(HeaderPairRecord { name, value });
}
h
};
transaction
.execute(sqlx::query_unchecked!(
r#"
UPDATE idempotency
SET
response_status_code = $3,
response_headers = $4,
response_body = $5
WHERE
user_id = $1 AND
idempotency_key = $2
"#,
user_id,
idempotency_key.as_ref(),
status_code,
headers,
body.as_ref()
))
.await?;
transaction.commit().await?;

let http_response = response_head.set_body(body).map_into_boxed_body();
Ok(http_response)
}

#[allow(clippy::large_enum_variant)]
pub enum NextAction {
// Return transaction for later usage
StartProcessing(Transaction<'static, Postgres>),
ReturnSavedResponse(HttpResponse),
}

pub async fn try_processing(
pool: &PgPool,
idempotency_key: &IdempotencyKey,
user_id: Uuid,
) -> Result<NextAction, anyhow::Error> {
let mut transaction = pool.begin().await?;
let query = sqlx::query!(
r#"
INSERT INTO idempotency (
user_id,
idempotency_key,
created_at
)
VALUES ($1, $2, now())
ON CONFLICT DO NOTHING
"#,
user_id,
idempotency_key.as_ref()
);
let n_inserted_rows = transaction.execute(query).await?.rows_affected();
if n_inserted_rows > 0 {
Ok(NextAction::StartProcessing(transaction))
} else {
let saved_response = get_saved_response(pool, idempotency_key, user_id)
.await?
.ok_or_else(|| anyhow::anyhow!("We expected a saved response, we didn't find it"))?;
Ok(NextAction::ReturnSavedResponse(saved_response))

rhyming words 2 by puzzlled

ask mask flask task bask
about throughout drought without scout doubt sprout
above glove dove love
across loss cross toss
add glad sad mad lad dad bad had
age stage wage engage sage cage
air chair hair care share fair rare chair repair
art part start apart chart heart cart depart
boy joy toy enjoy destroy employ
bag flag tag swag
baby maybe
bed said read red led dead fed wed head
bell well cell tell spell swell sell fell hostel smell shell
build filled killed skilled guild thrilled chilled fulfilled
burn learn stern earn concern turn return
ball small call fall tall mall wall
best test nest chest protest request suggest arrest invest
bore four roar for more score door explore
cat rat sat bat mat fat hat flat chat
car far star bar jar tar
chance advance glance finance enhance france dance trance
child wild smiled mild styled
class mass gas pass glass grass brass surpass
cook book took look hook
cool school rule tool pool fool
cut hut shut but what
day way say may stay ray bay clay decay
die by high why try sky buy cry rely guy
dirty thirty naughty thirsty
draw law saw jaw awe flaw claw paw
drop crop chop mop shop stop slope top swap
each beach reach speech teach
education population situation association administration communication
effect project object direct respect select perfect reflect detect
face race maze gaze lays case place space trace replace ace
false force source across resource horse boss
father honour scholar proper dollar brother taller
fault salt default vault assault
fox box ox stocks socks flocks
funny money honey sunny bunny
future fewer user newer humour cooper ruler
game same came name frame aim became shame lame
gate state great rate weight date eight straight plate
gift shift lift drift skit thrift
god odd nod squad
gold old told cold fold mould behold sold scold
gun one done sun son won fun
hammer grammar glamour stammer armour banner
hear cheer clear dear career severe ear adhere beer fear near
hour power tower flower flour shower our devour
invent percent spent extent represent rent prevent scent
jump pump dump stump
knife life wife
kind behind find mind designed blind
lady shady
laugh half calf behalf staff graph
last past cast vast contrast blast
lock stock walk block rock shock clock chalk
right kite height bite might
owl growl foul
boat coat float wrote note promote remote throat denote devote
cave gave save wave grave behave brave shave engrave
hole mole stole control whole roll soul goal toll poll
hot not cot got lot caught shot spot bought plot forgot

rhyming typing 1 by puzzlled

bat cat rat mat hat sat flat chat that brat
sun fun run bun pun gun stun done spun none
hot not lot pot got cot shot plot spot trot
win pin tin sin fin kin grin skin spin thin
cut hut nut but gut put shut strut glut mutt
lap tap map sap cap gap clap trap wrap slap
fit hit bit sit lit kit spit quit split grit
box fox ox pox socks blocks clocks rocks flocks
row low tow show glow flow throw slow grow blow
red bed fed led wed shed bled sped tread
man can fan ran tan pan span plan clan scan
day pay say may lay ray way clay play stay
top hop cop mop pop stop drop flop prop shop
big dig fig wig pig rig gig jig twig zig
tie lie die pie cry fry dry sky why try
dog fog log bog jog clog frog hog smog frog
car far jar bar star scar par char czar spar
new few dew brew flew grew crew chew view skew
ten pen hen men den then when yen zen glen

Pilate and Christ by msonnl

Pilate: "Oh, so this is Jesus Christ, I am really quite surprised. You look so small not a king at all. We all know that you are news but are you king. King of the Jews?" Jesus: "That's what you say" Pilate: "What do you mean by that? That is not an answer. You're deep in trouble, friend. Someone Christ king of the Jews. How can someone in your state be so cool about your fate? An amazing thing, this silent king. Since you come from Galilee, then you need not come to me. You're Herod's case!"

Trial Before Pilate by msonnl

Pilate: "Talk to me Jesus Christ. You've been brought here manacled, beaten by your own people. Do you have the first idea why you deserve it? Listen king of the Jews, where is your kingdom? Look at me, am I a Jew?" Jesus: "I have got no kingdom in this world I'm through. There may be a kingdom for me somewhere, if I only knew." Pilate: "Then you're a king?" Jesus: "It's you that say I am. I look for truth, and find that I get damned." Pilate: "But what is truth? Is truth unchanging law? We both have truths, are mine the same as yours?" Mob: "Crucify him!" Pilate: "What do you mean? You'd crucify your king? He's done no wrong. No, not the slightest thing! I see no reason, I find no evil. This man is harmless so why does he upset you? He's just misguided. Thinks he's important. But to keep you vultures happy, I shall flog him!"

3 letter 1000 words by puzzlled

the the the and and and for for for not not but but but all all can can one one get get get has has has had had her her him him his his out out out see see too too now now how why why any any way day day big big new new new old old old put put our our let let let man man say say was was set set end end try try run run fly fly top top yes yes yes may may red red bad bad eat eat ice ice sun sun sky sky fun fun hot hot key key sit sit win win pay pay fit fit box box cut cut net net dry dry add add joy joy bat bat fix fix lap lap arm arm bow bow tie tie toe toe pop pop rip rip bus bus hug hug pin pin row row the the the

and and and for for for not not but but but all all can can one one get get get has has has had had her her him him his his out out out see see too too now now how why why any any way day day big big new new new old old old put put our our let let let man man say say was was set set end end try try run run fly fly top top yes yes yes may may red red bad bad eat eat ice ice sun sun sky sky fun fun hot hot key key sit sit win win pay pay fit fit box box cut cut net net dry dry add add joy joy bat bat fix fix lap lap arm arm bow bow tie tie toe toe pop pop rip rip bus bus hug hug pin pin row row the the the and and and for for for not not but but but all all can can one one

get get get has has has had had her her him him his his out out out see see too too now now how why why any any way day day big big new new new old old old put put our our let let let man man say say was was set set end end try try run run fly fly top top yes yes yes may may red red bad bad eat eat ice ice sun sun sky sky fun fun hot hot key key sit sit win win pay pay fit fit box box cut cut net net dry dry add add joy joy bat bat fix fix lap lap arm arm bow bow tie tie toe toe pop pop rip rip bus bus hug hug pin pin row row the the the and and and for for for not not but but but all all can can one one get get get has has has had had her her him him his his out out out

see see too too now now how why why any any way day day big big new new new old old old put put our our let let let man man say say was was set set end end try try run run fly fly top top yes yes yes may may red red bad bad eat eat ice ice sun sun sky sky fun fun hot hot key key sit sit win win pay pay fit fit box box cut cut net net dry dry add add joy joy bat bat fix fix lap lap arm arm bow bow tie tie toe toe pop pop rip rip bus bus hug hug pin pin row row

LAW_6__31 by user654824

Soon the fame of Mata Hari and her sacred Indian dances spread beyond Paris. She was invited to Berlin, Vienna, Milan. Over the next few years she performed throughout Europe, mixed with the highest social circles, and earned an income that gave her an independence rarely enjoyed by a woman of the period. Then, near the end of World War I, she was arrested in France, tried, convicted, and finally executed as a German spy. Only during the trial did the truth come out: Mata Hari was not from Java or India, had not grown up in the Orient, did not have a drop of Eastern blood in her body. Her real name was Margaretha Zelle, and she came from the stolid northern province of Friesland, Holland.

LAW_6__30 by user654824

In August of 1905, Mata Hari performed for the first time in public. Crowds thronging to see her on opening night caused a riot. She had now become a cult figure, spawning many imitations. One reviewer wrote, "Mata Hari personifies all the poetry of India, its mysticism, its voluptuousness, its hypnotizing charm." Another noted," If India possesses such unexpected treasures, then all Frenchmen will emigrate to the shores of the Ganges."

LAW_6__29 by user654824

As Mata Hari gave more interviews, the story of her origins kept changing: She had grown up in India, her grandmother was the daughter of a Javanese princess, she had lived on the island of Sumatra where she had spent her time "horseback riding, gun in hand, and risking her life." No one knew anything certain about her, but journalists did not mind these changes in her biography. They compared her to an Indian goddess, a creature from the pages of Baudelaire whatever their imagination wanted to see in this mysterious woman from the East.

LAW_6__28 by user654824

The public wanted to know more about her. She told journalists that she was actually Dutch in origin, but had grown up on the island of Java. She would also talk about time spent in India, how she had learned sacred Hindu dances there, and how Indian women "can shoot straight, ride horseback, and are capable of doing logarithms and talk philosophy." By the summer of 1905, although few Parisians had actually seen Mata Hari dance, her name was on everyone's lips.

LAW_6__27 by user654824

Early that year, in the winter, small and select audiences would gather in a salon filled with Indian statues and other relics while an orchestra played music inspired by Hindu and Javanese melodies. After keeping the audience waiting and wondering, Mata Hari would suddenly appear, in a startling costume: a white cotton brassiere covered with Indian-type jewels; jeweled bands at the waist supporting a sarong that revealed as much as it concealed; bracelets up the arms. Then Mata Hari would dance, in a style no one in France had seen before, her whole body swaying as if she were in a trance. She told her excited and curious audience that her dances told stories from Indian mythology and Javanese folktales. Soon the cream of Paris, and ambassadors from far-off lands, were competing for invitations to the salon, where it was rumored that Mata Hari was actually performing sacred dances in the nude.

LAW_6__26 by user654824

Observance Of The Law
Beginning in 1905, rumors started to spread throughout Paris of a young Oriental girl who danced in a private home, wrapped in veils that she gradually discarded. A local journalist who had seen her dancing reported that "a woman from the Far East had come to Europe laden with perfume and jewels, to introduce some of the richness of the Oriental colour and life into the satiated society of European cities." Soon everyone knew the dancer's name: Mata Hari.

LAW_6__25 by user654824

Part II: Create An Air Of Mystery
In a world growing increasingly banal and familiar, what seem enigmatic instantly draws attention. Never make it too clear what you are doing or about to do. Do not show all your cards. An air of mystery heightens your presence; it also creates anticipation everyone will be watching you to see what happens next. Use mystery to beguile, seduce, even frighten.

LAW_6__24 by user654824

Authority: Be ostentatious and be seen.... What is not seen is as though it did not exist.... It was light that first caused all creation to shine forth. Display fills up many blanks, covers up deficiencies, and gives everything a second life, especially when it is backed by genuine merit. (Baltasar Gracian, 1601-1658)

LAW_6__23 by user654824

Image: The Limelight. The actor who steps into this brilliant light attains a heightened presence. All eyes are on him. There is room for only one actor at a time in the limelight's narrow beam; do whatever it takes to make yourself its focus. Make your gestures so large, amusing, and scandalous that the light stays on you while the other actors are left in the shadows.

LAW_6__20 by user654824

Edison would design visually dazzling experiments to display his discoveries with electricity. He would talk of future inventions that seemed fantastic at the time robots, and machines that could photograph thought and that he had no intention of wasting his energy on, but that made the public talk about him. He did everything he could to make sure that he received more attention than his great rival Nikola Tesla, who may actually have been more brilliant than his great rival Nikola Tesla, who may actually have been more brilliant than he was but whose name was far less known. In 1915, it was rumored that Edison and Tesla would be joint recipients of that year's Nobel Prize in physics. The prize was eventually given to a pair of English physicists; only later was it discovered that the prize committee had actually approached Edison, but he had turned them down, refusing to share the prize with Tesla. By that time his fame was more secure than Tesla's, and he thought it better to refuse the honor than to allow his rival the attention that would have come even from sharing the prize.

Berlibur ke Pantai by user109477

Pada suatu hari yang cerah, saya dan keluarga pergi berlibur ke pantai untuk menghabiskan akhir pekan. Kami berangkat pagi-pagi sekali, mengendarai mobil dengan penuh semangat menuju pantai yang terletak di luar kota. Setibanya di sana, kami disambut oleh suara ombak yang bergulung-gulung, langit biru tanpa awan, dan pasir putih yang halus di bawah kaki. Saya segera berlari ke tepi air, merasakan dinginnya air laut yang menyentuh jemari kaki saya. Adik saya sibuk membangun istana pasir, sementara ayah dan ibu duduk di bawah payung, menikmati pemandangan sambil membaca buku. Tidak lama kemudian, kami semua bermain di air, melompat bersama ombak dan tertawa lepas saat ombak besar datang menghampiri. Setelah lelah bermain, kami duduk di atas tikar sambil menikmati bekal yang dibawa dari rumah, nasi bungkus dengan ikan bakar yang lezat. Angin pantai yang sejuk membuat kami merasa damai dan tenang, seolah semua kekhawatiran hilang bersama suara ombak. Hari itu terasa begitu menyenangkan, dan ketika matahari mulai tenggelam di ufuk barat, kami berjalan menyusuri pantai, meninggalkan jejak kaki di pasir basah, sebelum akhirnya pulang dengan hati yang bahagia dan penuh kenangan indah.

LAW_6__22 by user654824

Once in the limelight you must constantly renew it by adapting and varying your method of courting attention. If you don't, the public will grow tired, will take you for granted, and will move on to a newer star. The game requires constant vigilance and creativity. Pablo Picasso never allowed himself to fade into the background; if his name became too attached to a particular style, he would deliberately upset the public with a new series of paintings that went against all expectations. Better to create something ugly and disturbing, he believed, than to let viewers grow too familiar with his work. Understand: People feel superior to the person whose actions they can predict. If you show them who is in control by playing against their expectations, you both gain their respect and tighten your hold on their fleeting attention.

LAW_6__21 by user654824

If you find yourself in a lowly position that offers little opportunity for you to draw attention, an effective trick is to attack the most visible, most famous, most powerful person you can find. When Pietro Aretino, a young Roman servant boy of the early sixteenth century, wanted to get attention as a writer of verses, he decided to publish a series of satirical poems ridiculing the pope and his affection for a pet elephant. The attack put Aretino in the public eye immediately. A slanderous attack on a person in a position of power would have a similar effect. Remember, however, to use such tactics sparingly after you have the public's attention, when the act can wear thin.

LAW_6__19 by user654824

The great scientist Thomas Edison knew that to raise money he had to remain in the public eye at any cost. Almost as important as the inventions themselves was how he presented them to the public and courted attention.