Building a Laravel Translation Package – Wrangling Translations



Laravel Tutorials
/
November 02, 2018

Building a Laravel Translation Package – Wrangling Translations

As we’ve discussed earlier in the series, out of the box, Laravel translations are stored in language files. These can be either PHP array-style syntax or straight up JSON files.

The Laravel Translation package interacts with the files in order to achieve the following:

  • List all languages
  • Add a language
  • List all translations
  • Add a translation
  • Update existing translations

The plan for the package is, much like many features of Laravel, to expose multiple drivers to power the translation management. The first driver will utilize Laravel’s existing file-based translations with plans to later add a database driver. With this in mind, we first define a contract to which driver will implement to ensure all the required methods are available to the package.

The file driver needs to interrogate the filesystem in order to return the data in the required format. This involves a lot of filtering, mapping and iterating, so we will lean quite heavily on Laravel’s collections.

Listing languages

To generate a collection of languages, we use the filesystem to get an array of directories from the configured language path, wrapping the result in a collection.

$directories = Collection::make($this->disk->directories($this->languageFilesPath));

Next, we utilize the mapWithKeys function to iterate over the directories, stripping the language from the path (it will be the last segment) and returning a key => value array.

return $directories->mapWithKeys(function ($directory) {
    $language = basename($directory);
    return [$language => $language];
});

The result looks something like this:

// $this->allLanguages()->toArray();

[
    ‘en’ => ‘en’,
    ‘fr’ => ‘fr’,
    ‘es’ => ‘es’,
];

Adding languages

To create a new language, we need to add a new directory and empty JSON file to the configured language path and name it after the language we’re adding.

$this->disk->makeDirectory(“{$this->languageFilesPath}/$language”);

