The U.S. Crackdown on Chinese American Researchers Endangers

Ethnically Chinese scientists are fighting a long history of U.S. persecution

Shortly after dawn on May 21, 2015, FBI agents came to physicist Xiaoxing Xi’s front door with guns drawn and a battering ram for backup. They arrested him on charges of wire fraud and released him only after he put his house up as collateral against a $100,000 bond.

Xi, who lived in a quiet suburb of Philadelphia, attracted attention as a world-renowned expert in thin films, substances used for building superconductors. The 57-year-old had just been named interim chair of Temple University’s physics department. He was the principal or co-principal investigator on nine federally funded research projects on thin films, had grants totaling over $1 million per year, and led a team of 14 researchers.

The professor was charged with four counts of wire fraud by the U.S. Department of Justice for allegedly sharing confidential scientific information with Chinese entities — specifically, illegally sharing the proprietary blueprints of a pocket heater device, citing four emails he sent to Chinese scientists in 2010 as evidence. According to the federal indictment, Xi’s emails had suggested collaborating on research in exchange for “lucrative and prestigious appointments.” If convicted, he faced a prison sentence of 80 years and $1 million in fines.

But the case unraveled before going to trial. Xi’s lawyers proved through the testimony of experts, including one of the pocket heater’s actual inventors, that Xi had actually shared the schematics of different devices that were not considered confidential. Further, everything Xi had shared was already publicly available in scientific journals.

Still, Xi paid dearly for this. His family spent over $200,000 in legal fees. Within weeks, he was put on paid leave, lost his chairmanship, and, later, most of his research funding.

“Very often, when people see other people being charged, they’ll think that this guy must have done something wrong,” Xi tells OneZero.

#future #usa #china #racism #science #data science

What is GEEK

Buddha Community

The U.S. Crackdown on Chinese American Researchers Endangers
Mike  Kozey

Mike Kozey

1656151740

Test_cov_console: Flutter Console Coverage Test

Flutter Console Coverage Test

This small dart tools is used to generate Flutter Coverage Test report to console

How to install

Add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dev_dependencies:
  test_cov_console: ^0.2.2

How to run

run the following command to make sure all flutter library is up-to-date

flutter pub get
Running "flutter pub get" in coverage...                            0.5s

run the following command to generate lcov.info on coverage directory

flutter test --coverage
00:02 +1: All tests passed!

run the tool to generate report from lcov.info

flutter pub run test_cov_console
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
 print_cov_constants.dart                    |    0.00 |    0.00 |    0.00 |    no unit testing|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

Optional parameter

If not given a FILE, "coverage/lcov.info" will be used.
-f, --file=<FILE>                      The target lcov.info file to be reported
-e, --exclude=<STRING1,STRING2,...>    A list of contains string for files without unit testing
                                       to be excluded from report
-l, --line                             It will print Lines & Uncovered Lines only
                                       Branch & Functions coverage percentage will not be printed
-i, --ignore                           It will not print any file without unit testing
-m, --multi                            Report from multiple lcov.info files
-c, --csv                              Output to CSV file
-o, --output=<CSV-FILE>                Full path of output CSV file
                                       If not given, "coverage/test_cov_console.csv" will be used
-t, --total                            Print only the total coverage
                                       Note: it will ignore all other option (if any), except -m
-p, --pass=<MINIMUM>                   Print only the whether total coverage is passed MINIMUM value or not
                                       If the value >= MINIMUM, it will print PASSED, otherwise FAILED
                                       Note: it will ignore all other option (if any), except -m
-h, --help                             Show this help

example run the tool with parameters

flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

report for multiple lcov.info files (-m, --multi)

It support to run for multiple lcov.info files with the followings directory structures:
1. No root module
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
2. With root module
<root>/coverage/lcov.info
<root>/lib/src
<root>/<module_a>
<root>/<module_a>/coverage/lcov.info
<root>/<module_a>/lib/src
<root>/<module_b>
<root>/<module_b>/coverage/lcov.info
<root>/<module_b>/lib/src
...
You must run test_cov_console on <root> dir, and the report would be grouped by module, here is
the sample output for directory structure 'with root module':
flutter pub run test_cov_console --file=coverage/lcov.info --exclude=_constants,_mock --multi
---------------------------------------------|---------|---------|---------|-------------------|
File                                         |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_a -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|
---------------------------------------------|---------|---------|---------|-------------------|
File - module_b -                            |% Branch | % Funcs | % Lines | Uncovered Line #s |
---------------------------------------------|---------|---------|---------|-------------------|
lib/src/                                     |         |         |         |                   |
 print_cov.dart                              |  100.00 |  100.00 |   88.37 |...,149,205,206,207|