if (! $this->disk->exists(“{$this->languageFilesPath}/{$language}.json”)) {
    $this->disk->put(
        “{$this->languageFilesPath}/$language.json”,
        json_encode((object) [], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
    );
}

Then, we use the filesystem to add a new file to the language path containing an empty JSON encoded array.

Using the JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT constants ensure the generated JSON is in the right format.

Listing translations

When listing translations we want to ensure we differentiate the group (array style) translations from the single (JSON style).

Group
To get the group translations, we can use the filesystem to get all the files from the language directory.

$groups Collection($this->disk->allFiles(“{$this->languageFilesPath}/{$language}“));

Then, to get the translations, we can iterate over all the files in the directory and use the filesystem’s getRequire method to require the file giving us direct access to the array.

$groups->mapWithKeys(function ($group) {
    return [$group->getBasename(‘.php’) => $this->disk->getRequire($group->getPathname())];
});

The result looks something like this:

[
    ‘auth’ => [
        ‘failed’ => ‘These credentials do not match our records’,
    ],
]

Single

We can get the single translations by using json_decode on the contents of the file.

if ($this->disk->exists($this->languageFilesPath.“/$language.json”)) {
    return new Collection(json_decode($this->disk->get($singlePath), true));
}

The result looks something like this:

[
    ‘hello’ => ‘hello’,
]

Adding/updating translations

Translations are added and updated in largely the same fashion. First, we get the contents of the file the translation should be added to in array format. Then, we check whether or not the key to be added already exists. If it does, we update the value and if not, we append the new key and value to the array. Finally, the whole array is written back to the file.

Group

$translations = $this->getGroupTranslationsFor($language);
$values = $translations->get($group);
$values[$key] = $value;
$translations->put($group, $values);
$this->disk->put(
    “{$this->languageFilesPath}/{$language}/{$group}.php”,
    “<?php\n\nreturn “.var_export($translations, true).‘;’.\PHP_EOL
);

Single

$translations = $this->getSingleTranslationsFor($language);
$translations->put($key, $value);
$this->disk->put(
    “{$this->languageFilesPath}/$language.json”,
    json_encode((object) $translations, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
);

Some of the code samples have been truncated for clarity. You can see the full code for the files mentioned in the article below:

Driver Interface
File Driver

This driver lays the foundation from which we can build upon. Next time, we’ll build out the user interface which will ship with the package. It utilizes a combination of Tailwind CSS and Vue.js, two frameworks which have been widely adopted by the Laravel community.


via Laravel News
Building a Laravel Translation Package – Wrangling Translations

Harvard Opens Up Its Massive Caselaw Access Project

Almost exactly three years ago, we wrote about the launch of an ambitious project by Harvard Law School to scan all federal and state court cases and get them online (for free) in a machine readable format (not just PDFs!), with open APIs for anyone to use. And, earlier this week, case.law officially launched, with 6.4 million cases, some going back as far as 1658. There are still some limitations — some placed on the project by its funding partner, Ravel, which was acquired by LexisNexis last year (though, the structure of the deal will mean some of these restrictions will likely decrease over time).

Also, the focus right now is really on providing this setup as a tool for others to build on, rather than as a straight up interface for anyone to use. As it stands, you can either access data via the site’s API, or by doing bulk downloads. Of course, the bulk downloads are, unfortunately, part of what’s limited by the Ravel/LexisNexis data. Bulk downloads are available for cases in Illinois and Arkansas, but that’s only because both of those states already make cases available online. Still, even with the Ravel/LexisNexis limitation, individual users can download up to 500 cases per day.

The real question is what will others build with the API. The site has launched with four sample applications that are all pretty cool.

  • H2O is a tool that law professors can use to easily create casebooks for students in various areas of law. Anything published on H2O gets a Creative Commons license and can then be shared widely. I wonder if professors like Eric Goldman, who offers an Internet Law Casebook, or James Grimmelmann, who has a different Internet Law Casebook, will eventually port them over to a platform like H2O.
  • A wordcloud app that currently shows the "most used words" in California cases in various years. Here, for example, are the word clouds in California cases from 1871… and 2012. See if you can tell which one’s which.
   
  • Caselaw Limericks that appears to randomly generate what it believes is a rhyming limerick from the case law. Here’s what I got:

Her son Julius is a confirmed thief.
He did not turn over a new leaf.
The vessel, not.
the parking lot.
Respondent concedes this in its brief.

    The quality overall is… a bit mixed. But it’s fun.
  • And, finally, in time for Halloween, Witchcraft in Law, which totals up cases that cite "witchcraft" by state.

Hopefully this inspires a lot more on the development side as well.

Permalink | Comments | Email This Story

via Techdirt
Harvard Opens Up Its Massive Caselaw Access Project

How Much Do Your Employees Actually Know About Cybersecurity?

Image Credit: TheDigitalArtist on Pixabay

In 2017, the globally known company Deloitte faced a cybersecurity crisis. That is, a cyber attack led to their blue-chip client data being compromised. The reason? The admin account that had access to their global email server did not have two-factor authentication.

Another catastrophic data breach took place at American Superconductor Corp (AMSC). That incident was caused by a former employee who brought the company’s intellectual property to his new employer, Sinovel. To make matters worse, Sinovel and AMSC are competitors. As a result of this former employee’s treachery, AMSC’s losses exceeded $1 billion. Plus, they almost went out of business.

 

RELATED ARTICLE: WEBSITE VULNERABILITIES: DON’T LET THEM SLOW YOUR BUSINESS DOWN

 

Do You Think It Will Never Happen to You?

These stories may seem like it-will-never-happen-in-my-company narratives. But let’s agree on this: your partners, your suppliers, your third-party vendors, and your current employees all represent a significant threat to your cybersecurity. Nonetheless, studies reveal that companies often miss this fact. When they do, they end up suffering sometimes ruinous losses.

A report from Shred-it shows that employee negligence—for example, an accidental loss of a device—caused 47 percent of organizations’ data breaches. Moreover, these data breaches cost organizations an average of $3,6 million globally in 2017. The report also revealed that more than 25 percent of respondents leave their computers unlocked and unattended. These numbers prove that even small mistakes can backfire and cause significant harm.

So, what actions could you implement to minimize the risks of a data breach in your company?

 

  • Communicate the Idea of Cybersecurity to Your Employees Clearly, Consistently, and Often

First of all, before you start, take the time to analyze the weakest points in your company’s cybersecurity. Then, define your company’s cybersecurity policy based on those weak points.

However, don’t forget to add basic information about how to read URL links. You want your employees to be able to recognize malicious emails or phishing attacks. What’s more, if your company has remote workers, ensure that those employees apply good cybersecurity practices outside of the office.

If you already have a good cybersecurity policy in hand, start a cybersecurity onboarding program for your employees based on that. However, remember that new vulnerabilities arise every day. Therefore, your IT department should continuously work to inform employees about possible types of attacks. Communication is key. Moreover, leaving your cybersecurity policy in a drawer is not an option.

 

  • Ensure Passwords Are Strong Enough

Remember Deloitte’s case mentioned earlier? A weak password cost them a lot. Make sure your employees understand the difference between strong and weak passwords. Two-factor authentication (also known as multi-factor authentication) is a way to ensure additional protection. Implementing two-factor authentication in your employees’ daily practices can be a huge step forward.

 

  • Communicate the Importance of Encryption

A study by Zug revealed that 70 percent of professionals work remotely at least once a week. Around 53 percent do so for at least half of the week. However, according to the study, more than half of small business owners admit they don’t have a cybersecurity policy for their remote workers.

If you are in a similar situation, you need to make sure your remote employees’ Internet connections are as secure as those for your in house employees. This can be tricky, as unsecured WiFi at various coffee shops can cause a serious threat to employees working remotely.

One of the solutions for upgrading security to the next level is a third-party VPN (virtual private network) service. A VPN can encrypt traffic and establish a secure and private user’s connection to the Internet. By rerouting all traffic that travels between the device and the web’s servers, a VPN creates a secure tunnel that is virtually impenetrable.

However, choose your VPN wisely. Look for the ones offering a no logs policy. That’s because if your VPN retains user activity logs, third parties could get access to your transferred data.

 

  • Help Employees Understand the Importance of Backups

Your employees don’t necessarily know how important backups are. They also might not understand that sometimes backups don’t work.

In some cases, when a cyber-criminal takes over access to a computer, the victim panics and even thinks about paying a ransom to get their files unlocked. Various companies are the primary target for criminals working on this kind of attack. And this comes as no surprise, as firms are often ready to pay much more than individual users are for getting their important data back.

Therefore, take the time to teach the employees the 3-2-1 backup rule. This rule suggests keeping three copies of all data. They should be stored on two different media, and one backup copy should be stored offsite. If something terrible happens, you can quickly restore data and avoid the possible stress and losses.

 

Strong Cybersecurity Is an Ongoing Concern

Creating a strong cybersecurity culture in your company won’t be a one-day job. On the contrary, it’s a never-ending process with a single primary goal. This goal—changing your employees’ mindset —is not an easy goal to reach. However, work diligently toward helping employees understand that small habits are of enormous importance. What’s more, all of those small habits will pay off in the long run.

The post How Much Do Your Employees Actually Know About Cybersecurity? appeared first on Business Opportunities.


via Business Opportunities Weblog
How Much Do Your Employees Actually Know About Cybersecurity?

Is This Worse Than ’68?


1968 Chicago Police Riots
1968 Chicago Police Riots

U.S.A.-(Ammoland.com)- Saturday, in Pittsburgh, a Sabbath celebration at the Tree of Life synagogue became the site of the largest mass murder of Jews in U.S. history. Eleven worshippers were killed by a racist gunman.

Friday, we learned the identity of the crazed criminal who mailed pipe bombs to a dozen leaders of the Democratic Party, including Barack Obama, Hillary Clinton and Joe Biden.

From restaurants to Capitol corridors, this campaign season we have seen ugly face-offs between leftist radicals and Republican senators.

Are we more divided than we have ever been? Are our politics more poisoned? Are we living in what Charles Dickens called “the worst of times” in America? Is today worse than 1968?

Certainly, the hatred and hostility, the bile and bitterness of our discourse, seem greater now than 50 years ago. But are the times really worse?

1968 began with one of the greatest humiliations in the history of the American Navy. The U.S. spy ship Pueblo was hijacked in international waters and its crew interned by North Korea.

A week later came the Tet Offensive, where every provincial capital in South Vietnam was attacked. A thousand U.S. troops died in February, 10,000 more through 1968.

Saigon Execution Eddie Adams 1968
Saigon Execution, Eddie Adams 1968

On March 14, anti-war Senator Gene McCarthy captured 42 percent of the vote in New Hampshire against President Johnson.

With LBJ wounded, Robert Kennedy leapt into the race, accusing the president who had enacted civil rights of “dividing the country” and removing himself from “the enduring and generous impulses that are the soul of this nation.” Lyndon Johnson, said Kennedy, is “calling upon the darker impulses of the American spirit.”

Today, RFK is remembered as a “uniter.”

With Gov. George Wallace tearing at Johnson from the right and Kennedy and McCarthy attacking from the left — and Nixon having cleared the Republican field with a landslide in New Hampshire — LBJ announced on March 31 he would not run again.

Four days later, Martin Luther King, leading a strike of garbage workers, was assassinated in Memphis. One hundred U.S. cities exploded in looting, arson and riots. The National Guard was called up everywhere and federal troops rushed to protect Washington, D.C., long corridors of which were gutted, not to be rebuilt for a generation.

Before April’s end, Columbia University had exploded in the worst student uprising of the decade. It was put down only after the NYPD was unleashed on the campus.

Nixon called the Columbia takeover by black and white radicals “the first major skirmish in a revolutionary struggle to seize the universities of this country and transform them into sanctuaries for radicals and vehicles for revolutionary political and social goals.” Which many have since become.

In June, Kennedy, after defeating McCarthy in the crucial primary of California, was mortally wounded in the kitchen of the hotel where he had declared victory. He was buried in Arlington beside JFK.

Nixon, who had swept every primary, was nominated on the first ballot in Miami Beach, and the Democratic Convention was set for late August.

Between the conventions, Soviet Premier Leonid Brezhnev sent his Warsaw Pact armies and hundreds of tanks into Czechoslovakia to crush the peaceful uprising known as “Prague Spring.”

With this bloodiest of military crackdowns since the Hungarian Revolution of 1956, Moscow sent a message to the West: There will be no going back in Europe. Once a Communist state, always a Communist state!

At the Democratic convention in Chicago, the thousands of radicals who had come to raise hell congregated nightly in Grant Park, across from the Hilton where the candidates and this writer were staying.

Baited day and night, the Chicago cops defending the hotel, by late in the week, had had enough. Early one evening, platoons of fresh police arrived and charged into the park clubbing and arresting scores of radicals as the TV cameras rolled. It would be called a “police riot.”

When Sen. Abe Ribicoff took the podium that night, he directed his glare at Mayor Richard J. Daley, accusing him of using “Gestapo tactics in the streets of Chicago.” Daley’s reply from the floor was unprintable.

Through September, Democratic candidate Hubert Humphrey could not speak at a rally without being cursed and shouted down.

Describing the radicals disrupting his every event, Humphrey said, these people “aren’t just hecklers,” but “highly disciplined, well-organized agitators. … Some are anarchists and some of these groups are dedicated to destroying the Democratic Party and destroying the country.”

After his slim victory, Nixon declared that his government would take as its theme the words on a girl’s placard that he had seen in the Ohio town of Deshler: “Bring us together.”

Nixon tried in his first months, but it was not to be.

According to Bryan Burrough, author of “Days of Rage, America’s Radical Underground, the FBI, and the Forgotten Age of Revolutionary Violence,” “During an eighteen month period in 1971 and 1972, the FBI reported more than 2,500 bombings on U.S. soil, nearly 5 a day.”

No, 2018 is not 1968, at least not yet.


About Patrick J. BuchananPat Buchanan

Patrick J. Buchanan is the author of the new book “The Greatest Comeback: How Richard Nixon Rose From Defeat to Create the New Majority.


via AmmoLand.com
Is This Worse Than ’68?

Prop Building Gets Easy With the Adafruit Prop-Maker FeatherWing


When it comes to building interactive props, you have always had two main areas where there is going to be tons of work and problem solving. There’s the physical structure and look, then there’s the interactive electronics. For many, learning the techniques for shaping foam or 3d printing came naturally, but the electronics were still a hurdle. There’s a lot to learn!

Adafruit has been listening and has just released the Prop-Maker FeatherWing. This is an add-on board to their feather microcontrollers that has some easy to use features specifically for adding lights and sound to your prop.  Check out this quick video of a light saber built using the system.

As I’ve mentioned each time I talk about the feather ecosystem, I love that this uses Circuit Python, which means you don’t need a compiler installed. You just plug this into any computer (or phone!) and open it like a storage device, then edit the text file that is there. That’s all. As for sound, you just drop .wav files onto it.

 

from the product description:

We looked at hundreds of prop builds, and thought about what would make for a great low-cost (but well-designed) add-on for our Feather boards. Here’s what we came up with:

  • Snap-in NeoPixel port – With a 3-pin JST connector, you can plug in one of our JST-wired NeoPixel strips directly, or use a 3-pin JST connector to wire up your favorite shape of addressable NeoPixel LEDs. This port provides high current drive from either the Feather Lipoly or USB port, whichever is higher. A level shifter gives you a clean voltage signal to reduce glitchiness no matter what chip you’re using
  • 3W RGB LED drivers – 3 high current MOSFETs will let you connect a 3W RGB LED for powerful eye-blasting glory. For most Feathers, the 3 pins are PWM capable so you can generate any color you like. Available as pin breakouts plus strain-relief holes
  • Triple-Axis Accelerometer with Tap Detection – The LIS3DH is our favorite accelerometer, you can use this for detection motion, tilt or taps. Here’s an example of a light saber that makes sounds when swung or hit. We have code for this chip in both Arduino and CircuitPython.
  • Class D Audio Amplifier – Drive a 8Ω 1Watt speaker or 4Ω 3W speaker for sound effects. Plug and play with our cute and slim oval speaker, or connect a picoblade cable for your favorite speaker. For use only with Feathers that have analog audio out such as the Feather M0 Express and M4 series.
  • Low power mode! The power system for the RGB LED, NeoPixels and speaker amplifier can be controlled by a pin to cut power to them, so you have lower power usage when the prop is in sleep or off mode (but can wake up fast by listening to the button press or accelerometer data). When the power pin is set low, the current draw for just the wing is under 1mA and no there’s current draw from any attached NeoPixels – normally they’re about 1mA even when not lit.
  • Breakouts plus strain-relief hole for the enable pin and ground (for a mechanical switch that will power down the whole board)
  • Breakouts plus strain-relief holes for an external switch pin and ground (for a mechanical mode button)


via MAKE Magazine
Prop Building Gets Easy With the Adafruit Prop-Maker FeatherWing

Comic for October 28, 2018


Transcript

Dilbert: Can I go with you to the customer meeting? I’m worried you might promise something we can’t deliver.
The Boss: Don’t be ridiculous! I’ve been having customer meetings without engineers for years.
Dilbert: I know and they all turn into disasters.
The Boss: You worry too much! Everything will be fine!
Man: Can you replace our data centers with blockchain?
The Boss: Give us two days.


via Dilbert Daily Strip
Comic for October 28, 2018

FDA Approves First New Flu Drug In 20 Years


An anonymous reader quotes a report from Popular Science:

The Food & Drug Administration just announced that they had approved the aptly-named Xofluza, the first new antiviral drug in two decades, to help alleviate the symptoms of a flu infection. The reason Xofluza got a priority review from the FDA is that it works through a different mechanism than Tamiflu. Both are antivirals, meaning they prevent the replication of the virus, but they work at different stages in that process. First, a quick primer on how viruses infect you: a virus is basically a packet of genetic material that injects itself into a cell and hijacks the cell’s normal replication machinery, forcing it to produce millions of copies of the virus. A protein called viral neuraminidase allows those copies to exit the cell and go infect new parts of your body. Most of our effective antivirals are neuraminidase inhibitors — the virus can still replicate, but it’s prevented from escaping.

Xofluza works by preventing the viral replication in the first place. It blocks viral polymerase, an enzyme that helps make copies of the invading genetic material. This doesn’t necessarily make it better or more effective — the FDA notes that early trials suggest it’s about as effective as Tamiflu — but as the FDA Commissioner Scott Gottlieb pointed out in a press release, “Having more treatment options that work in different ways to attack the virus is important because flu viruses can become resistant to antiviral drugs.”


via Slashdot
FDA Approves First New Flu Drug In 20 Years

Episode 273 Scott Adams: Border Expert Brandon Darby About the Caravan


Posted October 26, 2018
in: #, #, #, #, #

Topics: 

  • Various cartels control various sections of the Mexican border areas
  • Passage, legal and illegal activities are all under cartel control
  • Illegal immigration is a significant portion of cartel profits
  • Journalists must pay the cartels for permission to cover the caravan
  • The cartels dictate what topics and things can be reported
  • The caravans are an attempt to protect the participants from the cartels
  • Our catch and release policies are encouraging illegal immigration
  • What percentage of the caravan are legit asylum seekers?

Brandon Darby

Breitbart Director

Border and Cartel Projects

@BrandonDarby

Podcast: Play in new window | Download


via Dilbert Blog
Episode 273 Scott Adams: Border Expert Brandon Darby About the Caravan

Katie Pavlich Lays Smackdown on David Hogg


David Hogg needs to come to understand that just because some people he went to school with were shot, he’s not really an expert on anything relating to guns, gun control, the Second Amendment, or anything else. Tragic as Parkland was, it didn’t mystically convey wisdom to either him or any of his cohorts.

At least former fellow-traveler Cameron Kasky has figured that out.

Hogg, however, hasn’t.

In a video, he commented that he believes gun control should have been addressed centuries ago.

Townhall‘s Katie Pavlich gave the perfect response to that.

Honestly, what more needs to be said?

Pavlich mimics a Paveway smart bomb by lowering the boom on Hogg’s pretentions of moral superiority on the issue of guns. More importantly, her point is 100 percent correct.

The Founding Fathers didn’t want gun control. They wanted unfettered access to military-grade arms, if not better. Remember that the British were shooting smoothbore muskets during the Revolution while many colonists were armed with rifled weapons. They were all muzzleloaders, but the colonists’ weapons had superior range. Civilian weapons were generally better than the military’s arms.

Our founders liked that. They knew that a government with the ability to restrict arms would soon use that ability to restrict other civil rights.

Pavlich clearly understands this.

Hogg, however, believes he is somehow more enlightened than the brilliant men who created our system of government. Based on what I’ve seen of the twit, that’s not hard to believe. I’ve seen a lot of arrogance come from the other side before, but it pales in comparison to Hogg’s.

In case the young Mr. Hogg sees this, let me lay a few things out very clearly.

The Founding Fathers wanted an armed populace. They didn’t want guns to be the exclusive domain of the government. More importantly, though, they wanted military-grade or better weapons in our hands because the purpose of the Second Amendment is, in part, to keep the government in check. While I’m sure they’d have found shootings like Parkland tragic, they’d have also pointed out that all of those shootings were carried out by damaged individuals and there was no reason to undo the Constitution because of what are really just isolated, though horrific, events.

When the Revolution was over and decided something better than the Articles of Confederation were needed, the Constitution was crafted and then, almost immediately, the Bill of Rights was created and ratified. It encoded precisely what our Founding Fathers intended when it came to guns. Their own writings make their intentions clear. They wanted us to be heavily armed and ready to shoot on a moment’s notice.

So yeah, they did take care of this stuff centuries ago. The fact that you don’t care for their solution doesn’t change that reality. Be a tinpot twit if you want–because you’ll never amass the power to become a tinpot dictator despite any lofty pretensions you may have–but the truth is what it is. No amount of rhetoric or hysterics will ever change that.

Thank God.

Author’s Bio:

Tom Knighton


Tom Knighton is a Navy veteran, a former newspaperman, a novelist, and a blogger and lifetime shooter. He lives with his family in Southwest Georgia.

https://ift.tt/2w2n5Gd


via Bearing Arms
Katie Pavlich Lays Smackdown on David Hogg