lib/                                         |         |         |         |                   |
 test_cov_console.dart                       |    0.00 |    0.00 |    0.00 |    no unit testing|
---------------------------------------------|---------|---------|---------|-------------------|
 All files with unit testing                 |  100.00 |  100.00 |   88.37 |                   |
---------------------------------------------|---------|---------|---------|-------------------|

Output to CSV file (-c, --csv, -o, --output)

flutter pub run test_cov_console -c --output=coverage/test_coverage.csv

#### sample CSV output file:
File,% Branch,% Funcs,% Lines,Uncovered Line #s
lib/,,,,
test_cov_console.dart,0.00,0.00,0.00,no unit testing
lib/src/,,,,
parser.dart,100.00,100.00,97.22,"97"
parser_constants.dart,100.00,100.00,100.00,""
print_cov.dart,100.00,100.00,82.91,"29,49,51,52,171,174,177,180,183,184,185,186,187,188,279,324,325,387,388,389,390,391,392,393,394,395,398"
print_cov_constants.dart,0.00,0.00,0.00,no unit testing
All files with unit testing,100.00,100.00,86.07,""

Installing

Use this package as an executable

Install it

You can install the package from the command line:

dart pub global activate test_cov_console

Use it

The package has the following executables:

$ test_cov_console

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add test_cov_console

With Flutter:

 $ flutter pub add test_cov_console

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  test_cov_console: ^0.2.2

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:test_cov_console/test_cov_console.dart';

example/lib/main.dart

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
        // This makes the visual density adapt to the platform that you run
        // the app on. For desktop platforms, the controls will be smaller and
        // closer together (more dense) than on mobile platforms.
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Author: DigitalKatalis
Source Code: https://github.com/DigitalKatalis/test_cov_console 
License: BSD-3-Clause license

#flutter #dart #test 

The U.S. Crackdown on Chinese American Researchers Endangers

Ethnically Chinese scientists are fighting a long history of U.S. persecution

Shortly after dawn on May 21, 2015, FBI agents came to physicist Xiaoxing Xi’s front door with guns drawn and a battering ram for backup. They arrested him on charges of wire fraud and released him only after he put his house up as collateral against a $100,000 bond.

Xi, who lived in a quiet suburb of Philadelphia, attracted attention as a world-renowned expert in thin films, substances used for building superconductors. The 57-year-old had just been named interim chair of Temple University’s physics department. He was the principal or co-principal investigator on nine federally funded research projects on thin films, had grants totaling over $1 million per year, and led a team of 14 researchers.

The professor was charged with four counts of wire fraud by the U.S. Department of Justice for allegedly sharing confidential scientific information with Chinese entities — specifically, illegally sharing the proprietary blueprints of a pocket heater device, citing four emails he sent to Chinese scientists in 2010 as evidence. According to the federal indictment, Xi’s emails had suggested collaborating on research in exchange for “lucrative and prestigious appointments.” If convicted, he faced a prison sentence of 80 years and $1 million in fines.

But the case unraveled before going to trial. Xi’s lawyers proved through the testimony of experts, including one of the pocket heater’s actual inventors, that Xi had actually shared the schematics of different devices that were not considered confidential. Further, everything Xi had shared was already publicly available in scientific journals.

Still, Xi paid dearly for this. His family spent over $200,000 in legal fees. Within weeks, he was put on paid leave, lost his chairmanship, and, later, most of his research funding.

“Very often, when people see other people being charged, they’ll think that this guy must have done something wrong,” Xi tells OneZero.

#future #usa #china #racism #science #data science

Importance of Market Research Before You Get a Mobile App Developed

With the infusion and escalated use of technology, the mobile app market has grown by leaps and bounds, especially in the last decade. Further estimated researches show that the size of the mobile app market will reach $407.31 billion by the year 2026. Thus, if you have some trending app ideas then this is the best time to invest in mobile app development.

Since the mobile app market is very dynamic, keeping up with the changing trends becomes very important. For doing this, in-depth market research before developing a mobile app is a very vital factor. The importance of mobile app market research can be realized from the fact that it gives the company valuable insights into their competitors. In addition, it gives you a clear idea about your own strengths and weaknesses as well.

The performance of mobile apps in the modern era depends significantly on the behind-the-scenes research work. Many studies have shown that mobile apps developed without adequate research die a premature death at the app store. Statically, around 72% of the upcoming mobile apps fail to make their mark on the market because of lousy research work.

This article will discuss why market research for your mobile application is needed and the difference it can bring into your overall business ROI.

How Market Research can help with successful Mobile App Development?
“In the long run, curiosity-driven research just works better. Real breakthroughs come from people focusing on what they’re excited about.” – Geoffrey Hinton, Psychologist and Computer Scientist

The business of mobile app development is very dynamic and it purely depends on the changing needs and wants of the customers. Doing market research is very crucial to build your stunning mobile app. Therefore, the businesses need to remain on the top of their game as far as knowing the latest market trends are concerned.

Due to its ever-changing nature, developing a mobile app is a very tough nut to crack. And without adequate market research, the whole process can become directionless in no time. The businesses wouldn’t know who their targeted audience are, which market is best for their mobile application, and most importantly the set of features to be bifurcated as must haves’ and which features to be added later as additional ones’.

In addition, full-throttle market research also helps in keeping the app development project within budget. It also assists the marketing team in coming up with unique ideas and enhancing the mobile application’s popularity.

A detailed analysis of the market for your business app will give you valuable insights and stop you from making terrible mistakes. Moreover, as you will understand the customers’ pain points, you wouldn’t cram the mobile app with unnecessary features.

With an increase in the number of options available, the patience levels of the users are declining at a rapid rate. They will instantly discard the mobile app if it keeps them waiting to do important tasks.

The in-depth market research also helps you become the pioneer in your industry using mobile apps as the platform to help your business reach greater heights.

Advantages of market research
The benefits that the businesses gain from market research for getting a cutting-edge mobile app developed are immense. We have listed some of the top advantages below:

Faster data collection
Market research for mobile apps allows faster data collection. This is one of the prominent answers to the question ‘why is app market research recommended as a must-do strategy?’ As the new-age customers use their smartphones more than any other device, it is easier to get faster responses through an app.

Better Insights
While doing in-depth research, the insights are not limited just to text-based questions. You can gauge the customer’s behavior from various touchpoints like their social media platform, photos, audio, video, etc. The market research gives you a more diverse data set for further analysis.

Enhances the brand value
The needs and wants of the consumers are constantly changing. Thus, it becomes difficult for businesses to find their core audience to target or which sections of a market will be more interested in their mobile application. Market research helps in fostering the customer-brand relationship and eventually increasing the brand value.

Better results
Through stoic mobile app market research, you can increase the usability of your mobile app. Various market research shows that 80% of smartphone users check their phone within 15 minutes of waking up. Thus, the more you engage with your customers on the mobile app, the more chances you will grow your business.

The process to conduct mobile app market research
It is inevitable for the business houses to have a clear idea about conducting their market research. Moreover, there is no explicit template that defines ways to conduct market research. In the quest to stand unique from its peers, each business conducts the research in its own way.

Broadly, the process of market research is categorized into two major categories:

Primary Research:
In Primary Research, the company must define the actual need of the app in the market. After this, they must design an optimal business model to keep the app relevant in the market. Once the business model is finalized, optimizing the marketing strategy for the app becomes the next step. Marketing strategy holds much more significance in the modern market as customers are more inclined towards personalized services.

Secondary Research:
Secondary Research mainly focuses on the main strength of the mobile app. When you define the core strength of the mobile app, bifurcating your target audience becomes easy. In addition, the company can optimize its social media strategy and cater to each of their targeted customers individually.

Continue to read : Importance-market-research-before-mobile-app-developed

#importance-market-research #mobile-app #market-research #appmarket-research #app-market-research

Global Recruitment Sourcing Services and Solutions | DK Business Patron

DK Business Patron, one of the most renowned firms in the outsourcing industry has launched its new Global financial research services. This addition to their existing ongoing business ventures will not only open new dimensions of the global market but will also help DK Business Patron to explore different aspects Financial research.

The new Global financial research services department would comply with all the associative services that are linked to finance and research. From asset management support to equity research, DK Business Patron has a team of well-trained managers that are quite capable of providing the desired services to the clients.

The new service shall have a combined package of Investment research, Sell-side research, corporate finance support, asset management support, investment banking support, equity research, financial research reports, and financial analysis. This package is designed keeping in mind all the necessary outsourced investment research services that a client shall require in the long run.

Unlike other outsourcing companies in India, DK Business Patron does not work just to provide services in return for the revenue generated. Rather, it believes in developing a strong client relationship which is possible only by satisfying the clients with its services. Which makes the launch of the new global financial research services another move towards increasing the already built international clientele.

DK Business Patron is an essential component in the outsourcing industry and has been providing outsourcing solutions to numerous clients for more than 8 years. Being a trusted company, DK Business Patron has earned the loyalty of a huge number of small as well as medium scale industries.

Being associated with outsourcing business for almost a decade has given DK Business Patron an upper hand in recognizing and establishing links with the target market. Launching a whole new global financial research services unit will not only help in increasing global connectivity and reach but would also aid in penetrating the outsourced financial research services segment.

Outsourcing financial research services have been in trend in the contemporary era. It not only provides strategic benefits but also helps in cost-saving and risk-sharing. Investments are a crucial part of the business and to find out the most beneficial investment seems to be the trickiest of all.

DK Business Patron claims to deliver services that would not only show tangible growth but would also focus on intangible aspects that lead to prosperity and development. Personnel trained especially to satisfy the customers in each and every aspect that is demanded has been set up in each department of the financial research services unit.

For a long time, India has become the hub of outsourcing services demanded by offshore clients. DK Business Patron has been one of the leading service providers in India for more than 8 years. Being situated in Delhi has given the firm required modernity and techno-savvy environment that any business enigma would require to cope-up with the testing competitive times.

After being associated with BPO Solution, KPO solution, and other IT-related outsourcing services, DK Business Patron has now decided to step foot into the financial sector with its new global financial research services. This move is surely going to be revolutionary and would turn around tables in the global market.

Building long-lasting relationships with the clients and smooth functioning have been strong points for DK Business Patron which helped it to open new dimensions of outsourced investment research services.

Industries usually outsource their business when the need to focus on core business activity intensifies. This makes it even more risky to handover secondary business activities in the hands of a third party. DK Business Patron has earned the trust of all the clients associated with it to date. It has not only stood up to the mark by providing satisfactory services but even after being a service provider, has been working dedicatedly just like an in-house unit.

Keeping in mind the ultimate goal of satisfying its clients and working together with them as one unit, the launch of the new global financial research services by DK Business Patron is going to be utterly profitable for all the new investors looking for a helping hand to thrive in the global market.

#outsourcing solutions #financial research #financial research services #financial research solutions #outsourced financial research services #financial research service outsourcing

Rust  Language

Rust Language

1640144506

Strings - The Rust Programming Language

Rust For Beginners Tutorial - Strings

In this video we're taking a look at the String, &String and &str types in Rust!

Exercise solutions: https://github.com/PascalPrecht/rustlings/commits/solutions 

---
0:00 Intro
0:09 Exercise 1
4:47 Exercise 2
10:38 Outro


Strings

There are two types of strings in Rust: String and &str.

A String is stored as a vector of bytes (Vec<u8>), but guaranteed to always be a valid UTF-8 sequence. String is heap allocated, growable and not null terminated.

&str is a slice (&[u8]) that always points to a valid UTF-8 sequence, and can be used to view into a String, just like &[T] is a view into Vec<T>.

fn main() {
    // (all the type annotations are superfluous)
    // A reference to a string allocated in read only memory
    let pangram: &'static str = "the quick brown fox jumps over the lazy dog";
    println!("Pangram: {}", pangram);

    // Iterate over words in reverse, no new string is allocated
    println!("Words in reverse");
    for word in pangram.split_whitespace().rev() {
        println!("> {}", word);
    }

    // Copy chars into a vector, sort and remove duplicates
    let mut chars: Vec<char> = pangram.chars().collect();
    chars.sort();
    chars.dedup();

    // Create an empty and growable `String`
    let mut string = String::new();
    for c in chars {
        // Insert a char at the end of string
        string.push(c);
        // Insert a string at the end of string
        string.push_str(", ");
    }

    // The trimmed string is a slice to the original string, hence no new
    // allocation is performed
    let chars_to_trim: &[char] = &[' ', ','];
    let trimmed_str: &str = string.trim_matches(chars_to_trim);
    println!("Used characters: {}", trimmed_str);

    // Heap allocate a string
    let alice = String::from("I like dogs");
    // Allocate new memory and store the modified string there
    let bob: String = alice.replace("dog", "cat");

    println!("Alice says: {}", alice);
    println!("Bob says: {}", bob);
}

More str/String methods can be found under the std::str and std::string modules

Literals and escapes

There are multiple ways to write string literals with special characters in them. All result in a similar &str so it's best to use the form that is the most convenient to write. Similarly there are multiple ways to write byte string literals, which all result in &[u8; N].

Generally special characters are escaped with a backslash character: \. This way you can add any character to your string, even unprintable ones and ones that you don't know how to type. If you want a literal backslash, escape it with another one: \\

String or character literal delimiters occuring within a literal must be escaped: "\"", '\''.

fn main() {
    // You can use escapes to write bytes by their hexadecimal values...
    let byte_escape = "I'm writing \x52\x75\x73\x74!";
    println!("What are you doing\x3F (\\x3F means ?) {}", byte_escape);

    // ...or Unicode code points.
    let unicode_codepoint = "\u{211D}";
    let character_name = "\"DOUBLE-STRUCK CAPITAL R\"";

    println!("Unicode character {} (U+211D) is called {}",
                unicode_codepoint, character_name );


    let long_string = "String literals
                        can span multiple lines.
                        The linebreak and indentation here ->\
                        <- can be escaped too!";
    println!("{}", long_string);
}

Sometimes there are just too many characters that need to be escaped or it's just much more convenient to write a string out as-is. This is where raw string literals come into play.

fn main() {
    let raw_str = r"Escapes don't work here: \x3F \u{211D}";
    println!("{}", raw_str);

    // If you need quotes in a raw string, add a pair of #s
    let quotes = r#"And then I said: "There is no escape!""#;
    println!("{}", quotes);

    // If you need "# in your string, just use more #s in the delimiter.
    // There is no limit for the number of #s you can use.
    let longer_delimiter = r###"A string with "# in it. And even "##!"###;
    println!("{}", longer_delimiter);
}

Want a string that's not UTF-8? (Remember, str and String must be valid UTF-8). Or maybe you want an array of bytes that's mostly text? Byte strings to the rescue!

use std::str;

fn main() {
    // Note that this is not actually a `&str`
    let bytestring: &[u8; 21] = b"this is a byte string";

    // Byte arrays don't have the `Display` trait, so printing them is a bit limited
    println!("A byte string: {:?}", bytestring);

    // Byte strings can have byte escapes...
    let escaped = b"\x52\x75\x73\x74 as bytes";
    // ...but no unicode escapes
    // let escaped = b"\u{211D} is not allowed";
    println!("Some escaped bytes: {:?}", escaped);


    // Raw byte strings work just like raw strings
    let raw_bytestring = br"\u{211D} is not escaped here";
    println!("{:?}", raw_bytestring);

    // Converting a byte array to `str` can fail
    if let Ok(my_str) = str::from_utf8(raw_bytestring) {
        println!("And the same as text: '{}'", my_str);
    }

    let _quotes = br#"You can also use "fancier" formatting, \
                    like with normal raw strings"#;

    // Byte strings don't have to be UTF-8
    let shift_jis = b"\x82\xe6\x82\xa8\x82\xb1\x82\xbb"; // "ようこそ" in SHIFT-JIS

    // But then they can't always be converted to `str`
    match str::from_utf8(shift_jis) {
        Ok(my_str) => println!("Conversion successful: '{}'", my_str),
        Err(e) => println!("Conversion failed: {:?}", e),
    };
}

For conversions between character encodings check out the encoding crate.

A more detailed listing of the ways to write string literals and escape characters is given in the 'Tokens' chapter of the Rust Reference.

#rust #programming #developer