text
stringlengths
184
4.48M
using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace R3Modeller.Core.Utils { public static class StringUtils { /// <summary> /// Replaces multiple spaces with a single space. /// where dots are spaces, '.....' or '.........' becomes '.' /// </summary> /// <param name="value"></param> /// <returns></returns> public static string CollapseSpaces(this string value) { return Regex.Replace(value, @"\s+", " "); } public static string JSubstring(this string @this, int startIndex, int endIndex) { return @this.Substring(startIndex, endIndex - startIndex); } public static bool IsEmpty(this string @this) { return string.IsNullOrEmpty(@this); } public static string Join(string a, string b, char join) { return new StringBuilder(32).Append(a).Append(join).Append(b).ToString(); } public static string Join(string a, string b, string c, char join) { return new StringBuilder(32).Append(a).Append(join).Append(b).Append(join).Append(c).ToString(); } public static string JoinString(this IEnumerable<string> elements, string delimiter, string finalDelimiter, string emptyEnumerator = "") { using (IEnumerator<string> enumerator = elements.GetEnumerator()) { return JoinString(enumerator, delimiter, finalDelimiter, emptyEnumerator); } } public static string JoinString(this IEnumerator<string> elements, string delimiter, string finalDelimiter, string emptyEnumerator = "") { if (!elements.MoveNext()) { return emptyEnumerator; } StringBuilder sb = new StringBuilder(); sb.Append(elements.Current); if (elements.MoveNext()) { string last = elements.Current; while (elements.MoveNext()) { sb.Append(delimiter).Append(last); last = elements.Current; } sb.Append(finalDelimiter).Append(last); } return sb.ToString(); } public static string Repeat(char ch, int count) { char[] chars = new char[count]; for (int i = 0; i < count; i++) chars[i] = ch; return new string(chars); } public static string Repeat(string str, int count) { StringBuilder sb = new StringBuilder(str.Length * count); for (int i = 0; i < count; i++) sb.Append(str); return sb.ToString(); } public static string FitLength(this string str, int length, char fit = ' ') { int strlen = str.Length; if (strlen > length) { return str.Substring(0, length); } if (strlen < length) { return str + Repeat(fit, length - strlen); } else { return str; } } public static bool EqualsIgnoreCase(this string @this, string value) { return @this.Equals(value, StringComparison.OrdinalIgnoreCase); } public static string RemoveChar(this string @this, char ch) { StringBuilder sb = new StringBuilder(@this.Length); foreach (char character in @this) { if (character != ch) { sb.Append(character); } } return sb.ToString(); } /// <summary> /// Split the input string by the given splitter, and provide the left and right values as out parameters (splitter is not included /// </summary> /// <param name="this">Value to split</param> /// <param name="splitter">Split value</param> /// <param name="a">Everything before the splitter</param> /// <param name="b">Everything after the splitter</param> /// <returns>True if the string contained the splitter, otherwise false</returns> public static bool Split(this string @this, string splitter, out string a, out string b) { int index; if (string.IsNullOrEmpty(@this) || (index = @this.IndexOf(splitter)) < 0) { a = b = null; return false; } a = @this.Substring(0, index); b = @this.Substring(index + splitter.Length); return true; } // remake of Format for explicitly 1 parameter // okay{0}then public static string InjectFormat(string format, string argument) { int i; if (format == null || (i = format.IndexOf('{', 0)) == -1) throw new Exception("Missing '{0}' somewhere in the source string"); char[] chars = new char[format.Length + argument.Length - 3]; format.CopyTo(0, chars, 0, i); argument.CopyTo(0, chars, i, argument.Length); format.CopyTo(i + 3, chars, i + argument.Length, chars.Length - (i + argument.Length)); return new string(chars); } public static unsafe string InjectOrUseChars(string src, int srcIndex, char* arg, int argc) { if (src == null) { return new string(arg, 0, argc); } else { char[] chars = new char[src.Length + argc]; src.CopyTo(0, chars, 0, srcIndex); for (int i = 0; i < argc; i++) chars[srcIndex + i] = arg[i]; int j = srcIndex + argc; src.CopyTo(srcIndex, chars, j, chars.Length - j); return new string(chars); } } // Took this from a minecraft plugin I made, because java's built in format function was annoying to // use so I made my own that outperformed it by about 2x... not to toot my own horn or anything ;) public static String Format(String format, params Object[] args) { // return splice(format, Appender.forArray(args)); // just as fast as below once JIT'd // Remaking this by accepting format.toCharArray() would not make it any faster, // and would actually make it slightly slower due to the extra array copy/allocation int i, j, k, num; if (format == null || (i = format.IndexOf('{', j = 0)) == -1) return format; // buffer of 2x format is typically the best result FastStringBuf sb = new FastStringBuf(format.Length * 2); do { if (i == 0 || format[i - 1] != '\\') { // check escape char sb.append(format, j, i); // append text between j and before '{' char if ((k = format.IndexOf('}', i)) != -1) { // get closing char index j = k + 1; // set last char to after closing char if ((num = ParseIntSigned(format, i + 1, k, 10)) >= 0 && num < args.Length) { sb.append(args[num]); // append content } else { // OLD: sb.append('{').append(format, i + 1, k).append('}'); sb.append(format, i, j); // append values between { and } } i = k; // set next search index to the '}' char } else { j = i; // set last char to the last '{' char } } else { // remove escape char sb.append(format, j, i - 1); // append text between last index and before the escape char j = i; // set last index to the '{' char, which was originally escaped } } while ((i = format.IndexOf('{', i + 1)) != -1); sb.append(format, j, format.Length); // append remainder of string return sb.ToString(); } // Try parse non-negative int, or return -1 on failure public static int ParseIntSigned(string chars, int index, int endIndex, int radix) { if (index < 0 || endIndex <= index) { return -1; } char first = chars[index]; if (first < '0') { // Possible leading "+" if (first != '+' || (endIndex - index) == 1) return -1; // Cannot have lone "+" index++; } int result = 0; const int limit = -int.MaxValue; // Integer.MIN_VALUE + 1 int radixMinLimit = limit / radix; while (index < endIndex) { // Accumulating negatively avoids surprises near MAX_VALUE int digit = Digit(chars[index++], radix); if (digit < 0 || result < radixMinLimit) return -1; if ((result *= radix) < limit + digit) return -1; result -= digit; } return -result; } // https://stackoverflow.com/a/40041591/11034928 public static int Digit(char value, int radix) { if (radix <= 0 || radix > 36) return -1; // Or throw exception if (radix <= 10) return value >= '0' && value < '0' + radix ? value - '0' : -1; else if (value >= '0' && value <= '9') return value - '0'; else if (value >= 'a' && value < 'a' + radix - 10) return value - 'a' + 10; else if (value >= 'A' && value < 'A' + radix - 10) return value - 'A' + 10; return -1; } public static string SplitLast(string str, char ch) { int index = str.LastIndexOf(ch); return index == -1 ? str : str.Substring(index + 1); } public static string GetTypeName(string className) { if (string.IsNullOrEmpty(className)) { return ""; } int lastIndex = className.LastIndexOf('/'); return lastIndex == -1 ? className : className.Substring(lastIndex + 1); } public static string GetNonDescriptiveTypeName(string className) { if (string.IsNullOrEmpty(className)) { return ""; } // Remove L; (Lpackage/Class;) if (className.Length > 0 && className[0] == 'L' && className[className.Length - 1] == ';') { className = className.Substring(1, className.Length - 2); } int lastIndex = className.LastIndexOf('/'); if (lastIndex != -1) { className = className.Substring(lastIndex + 1); } return className; } public static int CountCharsAtStart(string str, char character, int startIndex = 0) { int j = startIndex, len = str.Length; while (j < len && str[j] == character) ++j; return j - startIndex; } } }
--- title: "\"2024 Approved The New Wave of YouTube Channel Titles Perfect for Vloggers (Limited to 156 Characters)\"" date: 2024-05-31T12:42:05.369Z updated: 2024-06-01T12:42:05.369Z tags: - ai video - ai youtube categories: - ai - youtube description: "\"This Article Describes 2024 Approved: The New Wave of YouTube Channel Titles: Perfect for Vloggers (Limited to 156 Characters)\"" excerpt: "\"This Article Describes 2024 Approved: The New Wave of YouTube Channel Titles: Perfect for Vloggers (Limited to 156 Characters)\"" keywords: "YouTubE vLog TitleS,VideoChannelOptiMes,VlogGrowthStrategies,TitleCraftForVloggers,EngagEBoostTitles,ChannelsImpactFix,StratGainsyTitles" thumbnail: https://www.lifewire.com/thmb/qDgmIGv-MKnWSKLikR57Fui58lY=/400x300/filters:no_upscale():max_bytes(150000):strip_icc()/GettyImages-693170166-5a99f020c67335003717a070.jpg --- ## The New Wave of YouTube Channel Titles: Perfect for Vloggers (Limited to 156 Characters) # 50+ Youtube Channel Names for Vloggers \[100% New\] ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) ##### Richard Bennett Mar 27, 2024• Proven solutions [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) Want to make a lasting impression on your YouTube fans? Have a great name! One of the vital decisions you have to take while beginning your vlog channel is selecting a vlog channel name. Believe it or not, your vlog channel name can impact the channel's success, so choosing the ideal one is essential. If you're unsure of how to have the best vlog channel names or are just looking for channel rebranding, you've come to the right place! Here, we've 50+ lists of the best **YouTube channel names for vloggers**, along with sections discussing how you can select the ideal one plus their importance for the channel's growth. * [Part 1: Why are Vlog Channel Names Important?](#part1) * [Part 2: What to Consider Before Picking YouTube channel names for Vloggers?](#part2) * [Part 3: 50+ Vlog Channel Names Ideas in 2021](#part3) * [Part 4: Top 5 Free Vlog Channel Name Generators in 2021](#part4) * [Part 5: Versatile YouTube Vlogs Editor](#part5) ## Part 1: Why are Vlog Channel Names Important? Your Channel Name appears on your channel page, videos, and in YouTube's search results. Just like a boring title, a generic vlog channel name will not last in the viewer's memory, precisely when there's so much competition vying for their YouTube engagement and attention. However, using attention-grabbing, punchy words can make for an entertaining YouTube channel name for vloggers. Remember, if your YouTube channel becomes successful, this will be the name that everyone knows you. ## Part 2: What to Consider Before Picking YouTube channel names for Vloggers? Selecting a vlog channel name might not be simple as it seems. There are multiple options out there, so how will you know if you've chosen the right one? To help you decide better, we've designed a step-by-step guide that shows you exactly how to develop some excellent **vlog channel name ideas**. **Step 1: Consider the Image You Want to Portray** Vlog channel names often highlight the brand or person on the other end. While not the case for all, you will notice how many define their overall objective or mission. This can be ideal to begin when thinking of new Youtube channel names for vloggers. Don't pretend to be someone you're not when you select your vlog channel name. It's pretty vital that you, the channel owner, portray a message or an image that feels natural and provides your audience with an opportunity for best relation and recognition. **Step 2: Stay Consistent with Your YouTube Niche** The name you select must also reflect the niche upon which you based your channel. If you have a new channel, it can be hard to compete with more prominent vlog channels that cover important content topics. That's why you should try to be particular and become the best at designing topics for the subject you've selected. While you may get required exposure with a random name to grow your channel, it's better, to begin with, something focal to the point. **Step 3: Get a Feel for Your Target Audience** Your target audience could be a huge factor in selecting the best name for a vlogging channel. Also, consider other vlog channels in the niche you've chosen and read through their video comments. Search out what your audience likes and vice versa. A precise scenario of your audience's interests will allow you to choose the best name for a vlogging channel. **Step 4: Keep Your Channel Name Short** A YouTube channel name, or username, is max up to 60 characters, but generally, you get nowhere near that! Long channel names are not essential and can also be confusing to the viewers. They can also be tough to replicate or spell while searching. A concise, short username for your YouTube vlog channel can also give you the image of having more authority. **Step 5: Make Your Channel Name Memorable** Remember, if your YouTube vlog channel namebecomes excellent, this will be the name that everyone knows you by. It will be there with your videos, your playlists, and thumbnails. You don't want a bad image that drags you downwards, but add creative writing tools like word plays, abbreviations, sibilance, alliteration, and puns to increase memorability. ## Part 3: 50+ Vlog Channel Names Ideas in 2022 Strictly Cyber Top Song Critic Hashtag Hits All Things Sports The Virtual Coach Game Hub CyberLife The Daily Cloud Inner Sphere Fashion Channel Button Smasher Numb thumbs Gentle Gamer Headset Hero Headset Heaven Headset Habitat / Home Headset Hub Gorgeous Gamer Avatar auditions 3D Josh abroad broad adventures abroad van life \[country\] life van fan suitcase suckers hotel hobbyists travel treats transit travel travel tricks life (long) lovers love \[name\] lovebirds hug my husband / housewife / boyfriend / girlfriend husband at home cuddle my girlfriend couples paradise trouble in paradise couple productions couples therapy in a nutshell tutorial hero info nuggets \[name\] teaches \[topic\] \[topic\] by \[name\] learning \[topic\] curiosity satisfied \[topic\] academy / school / tutorials / teacher / made easy / explained / for beginners edu owl nothing too difficult ## **Part 4: Top 5 Free Vlog Channel Name Generators in 2022** There are numerous ways to personalizing a cool YouTube vlog channel nameor brainstorm fantastic vlog channel name ideas. Check out some of the most used YouTube name generator tools that got the higher ranking even from professionals. ### 1.[Spinxo](https://www.spinxo.com/youtube-names/) ![name generator spinxo](https://images.wondershare.com/filmora/article-images/twitch-name-generator-spinxo.jpg) This platform helps users search for cool names as per their characters, descriptions, niche, etc. You can begin the search with universal keywords and a set of specific details. Spinxo also helps YouTubers to manage contests online and grab the best suggestions for vlog names. **Queries Required**: They can be raised based on multiple things you like, such as Niche, Keywords, and Topics. **Ideal for**: Those who have few specific directions about the name. **No. of Results**: 30 names. ### 2.[Screen Name Generator](http://namenami.com/screen-name-generator) ![screen name generator](https://images.wondershare.com/filmora/article-images/screen-name-generator.jpg) Gamers will admire this YouTube name generator tool that works based on the YouTubers' provided prefix. It has sections like fantasy name generators, place name generators, username generators, thing names, etc. **Queries Required**: It can be with prefix and suffix. **Ideal for**: Those who have a specific direction and need for the name. **No. of Results**: One name. ### 3.[Username Generator](http://namegenerators.org/username-generator/) Username Generator makes it simpler to look for game-specific usernames. Users can put in the keywords and number of lines as their preferences. Then, the software will get you the most appropriate vlog channel names ideas. **Queries Needed**: Based on the keywords only. **Best for**: those of all genres. **No. of Results**: Hundreds of names. ### 4.[Name Generator](https://www.namegenerator.biz/youtube-name-generator.php) This name generator tool also helps people to get the best random combo names where details are pretty particular to content related to your entered works like "vids," "director," "TV," "channel," etc. Every time you tap the **Generate** tab provided, it will offer you the most random names. **Queries Required**: Based on Prefix and Suffix **Ideal for**: Those who have particular directions with the name. **No. of Results**: 1 ### 5.[Scratch](https://scratch.mit.edu/projects/18362376/) ![scratch name generator](https://images.wondershare.com/filmora/article-images/scratch.png) With this software, you can get the best names for vlogging channels with caps specifications that look awesome. You can select game highlights for your channel name. And, one can also prefer to put several words into the list to get finer results. **Queries Needed**: Works with keywords only. **Best for**: Those of all genres. **No. of Results**: One name. ## Part 5: Versatile YouTube Vlogs Editor [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) After you have decided to develop your YouTube vlog channel, the first thing you'll look for is premium-looking video editing. And, here, we recommend using Filmora9 to edit YouTube vlogs easily. You can use Filmora to make YouTube vlogs with built-in royalty-free audio. The software also can help you create fantastic YouTube intros. It consists of 500 plus templates, text resources, and transition effects. Filmora is the ideal editing tool to make a green screen and split-screen video for YouTubers. Free Download it now to watch if it's the best for you! ### Conclusion So, now, do you think you got some cool YouTube channel names for vloggers? Share your feedback towards the end of the blog, and let us know if you've ever used a free YouTube name generator! [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) Want to make a lasting impression on your YouTube fans? Have a great name! One of the vital decisions you have to take while beginning your vlog channel is selecting a vlog channel name. Believe it or not, your vlog channel name can impact the channel's success, so choosing the ideal one is essential. If you're unsure of how to have the best vlog channel names or are just looking for channel rebranding, you've come to the right place! Here, we've 50+ lists of the best **YouTube channel names for vloggers**, along with sections discussing how you can select the ideal one plus their importance for the channel's growth. * [Part 1: Why are Vlog Channel Names Important?](#part1) * [Part 2: What to Consider Before Picking YouTube channel names for Vloggers?](#part2) * [Part 3: 50+ Vlog Channel Names Ideas in 2021](#part3) * [Part 4: Top 5 Free Vlog Channel Name Generators in 2021](#part4) * [Part 5: Versatile YouTube Vlogs Editor](#part5) ## Part 1: Why are Vlog Channel Names Important? Your Channel Name appears on your channel page, videos, and in YouTube's search results. Just like a boring title, a generic vlog channel name will not last in the viewer's memory, precisely when there's so much competition vying for their YouTube engagement and attention. However, using attention-grabbing, punchy words can make for an entertaining YouTube channel name for vloggers. Remember, if your YouTube channel becomes successful, this will be the name that everyone knows you. ## Part 2: What to Consider Before Picking YouTube channel names for Vloggers? Selecting a vlog channel name might not be simple as it seems. There are multiple options out there, so how will you know if you've chosen the right one? To help you decide better, we've designed a step-by-step guide that shows you exactly how to develop some excellent **vlog channel name ideas**. **Step 1: Consider the Image You Want to Portray** Vlog channel names often highlight the brand or person on the other end. While not the case for all, you will notice how many define their overall objective or mission. This can be ideal to begin when thinking of new Youtube channel names for vloggers. Don't pretend to be someone you're not when you select your vlog channel name. It's pretty vital that you, the channel owner, portray a message or an image that feels natural and provides your audience with an opportunity for best relation and recognition. **Step 2: Stay Consistent with Your YouTube Niche** The name you select must also reflect the niche upon which you based your channel. If you have a new channel, it can be hard to compete with more prominent vlog channels that cover important content topics. That's why you should try to be particular and become the best at designing topics for the subject you've selected. While you may get required exposure with a random name to grow your channel, it's better, to begin with, something focal to the point. **Step 3: Get a Feel for Your Target Audience** Your target audience could be a huge factor in selecting the best name for a vlogging channel. Also, consider other vlog channels in the niche you've chosen and read through their video comments. Search out what your audience likes and vice versa. A precise scenario of your audience's interests will allow you to choose the best name for a vlogging channel. **Step 4: Keep Your Channel Name Short** A YouTube channel name, or username, is max up to 60 characters, but generally, you get nowhere near that! Long channel names are not essential and can also be confusing to the viewers. They can also be tough to replicate or spell while searching. A concise, short username for your YouTube vlog channel can also give you the image of having more authority. **Step 5: Make Your Channel Name Memorable** Remember, if your YouTube vlog channel namebecomes excellent, this will be the name that everyone knows you by. It will be there with your videos, your playlists, and thumbnails. You don't want a bad image that drags you downwards, but add creative writing tools like word plays, abbreviations, sibilance, alliteration, and puns to increase memorability. ## Part 3: 50+ Vlog Channel Names Ideas in 2022 Strictly Cyber Top Song Critic Hashtag Hits All Things Sports The Virtual Coach Game Hub CyberLife The Daily Cloud Inner Sphere Fashion Channel Button Smasher Numb thumbs Gentle Gamer Headset Hero Headset Heaven Headset Habitat / Home Headset Hub Gorgeous Gamer Avatar auditions 3D Josh abroad broad adventures abroad van life \[country\] life van fan suitcase suckers hotel hobbyists travel treats transit travel travel tricks life (long) lovers love \[name\] lovebirds hug my husband / housewife / boyfriend / girlfriend husband at home cuddle my girlfriend couples paradise trouble in paradise couple productions couples therapy in a nutshell tutorial hero info nuggets \[name\] teaches \[topic\] \[topic\] by \[name\] learning \[topic\] curiosity satisfied \[topic\] academy / school / tutorials / teacher / made easy / explained / for beginners edu owl nothing too difficult ## **Part 4: Top 5 Free Vlog Channel Name Generators in 2022** There are numerous ways to personalizing a cool YouTube vlog channel nameor brainstorm fantastic vlog channel name ideas. Check out some of the most used YouTube name generator tools that got the higher ranking even from professionals. ### 1.[Spinxo](https://www.spinxo.com/youtube-names/) ![name generator spinxo](https://images.wondershare.com/filmora/article-images/twitch-name-generator-spinxo.jpg) This platform helps users search for cool names as per their characters, descriptions, niche, etc. You can begin the search with universal keywords and a set of specific details. Spinxo also helps YouTubers to manage contests online and grab the best suggestions for vlog names. **Queries Required**: They can be raised based on multiple things you like, such as Niche, Keywords, and Topics. **Ideal for**: Those who have few specific directions about the name. **No. of Results**: 30 names. ### 2.[Screen Name Generator](http://namenami.com/screen-name-generator) ![screen name generator](https://images.wondershare.com/filmora/article-images/screen-name-generator.jpg) Gamers will admire this YouTube name generator tool that works based on the YouTubers' provided prefix. It has sections like fantasy name generators, place name generators, username generators, thing names, etc. **Queries Required**: It can be with prefix and suffix. **Ideal for**: Those who have a specific direction and need for the name. **No. of Results**: One name. ### 3.[Username Generator](http://namegenerators.org/username-generator/) Username Generator makes it simpler to look for game-specific usernames. Users can put in the keywords and number of lines as their preferences. Then, the software will get you the most appropriate vlog channel names ideas. **Queries Needed**: Based on the keywords only. **Best for**: those of all genres. **No. of Results**: Hundreds of names. ### 4.[Name Generator](https://www.namegenerator.biz/youtube-name-generator.php) This name generator tool also helps people to get the best random combo names where details are pretty particular to content related to your entered works like "vids," "director," "TV," "channel," etc. Every time you tap the **Generate** tab provided, it will offer you the most random names. **Queries Required**: Based on Prefix and Suffix **Ideal for**: Those who have particular directions with the name. **No. of Results**: 1 ### 5.[Scratch](https://scratch.mit.edu/projects/18362376/) ![scratch name generator](https://images.wondershare.com/filmora/article-images/scratch.png) With this software, you can get the best names for vlogging channels with caps specifications that look awesome. You can select game highlights for your channel name. And, one can also prefer to put several words into the list to get finer results. **Queries Needed**: Works with keywords only. **Best for**: Those of all genres. **No. of Results**: One name. ## Part 5: Versatile YouTube Vlogs Editor [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) After you have decided to develop your YouTube vlog channel, the first thing you'll look for is premium-looking video editing. And, here, we recommend using Filmora9 to edit YouTube vlogs easily. You can use Filmora to make YouTube vlogs with built-in royalty-free audio. The software also can help you create fantastic YouTube intros. It consists of 500 plus templates, text resources, and transition effects. Filmora is the ideal editing tool to make a green screen and split-screen video for YouTubers. Free Download it now to watch if it's the best for you! ### Conclusion So, now, do you think you got some cool YouTube channel names for vloggers? Share your feedback towards the end of the blog, and let us know if you've ever used a free YouTube name generator! [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) Want to make a lasting impression on your YouTube fans? Have a great name! One of the vital decisions you have to take while beginning your vlog channel is selecting a vlog channel name. Believe it or not, your vlog channel name can impact the channel's success, so choosing the ideal one is essential. If you're unsure of how to have the best vlog channel names or are just looking for channel rebranding, you've come to the right place! Here, we've 50+ lists of the best **YouTube channel names for vloggers**, along with sections discussing how you can select the ideal one plus their importance for the channel's growth. * [Part 1: Why are Vlog Channel Names Important?](#part1) * [Part 2: What to Consider Before Picking YouTube channel names for Vloggers?](#part2) * [Part 3: 50+ Vlog Channel Names Ideas in 2021](#part3) * [Part 4: Top 5 Free Vlog Channel Name Generators in 2021](#part4) * [Part 5: Versatile YouTube Vlogs Editor](#part5) ## Part 1: Why are Vlog Channel Names Important? Your Channel Name appears on your channel page, videos, and in YouTube's search results. Just like a boring title, a generic vlog channel name will not last in the viewer's memory, precisely when there's so much competition vying for their YouTube engagement and attention. However, using attention-grabbing, punchy words can make for an entertaining YouTube channel name for vloggers. Remember, if your YouTube channel becomes successful, this will be the name that everyone knows you. ## Part 2: What to Consider Before Picking YouTube channel names for Vloggers? Selecting a vlog channel name might not be simple as it seems. There are multiple options out there, so how will you know if you've chosen the right one? To help you decide better, we've designed a step-by-step guide that shows you exactly how to develop some excellent **vlog channel name ideas**. **Step 1: Consider the Image You Want to Portray** Vlog channel names often highlight the brand or person on the other end. While not the case for all, you will notice how many define their overall objective or mission. This can be ideal to begin when thinking of new Youtube channel names for vloggers. Don't pretend to be someone you're not when you select your vlog channel name. It's pretty vital that you, the channel owner, portray a message or an image that feels natural and provides your audience with an opportunity for best relation and recognition. **Step 2: Stay Consistent with Your YouTube Niche** The name you select must also reflect the niche upon which you based your channel. If you have a new channel, it can be hard to compete with more prominent vlog channels that cover important content topics. That's why you should try to be particular and become the best at designing topics for the subject you've selected. While you may get required exposure with a random name to grow your channel, it's better, to begin with, something focal to the point. **Step 3: Get a Feel for Your Target Audience** Your target audience could be a huge factor in selecting the best name for a vlogging channel. Also, consider other vlog channels in the niche you've chosen and read through their video comments. Search out what your audience likes and vice versa. A precise scenario of your audience's interests will allow you to choose the best name for a vlogging channel. **Step 4: Keep Your Channel Name Short** A YouTube channel name, or username, is max up to 60 characters, but generally, you get nowhere near that! Long channel names are not essential and can also be confusing to the viewers. They can also be tough to replicate or spell while searching. A concise, short username for your YouTube vlog channel can also give you the image of having more authority. **Step 5: Make Your Channel Name Memorable** Remember, if your YouTube vlog channel namebecomes excellent, this will be the name that everyone knows you by. It will be there with your videos, your playlists, and thumbnails. You don't want a bad image that drags you downwards, but add creative writing tools like word plays, abbreviations, sibilance, alliteration, and puns to increase memorability. ## Part 3: 50+ Vlog Channel Names Ideas in 2022 Strictly Cyber Top Song Critic Hashtag Hits All Things Sports The Virtual Coach Game Hub CyberLife The Daily Cloud Inner Sphere Fashion Channel Button Smasher Numb thumbs Gentle Gamer Headset Hero Headset Heaven Headset Habitat / Home Headset Hub Gorgeous Gamer Avatar auditions 3D Josh abroad broad adventures abroad van life \[country\] life van fan suitcase suckers hotel hobbyists travel treats transit travel travel tricks life (long) lovers love \[name\] lovebirds hug my husband / housewife / boyfriend / girlfriend husband at home cuddle my girlfriend couples paradise trouble in paradise couple productions couples therapy in a nutshell tutorial hero info nuggets \[name\] teaches \[topic\] \[topic\] by \[name\] learning \[topic\] curiosity satisfied \[topic\] academy / school / tutorials / teacher / made easy / explained / for beginners edu owl nothing too difficult ## **Part 4: Top 5 Free Vlog Channel Name Generators in 2022** There are numerous ways to personalizing a cool YouTube vlog channel nameor brainstorm fantastic vlog channel name ideas. Check out some of the most used YouTube name generator tools that got the higher ranking even from professionals. ### 1.[Spinxo](https://www.spinxo.com/youtube-names/) ![name generator spinxo](https://images.wondershare.com/filmora/article-images/twitch-name-generator-spinxo.jpg) This platform helps users search for cool names as per their characters, descriptions, niche, etc. You can begin the search with universal keywords and a set of specific details. Spinxo also helps YouTubers to manage contests online and grab the best suggestions for vlog names. **Queries Required**: They can be raised based on multiple things you like, such as Niche, Keywords, and Topics. **Ideal for**: Those who have few specific directions about the name. **No. of Results**: 30 names. ### 2.[Screen Name Generator](http://namenami.com/screen-name-generator) ![screen name generator](https://images.wondershare.com/filmora/article-images/screen-name-generator.jpg) Gamers will admire this YouTube name generator tool that works based on the YouTubers' provided prefix. It has sections like fantasy name generators, place name generators, username generators, thing names, etc. **Queries Required**: It can be with prefix and suffix. **Ideal for**: Those who have a specific direction and need for the name. **No. of Results**: One name. ### 3.[Username Generator](http://namegenerators.org/username-generator/) Username Generator makes it simpler to look for game-specific usernames. Users can put in the keywords and number of lines as their preferences. Then, the software will get you the most appropriate vlog channel names ideas. **Queries Needed**: Based on the keywords only. **Best for**: those of all genres. **No. of Results**: Hundreds of names. ### 4.[Name Generator](https://www.namegenerator.biz/youtube-name-generator.php) This name generator tool also helps people to get the best random combo names where details are pretty particular to content related to your entered works like "vids," "director," "TV," "channel," etc. Every time you tap the **Generate** tab provided, it will offer you the most random names. **Queries Required**: Based on Prefix and Suffix **Ideal for**: Those who have particular directions with the name. **No. of Results**: 1 ### 5.[Scratch](https://scratch.mit.edu/projects/18362376/) ![scratch name generator](https://images.wondershare.com/filmora/article-images/scratch.png) With this software, you can get the best names for vlogging channels with caps specifications that look awesome. You can select game highlights for your channel name. And, one can also prefer to put several words into the list to get finer results. **Queries Needed**: Works with keywords only. **Best for**: Those of all genres. **No. of Results**: One name. ## Part 5: Versatile YouTube Vlogs Editor [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) After you have decided to develop your YouTube vlog channel, the first thing you'll look for is premium-looking video editing. And, here, we recommend using Filmora9 to edit YouTube vlogs easily. You can use Filmora to make YouTube vlogs with built-in royalty-free audio. The software also can help you create fantastic YouTube intros. It consists of 500 plus templates, text resources, and transition effects. Filmora is the ideal editing tool to make a green screen and split-screen video for YouTubers. Free Download it now to watch if it's the best for you! ### Conclusion So, now, do you think you got some cool YouTube channel names for vloggers? Share your feedback towards the end of the blog, and let us know if you've ever used a free YouTube name generator! [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) Want to make a lasting impression on your YouTube fans? Have a great name! One of the vital decisions you have to take while beginning your vlog channel is selecting a vlog channel name. Believe it or not, your vlog channel name can impact the channel's success, so choosing the ideal one is essential. If you're unsure of how to have the best vlog channel names or are just looking for channel rebranding, you've come to the right place! Here, we've 50+ lists of the best **YouTube channel names for vloggers**, along with sections discussing how you can select the ideal one plus their importance for the channel's growth. * [Part 1: Why are Vlog Channel Names Important?](#part1) * [Part 2: What to Consider Before Picking YouTube channel names for Vloggers?](#part2) * [Part 3: 50+ Vlog Channel Names Ideas in 2021](#part3) * [Part 4: Top 5 Free Vlog Channel Name Generators in 2021](#part4) * [Part 5: Versatile YouTube Vlogs Editor](#part5) ## Part 1: Why are Vlog Channel Names Important? Your Channel Name appears on your channel page, videos, and in YouTube's search results. Just like a boring title, a generic vlog channel name will not last in the viewer's memory, precisely when there's so much competition vying for their YouTube engagement and attention. However, using attention-grabbing, punchy words can make for an entertaining YouTube channel name for vloggers. Remember, if your YouTube channel becomes successful, this will be the name that everyone knows you. ## Part 2: What to Consider Before Picking YouTube channel names for Vloggers? Selecting a vlog channel name might not be simple as it seems. There are multiple options out there, so how will you know if you've chosen the right one? To help you decide better, we've designed a step-by-step guide that shows you exactly how to develop some excellent **vlog channel name ideas**. **Step 1: Consider the Image You Want to Portray** Vlog channel names often highlight the brand or person on the other end. While not the case for all, you will notice how many define their overall objective or mission. This can be ideal to begin when thinking of new Youtube channel names for vloggers. Don't pretend to be someone you're not when you select your vlog channel name. It's pretty vital that you, the channel owner, portray a message or an image that feels natural and provides your audience with an opportunity for best relation and recognition. **Step 2: Stay Consistent with Your YouTube Niche** The name you select must also reflect the niche upon which you based your channel. If you have a new channel, it can be hard to compete with more prominent vlog channels that cover important content topics. That's why you should try to be particular and become the best at designing topics for the subject you've selected. While you may get required exposure with a random name to grow your channel, it's better, to begin with, something focal to the point. **Step 3: Get a Feel for Your Target Audience** Your target audience could be a huge factor in selecting the best name for a vlogging channel. Also, consider other vlog channels in the niche you've chosen and read through their video comments. Search out what your audience likes and vice versa. A precise scenario of your audience's interests will allow you to choose the best name for a vlogging channel. **Step 4: Keep Your Channel Name Short** A YouTube channel name, or username, is max up to 60 characters, but generally, you get nowhere near that! Long channel names are not essential and can also be confusing to the viewers. They can also be tough to replicate or spell while searching. A concise, short username for your YouTube vlog channel can also give you the image of having more authority. **Step 5: Make Your Channel Name Memorable** Remember, if your YouTube vlog channel namebecomes excellent, this will be the name that everyone knows you by. It will be there with your videos, your playlists, and thumbnails. You don't want a bad image that drags you downwards, but add creative writing tools like word plays, abbreviations, sibilance, alliteration, and puns to increase memorability. ## Part 3: 50+ Vlog Channel Names Ideas in 2022 Strictly Cyber Top Song Critic Hashtag Hits All Things Sports The Virtual Coach Game Hub CyberLife The Daily Cloud Inner Sphere Fashion Channel Button Smasher Numb thumbs Gentle Gamer Headset Hero Headset Heaven Headset Habitat / Home Headset Hub Gorgeous Gamer Avatar auditions 3D Josh abroad broad adventures abroad van life \[country\] life van fan suitcase suckers hotel hobbyists travel treats transit travel travel tricks life (long) lovers love \[name\] lovebirds hug my husband / housewife / boyfriend / girlfriend husband at home cuddle my girlfriend couples paradise trouble in paradise couple productions couples therapy in a nutshell tutorial hero info nuggets \[name\] teaches \[topic\] \[topic\] by \[name\] learning \[topic\] curiosity satisfied \[topic\] academy / school / tutorials / teacher / made easy / explained / for beginners edu owl nothing too difficult ## **Part 4: Top 5 Free Vlog Channel Name Generators in 2022** There are numerous ways to personalizing a cool YouTube vlog channel nameor brainstorm fantastic vlog channel name ideas. Check out some of the most used YouTube name generator tools that got the higher ranking even from professionals. ### 1.[Spinxo](https://www.spinxo.com/youtube-names/) ![name generator spinxo](https://images.wondershare.com/filmora/article-images/twitch-name-generator-spinxo.jpg) This platform helps users search for cool names as per their characters, descriptions, niche, etc. You can begin the search with universal keywords and a set of specific details. Spinxo also helps YouTubers to manage contests online and grab the best suggestions for vlog names. **Queries Required**: They can be raised based on multiple things you like, such as Niche, Keywords, and Topics. **Ideal for**: Those who have few specific directions about the name. **No. of Results**: 30 names. ### 2.[Screen Name Generator](http://namenami.com/screen-name-generator) ![screen name generator](https://images.wondershare.com/filmora/article-images/screen-name-generator.jpg) Gamers will admire this YouTube name generator tool that works based on the YouTubers' provided prefix. It has sections like fantasy name generators, place name generators, username generators, thing names, etc. **Queries Required**: It can be with prefix and suffix. **Ideal for**: Those who have a specific direction and need for the name. **No. of Results**: One name. ### 3.[Username Generator](http://namegenerators.org/username-generator/) Username Generator makes it simpler to look for game-specific usernames. Users can put in the keywords and number of lines as their preferences. Then, the software will get you the most appropriate vlog channel names ideas. **Queries Needed**: Based on the keywords only. **Best for**: those of all genres. **No. of Results**: Hundreds of names. ### 4.[Name Generator](https://www.namegenerator.biz/youtube-name-generator.php) This name generator tool also helps people to get the best random combo names where details are pretty particular to content related to your entered works like "vids," "director," "TV," "channel," etc. Every time you tap the **Generate** tab provided, it will offer you the most random names. **Queries Required**: Based on Prefix and Suffix **Ideal for**: Those who have particular directions with the name. **No. of Results**: 1 ### 5.[Scratch](https://scratch.mit.edu/projects/18362376/) ![scratch name generator](https://images.wondershare.com/filmora/article-images/scratch.png) With this software, you can get the best names for vlogging channels with caps specifications that look awesome. You can select game highlights for your channel name. And, one can also prefer to put several words into the list to get finer results. **Queries Needed**: Works with keywords only. **Best for**: Those of all genres. **No. of Results**: One name. ## Part 5: Versatile YouTube Vlogs Editor [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) After you have decided to develop your YouTube vlog channel, the first thing you'll look for is premium-looking video editing. And, here, we recommend using Filmora9 to edit YouTube vlogs easily. You can use Filmora to make YouTube vlogs with built-in royalty-free audio. The software also can help you create fantastic YouTube intros. It consists of 500 plus templates, text resources, and transition effects. Filmora is the ideal editing tool to make a green screen and split-screen video for YouTubers. Free Download it now to watch if it's the best for you! ### Conclusion So, now, do you think you got some cool YouTube channel names for vloggers? Share your feedback towards the end of the blog, and let us know if you've ever used a free YouTube name generator! [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Boosting Your Content Quality: Essential Tips for YouTube Users # How to Use YouTube Enhancements ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) ##### Richard Bennett Mar 27, 2024• Proven solutions YouTube has integrated a free video editor to facilitate the work of YouTubers and allow them to process their videos prior to uploading. Although nobody can claim these features can live up to the sophisticated features of the professional video editors, YouTube enhancements are useful and cool which offer a simple way to improve the quality of the videos and do not require any technical knowledge on your behalf. --- If you are looking for a more professional approach in video editing, you should try out [Wondershare Filmora(for Windows and Mac)](https://tools.techidaily.com/wondershare/filmora/download/). This is an exceptionally versatile and powerful tool, which will allow you to gain full control over the videos you wish to edit. It is very easy to use, and it will open up a new world of potentials in video editing. There is a free trial that you can benefit from, so as to see if Filmora meets your criteria in full prior to your purchase. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) --- * [Part 1: How to Use YouTube Enhancements](#part1) * [Part 2: How to Use Wondershare Filmora to Improve Video Qualtiy](#part2) ## How to Use YouTube Enhancements First of all, you need to locate YouTube Enhancements. As soon as you have logged into your YouTube channel, you should go to the Video Manager. There you choose Edit and YouTube Enhancements, and you are ready to go. There are three distinctive categories that you can use, in order to edit your video. You can choose among Quick Fix, Filters, and Blurring Effects. As you can see, there are features that pretty much cover the basics in video editing under these categories. ![Locate enhancements features](https://images.wondershare.com/filmora/article-images/locate-enhancements-feature.jpg ) Quick Fix promptly addresses issues that have to do with the contrast and saturation, as well as offers the ability to rotate or trim the video. There is nothing sophisticated there, but it is a really easy and practical solution for those who do not wish to waste time editing. It is cool that you can also stabilize your video or allow for Slow Motion or Timelapse effects. This is definitely an improvement for YouTube videos. ![Qucik Fix](https://images.wondershare.com/filmora/article-images/quick-fix.jpg ) Filters feel a lot like those used on Instagram. They are neat and cool, of course, covering many of the demands for sophisticated editing. You can find filters like Lomo-ish, Old Fashioned, Heat Map, Cartoon, Cross Process, Festival and much more on YouTube Enhancements. You can also adjust the lighting and colors, so as to fine-tune your video. ![YouTube Filters](https://images.wondershare.com/filmora/article-images/youtube-filters.jpg ) Blurring Effects are perhaps the most advanced on YouTube Enhancements, and they provide the opportunity to maintain your privacy, by removing people’s distinctive details from the video and blurring them or putting mosaic on their face. With this tool, you can also blur objects on the video, which can increase your privacy even more. For instance, you can blur the plates of your car or your address. Last, there are some hilarious effects that you should check out. ![YouTube Costum Blurring](https://images.wondershare.com/filmora/article-images/youtube-costum-blurring.jpg ) Once you are done, there is an option to preview the video that you have edited. In this way, you will know if the editions that you have made are sufficient for you or not. Finally, you can choose either to save the video as a new file or revert to the original video. These options are welcome, as sometimes you just do not get what you have expected and you do not want to replace the video you have already uploaded. ## How to Use Wondershare Filmora to improve YouTube videos These are the steps that you need to follow, so as to proceed with high-quality video editing on Filmora: * Open Wordershare Filmora * Choose if you want 16:9 or 4:3 aspect ratio * Tap Import so as to upload the files * Drag and drop them, in order to place them in the right order ![Import Video](https://images.wondershare.com/filmora/article-images/import-videos.jpg ) * Click Edit and adjust the settings (rotation, contrast, saturation, brightness, hue, auto de-noise and speed) ![Adjust Contrast Saturation](https://images.wondershare.com/filmora/article-images/adjust-contrast-saturation.jpg ) * Click OK, and you are done with the improvement of Video Quality If you wish to fine-tune the images of the videos and place special filters, you can go ahead as follows: * Tap the Effect button * Drag the effect you want to use on the timeline (you can choose from a wide variety of effects, including Bokeh and Light Leaks, Old Film, etc.) ![Free Movie Special Effect](https://images.wondershare.com/filmora/article-images/free-movie-special-effects.jpg ) After having finished with the video editing process, you can preview the video and see if it is of acceptable quality standards. You can do that by clicking on the Play button. Then you can click on the Create button and save the video where you want, in the format of your choosing. It is also possible for you to burn the video on a DVD or share it online using YouTube or Facebook. ![Format Supported by Filmora](https://images.wondershare.com/filmora/article-images/format-supported-by-filmora.png ) [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions YouTube has integrated a free video editor to facilitate the work of YouTubers and allow them to process their videos prior to uploading. Although nobody can claim these features can live up to the sophisticated features of the professional video editors, YouTube enhancements are useful and cool which offer a simple way to improve the quality of the videos and do not require any technical knowledge on your behalf. --- If you are looking for a more professional approach in video editing, you should try out [Wondershare Filmora(for Windows and Mac)](https://tools.techidaily.com/wondershare/filmora/download/). This is an exceptionally versatile and powerful tool, which will allow you to gain full control over the videos you wish to edit. It is very easy to use, and it will open up a new world of potentials in video editing. There is a free trial that you can benefit from, so as to see if Filmora meets your criteria in full prior to your purchase. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) --- * [Part 1: How to Use YouTube Enhancements](#part1) * [Part 2: How to Use Wondershare Filmora to Improve Video Qualtiy](#part2) ## How to Use YouTube Enhancements First of all, you need to locate YouTube Enhancements. As soon as you have logged into your YouTube channel, you should go to the Video Manager. There you choose Edit and YouTube Enhancements, and you are ready to go. There are three distinctive categories that you can use, in order to edit your video. You can choose among Quick Fix, Filters, and Blurring Effects. As you can see, there are features that pretty much cover the basics in video editing under these categories. ![Locate enhancements features](https://images.wondershare.com/filmora/article-images/locate-enhancements-feature.jpg ) Quick Fix promptly addresses issues that have to do with the contrast and saturation, as well as offers the ability to rotate or trim the video. There is nothing sophisticated there, but it is a really easy and practical solution for those who do not wish to waste time editing. It is cool that you can also stabilize your video or allow for Slow Motion or Timelapse effects. This is definitely an improvement for YouTube videos. ![Qucik Fix](https://images.wondershare.com/filmora/article-images/quick-fix.jpg ) Filters feel a lot like those used on Instagram. They are neat and cool, of course, covering many of the demands for sophisticated editing. You can find filters like Lomo-ish, Old Fashioned, Heat Map, Cartoon, Cross Process, Festival and much more on YouTube Enhancements. You can also adjust the lighting and colors, so as to fine-tune your video. ![YouTube Filters](https://images.wondershare.com/filmora/article-images/youtube-filters.jpg ) Blurring Effects are perhaps the most advanced on YouTube Enhancements, and they provide the opportunity to maintain your privacy, by removing people’s distinctive details from the video and blurring them or putting mosaic on their face. With this tool, you can also blur objects on the video, which can increase your privacy even more. For instance, you can blur the plates of your car or your address. Last, there are some hilarious effects that you should check out. ![YouTube Costum Blurring](https://images.wondershare.com/filmora/article-images/youtube-costum-blurring.jpg ) Once you are done, there is an option to preview the video that you have edited. In this way, you will know if the editions that you have made are sufficient for you or not. Finally, you can choose either to save the video as a new file or revert to the original video. These options are welcome, as sometimes you just do not get what you have expected and you do not want to replace the video you have already uploaded. ## How to Use Wondershare Filmora to improve YouTube videos These are the steps that you need to follow, so as to proceed with high-quality video editing on Filmora: * Open Wordershare Filmora * Choose if you want 16:9 or 4:3 aspect ratio * Tap Import so as to upload the files * Drag and drop them, in order to place them in the right order ![Import Video](https://images.wondershare.com/filmora/article-images/import-videos.jpg ) * Click Edit and adjust the settings (rotation, contrast, saturation, brightness, hue, auto de-noise and speed) ![Adjust Contrast Saturation](https://images.wondershare.com/filmora/article-images/adjust-contrast-saturation.jpg ) * Click OK, and you are done with the improvement of Video Quality If you wish to fine-tune the images of the videos and place special filters, you can go ahead as follows: * Tap the Effect button * Drag the effect you want to use on the timeline (you can choose from a wide variety of effects, including Bokeh and Light Leaks, Old Film, etc.) ![Free Movie Special Effect](https://images.wondershare.com/filmora/article-images/free-movie-special-effects.jpg ) After having finished with the video editing process, you can preview the video and see if it is of acceptable quality standards. You can do that by clicking on the Play button. Then you can click on the Create button and save the video where you want, in the format of your choosing. It is also possible for you to burn the video on a DVD or share it online using YouTube or Facebook. ![Format Supported by Filmora](https://images.wondershare.com/filmora/article-images/format-supported-by-filmora.png ) [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions YouTube has integrated a free video editor to facilitate the work of YouTubers and allow them to process their videos prior to uploading. Although nobody can claim these features can live up to the sophisticated features of the professional video editors, YouTube enhancements are useful and cool which offer a simple way to improve the quality of the videos and do not require any technical knowledge on your behalf. --- If you are looking for a more professional approach in video editing, you should try out [Wondershare Filmora(for Windows and Mac)](https://tools.techidaily.com/wondershare/filmora/download/). This is an exceptionally versatile and powerful tool, which will allow you to gain full control over the videos you wish to edit. It is very easy to use, and it will open up a new world of potentials in video editing. There is a free trial that you can benefit from, so as to see if Filmora meets your criteria in full prior to your purchase. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) --- * [Part 1: How to Use YouTube Enhancements](#part1) * [Part 2: How to Use Wondershare Filmora to Improve Video Qualtiy](#part2) ## How to Use YouTube Enhancements First of all, you need to locate YouTube Enhancements. As soon as you have logged into your YouTube channel, you should go to the Video Manager. There you choose Edit and YouTube Enhancements, and you are ready to go. There are three distinctive categories that you can use, in order to edit your video. You can choose among Quick Fix, Filters, and Blurring Effects. As you can see, there are features that pretty much cover the basics in video editing under these categories. ![Locate enhancements features](https://images.wondershare.com/filmora/article-images/locate-enhancements-feature.jpg ) Quick Fix promptly addresses issues that have to do with the contrast and saturation, as well as offers the ability to rotate or trim the video. There is nothing sophisticated there, but it is a really easy and practical solution for those who do not wish to waste time editing. It is cool that you can also stabilize your video or allow for Slow Motion or Timelapse effects. This is definitely an improvement for YouTube videos. ![Qucik Fix](https://images.wondershare.com/filmora/article-images/quick-fix.jpg ) Filters feel a lot like those used on Instagram. They are neat and cool, of course, covering many of the demands for sophisticated editing. You can find filters like Lomo-ish, Old Fashioned, Heat Map, Cartoon, Cross Process, Festival and much more on YouTube Enhancements. You can also adjust the lighting and colors, so as to fine-tune your video. ![YouTube Filters](https://images.wondershare.com/filmora/article-images/youtube-filters.jpg ) Blurring Effects are perhaps the most advanced on YouTube Enhancements, and they provide the opportunity to maintain your privacy, by removing people’s distinctive details from the video and blurring them or putting mosaic on their face. With this tool, you can also blur objects on the video, which can increase your privacy even more. For instance, you can blur the plates of your car or your address. Last, there are some hilarious effects that you should check out. ![YouTube Costum Blurring](https://images.wondershare.com/filmora/article-images/youtube-costum-blurring.jpg ) Once you are done, there is an option to preview the video that you have edited. In this way, you will know if the editions that you have made are sufficient for you or not. Finally, you can choose either to save the video as a new file or revert to the original video. These options are welcome, as sometimes you just do not get what you have expected and you do not want to replace the video you have already uploaded. ## How to Use Wondershare Filmora to improve YouTube videos These are the steps that you need to follow, so as to proceed with high-quality video editing on Filmora: * Open Wordershare Filmora * Choose if you want 16:9 or 4:3 aspect ratio * Tap Import so as to upload the files * Drag and drop them, in order to place them in the right order ![Import Video](https://images.wondershare.com/filmora/article-images/import-videos.jpg ) * Click Edit and adjust the settings (rotation, contrast, saturation, brightness, hue, auto de-noise and speed) ![Adjust Contrast Saturation](https://images.wondershare.com/filmora/article-images/adjust-contrast-saturation.jpg ) * Click OK, and you are done with the improvement of Video Quality If you wish to fine-tune the images of the videos and place special filters, you can go ahead as follows: * Tap the Effect button * Drag the effect you want to use on the timeline (you can choose from a wide variety of effects, including Bokeh and Light Leaks, Old Film, etc.) ![Free Movie Special Effect](https://images.wondershare.com/filmora/article-images/free-movie-special-effects.jpg ) After having finished with the video editing process, you can preview the video and see if it is of acceptable quality standards. You can do that by clicking on the Play button. Then you can click on the Create button and save the video where you want, in the format of your choosing. It is also possible for you to burn the video on a DVD or share it online using YouTube or Facebook. ![Format Supported by Filmora](https://images.wondershare.com/filmora/article-images/format-supported-by-filmora.png ) [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions YouTube has integrated a free video editor to facilitate the work of YouTubers and allow them to process their videos prior to uploading. Although nobody can claim these features can live up to the sophisticated features of the professional video editors, YouTube enhancements are useful and cool which offer a simple way to improve the quality of the videos and do not require any technical knowledge on your behalf. --- If you are looking for a more professional approach in video editing, you should try out [Wondershare Filmora(for Windows and Mac)](https://tools.techidaily.com/wondershare/filmora/download/). This is an exceptionally versatile and powerful tool, which will allow you to gain full control over the videos you wish to edit. It is very easy to use, and it will open up a new world of potentials in video editing. There is a free trial that you can benefit from, so as to see if Filmora meets your criteria in full prior to your purchase. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) --- * [Part 1: How to Use YouTube Enhancements](#part1) * [Part 2: How to Use Wondershare Filmora to Improve Video Qualtiy](#part2) ## How to Use YouTube Enhancements First of all, you need to locate YouTube Enhancements. As soon as you have logged into your YouTube channel, you should go to the Video Manager. There you choose Edit and YouTube Enhancements, and you are ready to go. There are three distinctive categories that you can use, in order to edit your video. You can choose among Quick Fix, Filters, and Blurring Effects. As you can see, there are features that pretty much cover the basics in video editing under these categories. ![Locate enhancements features](https://images.wondershare.com/filmora/article-images/locate-enhancements-feature.jpg ) Quick Fix promptly addresses issues that have to do with the contrast and saturation, as well as offers the ability to rotate or trim the video. There is nothing sophisticated there, but it is a really easy and practical solution for those who do not wish to waste time editing. It is cool that you can also stabilize your video or allow for Slow Motion or Timelapse effects. This is definitely an improvement for YouTube videos. ![Qucik Fix](https://images.wondershare.com/filmora/article-images/quick-fix.jpg ) Filters feel a lot like those used on Instagram. They are neat and cool, of course, covering many of the demands for sophisticated editing. You can find filters like Lomo-ish, Old Fashioned, Heat Map, Cartoon, Cross Process, Festival and much more on YouTube Enhancements. You can also adjust the lighting and colors, so as to fine-tune your video. ![YouTube Filters](https://images.wondershare.com/filmora/article-images/youtube-filters.jpg ) Blurring Effects are perhaps the most advanced on YouTube Enhancements, and they provide the opportunity to maintain your privacy, by removing people’s distinctive details from the video and blurring them or putting mosaic on their face. With this tool, you can also blur objects on the video, which can increase your privacy even more. For instance, you can blur the plates of your car or your address. Last, there are some hilarious effects that you should check out. ![YouTube Costum Blurring](https://images.wondershare.com/filmora/article-images/youtube-costum-blurring.jpg ) Once you are done, there is an option to preview the video that you have edited. In this way, you will know if the editions that you have made are sufficient for you or not. Finally, you can choose either to save the video as a new file or revert to the original video. These options are welcome, as sometimes you just do not get what you have expected and you do not want to replace the video you have already uploaded. ## How to Use Wondershare Filmora to improve YouTube videos These are the steps that you need to follow, so as to proceed with high-quality video editing on Filmora: * Open Wordershare Filmora * Choose if you want 16:9 or 4:3 aspect ratio * Tap Import so as to upload the files * Drag and drop them, in order to place them in the right order ![Import Video](https://images.wondershare.com/filmora/article-images/import-videos.jpg ) * Click Edit and adjust the settings (rotation, contrast, saturation, brightness, hue, auto de-noise and speed) ![Adjust Contrast Saturation](https://images.wondershare.com/filmora/article-images/adjust-contrast-saturation.jpg ) * Click OK, and you are done with the improvement of Video Quality If you wish to fine-tune the images of the videos and place special filters, you can go ahead as follows: * Tap the Effect button * Drag the effect you want to use on the timeline (you can choose from a wide variety of effects, including Bokeh and Light Leaks, Old Film, etc.) ![Free Movie Special Effect](https://images.wondershare.com/filmora/article-images/free-movie-special-effects.jpg ) After having finished with the video editing process, you can preview the video and see if it is of acceptable quality standards. You can do that by clicking on the Play button. Then you can click on the Create button and save the video where you want, in the format of your choosing. It is also possible for you to burn the video on a DVD or share it online using YouTube or Facebook. ![Format Supported by Filmora](https://images.wondershare.com/filmora/article-images/format-supported-by-filmora.png ) [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins>
import * as React from 'react'; import Button from '@mui/material/Button'; import TextField from '@mui/material/TextField'; import Dialog from '@mui/material/Dialog'; import DialogActions from '@mui/material/DialogActions'; import DialogContent from '@mui/material/DialogContent'; import DialogTitle from '@mui/material/DialogTitle'; export default function AddCustomer({ addCustomer }) { const [open, setOpen] = React.useState(false); const [customer, setCustomer] = React.useState( { firstname: '', lastname: '', email: '', phone: '', streetaddress: '', postcode: '', city: '' } ); const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const handleCreate = () => { addCustomer(customer); handleClose(); setCustomer( { firstname: '', lastname: '', email: '', phone: '', streetaddress: '', postcode: '', city: '' } ) }; return ( <div> <Button variant="outlined" onClick={handleClickOpen}> Add a new customer </Button> <Dialog open={open} onClose={handleClose}> <DialogTitle>Add a new customer</DialogTitle> <DialogContent> <TextField autoFocus value={customer.firstname} onChange={e => setCustomer({ ...customer, firstname: e.target.value })} margin="dense" label="First name" fullWidth variant="standard" /> <TextField autoFocus value={customer.lastname} onChange={e => setCustomer({ ...customer, lastname: e.target.value })} margin="dense" label="Last name" fullWidth variant="standard" /> <TextField autoFocus value={customer.email} onChange={e => setCustomer({ ...customer, email: e.target.value })} margin="dense" label="Email" fullWidth variant="standard" /> <TextField autoFocus value={customer.phone} onChange={e => setCustomer({ ...customer, phone: e.target.value })} margin="dense" label="Phone" fullWidth variant="standard" /> <TextField autoFocus value={customer.streetaddress} onChange={e => setCustomer({ ...customer, streetaddress: e.target.value })} margin="dense" label="Street address" fullWidth variant="standard" /> <TextField autoFocus value={customer.postcode} onChange={e => setCustomer({ ...customer, postcode: e.target.value })} margin="dense" label="Postcode" fullWidth variant="standard" /> <TextField autoFocus value={customer.city} onChange={e => setCustomer({ ...customer, city: e.target.value })} margin="dense" label="City" fullWidth variant="standard" /> </DialogContent> <DialogActions> <Button onClick={handleClose}>Cancel</Button> <Button onClick={handleCreate}>Add</Button> </DialogActions> </Dialog> </div> ); }
# --- Amy Jiravisitcul. 2 Apr 2022 ---- rm(list = ls()) # clear working environment setwd("~/Downloads/States from Fall 2021/") install.packages("tidyverse") # install tidyverse library(tidyverse) install.packages("readxl") # CRAN version library(readxl) install.packages("ggplot2") library(ggplot2) install.packages("data.table") library(data.table) install.packages('segregation') library(segregation) getwd() # Data downloaded https://rptsvr1.tea.texas.gov/perfreport/tapr/2021/xplore/DownloadSelData.html # --- FULL SCHOOL-LEVEL ENROLLMENT FILE ------ enrl <- read.csv('raw data/TX_CSTUD.csv') names(enrl) <- tolower(names(enrl)) str(enrl) # variable documentation https://rptsvr1.tea.texas.gov/perfreport/tapr/2021/xplore/cstud.html enrl <- enrl %>% mutate(district = case_when(campname == "MAGNOLIA MONTESSORI FOR ALL" ~ "AUSTIN ISD", campname == "THE GATHERING PLACE" ~ "NORTHSIDE ISD", TRUE ~ distname), school = campname, total = cpntallc, amind = cpntindc, asian = cpntasic + cpntpcic, black = cpntblac, hisp = cpnthisc, white = cpntwhic, mult = cpnttwoc, ecdis = cpntecoc, el = cpntlepc, swd = cpntspec) %>% select(district:swd) aisd <- enrl %>% filter(district == "AUSTIN ISD") %>% group_by(district) %>% summarize(dist_total = sum(total), dist_amind = sum(amind)/sum(total), dist_asian = sum(asian)/sum(total), dist_black = sum(black)/sum(total), dist_hisp = sum(hisp)/sum(total), dist_white = sum(white)/sum(total), dist_mult = sum(mult)/sum(total), dist_ecdis = sum(ecdis)/sum(total), dist_el = sum(el)/sum(total), dist_swd = sum(swd)/sum(total)) nisd <- enrl %>% filter(district == "NORTHSIDE ISD") %>% group_by(district) %>% summarize(dist_total = sum(total), dist_amind = sum(amind)/sum(total), dist_asian = sum(asian)/sum(total), dist_black = sum(black)/sum(total), dist_hisp = sum(hisp)/sum(total), dist_white = sum(white)/sum(total), dist_mult = sum(mult)/sum(total), dist_ecdis = sum(ecdis)/sum(total), dist_el = sum(el)/sum(total), dist_swd = sum(swd)/sum(total)) memb_enrl <- enrl %>% filter(str_detect(school, "MAGNOLIA MONT")| str_detect(school, "GATHERING PL")) %>% mutate(amind = amind/total, asian = asian/total, black = black/total, hisp = hisp/total, white = white/total, mult = mult/total, ecdis = ecdis/total, el = el/total, swd = swd/total) %>% merge(rbind(aisd,nisd)) aisd_ls <- enrl %>% filter(district == "AUSTIN ISD") %>% select(school, amind:mult) %>% gather(race, n, amind:mult) %>% mutual_local("race","school", weight = "n", wide = TRUE) %>% mutate(ls_dist = ls) %>% select(school, ls_dist) nisd_ls <- enrl %>% filter(district == "NORTHSIDE ISD") %>% select(school, amind:mult) %>% gather(race, n, amind:mult) %>% mutual_local("race","school", weight = "n", wide = TRUE) %>% mutate(ls_dist = ls) %>% select(school, ls_dist) memb_enrl <- memb_enrl %>% merge(rbind(aisd_ls, nisd_ls)) # county level # Bexar County includes San Antonio https://www.bexar.org/QuickLinks.aspx?CID=38 memb_enrl$county <- c("Travis County","Bexar County") bexar <- enrl %>% filter(district == "ALAMO HEIGHTS ISD"| district == "BASIS TEXAS"| district == "BEXAR COUNTY ACADEMY"| district == "BROOKS ACADEMIES OF TEXAS"| district == "BOERNE ISD"| district == "COMPASS ROSE ACADEMY"| district == "EAST CENTRAL ISD"| district == "EDGEWOOD ISD"| district == "ELEANOR KOLITZ HEBREW LANGUAGE ACA"| district == "FT SAM HOUSTON ISD"| district == "GEORGE GERVIN ACADEMY"| district == "GREAT HEARTS TEXAS"| district == "HARLANDALE ISD"| district == "HARMONY SCIENCE ACAD (SAN ANTONIO)"| district == "HENRY FORD ACADEMY ALAMEDA SCHOOL"| district == "HERITAGE ACADEMY"| district == "INSPIRE ACADEMIES"| district == "JUBILEE ACADEMIES"| district == "JUDSON ISD"| district == "LACKLAND ISD"| district == "LIGHTHOUSE PUBLIC SCHOOLS"| district == "NEW FRONTIERS PUBLIC SCHOOLS INC"| district == "NORTH EAST ISD"| district == "NORTHSIDE ISD"| district == "POR VIDA ACADEMY"| district == "POSITIVE SOLUTIONS CHARTER SCHOOL"| district == "PROMESA ACADEMY CHARTER SCHOOL"| district == "RANDOLPH FIELD ISD"| district == "SAN ANTONIO ISD"| district == "SAN ANTONIO PREPARATORY CHARTER SC"| district == "SCHOOL OF EXCELLENCE IN EDUCATION"| district == "SCHOOL OF SCIENCE AND TECHNOLOGY"| district == "SCHOOL OF SCIENCE AND TECHNOLOGY D"| district == "SOMERSET ISD"| district == "SOUTH SAN ANTONIO ISD"| district == "SOUTHSIDE ISD"| district == "SOUTHWEST ISD"| district == "SOUTHWEST PREPARATORY SCHOOL") bexar_ls <- bexar %>% select(school, amind:mult) %>% gather(race, n, amind:mult) %>% mutual_local("race","school", weight = "n", wide = TRUE) %>% mutate(ls_cty = ls) %>% select(school, ls_cty) bexar_agg <- bexar %>% mutate(county = "Bexar County") %>% group_by(county) %>% summarize(cty_total = sum(total), cty_amind = sum(amind)/sum(total), cty_asian = sum(asian)/sum(total), cty_black= sum(black)/sum(total), cty_hisp = sum(hisp)/sum(total), cty_white = sum(white)/sum(total), cty_mult = sum(mult)/sum(total), cty_ecdis = sum(ecdis)/sum(total), cty_el = sum(el)/sum(total), cty_swd = sum(swd)/sum(total)) # Travis County's districts https://rptsvr1.tea.texas.gov/cgi/sas/broker travis <- enrl %>% filter(district == "AUSTIN ISD"| district == "AUSTIN ACHIEVE PUBLIC SCHOOLS"| district == "AUSTIN DISCOVERY"| district == "CEDARS INTERNATIONAL ACADEMY"| district == "CHAPARRAL STAR ACADEMY"| district == "DEL VALLE ISD"| district == "EANES ISD"| district == "HARMONY SCIENCE ACADEMY (AUSTIN)"| district == "KIPP TEXAS PUBLIC SCHOOLS"| district == "LAGO VISTA ISD"| district == "LAKE TRAVIS ISD"| district == "MANOR ISD"| district == "NYOS CHARTER SCHOOL"| district == "PFLUGERVILLE ISD"| district == "PROMESA PUBLIC SCHOOLS"| district == "TEXAS EMPOWERMENT ACADEMY"| district == "THE EXCEL CENTER (FOR ADULTS)"| district == "UNIVERSITY OF TEXAS AT AUSTIN H S"| district == "UNIVERSITY OF TEXAS ELEMENTARY CHA"| district == "UNIVERSITY OF TEXAS UNIVERSITY CHA"| district == "VALOR PUBLIC SCHOOLS"| district == "WAYSIDE SCHOOLS") travis_agg <- travis %>% mutate(county = "Travis County") %>% group_by(county) %>% summarize(cty_total = sum(total), cty_amind = sum(amind)/sum(total), cty_asian = sum(asian)/sum(total), cty_black= sum(black)/sum(total), cty_hisp = sum(hisp)/sum(total), cty_white = sum(white)/sum(total), cty_mult = sum(mult)/sum(total), cty_ecdis = sum(ecdis)/sum(total), cty_el = sum(el)/sum(total), cty_swd = sum(swd)/sum(total)) travis_ls <- travis %>% select(school, amind:mult) %>% gather(race, n, amind:mult) %>% mutual_local("race","school", weight = "n", wide = TRUE) %>% mutate(ls_cty = ls) %>% select(school, ls_cty) memb_enrl <- memb_enrl %>% merge(rbind(travis_agg,bexar_agg)) %>% merge(rbind(travis_ls, bexar_ls)) %>% select(school, total:swd, ls_dist, ls_cty, district, dist_total:dist_swd, county, cty_total:cty_swd) write.csv(memb_enrl, file = file.path('output data/tx_enrl.csv'), row.names = FALSE)
export function calculateAge(birthday: any) { var ageDifMs = Date.now() - birthday; var ageDate = new Date(ageDifMs); // miliseconds from epoch return Math.abs(ageDate.getUTCFullYear() - 1970); } export function generateAvatar(name: string) { return `https://ui-avatars.com/api/?name=${name}&background=random`; } export function truncateText(text: string, maxLength: number) { if (text.length <= maxLength) { return text; } if (maxLength < 3) { return text.slice(0, maxLength); } return text.slice(0, maxLength - 3) + '...'; } export function getRandomLightColor() { // Generate random values for hue (0-360) and saturation (30-100). const hue = Math.floor(Math.random() * 361); const saturation = Math.floor(Math.random() * 71) + 30; // range: 30-100 // Convert HSL to RGB with a higher lightness value (35-70%) for a lighter color. const rgb = hslToRgb(hue, saturation, Math.floor(Math.random() * 26) + 35); // range: 35-70 // Convert the RGB components to a hexadecimal string representation. const colorHex = `#${componentToHex(rgb[0])}${componentToHex(rgb[1])}${componentToHex(rgb[2])}`; return colorHex; } function hslToRgb(h: number, s: number, l: number) { h /= 360; s /= 100; l /= 100; let r, g, b; if (s === 0) { r = g = b = l; // achromatic } else { const hue2rgb = (p: number, q: number, t: number) => { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; }; const q = l < 0.5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1 / 3); } return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; } function componentToHex(component: number) { const hex = component.toString(16); return hex.length === 1 ? '0' + hex : hex; } export function matchRoute(route: string, basePath: string, exact = false): boolean { if (exact) { return route === basePath; } // Create a regular expression pattern based on the dashboard base path const dashboardPattern = new RegExp(`^${basePath}(/[a-zA-Z0-9_-]+)*$`); // Check if the route matches the dashboard pattern return dashboardPattern.test(route); } export function CheckElectionStatus(_startDate: Date, _endDate: Date) { const currentDate: Date = new Date(); const startDate = new Date('10/09/2023'); const endDate = new Date(_endDate); // Extract the day, month, and year components of the dates const currentDay: Date = new Date( currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate() ); const startDay: Date = new Date( startDate.getFullYear(), startDate.getMonth(), startDate.getDate() ); const endDay: Date = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate()); console.log(currentDay, startDay); // Compare the current day with the start and end days if (currentDay > startDay) { return 'Not started'; } if (currentDay >= startDay && currentDay <= endDay) { return 'Active'; // User can vote } else { return 'Ended'; // User cannot vote } } // // Example usage: // const startDate: Date = new Date('2023-09-17'); // Replace with your start date // const endDate: Date = new Date('2023-09-17'); // Replace with your end date // if (CheckElectionStatus(startDate, endDate)) { // console.log('You can vote!'); // } else { // console.log('Voting is not allowed today.'); // } enum ElectionStatus { NotStarted, Active, Ended, } function _getElectionStatus(startDate: Date, endDate: Date): ElectionStatus { const currentDate: Date = new Date(); const currentDay: number = currentDate.getDate(); const currentMonth: number = currentDate.getMonth(); const currentYear: number = currentDate.getFullYear(); const startDay: number = new Date(startDate).getDate(); const startMonth: number = new Date(startDate).getMonth(); const startYear: number = new Date(startDate).getFullYear(); const endDay: number = new Date(endDate).getDate(); const endMonth: number = new Date(endDate).getMonth(); const endYear: number = new Date(endDate).getFullYear(); if ( currentYear < startYear || (currentYear === startYear && (currentMonth < startMonth || (currentMonth === startMonth && currentDay < startDay))) ) { return ElectionStatus.NotStarted; } else if ( currentYear > endYear || (currentYear === endYear && (currentMonth > endMonth || (currentMonth === endMonth && currentDay > endDay))) ) { return ElectionStatus.Ended; } else { return ElectionStatus.Active; } } export function getElectionStatus(startDate: Date, endDate: Date) { const electionStatus: ElectionStatus = _getElectionStatus(startDate, endDate); switch (electionStatus) { case ElectionStatus.NotStarted: return 'Pending'; break; case ElectionStatus.Active: return 'Active'; break; case ElectionStatus.Ended: return 'Completed'; break; default: return 'Invalid election status.'; } }
package mz.org.fgh.sifmoz.backend.therapeuticRegimen import grails.converters.JSON import grails.rest.RestfulController import grails.validation.ValidationException import mz.org.fgh.sifmoz.backend.utilities.JSONSerializer import static org.springframework.http.HttpStatus.CREATED import static org.springframework.http.HttpStatus.NOT_FOUND import static org.springframework.http.HttpStatus.NO_CONTENT import static org.springframework.http.HttpStatus.OK import static org.springframework.http.HttpStatus.UNPROCESSABLE_ENTITY import grails.gorm.transactions.ReadOnly import grails.gorm.transactions.Transactional class TherapeuticRegimenController extends RestfulController{ TherapeuticRegimenService therapeuticRegimenService static responseFormats = ['json', 'xml'] static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"] TherapeuticRegimenController() { super(TherapeuticRegimen) } def index(Integer max) { params.max = Math.min(max ?: 10, 100) render JSONSerializer.setObjectListJsonResponse(therapeuticRegimenService.list(params)) as JSON } def show(String id) { render JSONSerializer.setJsonObjectResponse(therapeuticRegimenService.get(id)) as JSON } @Transactional def save(TherapeuticRegimen therapeuticRegimen) { if (therapeuticRegimen == null) { render status: NOT_FOUND return } if (therapeuticRegimen.hasErrors()) { transactionStatus.setRollbackOnly() respond therapeuticRegimen.errors return } try { therapeuticRegimenService.save(therapeuticRegimen) } catch (ValidationException e) { respond therapeuticRegimen.errors return } respond therapeuticRegimen, [status: CREATED, view:"show"] } @Transactional def update(TherapeuticRegimen therapeuticRegimen) { if (therapeuticRegimen == null) { render status: NOT_FOUND return } if (therapeuticRegimen.hasErrors()) { transactionStatus.setRollbackOnly() respond therapeuticRegimen.errors return } try { therapeuticRegimenService.save(therapeuticRegimen) } catch (ValidationException e) { respond therapeuticRegimen.errors return } respond therapeuticRegimen, [status: OK, view:"show"] } @Transactional def delete(Long id) { if (id == null || therapeuticRegimenService.delete(id) == null) { render status: NOT_FOUND return } render status: NO_CONTENT } }
<div class="row"> <p *ngIf="!tasks"><em>Loading...</em></p> <button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal">New task</button> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Create a new task</h4> </div> <form name="createForm" role="form" #createForm="ngForm"> <div class="modal-body"> <div class="form-group"> <label for="field_name">Name</label> <input type="text" class="form-control" id="field_name" placeholder="Enter the name of this task" name="name" [(ngModel)]="newTask.name" required /> </div> <div class="form-group"> <label for="field_description">Description</label> <input type="text" class="form-control" id="field_description" placeholder="Enter the description of this task" name="description" [(ngModel)]="newTask.description" required /> </div> <div class="form-group"> <label for="field_dueDate">Due Date</label> <div class="d-flex"> <input id="field_dueDate" type="datetime-local" class="form-control" name="dueDate" [(ngModel)]="newTask.dueDate" required /> </div> </div> </div> <div class="modal-footer"> <button type="submit" [disabled]="createForm.form.invalid" class="btn btn-primary" data-dismiss="modal" (click)="add()">Create</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </form> </div> </div> </div> <div class="table-responsive" *ngIf="tasks"> <p *ngIf="tasks.length == 0">This project contains no tasks</p> <table class='table' *ngIf="tasks.length > 0"> <thead> <tr> <th>Task Name</th> <th>Task Description</th> <th>Reporter</th> <th>Status</th> <th *hasAnyAuthority="'Admin'">Operations</th> </tr> </thead> <tbody> <tr *ngFor="let task of tasks"> <td><a [routerLink]="['/task', task.id ]">{{task.name}}</a></td> <td>{{ task.description }}</td> <td *ngIf="task.reporter">{{ task.reporter.userName }}</td> <td *ngIf="!task.reporter">-</td> <td> <span *ngIf="task.status == true" class="label label-success">Done</span> <span *ngIf="task.status == false" class="label label-info">In work</span> </td> <td *hasAnyAuthority="'Admin'"><button class="btn btn-default" (click)="remove(task)">Delete</button></td> </tr> </tbody> </table> </div> </div>
import { Injectable } from '@angular/core'; import { Action, Selector, State, StateContext } from '@ngxs/store'; import { tap } from 'rxjs/operators'; import { patch } from '@ngxs/store/operators'; import { UserListDataService } from '../services/user-list-data.service'; import { GetUserList } from './user-list.actions'; import { UserModel } from '../model/user.model'; export interface UserListStateModel { users: UserModel[]; } @State<UserListStateModel>({ name: 'userList', defaults: { users: null, }, }) @Injectable() export class UserListState { constructor(private userDataService: UserListDataService) {} @Selector() static getUsers(state: UserListStateModel) { return state.users; } @Action(GetUserList) getUserList(ctx: StateContext<UserListStateModel>) { return this.userDataService.getUsers().pipe(tap((response) => ctx.setState(patch({ users: response })))); } }
#pragma once #include "clock_time.h" class Clock{ public: Clock(int hour, int minute, int second, double driftPerSecond); virtual ~Clock(); void reset(); void tick(); virtual void displayTime() = 0; protected: ClockTime _clockTime; double _driftPerSecond; double _totalDrift; }; class NaturalClock:public Clock{ public: virtual ~NaturalClock(); NaturalClock(int hour, int minute, int second, double driftPerSecond); virtual void displayTime() = 0; }; class MechanicalClock:public Clock{ public: virtual ~MechanicalClock(); MechanicalClock(int hour, int minute, int second, double driftPerSecond); virtual void displayTime() = 0; }; class DigitalClock:public Clock{ public: virtual ~DigitalClock(); DigitalClock(int hour, int minute, int second, double driftPerSecond); virtual void displayTime() = 0; }; class QuantumClock:public Clock{ public: virtual ~QuantumClock(); QuantumClock(int hour, int minute, int second, double driftPerSecond); virtual void displayTime() = 0; }; class SundialClock:public NaturalClock{ public: virtual ~SundialClock(); SundialClock(int hour, int minute, int second); virtual void displayTime(); }; class CuckooClock:public MechanicalClock{ public: virtual ~CuckooClock(); CuckooClock(int hour, int minute, int second); virtual void displayTime(); }; class GrandFatherClock:public MechanicalClock{ public: virtual ~GrandFatherClock(); GrandFatherClock(int hour, int minute, int second); virtual void displayTime(); }; class WristClock:public DigitalClock{ public: virtual ~WristClock(); WristClock(int hour, int minute, int second); virtual void displayTime(); }; class AtomicClock:public QuantumClock{ public: virtual ~AtomicClock(); AtomicClock(int hour, int minute, int second); virtual void displayTime(); };
import { useEffect, useState } from "react"; import { Button, Col, Container, Image, Row } from "react-bootstrap"; import { FormattedMessage, useIntl } from "react-intl"; import { useNavigate, useParams } from "react-router-dom"; import { getUsuarioById } from "../../../helpers/backend/usuarioBackend"; import "./UsuarioDetail.css"; function UsuarioDetail() { const navigate = useNavigate(); const intl = useIntl(); const txtExperience = intl.formatMessage({ id: 'experience' }); const txtProfilePicture = intl.formatMessage({ id: 'profile-picture' }); const params = useParams(); const token = localStorage.getItem("sessionToken"); const [usuario, setUsuario] = useState(); const [titulo, setTitulo] = useState(); const [experiencia, setExperiencia] = useState(); const [habilidades, setHabilidades] = useState(); const [antecedentes, setAntecedentes] = useState(); const [isCanguro, setIsCanguro] = useState(null); const [btnStatus, setBtnStatus] = useState(false); const usuarioId = params.usuarioId; function loadDetail (newUsuario) { if(isCanguro === null) { setIsCanguro(newUsuario.tipoUsuario.toLowerCase() !== "canguro"); } if(newUsuario.antecedentes.length === 0) { setAntecedentes(<li><FormattedMessage id="no-legal-background"/></li>) } else { setAntecedentes(newUsuario.antecedentes.map((ant) => <li>{ant.tipo}</li>)) } if(!isCanguro) { setTitulo(<h2><FormattedMessage id="abilities"/>:</h2>) setExperiencia(newUsuario.aniosExperiencia + " " + txtExperience) if (newUsuario.especialidades.length === 0) { setHabilidades(<li><FormattedMessage id="no-abilities"/></li>) } else { setHabilidades(newUsuario.especialidades.map((nec) => <li>{nec.tipo}</li>)) } setTitulo(<h2><FormattedMessage id="abilities"/>:</h2>) } else { setTitulo(<h2><FormattedMessage id="needs"/>:</h2>) setExperiencia("") if (newUsuario.necesidades.length === 0) { setHabilidades(<li><FormattedMessage id="no-needs"/></li>) } else { setHabilidades(newUsuario.necesidades.map((nec) => <li>{nec.tipo}</li>)) } } if(newUsuario.tipoUsuario.toLowerCase() !== "ambos") { setBtnStatus(true) } } useEffect( () => { console.log("Hay Internet?" + navigator.onLine) if(!navigator.onLine) { if(localStorage.getItem('userData') === null) { console.log("No hay datos en local storage") } else { const u = JSON.parse(localStorage.getItem('userData')); setUsuario(u); loadDetail(u); } } else { console.log("Hay internet") // Get of the user with the given id getUsuarioById(usuarioId).then((newUsuario) => { // If inexistent user, redirect to error page if (newUsuario.statusCode !== 500) { setUsuario(newUsuario); loadDetail(newUsuario); } else { navigate("/error"); } }); } }, [usuarioId, isCanguro, txtExperience] ); if (!token) { // return <Navigate to="/error"></Navigate>; } const changeBtnStatus = (tipo) => { if(tipo === isCanguro) { setIsCanguro(!isCanguro); } }; const seeOfertas = () => { navigate(`/usuarios/${usuarioId}/ofertas`); }; const seeResenias = () => { navigate('/resenias/user', { state: { usuarioId } }); }; const addResenia = () => { navigate('/resenias/new', { state: { usuarioId } }); }; const seeContratos = () => { navigate('/contratos/user', { state: { usuarioId } }); }; if (usuario) { return ( <Container className="usuario--detalle"> <Row className="center"> <Button className="btn-t2 small" type="button" disabled={btnStatus} onClick={() => changeBtnStatus(true)}><FormattedMessage id="kangaroo"/></Button> <Button className="btn-t2 small" type="button" disabled={btnStatus} onClick={() => changeBtnStatus(false)}><FormattedMessage id="guardian"/></Button> </Row> <Row className="lr-margin"> <Col className="info"> <Row> <h1 className="usuario--nombre">{usuario.nombre}</h1> </Row> <Row> <Col className="usuario--tipo" xs={2}> <FormattedMessage id={usuario.tipoUsuario}/> </Col> <Col className="usuario--exp"> {experiencia} </Col> </Row> {titulo} <ul> {habilidades} </ul> <h2><FormattedMessage id="contact-methods"/>:</h2> <ul> <li> <FormattedMessage id="email"/>: {usuario.correoElectronico} </li> <li> <FormattedMessage id="phone"/>: {usuario.celular} </li> </ul> <h2><FormattedMessage id="legal-background"/>:</h2> <ul> {antecedentes} </ul> </Col> <Col> <Row className="add-foto"> <Image className="foto" alt={`${txtProfilePicture} ${usuario.nombre}`} src={usuario.foto} /> </Row> </Col> </Row> <Row className="center"> <Button className="btn-t1 big" type="button" onClick={seeOfertas}><FormattedMessage id="view-offers"/></Button> <Button className="btn-t2 big" type="button" onClick={addResenia}><FormattedMessage id="add-review"/></Button> <Button className="btn-t1 big" type="button" onClick={seeResenias}><FormattedMessage id="view-reviews"/></Button> <Button className="btn-t2 big" type="button" onClick={seeContratos}><FormattedMessage id="view-contracts"/></Button> </Row> </Container> ); } else { navigate('/error'); } } export default UsuarioDetail;
// Copyright Maxjestic. #include "Weapon/Weapon.h" #include "Character/BlasterCharacter.h" #include "Components/SphereComponent.h" #include "Components/WidgetComponent.h" #include "Net/UnrealNetwork.h" AWeapon::AWeapon() { PrimaryActorTick.bCanEverTick = false; bReplicates = true; WeaponMesh = CreateDefaultSubobject<USkeletalMeshComponent>( "WeaponMesh" ); SetRootComponent( WeaponMesh ); WeaponMesh->SetCollisionResponseToAllChannels( ECR_Block ); WeaponMesh->SetCollisionResponseToChannel( ECC_Pawn, ECR_Ignore ); WeaponMesh->SetCollisionEnabled( ECollisionEnabled::NoCollision ); AreaSphere = CreateDefaultSubobject<USphereComponent>( "AreaSphere" ); AreaSphere->SetupAttachment( RootComponent ); AreaSphere->SetCollisionResponseToAllChannels( ECR_Ignore ); AreaSphere->SetCollisionEnabled( ECollisionEnabled::NoCollision ); PickupWidget = CreateDefaultSubobject<UWidgetComponent>( "PickupWidget" ); PickupWidget->SetupAttachment( RootComponent ); } void AWeapon::BeginPlay() { Super::BeginPlay(); if ( HasAuthority() ) { AreaSphere->SetCollisionResponseToChannel( ECC_Pawn, ECR_Overlap ); AreaSphere->SetCollisionEnabled( ECollisionEnabled::QueryAndPhysics ); AreaSphere->OnComponentBeginOverlap.AddDynamic( this, &ThisClass::OnSphereBeginOverlap ); AreaSphere->OnComponentEndOverlap.AddDynamic( this, &ThisClass::OnSphereEndOverlap ); } if ( PickupWidget ) { PickupWidget->SetVisibility( false ); } } void AWeapon::Tick( float DeltaTime ) { Super::Tick( DeltaTime ); } void AWeapon::GetLifetimeReplicatedProps( TArray<FLifetimeProperty>& OutLifetimeProps ) const { Super::GetLifetimeReplicatedProps( OutLifetimeProps ); DOREPLIFETIME( AWeapon, WeaponState ); } void AWeapon::OnSphereBeginOverlap( UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult ) { ABlasterCharacter* BlasterCharacter = Cast<ABlasterCharacter>( OtherActor ); if ( BlasterCharacter && PickupWidget ) { BlasterCharacter->SetOverlappingWeapon( this ); } } void AWeapon::OnSphereEndOverlap( UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex ) { ABlasterCharacter* BlasterCharacter = Cast<ABlasterCharacter>( OtherActor ); if ( BlasterCharacter && PickupWidget ) { BlasterCharacter->SetOverlappingWeapon( nullptr ); } } void AWeapon::OnRep_WeaponState() { SetWeaponState( WeaponState ); } void AWeapon::ShowPickupWidget( const bool bShowWidget ) const { if ( PickupWidget ) { PickupWidget->SetVisibility( bShowWidget ); } } void AWeapon::SetWeaponState( const EWeaponState State ) { WeaponState = State; switch ( WeaponState ) { case EWeaponState::EWS_Equipped: ShowPickupWidget( false ); AreaSphere->SetCollisionEnabled( ECollisionEnabled::NoCollision ); break; default: break; } }
package nl.hr.project3_4.straalbetaal.server.resources; import nl.hr.project3_4.straalbetaal.api.*; import nl.hr.project3_4.straalbetaal.server.services.Service; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; @Path("/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class Resource { private static final Logger LOG = Logger.getLogger(Resource.class.getName()); // Making Service static, making sure 1 Service instance is used for all request! private Service serv = new Service(); @GET @Path("/{IBAN}&{pincode}") public String getUserID(@PathParam("IBAN") String iban, @PathParam("pincode") long pincode) { LOG.info("Get request for userID with IBAN: " + iban + " and pincode: " + pincode); // JSON format -> Probably gonna use a Json format for clarity return ("{\"userid\":\"" + serv.getUserID(iban, pincode) + "\"}"); } /* * This and the method above could have been done together, but * because the DAO methods should have only 1 particular task, I * spread the calls into 2 different methods. */ @GET @Path("/{IBAN}&{pincode}/balance") public Long getBalance(@PathParam("IBAN") String iban) { LOG.info("Get request for balance with IBAN: " + iban); return serv.getBalance(iban); } @POST @Path("/{IBAN}&{pincode}/withdraw") public WithdrawResponse withdraw(@PathParam("IBAN") String iban, WithdrawRequest request) { WithdrawResponse response = new WithdrawResponse(); LOG.info("Post request for withdraw with IBAN: " + iban + " and amount: " + request.getAmount()); if(serv.withdraw(iban, request.getAmount())) { response.setResponse("Dank u voor pinnen."); response.setTransactionNumber(12345L); // Dummy return response; } else { response.setResponse("Saldo ontoereikend"); // throw new BadRequestException(Response.status(Response.Status.BAD_REQUEST).entity(response).build()); } return response; } }
import json import joblib import numpy as np import pandas as pd from flask import jsonify #=== === === === === === RESULT = "result" RESULT_FRAUD = "FRAUD" RESULT_NOT_FRAUD = "NOT-FRAUD" RESULT_UNKNOWN = "UNKNOWN" RESULT_ERROR = "ERROR" DATA_EMPTY_VALUE = "-" def post(request): homo_json = "" try: # getting the JSON data from the request data_json = request.json # getting field features names_list, fields_dict = load_fields() # validating the presence of parameters validate(names_list, fields_dict, data_json) # homologating values homo_json = homologate(names_list, fields_dict, data_json) # getting the prediction result = prediction(homo_json) # saging the data save_data(names_list, data_json, homo_json, result) response = {RESULT: result} return jsonify(response) except Exception as ex: # throwing the error in result error_msg = RESULT_ERROR+': '+str(ex.args[0]) save_data(names_list, data_json, homo_json, error_msg) response = {RESULT: error_msg} return jsonify(response), 400 # 400 Bad Request #=== === === === === === #=== === === === === === def get_field_by_name(fields_list, name): for field in fields_list: if field.get("name") == name: return field return None def load_fields(): fields_path = "data/fields.json" with open(fields_path, "r") as json_file: fields_list = json.load(json_file) names_list = [field["name"] for field in fields_list] fields_dict = { } for name in names_list: fields_dict[name] = get_field_by_name(fields_list, name) return names_list, fields_dict #=== === === === === === def validate(names_list, fields_dict, data_json): params_unknown_list = [ ] for key, value in data_json.items(): if not key in names_list: params_unknown_list.append(key) if len(params_unknown_list) > 0: raise Exception("Unknown Parameters: "+", ".join(params_unknown_list)) params_missed_list = [ ] for name in names_list: if fields_dict.get(name)["required"] in (True, "true"): if not name in data_json: params_missed_list.append(name) elif is_null_or_empty(data_json[name]): params_missed_list.append(name) if len(params_missed_list) > 0: raise Exception("Required Parameters: "+", ".join(params_missed_list)) params_nums_out_range_list = [ ] for name in names_list: if name in data_json and not is_null_or_empty(data_json[name]) \ and fields_dict.get(name)["type"] in ("number", "decimal"): if "min" in fields_dict.get(name): if float(data_json[name]) < int(fields_dict.get(name)["min"]): params_nums_out_range_list.append(name) if "max" in fields_dict.get(name): if float(data_json[name]) > int(fields_dict.get(name)["max"]): params_nums_out_range_list.append(name) if len(params_nums_out_range_list) > 0: raise Exception("Out of Range Parameters: "+", ".join(params_nums_out_range_list)) return names_list, fields_dict def is_null_or_empty(obj): if obj is None: return True elif isinstance(obj, str) and not obj.strip(): return True elif isinstance(obj, (list, tuple, dict, set)) and not obj: return True else: return False #=== === === === === === def homologate(names_list, fields_dict, data_json): homo_json = { } for name in names_list: # getting the final name to send to the model homo_name = name if 'encoded_name' in fields_dict[name]: homo_name = fields_dict[name]['encoded_name'] # if element is not sended, set null and continue if not name in data_json: homo_json[homo_name] = np.nan continue # if the value is null or empty, set null and continue value = data_json[name] if is_null_or_empty(value): homo_json[homo_name] = np.nan continue if 'encoded_func' in fields_dict[name] and fields_dict[name]['encoded_func']: variables = { 'value': value } exec(fields_dict[name]['encoded_func'], globals(), variables) result = variables.get('result') homo_json[homo_name] = result #continue # if there are not encoded list, set the value as float and continue if not 'encoded_list' in fields_dict[name]: homo_json[homo_name] = float(value) continue # getting the encoded list values_dict = { } list_filename = "models/"+fields_dict[name]['encoded_list'] with open(list_filename, "r") as json_file: values_dict = json.load(json_file) # if value is found, set the value as float and continue if value in values_dict: homo_json[homo_name] = float(values_dict[value]) continue elif str(value)+".0" in values_dict: homo_json[homo_name] = float(values_dict[str(value)+".0"]) continue # reached here, nothing more to do, set null homo_json[homo_name] = np.nan #print("data_json = ", data_json) #print("homo_json = ", homo_json) # returning the homologated JSON return homo_json #=== === === === === === def prediction(homo_json): model_filename = 'models/model_xgbv3_joblib.pkl' model_loaded = joblib.load(model_filename) homo_json["TransactionID"] = 0 dataframe_X = pd.DataFrame(homo_json, index=[0]) dataframe_X.set_index("TransactionID", inplace=True) dataframe_X = dataframe_X[model_loaded.get_booster().feature_names] y_pred = model_loaded.predict(dataframe_X) result = str(y_pred[0]) return RESULT_FRAUD if result == "1" else RESULT_NOT_FRAUD if result == "0" else RESULT_UNKNOWN #=== === === === === === def save_data(names_list, data_json, homo_json, result): data_filename = "data/data.csv" with open(data_filename, 'a') as file: result_normalized = '' if is_null_or_empty(result) else result.replace(',',';') homo_strg = str(homo_json).replace(',','; ').replace('\'','').replace('\"','') new_line = result_normalized + ', ' + json_csv_line(names_list, data_json) + ', ' + homo_strg file.write('\n'+new_line) def json_csv_line(names_list, data_json): values_list = [ ] for name in names_list: if name in data_json: if is_null_or_empty(data_json[name]): values_list.append(DATA_EMPTY_VALUE) else: values_list.append(str(data_json[name]).replace(',',';')) else: values_list.append(DATA_EMPTY_VALUE) return ', '.join(values_list) #=== === === === === ===
The aim of the Maybe type is to avoid using 'null' references. A Maybe<T> represents a possibly non-existent value of type T. The Maybe type makes it impossible (without deliberate effort to circumvent the API) to use the value when it does not exist. A Maybe<T> is either unknown(), in which case a known value does not exist, or definitely(v), in which case the value is known to be v. A Maybe<T> is iterable, which means you can use it with the for statement to extract a value and do something with it only if there is a value. class Customer { public Maybe<String> emailAddress() { ... } ... } for (String emailAddress : aCustomer.emailAddress()) { sendEmailTo(emailAddress); } Maybe<T> being iterable really comes into its own when combined with the Guava (previously google-collections) library, which has useful functions for working with iterables. You can then work in terms of entire collections of things that might or might not exist, without having to test for the existence of each one. For example, if I have a collection of 'maybe' email addresses, some of which might exist and some might not: Iterable<Maybe<String>> maybeEmailAddresses = ... I can get a set of only the actual email addresses in a single expression: Set<String> actualEmailAddresses = newHashSet(concat(maybeEmailAddresses)); The newHashSet and concat functions are defined by Guava. Concat creates an Iterable<T> from an Iterable<Iterable<T>>, concatenating the elements of each sequence into a single sequence. Because unknown() is an empty iterable, the concatenated iterable only returns the definite values. More likely, I have an iterable collection of Customers. Using a Function, I can write a single expression to get the email addresses of all customers who have an email address: Here's a function to map a customer to its 'maybe' email address: Function<Customer,Maybe<String>> toEmailAddress = new Function<Customer, Maybe<String>>() { public Maybe<String> apply(Customer c) { return c.emailAddress(); } }; And here's how to use it to get all the email addresses that my customers have, so I can send them product announcements: Set<String> emailAddresses = newHashSet( concat(transform(customers, toEmailAddress))); If I just want to send emails, I don't need the hash set: for (String emailAddress : concat(transform(customers, toEmailAddress))) { sendEmailTo(emailAddress); } The name "concat" is a bit obscure, so I'd probably define an alias named, for example, "definite", to make the code more readable at the point of use. And the Function definition is a bit clunky, but Java doesn't have (and doesn't look likely to get) a clean syntax for referring to existing functions. That's not to say that Maybe doesn't have useful methods to work with individual instances. For example, the otherwise method: T otherwise(T defaultValue); will return the Maybe's value if it is known and the defaultValue if it is not. E.g. assertThat(unknown().otherwise(""), equalTo("")); assertThat(definitely("foo").otherwise(""), equalTo("foo")); Otherwise is overloaded to take a Maybe<T> as a default: Maybe<T> otherwise(Maybe<T> maybeDefaultValue); which lets you chain otherwise expressions: assertThat(unknown().otherwise(definitely("X")).otherwise(""), equalTo("X")); Maybe also has a method that uses a function to map a Maybe<T> to a Maybe<U> <U> Maybe<U> to(Function<T,U> mapping); which would transform unknown() to unknown(), otherwise apply the function to the definite value and return the result wrapped in a Maybe. Similarly there is a query method that takes a Predicate<T> and maps a Maybe<T> to a Maybe<Boolean>. All of which API calls make it impossible (without deliberate effort) to try to get the value of nothing.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Font --> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet" /> <title>YouTube Clone</title> <link rel="stylesheet" href="css/style.css" /> <link rel="stylesheet" href="css/header.css" /> <link rel="stylesheet" href="css/sidebar.css" /> </head> <body> <header> <section class="left-section"> <img class="hamburger-menu" src="icons/hamburger-menu.svg" alt="" /> <img class="youtube-logo" src="icons/youtube-logo.svg" alt="" /> </section> <section class="middle-section"> <input class="search-bar" type="text" placeholder="Search" /> <button class="search-btn"> <img src="icons/search.svg" alt="" /> <div class="tooltip">Search</div> </button> <button class="voice-btn"> <img src="icons/voice-search-icon.svg" alt="" /> <div class="tooltip">Search with your voice</div> </button> </section> <section class="right-section"> <img class="right-section-icon" src="icons/upload.svg" alt="" /> <img class="right-section-icon" src="icons/youtube-apps.svg" alt="" /> <div class="notifications-container"> <img class="right-section-icon" src="icons/notifications.svg" alt="" /> <div class="notification-count">3</div> </div> <img class="my-channel-icon" src="thumbnails/my-channel.jpeg" alt="" /> </section> </header> <aside> <div class="menu-container"> <img class="side-icon" src="icons/home.svg" alt="" /> <p class="side-description">Home</p> </div> <div class="menu-container"> <img class="side-icon" src="icons/explore.svg" alt="" /> <p class="side-description">Explore</p> </div> <div class="menu-container"> <img class="side-icon" src="icons/subscriptions.svg" alt="" /> <p class="side-description">Subscriptions</p> </div> <div class="menu-container"> <img class="side-icon" src="icons/originals.svg" alt="" /> <p class="side-description">Originals</p> </div> <div class="menu-container"> <img class="side-icon" src="icons/youtube-music.svg" alt="" /> <p class="side-description">Youtube Music</p> </div> <div class="menu-container"> <img class="side-icon" src="icons/library.svg" alt="" /> <p class="side-description">Library</p> </div> </aside> <div class="video-grid"> <div class="video-preview"> <div class="thumbnail-row"> <img src="thumbnails/thumbnail-1.webp" alt="" /> </div> <div class="video-info-grid"> <div class="profile-picture"> <div class="profile-container"> <a href=""><img src="thumbnails/channel-1.jpeg" alt="" /></a> <div class="channel-tooltip"> <img src="thumbnails/channel-1.jpeg" alt="" /> <div> <p class="channel-name">Marques Brownlee</p> <p class="channel-subscriber">15M subscribers</p> </div> </div> </div> </div> <div class="video-info"> <p class="video-title"> Talking Tech and AI with Google CEO Sundar Pichai! </p> <p class="video-author">Marques Brownlee</p> <p class="video-stats">3.4M views &#183; 6 months ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <img src="thumbnails/thumbnail-2.webp" alt="" /> </div> <div class="video-info-grid"> <div class="profile-picture"> <img src="thumbnails/channel-2.jpeg" alt="" /> </div> <div class="video-info"> <p class="video-title">Try Not To Laugh Challenge #9</p> <p class="video-author">Markiplier</p> <p class="video-stats">19M views &#183; 4 years ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <img src="thumbnails/thumbnail-3.webp" alt="" /> </div> <div class="video-info-grid"> <div class="profile-picture"> <img src="thumbnails/channel-3.jpeg" alt="" /> </div> <div class="video-info"> <p class="video-title"> Crazy Tik Toks Taken Moments Before DISASTER </p> <p class="video-author">SSSniperWolf</p> <p class="video-stats">12M views &#183; 1 year ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <img src="thumbnails/thumbnail-4.webp" alt="" /> </div> <div class="video-info-grid"> <div class="profile-picture"> <img src="thumbnails/channel-4.jpeg" alt="" /> </div> <div class="video-info"> <p class="video-title"> The Simplest Math Problem No One Can Solve - Collatz Conjecture </p> <p class="video-author">Veritasium</p> <p class="video-stats">18M views &#183; 4 months ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <img src="thumbnails/thumbnail-1.webp" alt="" /> </div> <div class="video-info-grid"> <div class="profile-picture"> <img src="thumbnails/channel-1.jpeg" alt="" /> </div> <div class="video-info"> <p class="video-title"> Talking Tech and AI with Google CEO Sundar Pichai! </p> <p class="video-author">Marques Brownlee</p> <p class="video-stats">3.4M views &#183; 6 months ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <img src="thumbnails/thumbnail-2.webp" alt="" /> </div> <div class="video-info-grid"> <div class="profile-picture"> <img src="thumbnails/channel-2.jpeg" alt="" /> </div> <div class="video-info"> <p class="video-title">Try Not To Laugh Challenge #9</p> <p class="video-author">Markiplier</p> <p class="video-stats">19M views &#183; 4 years ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <img src="thumbnails/thumbnail-3.webp" alt="" /> </div> <div class="video-info-grid"> <div class="profile-picture"> <img src="thumbnails/channel-3.jpeg" alt="" /> </div> <div class="video-info"> <p class="video-title"> Crazy Tik Toks Taken Moments Before DISASTER </p> <p class="video-author">SSSniperWolf</p> <p class="video-stats">12M views &#183; 1 year ago</p> </div> </div> </div> <div class="video-preview"> <div class="thumbnail-row"> <img src="thumbnails/thumbnail-4.webp" alt="" /> </div> <div class="video-info-grid"> <div class="profile-picture"> <img src="thumbnails/channel-4.jpeg" alt="" /> </div> <div class="video-info"> <p class="video-title"> The Simplest Math Problem No One Can Solve - Collatz Conjecture </p> <p class="video-author">Veritasium</p> <p class="video-stats">18M views &#183; 4 months ago</p> </div> </div> </div> </div> </body> </html>
import numpy as np import matplotlib.pyplot as plt from replay_buffer import ReplayBuffer from utils.parse_args import parse_args from utils.plot_metrics import plot_metrics from utils.export_results import export_results import sys import pandas as pd from envs.BertrandInflation import BertrandEnv from envs.LinearBertrandInflation import LinearBertrandEnv from agents.ddpg import DDPGAgent from agents.dqn import DQNAgent from agents.sac import SACAgent models_dict = {'sac': SACAgent, 'ddpg': DDPGAgent, 'dqn': DQNAgent} envs_dict = {'bertrand': BertrandEnv, 'linear': LinearBertrandEnv} if __name__ == '__main__': # load args args = parse_args() # initiate environment env = envs_dict[args['env']] env = env(N = args['N'], k = args['k'], rho = args['rho'], v = args['v'], xi = args['xi'], timesteps = args['timesteps'], inflation_step = args['inflation_step']) # get dimensions #dim_states = env.N if args['use_lstm'] else env.k * env.N + env.k + 1 dim_states = (args['N'] * args['k']) + (args['k'] + 1 ) * 2 + args['N'] dim_actions = args['n_actions'] if args['model'] == 'dqn' else 1 # initiate agents model = models_dict[args['model']] agents = [model(dim_states, dim_actions) for _ in range(args['N'])] # initiate buffer buffer = ReplayBuffer(dim_states = dim_states, N = args['N'], buffer_size = args['buffer_size'], sample_size = args['sample_size']) prices_history = np.zeros((args['episodes'], args['timesteps'], args['N'])) actions_history = np.zeros((args['episodes'], args['timesteps'], args['N'])) monopoly_history = np.zeros((args['episodes'], args['timesteps'])) nash_history = np.zeros((args['episodes'], args['timesteps'])) rewards_history = np.zeros((args['episodes'], args['timesteps'], args['N'])) metric_history = np.zeros((args['episodes'], args['timesteps'])) # train for episode in range(args['episodes']): ob_t = env.reset() # initiate plot plot_dim = (2, 3) if args['plot_loss'] else (1, 3) fig, axes = plt.subplots(*plot_dim, figsize = (16, 6) if args['plot_loss'] else (16, 4)) axes = np.array(axes, ndmin = 2) for t in range(args['timesteps']): # select action actions = [agent.select_action(ob_t) for agent in agents] # trigger deviation #if (t > args['timesteps'] // 2) & (args['trigger_deviation']): # actions[0] = env.pN #actions = [env.pM for _ in range(env.N)] # step ob_t1, rewards, done, info = env.step(actions) # store transition experience = (ob_t, actions, rewards, ob_t1, done) buffer.store_transition(*experience) # update and plot if (t % args['update_steps'] == 0) & (t >= args['sample_size']): # update for agent_idx in range(args['N']): agent = agents[agent_idx] sample = buffer.sample(agent_idx) agent.update(*sample) # plot if t % args['plot_steps'] == 0: plot_args = (fig, axes, env.prices_history, env.monopoly_history, env.nash_history, env.rewards_history, env.metric_history, args['window']) plot_metrics(*plot_args, agent.actor_loss, agent.Q_loss) if args['plot_loss'] else plot_metrics(*plot_args) sys.stdout.write(f"\rEpisode: {episode + 1}/{args['episodes']} \t Training completion: {100 * t/args['timesteps']:.2f} % \t Delta: {info:.2f}") # update ob_t ob_t = ob_t1 # store metrics prices_history[episode] = np.array(env.prices_history)[args['k']:] monopoly_history[episode] = np.array(env.monopoly_history) nash_history[episode] = np.array(env.nash_history) rewards_history[episode] = np.array(env.rewards_history) metric_history[episode] = np.array(env.metric_history) # save plot #plt.savefig(f"figures/{args['exp_name']}.pdf") # export results #export_results(env.prices_history[env.k:], env.quantities_history, # env.monopoly_history[1:], env.nash_history[1:], # env.rewards_history, env.metric_history, # env.pi_N_history[1:], env.pi_M_history[1:], # env.costs_history[env.v+1:], args['exp_name']) # export prices_history = np.mean(prices_history, axis = 0) actions_history = np.mean(actions_history, axis = 0) monopoly_history = np.mean(monopoly_history, axis = 0) nash_history = np.mean(nash_history, axis = 0) rewards_history = np.mean(rewards_history, axis = 0) metric_history = np.mean(metric_history, axis = 0) results = pd.DataFrame({'monopoly': monopoly_history, 'nash': nash_history, 'metric': metric_history }) for agent in range(env.N): results[f'prices_{agent}'] = prices_history[:, agent] results[f'actions_{agent}'] = actions_history[:, agent] results[f'rewards_{agent}'] = rewards_history[:, agent] results.to_csv('metrics/experiment.csv')
import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { MongooseModule } from '@nestjs/mongoose'; import { envFilePathConfiguration } from './Configs/EnvFilePathConfig'; import { nestEnvConfiguration } from './Configs/NestEnvConfig'; import { ApplicationModule } from './Modules/ApplicationModule'; @Module({ imports: [ ConfigModule.forRoot({ envFilePath: [envFilePathConfiguration()], load: [nestEnvConfiguration], isGlobal: true, }), MongooseModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: async (configService: ConfigService) => ({ uri: configService.get<string>('MONGO_URL'), }), }), ApplicationModule, ], }) export class AppModule {}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Jamilli Gioielli</title> <!-- Favicon --> <link rel="shortcut icon" href="./assets/img/favicon_avatar_roxo.png" type="image/png" /> <!-- Icones --> <link rel="stylesheet" href="assets/fonts/style.css" /> <!-- Swiper --> <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css" /> <!-- STYLES --> <link rel="stylesheet" href="./css/estilos.css" /> <!-- Fonts --> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,400;0,600;0,700;0,900;1,400;1,700;1,800&family=Ubuntu:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet" /> <!-- SCRIPTS --> <script src="https://kit.fontawesome.com/6726683f80.js" crossorigin="anonymous" ></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.11/jquery.mask.min.js"></script> </head> <body> <header id="header"> <nav class="container"> <a class="logo" href="#"> &lt;/jamilligioielli&gt; </a> <!-- menu --> <div class="menu"> <ul class="grid"> <li><a class="title" href="#home"> Início </a></li> <li><a class="title" href="#about"> Sobre </a></li> <li><a class="title" href="#skills"> Skills </a></li> <li><a class="title" href="#projects"> Projetos </a></li> <li><a class="title" href="#contact"> Contato </a></li> <li id="switch"> <i class="switch icon-toggle-on"></i> <!--trocar para toggle-off --> </li> </ul> </div> <!-- /menu --> <div class="toggle icon-menu"></div> <div class="toggle icon-close"></div> </nav> </header> <main> <!-- HOME --> <section class="section" id="home"> <div class="container"> <div class="titulo-box"> <div class="titulo"> <span class="site-subtitle">Olá, meu nome é</span> <div class="site-title"> <h1> Jamilli <br /> Gioielli </h1> <div class="divider-1"></div> </div> <div class="icons grid"> <a href="https://github.com/jamilligioielli" target="_blank"> <i class="icon-github"></i> </a> <a href="https://codepen.io/jamilligioielli" target="_blank"> <i class="icon-codepen"></i> </a> <a href="https://www.linkedin.com/in/jamilligioielli/" target="_blank" > <i class="icon-linkedin"></i> </a> </div> </div> <div class="avatar"> <img src="./assets/img/avatar_home_sit.svg" alt="" /> </div> <div class="subtitulo"> <div class="snd-titulo"> <h2 class="site-title"> Posso te <br /> ajudar? </h2> <p class="text"> Uma jovem mochileira: tenho 17 anos e curso o terceiro ano do técnico de informática no IFSP, mas pode ter certeza que estou pronta para qualquer desafio! É só chamar! </p> </div> <div class="download-buttons grid"> <a href="mailto:jamilligioielli@outlook.com" class="submit-button" > Mande um email </a> <button class="cv-button"> <a href="./assets/files/jamilligioielli_curriculo.pdf" download="jamilligioielli_curriculo" target="_blank" > <i class="icon-download1"> </i> <span>Baixar CV</span> </a> </button> </div> </div> </div> </div> </section> <!-- ABOUT --> <section class="section" id="about"> <div class="container"> <div class="image-box"> <div class="image"> <img src="./assets/img/JamilliGioielli.png" alt="Foto Pessoal Jamilli" /> </div> </div> <div class="description"> <p>Sobre</p> <h2 class="site-subtitle">Quem sou eu?</h2> <p class="text"> Certamente sou a aprendiz de programadora mais tagarela que você vai conhecer! Por isso, me considero bastante observadora e atenta nos bate-papos... </p> <p class="text"> Gosto muito de passar um tempo lendo um bom livro, de qualquer assunto, mas também sou apaixonada por conversas empolgantes, principalmente quando acompanhadas de uma boa e velha xícara de café! </p> </div> </div> </section> <!-- SKILLS --> <section class="section" id="skills"> <div class="container"> <div class="skills-box"> <h2 class="site-subtitle">Skills</h2> <div class="lang-images"> <ul class="grid"> <li> <i class="icon-c" style="color: #024e88; background: #cbe7fd" ></i> </li> <li> <i class="icon-java" style="color: #023646; background: #c2e6f1" ></i> </li> <li> <i class="icon-css3" style="color: #115483; background: #cde9fd" ></i> </li> <li> <i class="icon-html5" style="color: #ca3207; background: #ffcabc" ></i> </li> <li> <i class="icon-git" style="color: #ad2b14; background: #facfc8" ></i> </li> <li> <i class="icon-mysql" style="color: #295272; background: #e7f1f8" ></i> </li> <li> <i class="icon-javascript" style="color: #9c8e20; background: #fffce3" ></i> </li> <li> <i class="icon-php" style="color: #262d8d; background: #dddeee" ></i> </li> </ul> </div> </div> </div> </section> <!-- PROJECTS --> <section class="section" id="projects"> <div class="container"> <header> <h2 class="site-subtitle">Conheça meus projetos</h2> <div class="divider-1"></div> </header> <div class="slider swiper-container"> <div class="swiper-wrapper"> <div class="slide swiper-slide"> <div class="image"> <img src="./assets//img/octopus.png" alt="Polvo Octupus" /> </div> <div class="description"> <h4 class="site-subtitle">Octupus</h4> <p class="text"> Sistema voltado para a prática de matemática básica com um banco de questões de vestibulares. </p> <div class="button"> <a href="https://github.com/jamilligioielli/Octupus" target="_blank" > Saiba Mais </a> </div> </div> </div> <div class="slide swiper-slide"> <div class="image"> <img src="./assets/img/maze.png" alt="Labirinto Techtravel" /> </div> <div class="description"> <h4 class="site-subtitle">Techtravel</h4> <p class="text"> Jogo de labirinto 2D voltado para informática, tendo a personagem histórica Ada Lovelace como protagonista. </p> <div class="button"> <a href="https://github.com/jamilligioielli/Techtravel" target="_blank" > Saiba Mais </a> </div> </div> </div> <div class="slide swiper-slide"> <div class="image"> <img src="./assets/img/sunny.png" alt="Sol Kuarasy" /> </div> <div class="description"> <h4 class="site-subtitle">Kûarasy</h4> <p class="text"> Projeto de loja virtual que pretende focar na cultura de vendedores imigrantes brasileiros - ainda em desenvolvimento </p> <div class="button"> <a href="https://github.com/jamilligioielli" target="_blank" > Saiba Mais </a> </div> </div> </div> <div class="slide swiper-slide"> <div class="image"> <img src="./assets/img/leonardo-da-vinci.png" alt="Leonardo da Vinci Portfolio" /> </div> <div class="description"> <h4 class="site-subtitle">Imersão CSS</h4> <p class="text"> Portfolio de Leonardo da Vinci feito com HTML e CSS </p> <div class="button"> <a href="https://jamilligioielli.github.io/aluraimersaojamilli/" target="_blank" > Saiba Mais </a> </div> </div> </div> </div> <!-- If we need navigation buttons --> <div class="swiper-button-prev"></div> <div class="swiper-button-next"></div> <!-- If we need pagination --> <div class="swiper-pagination"></div> </div> </div> </section> </main> <!-- CONTACT --> <section class="section grid" id="contact"> <div class="container"> <div class="contact-box"> <div class="description"> <h2 class="site-subtitle"><i> Me mande um oi! </i></h2> <div class="text"> <p> Vamos bater um papo, tomar um café e planejar coisas legais? Me encontre nas redes ou me mande uma mensagem por aqui :) </p> <div class="icons grid"> <a href="https://t.me/jamilligioielli"> <i class="icon-telegram"></i> @jamilligioielli </a> <a href="mailto:jamilligioielli@outlook.com"> <i class="icon-envelope"></i> jamilligioielli@outlook.com </a> </div> </div> </div> <div class="form"> <form action="https://formsubmit.co/jamilligioielli@outlook.com" method="POST" class="grid" > <div class="info-box"> <label for="idName">Nome</label> <input class="input" type="text" name="name" id="idName" autocomplete="off" required /> </div> <div class="info-box"> <label for="idEmail">Email</label> <input class="input" type="email" name="email" id="idEmail" autocomplete="off" required /> </div> <div class="info-box"> <label for="idCelular">Celular</label> <input class="input" type="tel" name="celular" id="idCelular" autocomplete="off" onkeypress="$(this).mask('(00) 0000-00009')" /> </div> <div class="info-box"> <label for="idSubject">Assunto</label> <input class="input" type="text" name="_subject" id="idSubject" autocomplete="off" required /> </div> <div class="info-box"> <label for="idMensage"> Mensagem </label> <textarea name="mensage" id="idMensage" cols="20" rows="5" size="50" ></textarea> </div> <input type="hidden" name="_next" value="" /> <input type="hidden" name="_captcha" value="false" /> <input type="submit" value="Enviar" class="submit-button" /> </form> </div> </div> </div> </section> <footer> <div class="brand"> <a class="logo" href="#home"> &lt;/jamilligioielli&gt; </a> <p>©2021 jamilligioielli.</p> <p>Todos os direitos reservados.</p> </div> <div class="icons grid"> <a href="https://github.com/jamilligioielli" target="_blank"> <i class="icon-github"></i> </a> <a href="https://codepen.io/jamilligioielli" target="_blank"> <i class="icon-codepen"></i> </a> <a href="https://www.linkedin.com/in/jamilligioielli/" target="_blank"> <i class="icon-linkedin"></i> </a> </div> </footer> <a href="#home" class="back-to-top"><i class="icon-arrow-up"></i></a> <!-- swiper --> <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script> <!-- scrollreveal --> <script src="https://unpkg.com/scrollreveal"></script> <!-- main.js --> <script src="./js/script.js"></script> </body> </html>
/* * The MIT License * * Copyright 2018 agvico. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package es.ujaen.simidat.agvico.moa.subgroupdiscovery.genetic.evaluators; import com.yahoo.labs.samoa.instances.Instance; import com.yahoo.labs.samoa.instances.InstancesHeader; import es.ujaen.simidat.agvico.moa.subgroupdiscovery.StreamMOEAEFEP; import es.ujaen.simidat.agvico.moa.subgroupdiscovery.genetic.GeneticAlgorithm; import es.ujaen.simidat.agvico.moa.subgroupdiscovery.genetic.individual.IndCAN; import es.ujaen.simidat.agvico.moa.subgroupdiscovery.genetic.operators.initialisation.RandomInitialisationCAN; import es.ujaen.simidat.agvico.moa.subgroupdiscovery.qualitymeasures.ContingencyTable; import java.util.ArrayList; import java.util.BitSet; /** * Improved version of the {@link EvaluatorCAN} class to calculate the quality * of a given individual or rule. * * This improved version make use of a BitSet for each attribute-value pair in * the population. These BitSets contains information about whether a given * examples is covered by the attribute value pair or not. Therefore, the * calculation the coverage of a rules is by means of bit operations among * several BitSets. * * @author Ángel Miguel García Vico (agvico@ujaen.es) * @since JDK 8.0 */ public class EvaluatorCANImproved extends Evaluator<IndCAN> { /** * Coverage information for each attribute-pair on each example */ private ArrayList<ArrayList<BitSet>> coverInformation; /** * The classes the samples belongs to */ private ArrayList<BitSet> classes; /** * The default constructor * * @param data The data itself * @param dataInfo The information about the variables * @param nLabels */ public EvaluatorCANImproved(ArrayList<Instance> data, InstancesHeader dataInfo, int nLabels) { super(data); coverInformation = new ArrayList<>(); // fill coverInformation with nulls according to the number of LLs or nominal variables it owns for (int i = 0; i < dataInfo.numInputAttributes(); i++) { coverInformation.add(new ArrayList<>()); if (dataInfo.inputAttribute(i).isNominal()) { for (int j = 0; j < dataInfo.inputAttribute(i).numValues(); j++) { coverInformation.get(i).add(null); } } else { for (int j = 0; j < nLabels; j++) { coverInformation.get(i).add(null); } } } // fill the classes array classes = new ArrayList<>(); // Add this lines for static data?? /*for (int i = 0; i < dataInfo.numClasses(); i++) { classes.add(new BitSet(data.size())); } for (int i = 0; i < data.size(); i++) { Instance inst = data.get(i); classes.get(((Double) inst.classValue()).intValue()).set(i); }*/ } @Override public void doEvaluation(IndCAN sample, boolean isTrain) { BitSet coverage = new BitSet(this.data.size()); boolean first = true; if (sample.isEmpty()) { if (sample.isEmpty()) { // If it is an empty rule, randomly initialise it and after that evaluate. RandomInitialisationCAN rInit = new RandomInitialisationCAN(sample); sample = rInit.doInitialisation(); } } for (int j = 0; j < sample.getSize(); j++) { if (sample.getCromElem(j) < coverInformation.get(j).size()) { if (coverInformation.get(j).get(sample.getCromElem(j)) == null) { BitSet aux = initialiseBitSet(sample, j); coverInformation.get(j).set(sample.getCromElem(j), aux); } // At this point, all variables in the rules are initialised. Do the bitset computations if (first) { coverage.or(coverInformation.get(j).get(sample.getCromElem(j))); first = false; } else { coverage.and(coverInformation.get(j).get(sample.getCromElem(j))); } } } sample.setCubre(coverage); // now, all variables have been processed , perform computing of the confusion matrix. BitSet noClass = (BitSet) classes.get(sample.getClas()).clone(); noClass.flip(0, this.data.size()); BitSet noCoverage = (BitSet) coverage.clone(); noCoverage.flip(0, this.data.size()); BitSet tp = (BitSet) coverage.clone(); tp.and(classes.get(sample.getClas())); BitSet tn = (BitSet) noCoverage.clone(); tn.and(noClass); BitSet fp = (BitSet) coverage.clone(); fp.and(noClass); BitSet fn = (BitSet) noCoverage.clone(); fn.and(classes.get(sample.getClas())); ContingencyTable confMatrix = new ContingencyTable(tp.cardinality(), fp.cardinality(), tn.cardinality(), fn.cardinality()); // Calculate the measures and set as evaluated super.calculateMeasures(sample, confMatrix, isTrain); sample.setEvaluated(true); } @Override public void doEvaluation(ArrayList<IndCAN> sample, boolean isTrain, GeneticAlgorithm<IndCAN> GA) { for (IndCAN ind : sample) { if (!ind.isEvaluated()) { doEvaluation(ind, isTrain); GA.TrialsPlusPlus(); ind.setNEval((int) GA.getTrials()); } } } /** * Initialise an attribute-value pair. It returns a bitset that determines * whether a given sample is covered by the attribute-value pair or not. * * @param sample * @param position * @return */ private BitSet initialiseBitSet(IndCAN sample, int position) { BitSet infoCovering = new BitSet(this.data.size()); // If this value is null, it means that the att-value pair has not been initialised yet. Lets initialise for (int i = 0; i < this.data.size(); i++) { if (data.get(i).inputAttribute(position).isNominal()) { // Nominal variable Double val = getData().get(i).valueInputAttribute(position); boolean missing = getData().get(i).isMissing(position); if (val.intValue() == sample.getCromElem(position) || missing) { infoCovering.set(i); } } else { // Numeric variable //System.out.println(j + " --- "+ sample.getCromElem(j)); try { float pertenencia = StreamMOEAEFEP.Fuzzy(position, sample.getCromElem(position), getData().get(i).valueInputAttribute(position)); if (pertenencia > 0 || data.get(i).isMissing(position)) { infoCovering.set(i); } } catch (ArrayIndexOutOfBoundsException ex) { System.err.println("ERROR: " + position + " ----- " + sample.getCromElem(position) + "\nChromosome: " + sample.getChromosome().toString()); System.exit(1); } } } return infoCovering; } @Override public void setData(ArrayList<Instance> data) { super.data = data; classes.clear(); for (int i = 0; i < data.get(0).numClasses(); i++) { classes.add(new BitSet(data.size())); } for (int i = 0; i < data.size(); i++) { Instance inst = data.get(i); classes.get(((Double) inst.classValue()).intValue()).set(i); } for (int i = 0; i < coverInformation.size(); i++) { for (int j = 0; j < coverInformation.get(i).size(); j++) { coverInformation.get(i).set(j, null); } } } }
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:ecommerce/features/shop/models/brand_model.dart'; import 'package:flutter/services.dart'; import 'package:get/get.dart'; import '../../../common/widgets/exceptions/exceptions.dart'; class BrandRepository extends GetxController { static BrandRepository get instance => Get.find(); /// Variables final _db = FirebaseFirestore.instance; /// Get all Brands Future<List<BrandModel>> getAllBrands() async{ try{ final querySnapshot = await _db.collection('Brands').get(); final result = querySnapshot.docs.map((doc) => BrandModel.fromSnapshot(doc)).toList(); return result; }on FirebaseException catch (e) { throw TFirebaseException(e.code).message; } on FormatException catch (_) { throw TFormatException(); } on PlatformException catch (e) { throw TPlatformException(e.code).message; }catch(e){ throw 'Something went wrong , please try again'; } } /// Get Brands For Category Future<List<BrandModel>> getBrandsForCategory(String categoryId) async{ try{ // Query to get all documents where categoryId matches the provided categoryId QuerySnapshot brandCategoryQuery = await _db.collection('BrandCategory').where('categoryId', isEqualTo: categoryId).get(); // Extract brandIds from the documents List<String> brandIds = brandCategoryQuery.docs.map((doc) => doc['brandId'] as String).toList(); // Query to get all documents where the brandId is in the list of brandIds, FieldPath.documentId to query documents in Collection final brandsQuery = await _db.collection('Brands').where(FieldPath.documentId, whereIn: brandIds).limit(2).get(); // Extract brand names or other relevant data from the documents List<BrandModel> brands= brandsQuery.docs.map((doc) => BrandModel.fromSnapshot(doc)).toList(); return brands; }on FirebaseException catch (e) { throw TFirebaseException(e.code).message; } on FormatException catch (_) { throw TFormatException(); } on PlatformException catch (e) { throw TPlatformException(e.code).message; }catch(e){ throw 'Something went wrong , please try again'; } } }
use super::constants::{ MANAGE_SERVERS_LONG, MANAGE_SERVERS_SHORT, MANAGE_STREAMS_LONG, MANAGE_STREAMS_SHORT, MANAGE_TOPICS_LONG, MANAGE_TOPICS_SHORT, MANAGE_USERS_LONG, MANAGE_USERS_SHORT, POLL_MESSAGES_LONG, POLL_MESSAGES_SHORT, READ_SERVERS_LONG, READ_SERVERS_SHORT, READ_STREAMS_LONG, READ_STREAMS_SHORT, READ_TOPICS_LONG, READ_TOPICS_SHORT, READ_USERS_LONG, READ_USERS_SHORT, SEND_MESSAGES_LONG, SEND_MESSAGES_SHORT, }; use iggy::models::permissions::GlobalPermissions; use std::str::FromStr; #[derive(Debug, PartialEq)] pub(super) enum GlobalPermission { ManageServers, ReadServers, ManageUsers, ReadUsers, ManageStreams, ReadStreams, ManageTopics, ReadTopics, PollMessages, SendMessages, } #[derive(Clone, Debug, PartialEq)] pub(crate) struct GlobalPermissionError(String); impl FromStr for GlobalPermission { type Err = GlobalPermissionError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { MANAGE_SERVERS_SHORT | MANAGE_SERVERS_LONG => Ok(GlobalPermission::ManageServers), READ_SERVERS_SHORT | READ_SERVERS_LONG => Ok(GlobalPermission::ReadServers), MANAGE_USERS_SHORT | MANAGE_USERS_LONG => Ok(GlobalPermission::ManageUsers), READ_USERS_SHORT | READ_USERS_LONG => Ok(GlobalPermission::ReadUsers), MANAGE_STREAMS_SHORT | MANAGE_STREAMS_LONG => Ok(GlobalPermission::ManageStreams), READ_STREAMS_SHORT | READ_STREAMS_LONG => Ok(GlobalPermission::ReadStreams), MANAGE_TOPICS_SHORT | MANAGE_TOPICS_LONG => Ok(GlobalPermission::ManageTopics), READ_TOPICS_SHORT | READ_TOPICS_LONG => Ok(GlobalPermission::ReadTopics), POLL_MESSAGES_SHORT | POLL_MESSAGES_LONG => Ok(GlobalPermission::PollMessages), SEND_MESSAGES_SHORT | SEND_MESSAGES_LONG => Ok(GlobalPermission::SendMessages), "" => Err(GlobalPermissionError("[empty]".to_owned())), _ => Err(GlobalPermissionError(s.to_owned())), } } } #[derive(Clone, Debug, PartialEq)] pub(crate) struct GlobalPermissionsArg { pub(crate) permissions: GlobalPermissions, } impl From<GlobalPermissionsArg> for GlobalPermissions { fn from(cmd: GlobalPermissionsArg) -> Self { cmd.permissions } } impl GlobalPermissionsArg { pub(super) fn new(permissions: Vec<GlobalPermission>) -> Self { let mut result = GlobalPermissionsArg { permissions: GlobalPermissions::default(), }; for permission in permissions { result.set_permission(permission); } result } fn set_permission(&mut self, permission: GlobalPermission) { match permission { GlobalPermission::ManageServers => self.permissions.manage_servers = true, GlobalPermission::ReadServers => self.permissions.read_servers = true, GlobalPermission::ManageUsers => self.permissions.manage_users = true, GlobalPermission::ReadUsers => self.permissions.read_users = true, GlobalPermission::ManageStreams => self.permissions.manage_streams = true, GlobalPermission::ReadStreams => self.permissions.read_streams = true, GlobalPermission::ManageTopics => self.permissions.manage_topics = true, GlobalPermission::ReadTopics => self.permissions.read_topics = true, GlobalPermission::PollMessages => self.permissions.poll_messages = true, GlobalPermission::SendMessages => self.permissions.send_messages = true, } } } impl FromStr for GlobalPermissionsArg { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let (values, errors): (Vec<_>, Vec<_>) = s .split(',') .map(|p| p.parse::<GlobalPermission>()) .partition(Result::is_ok); if !errors.is_empty() { let errors = errors .into_iter() .map(|e| format!("\"{}\"", e.err().unwrap().0)) .collect::<Vec<String>>(); return Err(format!( "Unknown global permission{} {}", match errors.len() { 1 => "", _ => "s", }, errors.join(", "), )); } Ok(GlobalPermissionsArg::new( values.into_iter().map(|p| p.unwrap()).collect(), )) } } #[cfg(test)] mod tests { use super::*; #[test] fn should_deserialize_single_permission() { assert_eq!( GlobalPermission::from_str("manage_servers").unwrap(), GlobalPermission::ManageServers ); assert_eq!( GlobalPermission::from_str("read_servers").unwrap(), GlobalPermission::ReadServers ); assert_eq!( GlobalPermission::from_str("manage_users").unwrap(), GlobalPermission::ManageUsers ); assert_eq!( GlobalPermission::from_str("read_users").unwrap(), GlobalPermission::ReadUsers ); assert_eq!( GlobalPermission::from_str("manage_streams").unwrap(), GlobalPermission::ManageStreams ); assert_eq!( GlobalPermission::from_str("read_streams").unwrap(), GlobalPermission::ReadStreams ); assert_eq!( GlobalPermission::from_str("manage_topics").unwrap(), GlobalPermission::ManageTopics ); assert_eq!( GlobalPermission::from_str("read_topics").unwrap(), GlobalPermission::ReadTopics ); assert_eq!( GlobalPermission::from_str("poll_messages").unwrap(), GlobalPermission::PollMessages ); assert_eq!( GlobalPermission::from_str("send_messages").unwrap(), GlobalPermission::SendMessages ); } #[test] fn should_deserialize_single_short_permission() { assert_eq!( GlobalPermission::from_str("m_srv").unwrap(), GlobalPermission::ManageServers ); assert_eq!( GlobalPermission::from_str("r_srv").unwrap(), GlobalPermission::ReadServers ); assert_eq!( GlobalPermission::from_str("m_usr").unwrap(), GlobalPermission::ManageUsers ); assert_eq!( GlobalPermission::from_str("r_usr").unwrap(), GlobalPermission::ReadUsers ); assert_eq!( GlobalPermission::from_str("m_str").unwrap(), GlobalPermission::ManageStreams ); assert_eq!( GlobalPermission::from_str("r_str").unwrap(), GlobalPermission::ReadStreams ); assert_eq!( GlobalPermission::from_str("m_top").unwrap(), GlobalPermission::ManageTopics ); assert_eq!( GlobalPermission::from_str("r_top").unwrap(), GlobalPermission::ReadTopics ); assert_eq!( GlobalPermission::from_str("p_msg").unwrap(), GlobalPermission::PollMessages ); assert_eq!( GlobalPermission::from_str("s_msg").unwrap(), GlobalPermission::SendMessages ); } #[test] fn should_not_deserialize_single_permission() { let wrong_permission = GlobalPermission::from_str("rad_topic"); assert!(wrong_permission.is_err()); assert_eq!( wrong_permission.unwrap_err(), GlobalPermissionError("rad_topic".to_owned()) ); let empty_permission = GlobalPermission::from_str(""); assert!(empty_permission.is_err()); assert_eq!( empty_permission.unwrap_err(), GlobalPermissionError("[empty]".to_owned()) ); } #[test] fn should_not_deserialize_single_short_permission() { let wrong_permission = GlobalPermission::from_str("w_top"); assert!(wrong_permission.is_err()); assert_eq!( wrong_permission.unwrap_err(), GlobalPermissionError("w_top".to_owned()) ); let wrong_permission = GlobalPermission::from_str("p_top"); assert!(wrong_permission.is_err()); assert_eq!( wrong_permission.unwrap_err(), GlobalPermissionError("p_top".to_owned()) ); } #[test] fn should_deserialize_permissions() { assert_eq!( GlobalPermissionsArg::from_str("manage_servers,read_servers,manage_users,read_users,manage_streams,read_streams,manage_topics,read_topics,poll_messages,send_messages") .unwrap(), GlobalPermissionsArg { permissions: GlobalPermissions { manage_servers: true, read_servers: true, manage_users: true, read_users: true, manage_streams: true, read_streams: true, manage_topics: true, read_topics: true, poll_messages: true, send_messages: true, } } ); assert_eq!( GlobalPermissionsArg::from_str("manage_topics,read_topics").unwrap(), GlobalPermissionsArg { permissions: GlobalPermissions { manage_servers: false, read_servers: false, manage_users: false, read_users: false, manage_streams: false, read_streams: false, manage_topics: true, read_topics: true, poll_messages: false, send_messages: false, } } ); assert_eq!( GlobalPermissionsArg::from_str("send_messages,manage_servers").unwrap(), GlobalPermissionsArg { permissions: GlobalPermissions { manage_servers: true, read_servers: false, manage_users: false, read_users: false, manage_streams: false, read_streams: false, manage_topics: false, read_topics: false, poll_messages: false, send_messages: true, } } ); } #[test] fn should_deserialize_short_permissions() { assert_eq!( GlobalPermissionsArg::from_str( "m_srv,r_srv,m_usr,r_usr,m_str,r_str,m_top,r_top,p_msg,s_msg" ) .unwrap(), GlobalPermissionsArg { permissions: GlobalPermissions { manage_servers: true, read_servers: true, manage_users: true, read_users: true, manage_streams: true, read_streams: true, manage_topics: true, read_topics: true, poll_messages: true, send_messages: true, } } ); assert_eq!( GlobalPermissionsArg::from_str("m_top,r_top").unwrap(), GlobalPermissionsArg { permissions: GlobalPermissions { manage_servers: false, read_servers: false, manage_users: false, read_users: false, manage_streams: false, read_streams: false, manage_topics: true, read_topics: true, poll_messages: false, send_messages: false, } } ); assert_eq!( GlobalPermissionsArg::from_str("s_msg,m_srv").unwrap(), GlobalPermissionsArg { permissions: GlobalPermissions { manage_servers: true, read_servers: false, manage_users: false, read_users: false, manage_streams: false, read_streams: false, manage_topics: false, read_topics: false, poll_messages: false, send_messages: true, } } ); } #[test] fn should_not_deserialize_permissions() { let wrong_id = GlobalPermissionsArg::from_str("4a"); assert!(wrong_id.is_err()); assert_eq!(wrong_id.unwrap_err(), "Unknown global permission \"4a\""); let wrong_permission = GlobalPermissionsArg::from_str("read_topic"); assert!(wrong_permission.is_err()); assert_eq!( wrong_permission.unwrap_err(), "Unknown global permission \"read_topic\"" ); let multiple_wrong = GlobalPermissionsArg::from_str("read_topic,sent_messages"); assert!(multiple_wrong.is_err()); assert_eq!( multiple_wrong.unwrap_err(), "Unknown global permissions \"read_topic\", \"sent_messages\"" ); } #[test] fn should_not_deserialize_short_permissions() { let wrong_permission = GlobalPermissionsArg::from_str("r_topic"); assert!(wrong_permission.is_err()); assert_eq!( wrong_permission.unwrap_err(), "Unknown global permission \"r_topic\"" ); let multiple_wrong = GlobalPermissionsArg::from_str("r_topic,sent_msg"); assert!(multiple_wrong.is_err()); assert_eq!( multiple_wrong.unwrap_err(), "Unknown global permissions \"r_topic\", \"sent_msg\"" ); } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .list-item { display: inline-block; width: 40px; text-align: center; } .list-enter-active, .list-leave-active { transition: all 1s; } .list-enter, .list-leave-to { opacity: 0; transform: translateY(30px); } </style> </head> <body> <div id="app"> <p> <button type="button" @click="add">Add</button> <button type="button" @click="remove">Remove</button> <transition-group name="list" tag="p"> <span v-for="(item, index) in items" :key="item" class="list-item">{{item}}</span> </transition-group> </p> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type="text/javascript"> const vm = new Vue({ el: '#app', data() { return { items: [1,2,3,4,5,6,7,8,9], nextNum: 10 } }, methods: { add() { this.items.splice(Math.floor(Math.random() * this.items.length), 0, this.nextNum ++) }, remove() { this.items.splice(Math.floor(Math.random() * (this.items.length-1)), 1) } } }) </script> </body> </html>
import React from "react"; import {createBoard} from "../board/create.js"; import {useForceUpdate} from "../hooks/index.js"; import {Loading} from "../components/Loading.jsx"; import {useDelay} from "../hooks/index.js"; export const BoardContext = React.createContext({}); // Import initial board data const loadBoardData = initialValue => { if (typeof initialValue === "function") { // Make sure to wrapp the call of this function inside a promise chain return Promise.resolve(null).then(() => { return initialValue(); }); } // Check if initial value is just an object else if (typeof initialValue === "object" && !!initialValue) { return Promise.resolve(initialValue); } // Other value is not supported return Promise.resolve({}); }; export const useBoard = () => { return React.useContext(BoardContext); }; export const withBoard = fn => { return props => { return fn(props, useBoard()); }; }; export const BoardProvider = props => { const forceUpdate = useForceUpdate()[1]; const board = React.useRef(null); // Import board data useDelay(props.delay, () => { loadBoardData(props.initialData) .then(boardData => { board.current = createBoard({ data: boardData, onUpdate: forceUpdate, }); forceUpdate(); }) .catch(error => { props?.onError?.(error); }); }); // If no board data has been provided, display a loading screen if (!board.current) { return ( <Loading /> ); } return ( <BoardContext.Provider value={board.current}> {props.render()} </BoardContext.Provider> ); }; BoardProvider.defaultProps = { initialData: null, delay: 1000, render: null, onError: null, };
@extends('admin.layouts.master') @section('title', 'Create Fast Food') @section('content') <div class="main-content"> <div class="section__content section__content--p30"> <div class="container-fluid"> <div class="row"> <div class="col-3 offset-8"> <a href="{{ route('product#list') }}"><button class="btn bg-dark text-white my-3">List</button></a> </div> </div> <div class="col-lg-6 offset-3"> <div class="card"> <div class="card-body"> <div class="card-title"> <h3 class="text-center title-2">Create your Product</h3> </div> <hr> <form action="{{ route('product#create') }}" method="post" novalidate="novalidate" enctype="multipart/form-data"> @csrf <div class="form-group"> <label class="control-label mb-1">Name</label> <input name="pizzaName" type="text" class="form-control" aria-required="true" aria-invalid="false" placeholder="Enter Product Name..." value="{{ old('pizzaName') }}"> @error('pizzaName') <small class="text-danger"> {{ $message }} </small> @enderror </div> <div class="form-group"> <label class="control-label mb-1">Category</label> <select name="pizzaCategory" class="form-control"> <option value="">Choose Category</option> @foreach ($categories as $category) <option value="{{ $category->id }}">{{ $category->name }}</option> @endforeach </select> @error('pizzaCategory') <small class="text-danger"> {{ $message }} </small> @enderror </div> <div class="form-group"> <label class="control-label mb-1">Description</label> <textarea name="pizzaDescription" class="form-control" rows="5" placeholder="Enter Description...">{{ old('pizzaDescription') }}</textarea> @error('pizzaDescription') <small class="text-danger"> {{ $message }} </small> @enderror </div> <div class="form-group"> <label class="control-label mb-1">Image</label> <input name="pizzaImage" type="file" class="form-control" aria-required="true" aria-invalid="false" value="{{ old('pizzaImage') }}"> @error('pizzaImage') <small class="text-danger"> {{ $message }} </small> @enderror </div> <div class="form-group"> <label class="control-label mb-1">Waiting Time</label> <input name="pizzaWaitingTime" type="number" class="form-control" aria-required="true" aria-invalid="false" value="{{ old('pizzaWaitingTime') }}" placeholder="Enter Waiting Time"> @error('pizzaWaitingTime') <small class="text-danger"> {{ $message }} </small> @enderror </div> <div class="form-group"> <label class="control-label mb-1">Price</label> <input name="pizzaPrice" type="number" class="form-control" aria-required="true" aria-invalid="false" placeholder="Enter Product Price..." value="{{ old('pizzaPrice') }}"> @error('pizzaPrice') <small class="text-danger"> {{ $message }} </small> @enderror </div> <div> <button id="payment-button" type="submit" class="btn btn-lg btn-info btn-block"> <span id="payment-button-amount">Create</span> <i class="fa-solid fa-circle-right"></i> </button> </div> </form> </div> </div> </div> </div> </div> </div> @endsection
import { useState } from "react"; import { useRouter } from 'next/router'; import { useSession, signIn, getSession } from 'next-auth/react'; import ReCAPTCHA from "react-google-recaptcha"; import axios from "axios"; import Image from "next/image"; import Link from "next/link"; import Head from "next/head"; // Components import PasswordInput from "components/form-elements/PasswordInput"; import Button from "components/buttons"; import { IndeterminateLinearLoader } from "components/Loader"; import { FormElement, Label, FormAlert, Input } from "components/form-elements"; import styled from "styled-components"; import toast, { Toaster } from "react-hot-toast"; import {FcGoogle} from "react-icons/fc"; const PageWrapper = styled.div` display: flex; align-items:center; justify-content: center; width: 100%; height: 100vh; padding: 2rem 1.5rem; `; const FormWrapper = styled.div` display: flex; align-items: center; justify-content: center; flex-direction: column; padding: 2rem 3rem; gap: 1rem; text-align: center; background:var(--card-bg); border-radius: 25px; box-shadow: 0px 10px 40px 0px rgba(0, 0, 0, 0.1); .logo{ img{ width: 100%; height: auto; object-fit: contain; max-width: 200px; margin: auto; } } .login{ display: flex; width:100%; padding: 0.75rem 1rem; align-items: center; gap: 1rem; flex-shrink: 0; font-size: 1rem; font-weight: 500; border: none; border-radius: 0.75rem; } ${FormElement}{ width: 100%; margin: 0; margin-bottom: 1rem; } .forgot-password{ display: block; font-size: 0.9rem; width: 100%; text-align: right; margin: 0.5rem 0; color: rgba(var(--theme-rgb), 0.75); &:hover{ color: rgba(var(--theme-rgb), 1); } } .or{ display: flex; align-items: center; justify-content: center; width: 100%; gap: 0.5rem; margin: 1rem 0; color: rgba(var(--grey-rgb), 0.5); &:before, &:after{ content: ""; flex: 1; height: 1px; background: rgba(var(--grey-rgb), 0.2); } } .social { display: flex; align-items: center; justify-content: center; width: 100%; gap: 1rem; flex-direction: column; button{ display: flex; width:100%; justify-content: flex-start; padding: 0.75rem 1rem; align-items: center; font-weight: 500; font-size: 1rem; gap: 1rem; flex-shrink: 0; border: none; color:inherit; border-radius: 0.75rem; &.google{ background: #FFF; box-shadow: 0px 2.4054rem 4.4672rem 0px rgba(0, 0, 0, 0.07); border: 1px solid rgba(var(--grey-rgb), 0.2); } &.github { background: #000; color: #f6f6f6; box-shadow: 0px 10px 40px 0px rgba(0, 0, 0, 0.1); } &.facebook { background: #1877F2; box-shadow: 0px 38.486881256103516px 71.47562408447266px 0px rgba(0, 0, 0, 0.07); } } } .no-account{ font-size: 0.9rem; font-weight: 500; margin-block: 1rem; text-align: center; display: block; a{ color: var(--theme); text-decoration: none; } } `; const Form = styled.form` display: flex; flex-direction: column; align-items: center; width: clamp(300px, 100%, 400px); ${'' /* gap: 1rem; */} ${FormElement} { width: 100%; } ${Button} { text-align: center; margin-inline: auto; } h2{ font-size: 1.5rem; font-weight: 600; margin-bottom: 0.5rem; } p{ font-size: 1rem; font-weight: 500; margin-bottom: 1rem; } .forgot-pass{ font-size: 0.9rem; font-weight: 500; margin-bottom: 1rem; } `; const metadata = { title: "Login to your account", description: "Login to your account", keywords: "login, login page, login form, login to account, login to dashboard, login" } export default function Login({ }) { const { session, status } = useSession(); const router = useRouter(); const [state, setState] = useState({ email: { value: "", error: false, errorMessage: "" }, password: { value: "", error: false, errorMessage: "" }, recaptcha: { verified: true, error: false, errorMessage: "" }, formState: { state: "initial" || "error" || "success" || "loading", message: "" } }); const isEmail = (email) => { const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } const handleCaptcha = async (value) => { await axios.post("/api/recaptcha", { token: value }).then((response) => { // console.log(response); setState({ ...state, recaptcha: { verified: response.data.verified, error: !response.data.verified, errorMessage: "" } }) }).catch((error) => { console.log(error); setState({ ...state, recaptcha: { verified: false, error: true, errorMessage: error.message || "Something went wrong" } }) }) } async function submitHandler(event) { event.preventDefault(); const enteredEmail = state.email.value; const enteredPassword = state.password.value; if (!isEmail(enteredEmail)) { toast.error("Please enter a valid email address"); return; } if (state.recaptcha.verified === false) { toast.error("Please verify that you are not a robot"); return; } const signInPromise = async() => new Promise(async (resolve, reject) => { try { signIn('credentials', { callbackUrl: router.query.continue || "/", email: enteredEmail, password: enteredPassword, redirect: false }).then((data) => { console.log(data); if (data.ok === false) { reject(data.error); return; } else if (data.ok === true) { resolve(data); router.push(router.query.continue || "/"); return; } resolve(data); }) .catch((error) => { console.log(error); reject(error); } ) } catch (error) { reject(error); } }) toast.promise(signInPromise(), { loading: 'Logging in...', success: "Logged in successfully", error: (err) => { return err || "An error occurred while logging in"; } }) } return ( <> <Head> <title>{metadata.title}</title> <meta name="description" content={metadata.description} /> <meta name="keywords" content={metadata.keywords} /> </Head> <PageWrapper> <FormWrapper> <div className="logo"> <Image src={"/logo512.png"} alt="Login Illustration" width={300} height={200} /> </div> <Form onSubmit={submitHandler}> <h2> Welcome to NITH Portal</h2> <p>Sign in to your account to continue</p> <FormElement> <Input type="email" placeholder="Enter your Email" outlined value={state.email.value} id="email" required onChange={(e) => { setState({ ...state, email: { value: e.target.value, error: !isEmail(e.target.value), errorMessage: "Please enter a valid email" } }) }} level={true} className={state.email.error ? "isInvalid" : ""} /> <Label htmlFor="email">Enter Your Email</Label> {state.email.error && <FormAlert nature="danger">{state.email.errorMessage}</FormAlert>} </FormElement> <FormElement> <PasswordInput placeholder="Enter your Password" outlined id="password" required value={state.password.value} className={state.password.error ? "isInvalid" : ""} onChange={(e) => { setState({ ...state, password: { value: e.target.value, error: false, errorMessage: "" } }) }} level={true} /> {state.password.error && <FormAlert nature="danger">{state.password.errorMessage}</FormAlert>} <Label htmlFor="password">Enter Your Password</Label> </FormElement> <FormElement align="center" className="m-0 g-0"> <ReCAPTCHA sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY} onChange={handleCaptcha} size="invisible" /> </FormElement> {state.formState.state === "error" && <FormAlert nature="danger">{state.formState.message}</FormAlert>} {state.formState.state === "success" && <FormAlert nature="success">{state.formState.message}</FormAlert>} {state.formState.state === "loading" && <IndeterminateLinearLoader />} <p className="forgot-password"><Link href="/forgot-password" >Forgot Password? </Link></p> <Button type="submit" onClick={submitHandler} className="login">Login </Button> <p className="or">Or</p> <div className="social"> <button type="button" onClick={() => signIn('google')} className="google"><FcGoogle size={18}/> Continue with Google </button> {/* <button onClick={() => signIn('github', { callbackUrl: rou ter.query.continue || "/dashboard" })} className="github apple"> <FiGithub size={18}/> Continue with Github </button> */} </div> {/* <p className="no-account">Don't have an account? <Link href="/signup">Sign Up</Link></p> */} </Form> </FormWrapper> </PageWrapper> <Toaster position="bottom-center" /> </>) } export async function getServerSideProps(context) { const session = await getSession(context); if (session) return { redirect: { destination: '/', permanent: false } } return { props: { }, } }
// Copyright (c) 2023 Sendbird, Inc. All rights reserved. import 'package:isar/isar.dart'; import 'package:sendbird_chat_sdk/sendbird_chat_sdk.dart'; import 'package:sendbird_chat_sdk/src/internal/db/schema/message/c_admin_message.dart'; import 'package:sendbird_chat_sdk/src/internal/db/schema/message/c_file_message.dart'; import 'package:sendbird_chat_sdk/src/internal/db/schema/message/c_notification_message.dart'; import 'package:sendbird_chat_sdk/src/internal/db/schema/message/c_user_message.dart'; import 'package:sendbird_chat_sdk/src/internal/db/schema/message/meta/c_channel_access.dart'; import 'package:sendbird_chat_sdk/src/internal/db/schema/message/meta/channel_access.dart'; import 'package:sendbird_chat_sdk/src/internal/db/schema/message/meta/channel_message.dart'; import 'package:sendbird_chat_sdk/src/internal/main/chat/chat.dart'; part 'c_channel_message.g.dart'; @collection class CChannelMessage { Id id = Isar.autoIncrement; @Index(unique: true, replace: true) late String rootId; @Index(composite: [CompositeIndex('rootId')]) @enumerated late MessageType messageType; @Index() late String channelUrl; @Index(composite: [CompositeIndex('channelUrl')]) @enumerated late ChannelType channelType; @Index() late int createdAt; @Index() @enumerated late SendingStatus sendingStatus; // sendingStatus for filtering late String? customType; // customType for filtering late String? senderId; // senderId for filtering CChannelMessage(); factory CChannelMessage.fromChannelMessage(ChannelMessage message) { return CChannelMessage() ..rootId = message.rootId ..messageType = message.messageType ..channelUrl = message.channelUrl ..channelType = message.channelType ..createdAt = message.createdAt ..sendingStatus = message.sendingStatus ..customType = message.customType ..senderId = message.senderId; } Future<ChannelMessage?> toChannelMessage(Chat chat, Isar isar) async { late RootMessage? message; if (messageType == MessageType.user) { final cUserMessage = await isar.cUserMessages.getByRootId(rootId); message = await cUserMessage?.toUserMessage(chat, isar); } else if (messageType == MessageType.file) { final cFileMessage = await isar.cFileMessages.getByRootId(rootId); message = await cFileMessage?.toFileMessage(chat, isar); } else if (messageType == MessageType.admin) { final cAdminMessage = await isar.cAdminMessages.getByRootId(rootId); message = await cAdminMessage?.toAdminMessage(chat, isar); } else if (messageType == MessageType.notification) { final cNotificationMessage = await isar.cNotificationMessages.getByRootId(rootId); message = await cNotificationMessage?.toNotificationMessage(chat, isar); } return message != null ? ChannelMessage( rootId: rootId, messageType: messageType, channelUrl: channelUrl, channelType: channelType, createdAt: createdAt, sendingStatus: sendingStatus, customType: customType, senderId: senderId, message: message, ) : null; } static Future<bool> hasMessages( Chat chat, Isar isar, String channelUrl) async { return await isar.cChannelMessages .where() .channelUrlEqualTo(channelUrl) .isNotEmpty(); } static Future<CChannelMessage> upsert( Chat chat, Isar isar, RootMessage message) async { final cChannelMessage = CChannelMessage.fromChannelMessage( ChannelMessage( rootId: message.rootId, messageType: message.messageType, channelUrl: message.channelUrl, channelType: message.channelType, createdAt: message.createdAt, sendingStatus: message is BaseMessage ? (message.sendingStatus ?? SendingStatus.none) : SendingStatus.succeeded, customType: message.customType, senderId: message is BaseMessage ? message.sender?.userId : null, message: message, ), ); // ChannelMessage await chat.dbManager.write(() async { await isar.cChannelMessages.put(cChannelMessage); }); // ChannelAccess await CChannelAccess.upsert( chat, isar, ChannelAccess( channelUrl: message.channelUrl, lastAccessedAt: DateTime.now().millisecondsSinceEpoch, ), ); return cChannelMessage; } static Future<ChannelMessage?> get( Chat chat, Isar isar, String rootId) async { final cChannelMessage = await isar.cChannelMessages.where().rootIdEqualTo(rootId).findFirst(); return await cChannelMessage?.toChannelMessage(chat, isar); } static Future<List<RootMessage>> getMessages( Chat chat, Isar isar, ChannelType channelType, String channelUrl, SendingStatus sendingStatus, int timestamp, MessageListParams params, bool isPrevious, // false: Next ) async { // [includeMetaArray] // When calling API, this value have to be `true` to make chunk. // [includeReactions] // When calling API, this value have to be `true` to make chunk. // [includeThreadInfo] // When calling API, this value have to be `true` to make chunk. // [includeParentMessageInfo] // When calling API, this value have to be `true` to make chunk. // [replyType] // Must call API, because this can not be queried with local cache. // [showSubChannelMessagesOnly] // Must call API, because this can not be queried with local cache. final cChannelMessages = await isar.cChannelMessages .where() // channelType & channelUrl & reverse .channelTypeChannelUrlEqualTo(channelType, channelUrl) .filter() // sendingStatus .optional(sendingStatus == SendingStatus.succeeded, (q) { return q.sendingStatusEqualTo(SendingStatus.succeeded); }) .optional(sendingStatus == SendingStatus.failed, (q) { return q.sendingStatusEqualTo(SendingStatus.failed); }) .optional(sendingStatus == SendingStatus.pending, (q) { return q.sendingStatusEqualTo(SendingStatus.pending); }) // timestamp & inclusive & reverse .optional(isPrevious, (q) { return q.createdAtLessThan(timestamp, include: params.inclusive); }) .optional(isPrevious == false, (q) { return q.createdAtGreaterThan(timestamp, include: params.inclusive); }) // messageType .optional(params.messageType == MessageTypeFilter.user, (q) { return q.messageTypeEqualTo(MessageType.user); }) .optional(params.messageType == MessageTypeFilter.file, (q) { return q.messageTypeEqualTo(MessageType.file); }) .optional(params.messageType == MessageTypeFilter.admin, (q) { return q.messageTypeEqualTo(MessageType.admin); }) // customTypes .optional(params.customTypes != null, (q) { return q.group((groupQ) { late QueryBuilder<CChannelMessage, CChannelMessage, QAfterFilterCondition> qb; bool isFirst = true; for (final customType in params.customTypes!) { if (isFirst) { qb = groupQ.customTypeEqualTo(customType); isFirst = false; } else { qb = qb.or().customTypeEqualTo(customType); } } return qb; }); }) // senderIds .optional(params.senderIds != null, (q) { return q.group((groupQ) { late QueryBuilder<CChannelMessage, CChannelMessage, QAfterFilterCondition> qb; bool isFirst = true; for (final senderId in params.senderIds!) { if (isFirst) { qb = groupQ.senderIdEqualTo(senderId); isFirst = false; } else { qb = qb.or().senderIdEqualTo(senderId); } } return qb; }); }) // isPrevious & reverse .optional(isPrevious, (q) { return q.sortByCreatedAtDesc(); }) .optional(isPrevious == false, (q) { return q.thenByCreatedAt(); }) // previousResultSize & params.nextResultSize .limit(isPrevious ? params.previousResultSize : params.nextResultSize) .findAll(); List<RootMessage> messages = []; for (final cChannelMessage in cChannelMessages) { final message = await cChannelMessage.toChannelMessage(chat, isar); if (message != null) { messages.add(message.message); } } // reversed if (messages.length >= 2) { if ((isPrevious && !params.reverse) || (!isPrevious && params.reverse)) { messages = messages.reversed.toList(); } } return messages; } static Future<List<BaseMessage>> getPendingMessages( Chat chat, Isar isar, ChannelType channelType, String channelUrl, ) async { final cChannelMessages = await isar.cChannelMessages .where() .channelTypeChannelUrlEqualTo(channelType, channelUrl) .filter() .sendingStatusEqualTo(SendingStatus.pending) .sortByCreatedAt() .findAll(); List<BaseMessage> messages = []; for (final cChannelMessage in cChannelMessages) { final message = await cChannelMessage.toChannelMessage(chat, isar); if (message != null && message.message is BaseMessage) { messages.add(message.message as BaseMessage); } } return messages; } static Future<List<BaseMessage>> getFailedMessages( Chat chat, Isar isar, ChannelType channelType, String channelUrl, bool reverse, ) async { final cChannelMessages = await isar.cChannelMessages .where() .channelTypeChannelUrlEqualTo(channelType, channelUrl) .filter() .sendingStatusEqualTo(SendingStatus.failed) .optional(!reverse, (q) => q.sortByCreatedAt()) .optional(reverse, (q) => q.thenByCreatedAtDesc()) .findAll(); List<BaseMessage> messages = []; for (final cChannelMessage in cChannelMessages) { final message = await cChannelMessage.toChannelMessage(chat, isar); if (message != null && message.message is BaseMessage) { messages.add(message.message as BaseMessage); } } return messages; } static Future<void> removeFailedMessages( Chat chat, Isar isar, ChannelType channelType, String channelUrl, List<BaseMessage> messages, ) async { await chat.dbManager.write(() async { // ChannelMessage await isar.cChannelMessages.deleteAllByRootId(messages .where((message) => message.sendingStatus == SendingStatus.failed) .map((message) => message.rootId) .toList()); // UserMessage await isar.cUserMessages.deleteAllByRootId(messages .where((message) => message.sendingStatus == SendingStatus.failed) .map((message) => message.rootId) .toList()); // FileMessage await isar.cFileMessages.deleteAllByRootId(messages .where((message) => message.sendingStatus == SendingStatus.failed) .map((message) => message.rootId) .toList()); }); } static Future<void> removeAllFailedMessages( Chat chat, Isar isar, ChannelType channelType, String channelUrl, ) async { await chat.dbManager.write(() async { // ChannelMessage await isar.cChannelMessages .where() .channelTypeChannelUrlEqualTo(channelType, channelUrl) .filter() .sendingStatusEqualTo(SendingStatus.failed) .deleteAll(); // UserMessage await isar.cUserMessages .where() .channelTypeChannelUrlEqualTo(channelType, channelUrl) .filter() .sendingStatusEqualTo(SendingStatus.failed) .deleteAll(); // FileMessage await isar.cFileMessages .where() .channelTypeChannelUrlEqualTo(channelType, channelUrl) .filter() .sendingStatusEqualTo(SendingStatus.failed) .deleteAll(); }); } static Future<void> removeAllPendingMessages( Chat chat, Isar isar, ChannelType channelType, String channelUrl, ) async { await chat.dbManager.write(() async { // ChannelMessage await isar.cChannelMessages .where() .channelTypeChannelUrlEqualTo(channelType, channelUrl) .filter() .sendingStatusEqualTo(SendingStatus.pending) .deleteAll(); // UserMessage await isar.cUserMessages .where() .channelTypeChannelUrlEqualTo(channelType, channelUrl) .filter() .sendingStatusEqualTo(SendingStatus.pending) .deleteAll(); // FileMessage await isar.cFileMessages .where() .channelTypeChannelUrlEqualTo(channelType, channelUrl) .filter() .sendingStatusEqualTo(SendingStatus.pending) .deleteAll(); }); } static Future<List<RootMessage>> getStartingPointMessages( Chat chat, Isar isar, ChannelType channelType, String channelUrl, int timestamp, ) async { // [includeMetaArray] // When calling API, this value have to be `true` to make chunk. // [includeReactions] // When calling API, this value have to be `true` to make chunk. // [includeThreadInfo] // When calling API, this value have to be `true` to make chunk. // [includeParentMessageInfo] // When calling API, this value have to be `true` to make chunk. // [replyType] // Must call API, because this can not be queried with local cache. // [showSubChannelMessagesOnly] // Must call API, because this can not be queried with local cache. final cChannelMessages = await isar.cChannelMessages .where() // channelType & channelUrl & reverse .channelTypeChannelUrlEqualTo(channelType, channelUrl) .filter() // timestamp .createdAtEqualTo(timestamp) // no limit .findAll(); List<RootMessage> messages = []; for (final cChannelMessage in cChannelMessages) { final message = await cChannelMessage.toChannelMessage(chat, isar); if (message != null) { messages.add(message.message); } } return messages; } static Future<void> delete(Chat chat, Isar isar, String rootId) async { await chat.dbManager.write(() async { await isar.cChannelMessages.deleteByRootId(rootId); }); } }
import datetime from wtforms import validators, fields, widgets from flask_wtf import FlaskForm from flask_wtf.file import FileAllowed from .fields import TagListField from banchi_client import models class TransactionForm(FlaskForm): date = fields.DateTimeField( "Date", format="%Y-%m-%d %H:%M:%S", widget=widgets.TextInput(), default=datetime.datetime.now, ) from_account_book_id = fields.SelectField("From Account Book") to_account_book_id = fields.SelectField("To Account Book") description = fields.StringField( "Description", validators=[validators.InputRequired()] ) value = fields.DecimalField( "Value", validators=[validators.InputRequired()], default=0, places=2 ) currency = fields.SelectField( "Currency", validators=[validators.InputRequired()], choices=[(e.value, e.value.upper()) for e in models.CurrencyEnum], )
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.connector; import java.io.IOException; import java.io.Reader; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.servlet.ReadListener; import org.apache.catalina.security.SecurityUtil; import org.apache.coyote.ActionCode; import org.apache.coyote.ContainerThreadMarker; import org.apache.coyote.Request; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.collections.SynchronizedStack; import org.apache.tomcat.util.net.ApplicationBufferHandler; import org.apache.tomcat.util.res.StringManager; /** * The buffer used by Tomcat request. This is a derivative of the Tomcat 3.3 * OutputBuffer, adapted to handle input instead of output. This allows * complete recycling of the facade objects (the ServletInputStream and the * BufferedReader). * * @author Remy Maucherat */ public class InputBuffer extends Reader implements ByteChunk.ByteInputChannel, ApplicationBufferHandler { /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(InputBuffer.class); private static final Log log = LogFactory.getLog(InputBuffer.class); public static final int DEFAULT_BUFFER_SIZE = 8 * 1024; // The buffer can be used for byte[] and char[] reading // ( this is needed to support ServletInputStream and BufferedReader ) public final int INITIAL_STATE = 0; public final int CHAR_STATE = 1; public final int BYTE_STATE = 2; /** * Encoder cache. */ private static final ConcurrentMap<Charset, SynchronizedStack<B2CConverter>> encoders = new ConcurrentHashMap<>(); // ----------------------------------------------------- Instance Variables /** * The byte buffer. */ private ByteBuffer bb; /** * The char buffer. */ private CharBuffer cb; /** * State of the output buffer. */ private int state = 0; /** * Flag which indicates if the input buffer is closed. */ private boolean closed = false; /** * Encoding to use. */ private String enc; /** * Current byte to char converter. */ protected B2CConverter conv; /** * Associated Coyote request. */ private Request coyoteRequest; /** * Buffer position. */ private int markPos = -1; /** * Char buffer limit. */ private int readLimit; /** * Buffer size. */ private final int size; // ----------------------------------------------------------- Constructors /** * Default constructor. Allocate the buffer with the default buffer size. */ public InputBuffer() { this(DEFAULT_BUFFER_SIZE); } /** * Alternate constructor which allows specifying the initial buffer size. * * @param size Buffer size to use */ public InputBuffer(int size) { this.size = size; bb = ByteBuffer.allocate(size); clear(bb); cb = CharBuffer.allocate(size); clear(cb); readLimit = size; } // ------------------------------------------------------------- Properties /** * Associated Coyote request. * * @param coyoteRequest Associated Coyote request */ public void setRequest(Request coyoteRequest) { this.coyoteRequest = coyoteRequest; } // --------------------------------------------------------- Public Methods /** * Recycle the output buffer. */ public void recycle() { state = INITIAL_STATE; // If usage of mark made the buffer too big, reallocate it if (cb.capacity() > size) { cb = CharBuffer.allocate(size); clear(cb); } else { clear(cb); } readLimit = size; markPos = -1; clear(bb); closed = false; if (conv != null) { conv.recycle(); encoders.get(conv.getCharset()).push(conv); conv = null; } enc = null; } /** * Close the input buffer. * * @throws IOException An underlying IOException occurred */ @Override public void close() throws IOException { closed = true; } public int available() { int available = availableInThisBuffer(); if (available == 0) { coyoteRequest.action(ActionCode.AVAILABLE, Boolean.valueOf(coyoteRequest.getReadListener() != null)); available = (coyoteRequest.getAvailable() > 0) ? 1 : 0; } return available; } private int availableInThisBuffer() { int available = 0; if (state == BYTE_STATE) { available = bb.remaining(); } else if (state == CHAR_STATE) { available = cb.remaining(); } return available; } public void setReadListener(ReadListener listener) { coyoteRequest.setReadListener(listener); } public boolean isFinished() { int available = 0; if (state == BYTE_STATE) { available = bb.remaining(); } else if (state == CHAR_STATE) { available = cb.remaining(); } if (available > 0) { return false; } else { return coyoteRequest.isFinished(); } } public boolean isReady() { if (coyoteRequest.getReadListener() == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("inputBuffer.requiresNonBlocking")); } return false; } if (isFinished()) { // If this is a non-container thread, need to trigger a read // which will eventually lead to a call to onAllDataRead() via a // container thread. if (!ContainerThreadMarker.isContainerThread()) { coyoteRequest.action(ActionCode.DISPATCH_READ, null); coyoteRequest.action(ActionCode.DISPATCH_EXECUTE, null); } return false; } // Checking for available data at the network level and registering for // read can be done sequentially for HTTP/1.x and AJP as there is only // ever a single thread processing the socket at any one time. However, // for HTTP/2 there is one thread processing the connection and separate // threads for each stream. For HTTP/2 the two operations have to be // performed atomically else it is possible for the connection thread to // read more data in to the buffer after the stream thread checks for // available network data but before it registers for read. if (availableInThisBuffer() > 0) { return true; } return coyoteRequest.isReady(); } boolean isBlocking() { return coyoteRequest.getReadListener() == null; } // ------------------------------------------------- Bytes Handling Methods /** * Reads new bytes in the byte chunk. * * @throws IOException An underlying IOException occurred */ @Override public int realReadBytes() throws IOException { if (closed) { return -1; } if (coyoteRequest == null) { return -1; } if (state == INITIAL_STATE) { state = BYTE_STATE; } try { return coyoteRequest.doRead(this); } catch (IOException ioe) { coyoteRequest.setErrorException(ioe); // An IOException on a read is almost always due to // the remote client aborting the request. throw new ClientAbortException(ioe); } } public int readByte() throws IOException { throwIfClosed(); if (checkByteBufferEof()) { return -1; } return bb.get() & 0xFF; } public int read(byte[] b, int off, int len) throws IOException { throwIfClosed(); if (checkByteBufferEof()) { return -1; } int n = Math.min(len, bb.remaining()); bb.get(b, off, n); return n; } /** * Transfers bytes from the buffer to the specified ByteBuffer. After the * operation the position of the ByteBuffer will be returned to the one * before the operation, the limit will be the position incremented by * the number of the transferred bytes. * * @param to the ByteBuffer into which bytes are to be written. * @return an integer specifying the actual number of bytes read, or -1 if * the end of the stream is reached * @throws IOException if an input or output exception has occurred */ public int read(ByteBuffer to) throws IOException { throwIfClosed(); if (checkByteBufferEof()) { return -1; } int n = Math.min(to.remaining(), bb.remaining()); int orgLimit = bb.limit(); bb.limit(bb.position() + n); to.put(bb); bb.limit(orgLimit); to.limit(to.position()).position(to.position() - n); return n; } // ------------------------------------------------- Chars Handling Methods /** * @param s New encoding value * * @deprecated This method will be removed in Tomcat 9.0.x */ @Deprecated public void setEncoding(String s) { enc = s; } public int realReadChars() throws IOException { checkConverter(); boolean eof = false; if (bb.remaining() <= 0) { int nRead = realReadBytes(); if (nRead < 0) { eof = true; } } if (markPos == -1) { clear(cb); } else { // Make sure there's enough space in the worst case makeSpace(bb.remaining()); if ((cb.capacity() - cb.limit()) == 0 && bb.remaining() != 0) { // We went over the limit clear(cb); markPos = -1; } } state = CHAR_STATE; conv.convert(bb, cb, this, eof); if (cb.remaining() == 0 && eof) { return -1; } else { return cb.remaining(); } } @Override public int read() throws IOException { throwIfClosed(); if (checkCharBufferEof()) { return -1; } return cb.get(); } @Override public int read(char[] cbuf) throws IOException { throwIfClosed(); return read(cbuf, 0, cbuf.length); } @Override public int read(char[] cbuf, int off, int len) throws IOException { throwIfClosed(); if (checkCharBufferEof()) { return -1; } int n = Math.min(len, cb.remaining()); cb.get(cbuf, off, n); return n; } @Override public long skip(long n) throws IOException { throwIfClosed(); if (n < 0) { throw new IllegalArgumentException(); } long nRead = 0; while (nRead < n) { if (cb.remaining() >= n) { cb.position(cb.position() + (int) n); nRead = n; } else { nRead += cb.remaining(); cb.position(cb.limit()); int nb = realReadChars(); if (nb < 0) { break; } } } return nRead; } @Override public boolean ready() throws IOException { throwIfClosed(); if (state == INITIAL_STATE) { state = CHAR_STATE; } return (available() > 0); } @Override public boolean markSupported() { return true; } @Override public void mark(int readAheadLimit) throws IOException { throwIfClosed(); if (cb.remaining() <= 0) { clear(cb); } else { if ((cb.capacity() > (2 * size)) && (cb.remaining()) < (cb.position())) { cb.compact(); cb.flip(); } } readLimit = cb.position() + readAheadLimit + size; markPos = cb.position(); } @Override public void reset() throws IOException { throwIfClosed(); if (state == CHAR_STATE) { if (markPos < 0) { clear(cb); markPos = -1; IOException ioe = new IOException(); coyoteRequest.setErrorException(ioe); throw ioe; } else { cb.position(markPos); } } else { clear(bb); } } private void throwIfClosed() throws IOException { if (closed) { IOException ioe = new IOException(sm.getString("inputBuffer.streamClosed")); coyoteRequest.setErrorException(ioe); throw ioe; } } public void checkConverter() throws IOException { if (conv != null) { return; } Charset charset = null; if (coyoteRequest != null) { charset = coyoteRequest.getCharset(); } if (charset == null) { if (enc == null) { charset = org.apache.coyote.Constants.DEFAULT_BODY_CHARSET; } else { charset = B2CConverter.getCharset(enc); } } SynchronizedStack<B2CConverter> stack = encoders.get(charset); if (stack == null) { stack = new SynchronizedStack<>(); encoders.putIfAbsent(charset, stack); stack = encoders.get(charset); } conv = stack.pop(); if (conv == null) { conv = createConverter(charset); } } private static B2CConverter createConverter(final Charset charset) throws IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { return AccessController.doPrivileged(new PrivilegedExceptionAction<B2CConverter>() { @Override public B2CConverter run() throws IOException { return new B2CConverter(charset); } }); } catch (PrivilegedActionException ex) { Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException) e; } else { throw new IOException(e); } } } else { return new B2CConverter(charset); } } @Override public void setByteBuffer(ByteBuffer buffer) { bb = buffer; } @Override public ByteBuffer getByteBuffer() { return bb; } @Override public void expand(int size) { // no-op } private boolean checkByteBufferEof() throws IOException { if (bb.remaining() == 0) { int n = realReadBytes(); if (n < 0) { return true; } } return false; } private boolean checkCharBufferEof() throws IOException { if (cb.remaining() == 0) { int n = realReadChars(); if (n < 0) { return true; } } return false; } private void clear(Buffer buffer) { buffer.rewind().limit(0); } private void makeSpace(int count) { int desiredSize = cb.limit() + count; if(desiredSize > readLimit) { desiredSize = readLimit; } if(desiredSize <= cb.capacity()) { return; } int newSize = 2 * cb.capacity(); if(desiredSize >= newSize) { newSize= 2 * cb.capacity() + count; } if (newSize > readLimit) { newSize = readLimit; } CharBuffer tmp = CharBuffer.allocate(newSize); int oldPosition = cb.position(); cb.position(0); tmp.put(cb); tmp.flip(); tmp.position(oldPosition); cb = tmp; tmp = null; } }
import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.LinkedList; import java.util.Iterator; import java.util.StringTokenizer; /** * @author: Wayne Iba * @date: 3-12-2012 * @version: Beta 0.5 * * BaseAgent controls a GOBAgent by either moving toward the food as given by * the smell sense, OR by moving toward another agent that is visible in its * field of view. The idea is to very simply enable a following behavior */ public class BaseAgent { private GridClient gc; private String retImage; private static final String retinalActionMap = "lbbbrll rrlfffrffffffffffffffffffff"; private static final int cellSize = 40; private static final int cx = 5; private static final int ry = 7; private static final int dashHeight=200; private LinkedList visField; private LinkedList visAgents; private GridDisplay gd; private boolean displaySense = true; private boolean termOut = false; // whether to display ascii form of visual map private String myID; // sensory fields private char smell = '?'; private String heading; private String inventory; private String ground; private String message; private String energy; private String lastActionStatus; private String worldTime; public BaseAgent(String h, int p) { gc = new GridClient(h, p); myID = gc.myID; visField = new LinkedList(); //the visual field contents will be held in linked list visAgents = new LinkedList(); //gd = new GridDisplay(cx, ry, cellSize); //initialize the graphical display //db = new Dashboard(cx * cellSize, dashHeight, gridOut); //add(gd); //add(db); } /** * chooseAction : check for a visible agent in the field of view * and move toward it if visible -- otherwise follow the nose toward food */ public String chooseAction() { // following another agent if present if ( inventory.length() > 2 && inventory.charAt(2) == '+' ) return "u"; else if ( smell == 'h' ) return "g +"; else if ( lastActionStatus.equals("fail") ) return "w"; else if ( ! visAgents.isEmpty() ) { GOBAgent tag = (GOBAgent) visAgents.getFirst(); int idx = (6 - tag.pos.y)*5 + tag.pos.x; return retinalActionMap.substring( idx, idx+1 ); } else return String.valueOf(smell); } /** * getSensoryInfo gets the direcion to the food * LINE0: # of lines to be sent or one of: die, success, or End * LINE1: smell (food direction) * LINE2: inventory * LINE3: visual contents * LINE4: ground contents * LINE5: messages * LINE6: remaining energy * LINE7: lastActionStatus * LINE8: world time * pre: gridIn is initialized and connected to the grid server socket * post: heading stores direction to the food f, b, l, r, or h */ public void getSensoryInfo() { String[] senseData = gc.sensoryGet(); // 1: get the smell info smell = senseData[0].toCharArray()[0]; heading = direction(smell); // 2: get the inventory inventory = senseData[1]; // 3: process the visual info processRetinalField(senseData[2]); // 4: get ground contents ground = senseData[3]; // 5: get messages message = senseData[4]; //CHECKS MESSAGES ****CHANGE**** // 6: energy energy = senseData[5]; // 7: lastActionStatus lastActionStatus = senseData[6]; // 8: world time worldTime = senseData[7]; // store or update according to the data just read. . . . //gd.updateGDObjects(visField); //db.updateLabels(heading, inventory, ground, energy, message, lastActionStatus, worldTime); } /* processRetinalField: takes a string input from the Maeden server and converts it into the GridObjects * Pre: String info contains list of list of list of chars(?) * Post: visual raphical map is constructed */ protected void processRetinalField(String info) { StringTokenizer visTokens = new StringTokenizer(info, "(", true); visTokens.nextToken(); visField.clear(); for (int i = 6; i >= 0; i--) { //iterate backwards so character printout displays correctly visTokens.nextToken(); for (int j=0; j <=4; j++) { //iterate through the columns visTokens.nextToken(); String visChars = visTokens.nextToken(); char[] visArray = visChars.toCharArray(); for(int x = 0; x < visChars.length(); x++) { char cellChar = visArray[x]; switch(cellChar) { //add the GridObjects for the graphical display case ' ': break; case '@': visField.addLast(new GOBRock(j, i, cellSize)); break; //Rock case '+': visField.addLast(new GOBFood(j, i, cellSize)); break; //Food case '#': visField.addLast(new GOBDoor(j, i, cellSize)); break; //Door case '*': visField.addLast(new GOBWall(j, i, cellSize)); break; //Wall case '=': visField.addLast(new GOBNarrows(j, i, cellSize)); break; //Narrows case 'K': visField.addLast(new GOBKey(j, i, cellSize)); break; //Key case 'T': visField.addLast(new GOBHammer(j, i, cellSize)); break; //Hammer case 'Q': visField.addLast(new GOBQuicksand(j, i, cellSize)); break; //Quicksand case 'O': visField.addLast(new GOBFoodCollect(j, i, cellSize)); break; //Food Collection case '$': visField.addLast(new GOBGold(j, i, cellSize, gd)); break; //Gold default: if(cellChar >= '0' && cellChar <= '9' && cellChar != String.valueOf(gc.myID).charAt(0)){ GOBAgent agnt = new GOBAgent(j, i, cellSize, 'N'); visField.addLast(agnt); visAgents.addLast(agnt); } else if((cellChar >= '0' && cellChar <= '9' && cellChar != String.valueOf(gc.myID).charAt(0) ) || cellChar == 'H') { GOBAgent agnt = new GOBAgent(j, i, cellSize, '?'); visField.addLast(agnt); visAgents.addLast(agnt); } } } //System.out.println("i: " + i + " j: " + j); } } } /** * direction and returns a string to display in the terminal * pre: heading has value f, b, l, r, or h * post: corresponding string is returned */ public String direction(char h) { switch(h) { case 'f': return "forward"; case 'b': return "back"; case 'l': return "left"; case 'r': return "right"; case 'h': return "here!"; } return "error with the direction"; } /** * run: .... */ public void run(){ while (true) { visAgents.clear(); getSensoryInfo(); //displaySenseInfo(); gc.effectorSend(chooseAction()); try {Thread.sleep(1000);} catch (Exception e) {System.out.println("failed sleeping"); } //gd.repaint(); } } /** * main: kicks things off */ public static void main(String[] args){ BaseAgent ba = new BaseAgent("localhost", GridClient.MAEDENPORT); ba.run(); } }
import 'package:cinemapedia/domain/entities/movie.dart'; abstract class LocalStorageRepository { // NOTA: Esto lo podemos hacer mandado la pelicula, o simplemente un booleano y de hecho lo vamos a hacer de las dos formas Future<void> toggleFavorite(Movie movie); Future<bool> isMovieFavorite(int movieId); // NOTA: Este método me va a ayudar a hacer la paginación donde el limit es para irlos cargando de 10 en 10 y el offset es para // hacer la paginación Future<List<Movie>> loadMovies({int limit = 10, offset = 0}); }
// GuildMemberData.ts - Module for my "guild member data" class. // Apr 5, 2021 // Chris M. // https://github.com/RealTimeChris 'use strict'; import Level from 'level-ts'; import FoundationClasses from './FoundationClasses'; /** * Class representing the init data for a guild member data structure. */ interface GuildMemberDataInitData { dataBase: Level; displayName: string; guildId: string; id: string; userName: string; } /** * Class representing a single guild member. */ export default class GuildMemberData extends FoundationClasses.DiscordEntity { public static readonly guildMembersData: Map<string, GuildMemberData> = new Map<string, GuildMemberData>(); public readonly dataBase: Level; public readonly dataBaseKey: string; public readonly displayName: string; public readonly guildId: string; public readonly id: string; public readonly userName: string; public currency: FoundationClasses.Currency = {timeOfLastDeposit: 0, wallet: 10000, bank: 10000}; public items: FoundationClasses.InventoryItem[] = []; public lastTimeRobbed: number = 0; public lastTimeWorked: number = 0; public roles: FoundationClasses.InventoryRole[] = []; public async getFromDataBase(): Promise<void> { try{ const guildMemberData = await this.dataBase.get(this.dataBaseKey) as GuildMemberData; this.currency = guildMemberData.currency; this.items = guildMemberData.items; this.lastTimeRobbed = guildMemberData.lastTimeRobbed; this.lastTimeWorked = guildMemberData.lastTimeWorked; this.roles = guildMemberData.roles; } catch(error) { if (error.type === 'NotFoundError') { console.log(`No entry found for user by the Id of ${this.id} with name ${this.userName}, creating one!`); console.log(this); } } } public async writeToDataBase(): Promise<void> { if (this.userName === ''|| this.displayName === '') { const error = new Error(); error.name = "Non-Initialized Structure"; error.message = "You've forgotten to initialize the GuildMemberData structure!"; throw error; } await this.dataBase.put(this.dataBaseKey, this); GuildMemberData.guildMembersData.set(this.dataBaseKey, this); } constructor(initData: GuildMemberDataInitData) { super(); const IdRegExp = /\d{17,18}/; this.dataBase = initData.dataBase; this.displayName = initData.displayName.trim(); this.guildId = initData.guildId.trim(); this.id = initData.id.trim(); this.userName = initData.userName.trim(); if (!IdRegExp.test(this.id)|| !IdRegExp.test(this.guildId)) { const error = new Error(); error.name = "Guild Member Id and/or Guild Id Issue"; error.message = "You've passed an invalid guild member Id and/or guild Id to the constructor:\n" + this.id + "\n" + this.guildId; throw error; } this.dataBaseKey = this.guildId + " + " + this.id; } }
#!/usr/bin/env python2 # -*- coding: utf8 -*- # Terminator by Chris Jones <cmsj@tenshu.net> # GPL v2 only """titlebar.py - classes necessary to provide a terminal title bar""" from gi.repository import Gtk, Gdk from gi.repository import GObject from gi.repository import Pango import random import itertools from version import APP_NAME from util import dbg, uhoextract, get_home_dir from terminator import Terminator from editablelabel import EditableLabel from translation import _ # pylint: disable-msg=R0904 # pylint: disable-msg=W0613 class Titlebar(Gtk.EventBox): """Class implementing the Titlebar widget""" terminator = None terminal = None config = None oldtitle = None termtext = None label = None ebox = None groupicon = None grouplabel = None groupentry = None bellicon = None _autotext = '' _tsize = '' _tabcapt = '' sizetext = '' titlefixed = False # True # False custom_title = '' # raw _ctitle = '' # output _ostitle = '' custom_caption = '' _tabcapt = '' custom_env = '' _custenv = '' hidesize = None __gsignals__ = { 'clicked': (GObject.SignalFlags.RUN_LAST, None, ()), 'edit-done': (GObject.SignalFlags.RUN_LAST, None, ()), 'create-group': (GObject.SignalFlags.RUN_LAST, None, (GObject.TYPE_STRING,)), } def __init__(self, terminal): """Class initialiser""" GObject.GObject.__init__(self) self.terminator = Terminator() self.terminal = terminal self.config = self.terminal.config self.label = EditableLabel() self.label.connect('edit-done', self.on_edit_done) self.ebox = Gtk.EventBox() grouphbox = Gtk.HBox() self.grouplabel = Gtk.Label(ellipsize='end') self.groupicon = Gtk.Image() self.bellicon = Gtk.Image() self.bellicon.set_no_show_all(True) self.titlefixed = False self.groupentry = Gtk.Entry() self.groupentry.set_no_show_all(True) self.groupentry.connect('focus-out-event', self.groupentry_cancel) self.groupentry.connect('activate', self.groupentry_activate) self.groupentry.connect('key-press-event', self.groupentry_keypress) groupsend_type = self.terminator.groupsend_type if self.terminator.groupsend == groupsend_type['all']: icon_name = 'all' elif self.terminator.groupsend == groupsend_type['group']: icon_name = 'group' elif self.terminator.groupsend == groupsend_type['off']: icon_name = 'off' self.set_from_icon_name('_active_broadcast_%s' % icon_name, Gtk.IconSize.MENU) grouphbox.pack_start(self.groupicon, False, True, 2) grouphbox.pack_start(self.grouplabel, False, True, 2) grouphbox.pack_start(self.groupentry, False, True, 2) self.ebox.add(grouphbox) self.ebox.show_all() self.bellicon.set_from_icon_name('terminal-bell', Gtk.IconSize.MENU) viewport = Gtk.Viewport(hscroll_policy='natural') viewport.add(self.label) hbox = Gtk.HBox() hbox.pack_start(self.ebox, False, True, 0) hbox.pack_start(Gtk.VSeparator(), False, True, 0) hbox.pack_start(viewport, True, True, 0) hbox.pack_end(self.bellicon, False, False, 2) self.add(hbox) hbox.show_all() self.set_no_show_all(True) self.show() self.connect('button-press-event', self.on_clicked) def connect_icon(self, func): """Connect the supplied function to clicking on the group icon""" self.ebox.connect('button-press-event', func) def update_visibility(self): """Make the titlebar be visible or not""" if not self.get_desired_visibility(): dbg('hiding titlebar') self.hide() self.label.hide() else: dbg('showing titlebar') self.show() self.label.show() def get_desired_visibility(self): """Returns True if the titlebar is supposed to be visible. False if not""" if self.editing() == True or self.terminal.group: dbg('implicit desired visibility') return(True) else: dbg('configured visibility: %s' % self.config['show_titlebar']) return(self.config['show_titlebar']) def set_from_icon_name(self, name, size = Gtk.IconSize.MENU): """Set an icon for the group label""" if not name: self.groupicon.hide() return self.groupicon.set_from_icon_name(APP_NAME + name, size) self.groupicon.show() def update_terminal_size(self, width, height): """Update the displayed terminal size""" self.sizetext = " %sx%s" % (width, height) self.update() def update_terminal_title(self, widget, title): """Update the terminal title from signal""" # self._tabcapt self._ctitle self._autotext self._tsize self._ostitle = title self.update() # Return False so we don't interrupt any chains of signal handling return False def get_custom_title(self): """Return custom title if it is set, otherwise return empty """ return self.custom_title def set_custom_title(self, ctitle): """Set a custom title""" if ctitle: self.custom_title = ctitle self._ctitle = "%s| " % ctitle self.label.set_edit_base("%s" % ctitle) else: self.custom_title = '' self._ctitle = '' self.label.set_edit_base('NewTitle') self.update() def set_custom_caption(self, capt): """Set tabcaption""" if capt: self.custom_caption = capt self._tabcapt = "[%s] " % capt else: self.custom_caption = '' self._tabcapt = '' self.update() def set_custom_env(self, cenv): """Set custom environment name""" if cenv: self._custenv = "env:%s " % cenv else: self._custenv = '' self.update() def make_labeltext(self): title = self._ostitle # FIXME title fiddling assumes standard linux PS1 # pobably we oughta get cwd ourselves if not title: title = 'user@host:/some/path' pathpart = self.terminal.get_cwd() homepart = get_home_dir() if pathpart.startswith(homepart): # Tilde is barely noticeable with system font on high dpi displays. #pathpart = pathpart.replace(homepart,'<HOME>',1) pathpart = pathpart.replace(homepart,'⁓',1) if self.titlefixed: if self._ctitle: self._autotext = '' elif self.config['title_hide_userhost']: self._autotext = '@' else: # user OR remote OR R@REMOTE self._autotext = "%s" % uhoextract(title, smart=True) elif self.config['title_hide_path'] \ and self.config['title_hide_userhost']: self._autotext = r'.' elif self.config['title_hide_path']: self._autotext = "%s" % uhoextract(title) elif self.config['title_hide_userhost']: self._autotext = "%s" % pathpart else: self._autotext = "%s" % title # forcibly show at bar even if tabs are hidden if self.config['title_hide_tabcaption'] \ and not self.config['tabs_hidden']: self._tabcapt = '' elif self.custom_caption: self._tabcapt = "[%s] " % self.custom_caption else: self._tabcapt = '' if self.config['title_hide_sizetext']: self._tsize = '' else: self._tsize = self.sizetext def update(self, other=None): """Update our contents""" default_bg = False self.make_labeltext() #self.label.set_text("%s%s%s%s%s" % (self._tabcapt, self._ctitle, self._custenv, self._autotext, self._tsize), force=True) self.label.set_text("%s%s%s%s%s" % (self._custenv, self._tabcapt, self._ctitle, self._autotext, self._tsize), force=True) if (not self.config['title_use_system_font']) and self.config['title_font']: title_font = Pango.FontDescription(self.config['title_font']) else: title_font = Pango.FontDescription(self.config.get_system_prop_font()) self.label.modify_font(title_font) self.grouplabel.modify_font(title_font) if other: term = self.terminal terminator = self.terminator if other == 'window-focus-out': title_fg = self.config['title_inactive_fg_color'] title_bg = self.config['title_inactive_bg_color'] icon = '_receive_off' default_bg = True group_fg = self.config['title_inactive_fg_color'] group_bg = self.config['title_inactive_bg_color'] elif term != other and term.group and term.group == other.group: if terminator.groupsend == terminator.groupsend_type['off']: title_fg = self.config['title_inactive_fg_color'] title_bg = self.config['title_inactive_bg_color'] icon = '_receive_off' default_bg = True else: title_fg = self.config['title_receive_fg_color'] title_bg = self.config['title_receive_bg_color'] icon = '_receive_on' group_fg = self.config['title_receive_fg_color'] group_bg = self.config['title_receive_bg_color'] elif term != other and not term.group or term.group != other.group: if terminator.groupsend == terminator.groupsend_type['all']: title_fg = self.config['title_receive_fg_color'] title_bg = self.config['title_receive_bg_color'] icon = '_receive_on' else: title_fg = self.config['title_inactive_fg_color'] title_bg = self.config['title_inactive_bg_color'] icon = '_receive_off' default_bg = True group_fg = self.config['title_inactive_fg_color'] group_bg = self.config['title_inactive_bg_color'] else: # We're the active terminal title_fg = self.config['title_transmit_fg_color'] title_bg = self.config['title_transmit_bg_color'] if terminator.groupsend == terminator.groupsend_type['all']: icon = '_active_broadcast_all' elif terminator.groupsend == terminator.groupsend_type['group']: icon = '_active_broadcast_group' else: icon = '_active_broadcast_off' group_fg = self.config['title_transmit_fg_color'] group_bg = self.config['title_transmit_bg_color'] self.label.modify_fg(Gtk.StateType.NORMAL, Gdk.color_parse(title_fg)) self.grouplabel.modify_fg(Gtk.StateType.NORMAL, Gdk.color_parse(group_fg)) self.modify_bg(Gtk.StateType.NORMAL, Gdk.color_parse(title_bg)) if not self.get_desired_visibility(): if default_bg == True: color = term.get_style_context().get_background_color(Gtk.StateType.NORMAL) # VERIFY FOR GTK3 else: color = Gdk.color_parse(title_bg) self.update_visibility() self.ebox.modify_bg(Gtk.StateType.NORMAL, Gdk.color_parse(group_bg)) self.set_from_icon_name(icon, Gtk.IconSize.MENU) def set_group_label(self, name): """Set the name of the group""" if name: self.grouplabel.set_text(name) self.grouplabel.show() else: self.grouplabel.set_text('') self.grouplabel.hide() self.update_visibility() def on_clicked(self, widget, event): """Handle a click on the label""" self.show() self.label.show() self.emit('clicked') def on_edit_done(self, widget): """Re-emit an edit-done signal from an EditableLabel""" if widget == self.label: if widget.is_custom(): self.set_custom_title(widget.get_text()) else: self.set_custom_title('') self.make_labeltext() self.emit('edit-done') def editing(self): """Determine if we're currently editing a group name or title""" return(self.groupentry.get_property('visible') or self.label.editing()) def create_group(self): """Create a new group""" if self.terminal.group: self.groupentry.set_text(self.terminal.group) else: defaultmembers=[_('Alpha'),_('Beta'),_('Gamma'),_('Delta'),_('Epsilon'),_('Zeta'),_('Eta'), _('Theta'),_('Iota'),_('Kappa'),_('Lambda'),_('Mu'),_('Nu'),_('Xi'), _('Omicron'),_('Pi'),_('Rho'),_('Sigma'),_('Tau'),_('Upsilon'),_('Phi'), _('Chi'),_('Psi'),_('Omega')] currentgroups=set(self.terminator.groups) for i in range(1,4): defaultgroups=set(map(''.join, list(itertools.product(defaultmembers,repeat=i)))) freegroups = list(defaultgroups-currentgroups) if freegroups: self.groupentry.set_text(random.choice(freegroups)) break else: self.groupentry.set_text('') self.groupentry.show() self.grouplabel.hide() self.groupentry.grab_focus() self.update_visibility() def groupentry_cancel(self, widget, event): """Hide the group name entry""" self.groupentry.set_text('') self.groupentry.hide() self.grouplabel.show() self.get_parent().grab_focus() def groupentry_activate(self, widget): """Actually cause a group to be created""" groupname = self.groupentry.get_text() or None dbg('Titlebar::groupentry_activate: creating group: %s' % groupname) self.groupentry_cancel(None, None) last_focused_term=self.terminator.last_focused_term if self.terminal.targets_for_new_group: [term.titlebar.emit('create-group', groupname) for term in self.terminal.targets_for_new_group] self.terminal.targets_for_new_group = None else: self.emit('create-group', groupname) last_focused_term.grab_focus() self.terminator.focus_changed(last_focused_term) def groupentry_keypress(self, widget, event): """Handle keypresses on the entry widget""" key = Gdk.keyval_name(event.keyval) if key == 'Escape': self.groupentry_cancel(None, None) def icon_bell(self): """A bell signal requires we display our bell icon""" self.bellicon.show() GObject.timeout_add(1000, self.icon_bell_hide) def icon_bell_hide(self): """Handle a timeout which means we now hide the bell icon""" self.bellicon.hide() return(False) GObject.type_register(Titlebar)
<?php /** * Callback function. here we prepare complete table for task * @return array */ function brilliant_pr_task_list_complete() { global $user; //Create a list of headers for Html table if (in_array('administrator', $user->roles) || in_array('curator', $user->roles)) { $header = array( array('data' => t('ID'), 'field' => 'tid', 'sort' => 'asc'), array('data' => t('Title'), 'field' => 'title'), array('data' => t('Project ref')), array('data' => t('Total time spent')), array('data' => t('Implementor'), 'field' => 'time_spent'), array('data' => t('Created'), 'field' => 'created'), array('data' => t('DDT'), 'field' => 'dead_time'), array('data' => t('Author')), array('data' => t('Author\'s email')), array('data' => t('Delete task')), ); } elseif (in_array('implementor', $user->roles)) { $header = array( array('data' => t('ID'), 'field' => 'tid', 'sort' => 'asc'), array('data' => t('Title'), 'field' => 'title'), array('data' => t('Project ref')), array('data' => t('Total time spent')), array('data' => t('Curator'), 'field' => 'time_spent'), array('data' => t('Created'), 'field' => 'created'), array('data' => t('DDT'), 'field' => 'dead_time'), array('data' => t('Author')), array('data' => t('Author\'s email')), ); } else { $header = array( array('data' => t('ID'), 'field' => 'tid', 'sort' => 'asc'), array('data' => t('Title'), 'field' => 'title'), array('data' => t('Project ref')), array('data' => t('Total time spent')), array('data' => t('Curator')), array('data' => t('Created'), 'field' => 'created'), array('data' => t('DDT'), 'field' => 'dead_time'), ); } //Create the Sql query. $query = db_select('brilliant_pr_task', 't') ->condition('status', '1', '=') //wait projects ->extend('PagerDefault') //Pager Extender ->limit(5) //5 results per page ->extend('TableSort') //Sorting Extender ->orderByHeader($header)//Field to sort on is picked from $header ->fields('t', array( 'tid', 'title', 'ref', 'created', 'dead_time', 'uid', 'implementor', 'curator', )); $results = $query ->execute(); $rows = array(); foreach ($results as $entity) { $project_entity = brilliant_pr_project_load($pid = $entity->ref); if ($user->uid && $account = user_load($entity->uid)) { if ($user->name == $entity->curator || in_array('administrator', $user->roles) || $user->name == $entity->implementor || $user->name == $project_entity->customer_name) { $user_name = $account->uid; $user_mail = $account->mail; $implementor = user_load_by_name($entity->implementor); $curator = user_load_by_name($entity->curator); if (in_array('administrator', $user->roles) || in_array('curator', $user->roles)) { $rows[] = array( 'data' => array( $entity->tid, l($entity->title, 'entity/brilliant_pr_task/basic/' . $entity->tid), isset($project_entity->pid) ? l($project_entity->title, 'entity/brilliant_pr_project/basic/' . $project_entity->pid) : '-', '-', get_name($implementor->uid), format_date($entity->created), date('Y-m-d H:i:s', $entity->dead_time), l(get_name($user_name), 'user/' . $entity->uid), l($user_mail, 'mailto:' . $user_mail), l(t('delete'), 'entity/brilliant_pr_task/basic/' . $entity->tid . '/remove'), ) ); #end row[] } elseif ($user->name == $entity->implementor) { $rows[] = array( 'data' => array( $entity->tid, l($entity->title, 'entity/brilliant_pr_task/basic/' . $entity->tid), isset($project_entity->pid) ? l($project_entity->title, 'entity/brilliant_pr_project/basic/' . $project_entity->pid) : '-', '-', get_name($curator->uid), format_date($entity->created), date('Y-m-d H:i:s', $entity->dead_time), l(get_name($user_name), 'user/' . $entity->uid), l($user_mail, 'mailto:' . $user_mail), ) ); #end row[] } else { $rows[] = array( 'data' => array( $entity->tid, l($entity->title, 'entity/brilliant_pr_task/basic/' . $entity->tid), isset($project_entity->pid) ? l($project_entity->title, 'entity/brilliant_pr_project/basic/' . $project_entity->pid) : '-', '-', get_name($implementor->uid), format_date($entity->created), date('Y-m-d H:i:s', $entity->dead_time), ) ); #end row[] } } } } #end foreach if (!empty($entity) && $user->name == $entity->curator || !empty($entity) && $user->name == $entity->implementor || !empty($entity) && in_array('administrator', $user->roles) || !empty($entity) && in_array('customer', $user->roles) ) { $content = t('Hello') . ', ' . get_name($user->uid) . '<br>'; if (in_array('administrator', $user->roles)) { $content .= l(t('Delete all tasks'), 'entity/brilliant_pr_task/basic/remove_all'); } $html = $content . theme('table', array( 'header' => $header, 'rows' => $rows, 'caption' => '<h3>' . t('Completed tasks') . '</h3>', //Optional Caption for the table 'sticky' => TRUE, //Optional to indicate whether the table headers should be sticky 'empty' => t('Not found any completed task.'), //Optional empty text for the table if result test is empty ) ); $html .= theme('pager', array( 'tags' => array(), ) ); } else { $content = '<div class="alert alert-info a-message alert-dismissable">'.'<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'.t('Not found any completed tasks.') .'</div>'; $html = $content; } return ($html); }
import React, { useEffect, useState } from "react"; const Clock = () => { const [currentTime, setCurrentTime] = useState(new Date()); useEffect(() => { const tickInterval = setInterval(() => { setCurrentTime(new Date()); }, 1000); return () => { clearInterval(tickInterval); }; }, []); // with no dependency, would cause an infinite loop return <span>{currentTime.toLocaleTimeString("en-US")}</span>; }; export default Clock;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>mart</title> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Roboto:300,300i,400,400i,500,500i,700,700i" rel="stylesheet"> <link rel="stylesheet" href="css/normalaize.css"> <link rel="stylesheet" href="css/styles.css"> </head> <body> <div class="wrapper"> <div class="container"> <header class="clearfix"> <h1 class="logo"><a href="#">mart</a></h1> <nav class="navigation"> <ul class="navigation-container"> <li class="navigation-item"><a href="#">home</a></li> <li class="navigation-item"><a href="#">about us</a></li> <li class="navigation-item"> <a href="#">page</a></li> <li class="navigation-item"><a href="#">shop</a></li> <li class="navigation-item"><a href="#">blog</a></li> <li class="navigation-item"><a href="#">contatc us</a></li> </ul> </nav> </header> <main> <section class="clearfix"> <h2 class="name">featured products</h2> <figure class="photo"> <img src="img/women shoes .jpg" alt="Shoes for Lady" width="255" height="282"> <figcaption><span class="cost">blue tshirt<span class="number1">$26</span></span></figcaption> </figure> <figure class="photo"> <img src="img/belt.jpg" alt="woman belt" width="255" height="282"> <figcaption><span class="cost">woman shirt<span class="number2">$31</span></span></figcaption> </figure> <figure class="photo"> <img src="img/hat.jpg" alt="hat" width="255" height="282"> <figcaption><span class="cost">yellow tshirt<span class="number3">$21</span></span></figcaption> </figure> <figure class="photo"> <img src="img/ladies` bag .jpg" alt="HANDBAG" width="255px" height="282px"> <figcaption><span class="cost">cool lingerie<span class="number4">$56</span></span></figcaption> </figure> </section> <section class="clearfix"> <figure class="photo"> <img src="img/handbag.jpg" alt="laxary Case" width="255" height="282"> <figcaption ><span class="cost">blue tshirt<span class="number1">$26</span></span></figcaption> </figure> <figure class="photo"> <img src="img/belt for woman.jpg" alt="belt for men" width="255" height="282"> <figcaption ><span class="cost">woman shirt<span class="number2">$31</span></span></figcaption> </figure> <figure class="photo"> <img src="img/shoes .jpg" alt="shoes" width="255" height="282"> <figcaption><span class="cost">yellow tshirt<span class="number3">$21</span></span></figcaption> </figure> <figure class="photo"> <img src="img/sunglasses.jpg" alt="sunglasses" width="255" height="282"> <figcaption><span class="cost">cool lingerie<span class="number4">$56</span></span></figcaption> </figure> </section> <section class="clearfix"> <h2 class="name2">latest news</h2> <div class="photo3"> <img src="img/mini-laptop.jpg" alt="mini-lasptop" width="347" height="261"> <h3 class="sign">Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet. Aenean </h3> <p class="describe">Nam nec tellus a odio tincidunt auc. Duis sed odio sit amet nibh vulputate cursus a sit amet mauris. Morbi accumsan ipsum velit. Nam nec tellus a odi</p> <button class="click">Read More</button> </div> <div class="photo3"> <img src="img/girls .png" alt="bus" width="347" height="261"> <h3 class="sign">Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet. Aenean </h3> <p class="describe">Nam nec tellus a odio tincidunt auc. Duis sed odio sit amet nibh vulputate cursus a sit amet mauris. Morbi accumsan ipsum velit. Nam nec tellus a odi</p> <button class="click">Read More</button> </div> <div class="photo3"> <img src="img/bus.jpg" alt="bus" width="347" height="261"> <h3 class="sign">Lorem Ipsum. Proin gravida nibh vel velit auctor aliquet. Aenean </h3> <p class="describe">Nam nec tellus a odio tincidunt auc. Duis sed odio sit amet nibh vulputate cursus a sit amet mauris. Morbi accumsan ipsum velit. Nam nec tellus a odi</p> <button class="click">Read More</button> </div> </section> </main> </div> </div> </body> </html>
const express = require("express"); const dotenv = require("dotenv"); const path = require("path"); const cors = require("cors"); const plaqueRouter = require("./routes/plaqueRouter"); const permisOneRouter = require("./routes/permisRouteOne"); const userRouter = require("./routes/usersRouter"); const permisRouter = require("./routes/permisRoute"); const histoRouter = require("./routes/histoRoutes"); const declarationsRouter = require("./routes/declarationsRouter"); const controleRouter = require("./routes/controleRouter"); const assuranceRouter = require("./routes/assuranceRouter"); const InfraRouter = require("./routes/infactionRoutes"); const payementRouter = require("./routes/payementRouter"); const bindUser = require("./middleware/bindUser"); const alertRouter = require("./routes/alertRouter"); const fileUpload = require("express-fileupload"); const signalementRouter = require("./routes/singalementRouter"); const immaPermisRouter = require("./routes/ImmatriPermisRoutes"); const voyageRouter = require("./routes/voyageRoutes"); const systRouter = require("./routes/systRouter"); const psrRouter = require("./routes/psrRouter"); const requireAuth = require("./middleware/requireAuth"); const app = express(); dotenv.config({ path: path.join(__dirname, "./.env") }); app.use(cors()); app.use(express.static(__dirname + "/public")); app.use(fileUpload()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.all("*", bindUser); app.use("/plaques", plaqueRouter); app.use("/permis", permisRouter); app.use("/numeroPermis", permisOneRouter); app.use("/permisOne", permisRouter); app.use("/opj_declarations", declarationsRouter); app.use("/controles", controleRouter); app.use("/assurances", assuranceRouter); app.use("/historiques", histoRouter); app.use("/infractions", InfraRouter); app.use("/users", userRouter); app.use("/payements", payementRouter); app.use("/alerts", alertRouter); app.use("/signalements", signalementRouter); app.use("/immaPermis", immaPermisRouter); app.use("/tracking", voyageRouter); app.use("/syst", systRouter); app.use("/psr", requireAuth, psrRouter); app.all("*", (req, res) => { res.status(404).json({ errors: { main: "Page non trouvé", }, }); }); const port = process.env.PORT || 8000; app.listen(port, async () => { console.log("server is running on port: " + port); });
// ********************************************************************************************************************* // *** CONFIDENTIAL --- CUSTOM STUDIOS *** // ********************************************************************************************************************* // * Auth: ColeCai * // * Date: 2023/11/21 21:21:43 * // * Proj: codec * // * Pack: ascii85 * // * File: ascii85.go * // *-------------------------------------------------------------------------------------------------------------------* // * Overviews: * // *-------------------------------------------------------------------------------------------------------------------* // * Functions: * // * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - * package ascii85 import ( "github.com/caijunjun/codec/base" ) const ( codec = "ascii85" ) var ( StdCodec = NewCodec() ) type ascii85Codec struct{} func NewCodec() base.IEncoding { return &ascii85Codec{} } func (a *ascii85Codec) maxEncodeLen(n int) int { return (n + 3) / 4 * 5 } func (a *ascii85Codec) encode(dst, src []byte) int { if len(src) == 0 { return 0 } n := 0 for len(src) > 0 { dst[0] = 0 dst[1] = 0 dst[2] = 0 dst[3] = 0 dst[4] = 0 // Unpack 4 bytes into uint32 to repack into base 85 5-byte. var v uint32 switch len(src) { default: v |= uint32(src[3]) fallthrough case 3: v |= uint32(src[2]) << 8 fallthrough case 2: v |= uint32(src[1]) << 16 fallthrough case 1: v |= uint32(src[0]) << 24 } // Special case: zero (!!!!!) shortens to z. if v == 0 && len(src) >= 4 { dst[0] = 'z' dst = dst[1:] src = src[4:] n++ continue } // Otherwise, 5 base 85 digits starting at !. for i := 4; i >= 0; i-- { dst[i] = '!' + byte(v%85) v /= 85 } // If src was short, discard the low destination bytes. m := 5 if len(src) < 4 { m -= 4 - len(src) src = nil } else { src = src[4:] } dst = dst[m:] n += m } return n } func (a *ascii85Codec) Encode(src []byte) ([]byte, error) { dst := make([]byte, a.maxEncodeLen(len(src))) n := a.encode(dst, src) return dst[:n], nil } func (a *ascii85Codec) decode(dst, src []byte, flush bool) (ndst, nsrc int, err error) { var v uint32 var nb int for i, b := range src { if len(dst)-ndst < 4 { return } switch { case b <= ' ': continue case b == 'z' && nb == 0: nb = 5 v = 0 case '!' <= b && b <= 'u': v = v*85 + uint32(b-'!') nb++ default: return 0, 0, base.ErrEncodedText(codec, b, i) } if nb == 5 { nsrc = i + 1 dst[ndst] = byte(v >> 24) dst[ndst+1] = byte(v >> 16) dst[ndst+2] = byte(v >> 8) dst[ndst+3] = byte(v) ndst += 4 nb = 0 v = 0 } } if flush { nsrc = len(src) if nb > 0 { // The number of output bytes in the last fragment // is the number of leftover input bytes - 1: // the extra byte provides enough bits to cover // the inefficiency of the encoding for the block. if nb == 1 { size := len(src) return 0, 0, base.ErrEncodedText(codec, src[size-1], size-1) } for i := nb; i < 5; i++ { // The short encoding truncated the output value. // We have to assume the worst case values (digit 84) // in order to ensure that the top bits are correct. v = v*85 + 84 } for i := 0; i < nb-1; i++ { dst[ndst] = byte(v >> 24) v <<= 8 ndst++ } } } return } func (a *ascii85Codec) Decode(src []byte) ([]byte, error) { dst := make([]byte, 4*len(src)) n, _, err := a.decode(dst, src, true) if err != nil { return nil, err } return dst[:n], nil }
const Sequelize = require('sequelize'); const {models} = require('./model'); const {log, biglog, errorlog, colorize} = require("./out"); exports.helpCmd = (socket,rl) => { log (socket,"Commandos:"); log (socket," h|help - Muestra esta ayuda."); log (socket," list - Listar los quizzes existentes."); log (socket," show <id> - Muestra la pregunta y la respuesta el quiz indicado."); log (socket," add - Añadir un nuevo quiz interactivamente."); log (socket," delete <id> - Borrar el quiz indicado."); log (socket," edit <id> - Editar el quiz indicado."); log (socket," test <id> - Probar el quiz indicado."); log (socket," p|play - Jugar a preguntar aleatoriamente todos los quizzes."); log (socket," credits - Créditos."); log (socket," q|quit - Salir del programa."); rl.prompt(); }; exports.quitCmd = (socket,rl) => { rl.close(); //rl.prompt(); socket.end(); }; const makeQuestion = (rl, text) => { return new Sequelize.Promise((resolve, reject) => { rl.question(colorize(text, 'red'), answer => { resolve(answer.trim()); }); }); }; exports.addCmd = (socket,rl) => { makeQuestion(rl, ' Introduzca una pregunta: ') .then(q => { return makeQuestion(rl, ' Introduzca la respuesta ') .then(a => { return {question: q, answer: a}; }); }) .then(quiz => { return models.quiz.create(quiz); }) .then((quiz) => { log(socket,` ${colorize('Se ha añadido', 'magenta')}: ${quiz.question} ${colorize('=>', 'magenta')} ${quiz.answer}`) }) .catch(Sequelize.ValidationError, error => { errorlog(socket,'El quiz es erróneo:'); error.errors.forEach(({message}) => errorlog(message)); }) .catch(error => { errorlog(socket,error.message); }) .then(() => { rl.prompt(); }); }; exports.listCmd = (socket,rl) => { models.quiz.findAll() .each(quiz => { log(socket,` [${colorize(quiz.id,'magenta')}]: ${quiz.question} `); }) .catch(error => { errorlog(socket,error.message); }) .then(() => { rl.prompt(); }); }; const validateId = id => { return new Sequelize.Promise((resolve,reject) => { if (typeof id === "undefined"){ reject(new Error(`Falta el parámetro <id>.`)); } else { id = parseInt(id); if (Number.isNaN(id)){ reject(new Error(`El valor del parámetro <id> no es un número.`)); } else { resolve(id); } } }); }; exports.showCmd = (socket,rl, id) => { validateId(id) .then(id => models.quiz.findById(id)) .then(quiz => { if (!quiz){ throw new Error(`No existe un quiz asociado al id=${id}.`); } log(socket,`[${colorize(quiz.id,'magenta')}]: ${quiz.question} ${colorize('=>','magenta')} ${quiz.answer}`); }) .catch(error => { errorlog(socket,error.message); }) .then(() => { rl.prompt(); }); }; exports.testCmd = (socket,rl, id) => { validateId(id) .then(id => models.quiz.findById(id)) .then(quiz => { if(!quiz){ throw new Error(`No existe un quiz asociado al id=${id}.`); rl.prompt(); } return new Promise((resolve,reject) => { makeQuestion(rl, quiz.question) .then(answer => { quiz.answer = quiz.answer.toLowerCase().trim(); answer = answer.toLowerCase().trim(); if(quiz.answer === answer){ log(socket,'Su respuesta es correcta.'); biglog(socket,'Correcta', 'green'); resolve(); }else{ log(socket,'Su respuesta es incorrecta.'); biglog(socket,'Incorrecta', 'red'); resolve(); } }) }) }) .catch(error => { errorlog(socket,error.message); }) .then(() => { rl.prompt(); }); } exports.playCmd = (socket,rl) =>{ }; exports.deleteCmd = (socket,rl, id) => { validateId(id) .then(id => models.quiz.destroy({where: {id}})) .catch(error => { errorlog(socket,error.message); }) .then(() => { rl.prompt(); }); }; exports.editCmd = (socket,rl, id) => { validateId(id) .then(id => models.quiz.findById(id)) .then(quiz => { if (!quiz){ throw new Error(`Ǹo existe un quiz asociado al id=${id}.`); } process.stdout.isTTY && setTimeout(() => {rl.write(quiz.question)}, 0); return makeQuestion(rl, ' Introduzca la pregunta: ') .then(q => { process.stdout.isTTY && setTimeout(() => {rl.write(quiz.answer)}, 0); return makeQuestion(rl, 'Introduzca la respuesta ') .then(a => { quiz.question = q; quiz.answer = a; return quiz; }); }); }) .then(quiz => { return quiz.save(); }) .then(quiz => { log(socket,`Se ha cambiado el quiz ${colorize(quiz.id, 'magenta')} por: ${quiz.question} ${colorize('=>', 'magenta')} ${quiz.answer}`) }) .catch(Sequelize.ValidationError, error => { errorlog(socket,'El quiz es erróneo:'); error.errors.forEach(({message}) => errorlog(message)); }) .catch(error => { errorlog(socket,error.message); }) .then(() => { rl.prompt(); }); }; exports.creditsCmd = (socket,rl) => { log(socket,'Autor de la práctica:'); log(socket,'Javier Medina'); rl.prompt(); };
import React from 'react'; import { render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import renderer from 'react-test-renderer'; import { testComponentRender } from '../../../utils/testingUtils'; import NavigationAction from '../NavigationAction'; const testId = 'navigationAction'; type NavigationActionProps = React.ComponentProps<typeof NavigationAction>; const renderComponent = (props: NavigationActionProps = {}) => render( <NavigationAction data-testid={testId} {...props} />, ); describe('Компонент NavigationAction', () => { testComponentRender(renderComponent); it('snapshot совпадает', () => { const tree = renderer.create(<NavigationAction />).toJSON(); const tree2 = renderer.create(<NavigationAction active />).toJSON(); const tree3 = renderer.create(<NavigationAction icon={<i className="bi bi-palette2" />} />).toJSON(); const tree4 = renderer.create(<NavigationAction className="className" />).toJSON(); const tree5 = renderer.create(<NavigationAction linkProps={{ href: 'href', target: 'target' }} />).toJSON(); const tree6 = renderer.create(<NavigationAction component="link" />).toJSON(); const tree7 = renderer.create(<NavigationAction>text</NavigationAction>).toJSON(); const tree8 = renderer.create(<NavigationAction horizontal />).toJSON(); expect(tree).toMatchSnapshot(); expect(tree2).toMatchSnapshot(); expect(tree3).toMatchSnapshot(); expect(tree4).toMatchSnapshot(); expect(tree5).toMatchSnapshot(); expect(tree6).toMatchSnapshot(); expect(tree7).toMatchSnapshot(); expect(tree8).toMatchSnapshot(); }); });
/// # Sample /// Type Declarations /// /// # Description /// User-defined types, or UDTs as they are commonly called, are supported /// in Q#. They are immutable but support a copy-and-update construct. namespace MyQuantumApp { @EntryPoint() operation Main() : Unit { // UDTs are defined with the `newtype` keyword. newtype Point3d = (X : Double, Y : Double, Z : Double); // The items within a UDT can be either named or unnamed. newtype DoubleInt = (Double, ItemName : Int); // UDTs can also be nested. newtype Nested = (Double, (ItemName : Int, String)); let point = Point3d(1.0, 2.0, 3.0); // Items within a UDT can be accessed either by their name, // or by deconstruction. // The below line accesses the field `x` on `point` by // name, using the item access operator `::`: let x : Double = point::X; // The below line accesses the field `x` via deconstruction: let (x, _, _) = point!; // The below line uses the unwrap operator `!` to access the entire // tuple. The type of `unwrappedTuple` is `(Double, Double, Double)`. let unwrappedTuple = point!; } }
# -*- coding: utf-8 -*- """ Brief: Heuristics on the smallest singular value of discrete Gaussian matrices over modules over cyclotomic rings. [Bound testing] """ #-- Import --# from sage.stats.distributions.discrete_gaussian_lattice import DiscreteGaussianDistributionLatticeSampler from scipy import linalg import argparse #-- End Import --# #-- Parameter parser --# parser = argparse.ArgumentParser(description='Heuristics on the smallest \ singular value of discrete Gaussian matrices over modules (over \ cyclotomic rings).') parser.add_argument('--nu', metavar='nu', type=int, default=128, help='Integer representing the nu-th cyclotomic field (default: 128).') parser.add_argument('--d', metavar='d', type=int, default=4, help='Module rank (default: 4).') parser.add_argument('--nb', metavar='nb', type=int, default=100, help='Number of sampled matrices (default: 100).') #-- Module Discrete Gaussian Sampler --# def sample_multiplication_matrix(n, sampler): """ Sample a discrete Gaussian vector from sampler and compute its multiplication matrix w.r.t. the Minkowski embedding over cyclotomic rings. - input: (int) n -- Cyclotomic ring degree ( ) sampler -- Discrete Gaussian Lattice Sampler - output: (matrix) M_sigmaH -- (n x n) multiplication matrix """ v = sampler()/sqrt(2) M_sigmaH = block_diagonal_matrix( [matrix(RDF, 2, [[v[2*i], -v[2*i+1]],[v[2*i+1], v[2*i]]]) for i in range(n//2)] ) del v return M_sigmaH def sample_structured_gaussian_matrix(n, d, sampler): return block_matrix(RDF, d, d, [[sample_multiplication_matrix(n, sampler) for _ in range(d)] for _ in range(d)]) if __name__ == '__main__': args = parser.parse_args() # Computing lattice basis of sigma_H(R) K = CyclotomicField(args.nu) n = K.degree() """ Using K.minkowski_embedding(prec=None) does not generate a matrix in RDF and K.minkowski_embedding().change_ring(RDF) does not work for DGS for some reason """ basis = zero_matrix(RDF, n,n) basis.set_block(0,0, K.minkowski_embedding()) del K # Setting parameters q = 8380417 # Modulus chosen in CRYSTALS Dilithium gamma = 2**(1/(2*args.d-1)) * n * q**((args.d-1)/(n*(2*args.d-1))) lower_bound = gamma * (n*args.d)**(-1/2) / 10 # Initializing Discrete Gaussian Sampler DGSampler = DiscreteGaussianDistributionLatticeSampler(basis, gamma) # Heuristics smin_sum, lower, lowest = 0, 0, n * args.d * gamma for _ in range(args.nb): # Sampling matrix mat = sample_structured_gaussian_matrix(n, args.d, DGSampler) # Computing smallest singular value smin = linalg.svd(mat, compute_uv=False)[-1] del mat smin_sum += smin if smin < lower_bound: lower += 1 if smin < lowest: lowest = smin # Output print('###### HEURISTICS RESULTS (%d-th cyclotomic field) ######'%args.nu) print('[*] Tested bound: gamma * (n*d)**(-1/2) / 10 for \ gamma = 2^{1 / (2d-1)} * n * q^{(d-1) / (n(2d-1))}') print(60*'_') print('''- Degree: %d - Rank: %d - Dimension: %d - Gaussian parameter: %.5f - Lowest s_min: %.5f - Average s_min: %.5f - Tested Lower Bound: %.5f - Number of failures (below lower bound): %d/%d''' % (n, args.d, n*args.d, gamma, lowest, smin_sum/args.nb, lower_bound, lower, args.nb)) print(60*'_')
using Data.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Data.Configurations { public class PatientConfiguration : IEntityTypeConfiguration<Patient> { public void Configure(EntityTypeBuilder<Patient> builder) { builder.HasKey(x => x.Id); builder.Property(x => x.Id) .ValueGeneratedOnAdd(); builder.Property(x => x.OIB) .IsRequired() .HasMaxLength(11); builder.Property(x => x.MBO) .IsRequired() .HasMaxLength(9); builder.Property(x => x.FullName) .IsRequired() .HasMaxLength(100); builder.Property(x => x.DateOfBirth) .IsRequired(); builder.Property(x => x.Gender) .IsRequired(); builder.Property(x => x.DiagnosisCode) .IsRequired() .HasMaxLength(5); builder.Property(x => x.AdmissionDate) .IsRequired(); builder.Property(x => x.DischargeDate) .IsRequired(false); builder.Property(x => x.IsDischarged) .IsRequired(); builder.Property(x => x.InsuranceStatus) .IsRequired(); builder.HasIndex(x => x.OIB) .IsUnique(); builder.HasIndex(x => x.MBO) .IsUnique(); // One-to-Many relation builder.HasMany(x => x.MedicalRecords) .WithOne(x => x.Patient) .HasForeignKey(x => x.PatientId); } } }
use std::io; use advent_of_code_2020_rust::utils::file::lines_from_file; use advent_of_code_2020_rust::day4_common::ValidDocCounter; fn main() -> io::Result<()> { let valid = vec!["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]; let lines = lines_from_file("data/day4.txt")?; let count = SimpleValidDocCounter.number_valid_passports(&lines, &valid); println!("{:?}", count); Ok(()) } struct SimpleValidDocCounter; impl <'a> ValidDocCounter for SimpleValidDocCounter { fn validate_doc(&self, doc: &Vec<(&str, &str)>, expected_values: &Vec<&str>) -> usize { let fields = doc.iter().map(|(f, _)| *f).collect::<Vec<&str>>(); expected_values.iter().map(|expected| fields.contains(expected) as usize).product::<usize>() } } #[test] fn example_test() -> io::Result<()> { let lines = lines_from_file("data/day4-example1.txt")?; let valid = vec!["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]; assert_eq!(2, SimpleValidDocCounter.number_valid_passports(&lines, &valid)); Ok(()) } #[test] fn extract_fields_test() { let row = "iyr:2010 ecl:gry hgt:181cm pid:591597745 byr:1920 hcl:#6b5442 eyr:2029 cid:123"; let actuals = SimpleValidDocCounter.extract_fields(row); vec!["iyr", "ecl", "hgt", "pid", "byr", "hcl", "eyr", "cid"] .iter() .zip(actuals) .for_each(|(expected, actual)| { assert_eq!(*expected, actual.0) }); } #[test] fn valid_doc_test() { let valid = vec!["aaa", "bbb", "ccc"]; assert_eq!(0, SimpleValidDocCounter.validate_doc(&vec![("aaa", ""), ("bbb", "")], &valid)); assert_eq!(0, SimpleValidDocCounter.validate_doc(&vec![("aaa", "")], &valid)); assert_eq!(1, SimpleValidDocCounter.validate_doc(&vec![("aaa", ""), ("bbb", ""), ("ccc", "")], &valid)); assert_eq!(1, SimpleValidDocCounter.validate_doc(&vec![("aaa", ""), ("ddd", ""), ("bbb", ""), ("ccc", "")], &valid)); }
#pragma once #include <atomic> #include <condition_variable> #include <memory> #include <mutex> #include <queue> #include <thread> #include "base/message_loop/message_pump.h" #include "base/time/time_ticks.h" namespace base { class DelayedTaskManager { public: struct DelayedTask { bool operator<(const DelayedTask& rhs) const; TimeTicks start_time; std::weak_ptr<MessagePump> message_pump; mutable MessagePump::PendingTask pending_task; }; using TimeTicksProvider = TimeTicks (*)(); DelayedTaskManager(TimeTicksProvider time_ticks_provider = &TimeTicks::Now); ~DelayedTaskManager(); void QueueDelayedTask(DelayedTask delayed_task); void ScheduleAllReadyTasksForTests(); private: void ScheduleTasksUntilStop(); void ScheduleAllReadyTasksLocked(); void WaitForNextTaskOrStopLocked(std::unique_lock<std::mutex>& lock); std::optional<TimeDelta> NextTaskRemainingDelayLocked() const; const TimeTicksProvider time_ticks_provider_; std::thread scheduler_thread_; std::mutex mutex_; std::condition_variable cond_var_; // Everything below is locked behind |mutex_|. bool stopped_; std::priority_queue<DelayedTask> delayed_tasks_; }; } // namespace base
import React, { useEffect } from 'react' import { addToCart, clearCart, decreaseCart, getTotals, selectCartItems, selectcartTotalAmount } from '../features/cartSlice' import { useDispatch, useSelector } from 'react-redux'; import { NumericFormat } from 'react-number-format'; import '../css/cart.css' import { Link } from "react-router-dom"; function CartLayout() { const dispatch = useDispatch() const data1 = useSelector(selectCartItems) const cartTotalAmount = useSelector(selectcartTotalAmount); // console.log(cartTotalAmount); useEffect(() => { dispatch(getTotals()) }, [data1, dispatch]) const handleRemoveCart = () => { dispatch(clearCart()); } const handleDecrease = (item) => { dispatch(decreaseCart(item)) } const handleIncrease = (item) => { dispatch(addToCart(item)) } return ( <div id='cart'> <h3 className="text-center">Your Shopping Bag</h3> <div className='row'> <div className='col-lg-9' > {data1?.map((item) => ( <div key={item.id} className='row' id='cart1'> <div className='col-5 col-lg-2 col-sm-4'> <img src={item.image} alt={item.name} className="img-fluid" /> </div> <div className='col-6 col-lg-7 col-sm-4'> <h6 className='text-[0.8rem] text-black'>{item?.name}</h6> <p className='text-red-600 mx-2'> <NumericFormat value={item.Gia * item.cartQuantity} thousandSeparator="," displayType="text" renderText={(value) => <b id="price">Giá: {value}₫</b>} /> </p> </div> <div className='col col-lg-2 col-sm-3 m-2'> <div className='row'> <button onClick={() => handleDecrease(item)} >-</button> <p className='number'>{item.cartQuantity}</p> <button onClick={() => handleIncrease(item)} >+</button> </div> </div> </div> ))} </div> <div className='col-lg-3' id='cart2'> <h5 className='text-center'>Danh sách sản phẩm</h5> {data1?.map((item) => ( <div className='row' id='cart2_1'> <div className='col-6'> <p className=' text-black'>{item?.name}</p> </div> <div className='col-2'> <p className='text-red-700 font-bold w-6 h-6 rounded-full bg-blue-700 mt-1'>{item.cartQuantity}</p> </div> <div className='col'> <p> <NumericFormat value={item.Gia * item.cartQuantity} thousandSeparator="," displayType="text" renderText={(value) => <b id="price"> {value}₫</b>} /> </p> </div> </div> ))} <p className='text-[0.8rem] text-red-600'> <NumericFormat value={cartTotalAmount} thousandSeparator="," displayType="text" renderText={(value) => <b id="price">Tổng tiền: {value}₫</b>} /></p> <div className='row' style={{ marginRight: '20px' }}> <button className='col'> <Link to='/dathang' style={{ color: 'black' }}> Đặt hàng </Link></button> <button className='col' onClick={handleRemoveCart}>Xóa giỏ hàng</button> </div> </div> </div> </div> ) } export default CartLayout
// Overload -> Uma função se comporta de maneiras diferentes dependendo da quantidade de parâmetros passados // type Adder contem as possíveis maneiras de chamar a nossa função. type Adder = { (x: number): number; (x: number, y: number): number; (...args: number[]): number; }; const adder: Adder = (x: number, y?: number, ...args: number[]): number => { if (args.length > 0) { return args.reduce((acc, val) => acc + val, 0) + x + (y || 0); } return x + (y || 0); }; // Primeiro overload (x: number): number console.log(adder(1)); // Segundo overload (x: number, y: number): number; console.log(adder(1, 1)); // Terceiro overload (...args: number[]): number; console.log(adder(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1));
# Conditions and Effects ## Conditions Conditions are essentially the prerequisites or requirements that need to be met for an action to be executed. They are tied to the game's state, represented by `WorldKey`. - **Key**: This is the `WorldKey` that the condition checks. Think of it as a variable or a state in the game world, like "PlayerHealth" or "HasAmmo." - **Comparison**: This is how the `WorldKey` is compared to a specific value to determine if the condition is met. The available comparisons are "SmallerThan," "SmallerThanOrEqual," "GreaterThan," and "GreaterThanOrEqual." - **Value**: This is the specific value that the `WorldKey` is compared against using the specified comparison. For example, a condition might be set up like this: - **Key**: PlayerHealth - **Comparison**: GreaterThan - **Value**: 50 This condition checks if the player's health is greater than 50. ## Effects Effects describe the changes that an action brings about in the game's state, again represented by `WorldKey`. - **Key**: This is the `WorldKey` that the effect modifies. For instance, "PlayerHealth" or "AmmoCount." - **Type**: This indicates whether the `WorldKey` value will increase or decrease as a result of the action. For instance, an effect might be: - **Key**: AmmoCount - **Type**: Decrease This effect would decrease the ammo count when the action is executed. ## Matching Conditions and Effects The system matches conditions and effects to determine the sequence of actions that lead to a goal. Here's how the matching works based on the provided documentation: - **SmallerThan** and **SmallerThanOrEqual** comparisons in conditions look for actions with **negative effects**. This means if a condition requires a `WorldKey` to be less than a certain value, the system will look for actions that decrease that `WorldKey`. - **GreaterThan** and **GreaterThanOrEqual** comparisons in conditions look for actions with **positive effects**. So, if a condition requires a `WorldKey` to be greater than a certain value, the system will search for actions that increase that `WorldKey`. For example, if there's a condition that checks if "AmmoCount" is `SmallerThan` 5, the system might look for an action with a negative effect on "AmmoCount" (like "ShootBullet"). Conversely, if the condition checks if "AmmoCount" is `GreaterThan` 10, the system might look for an action with a positive effect on "AmmoCount" (like "ReloadGun"). In essence, the GOAP system uses these conditions and effects to build a graph of possible actions and sequences, which is then used by the planner to determine the best course of action to achieve a goal. ## Examples Setting conditions and effects through code. {% code title="Creat" lineNumbers="true" %} ```csharp var builder = new GoapSetBuilder("GettingStartedSet"); builder.AddAction<ShootBullet>() .AddCondition<AmmoCount>(Comparison.GreaterThanOrEqual, 1) .AddEffect<AmmoCount>(false) ``` {% endcode %} Setting conditions and effects through the inspector. ![action-config.png](../images/scriptable_action.png)
<?php declare(strict_types=1); namespace Skrepr\IdType\ValueResolver; use Skrepr\IdType\ValueObject\AbstractUuid; use Doctrine\ORM\Mapping\ClassMetadataInfo; use Doctrine\Persistence\ManagerRegistry; use ReflectionNamedType; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ValueResolverInterface; use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Uid\Uuid; class EntityValueResolver implements ValueResolverInterface { public function __construct( private readonly ManagerRegistry $registry, ) { } /** * @return array<int, object|null> */ public function resolve(Request $request, ArgumentMetadata $argument): iterable { // first check to see if argument is of a class-type $argumentType = $argument->getType() ?? ''; if (!class_exists($argumentType)) { return []; } // check if the requested class is in the entity manager $manager = $this->registry->getManagerForClass($argumentType); if ($manager === null) { return []; } // check if primary key is of type AbstractUuid $meta = $manager->getClassMetadata($argumentType); if ($meta instanceof ClassMetadataInfo) { $reflectionIdType = $meta->getSingleIdReflectionProperty()?->getType(); } if (isset($reflectionIdType) && $reflectionIdType instanceof ReflectionNamedType) { $idType = $reflectionIdType->getName(); } if ( !isset($idType) || !is_subclass_of($idType, AbstractUuid::class, true) ) { return []; } // get the value from the request, based on the argument name $value = $request->attributes->get($argument->getName()); if (!is_string($value)) { return []; } if (!Uuid::isValid($value)) { throw new NotFoundHttpException(sprintf('The uid for the "%s" parameter is invalid.', $argument->getName())); } $object = $manager->find($argumentType, $idType::fromString($value)); if ($object === null && !$argument->isNullable()) { throw new NotFoundHttpException(sprintf('"%s" object not found by "%s".', $argumentType, self::class)); } return [$object]; } }
import { SeverityLevel } from '@microsoft/applicationinsights-web'; import { ThunkAction } from 'redux-thunk'; import { getIndexOfAppointment } from '../utils/AppointmentHelpers'; import { SetNextAppointmentForConsultation, SetPreviousAppointmentConsultation, } from './ConsultationActions'; import { RootState } from '../store'; import SetTrackTrace from '../telemetry/SetTrackTrace'; import IAppointmentData from '../types/IncomingDataModels/Appointment'; import { Appointment_Types } from '../reducers/AppointmentsReducer'; import { Action } from '../types/ActionType'; export const SetAppointments = ( appointments: Array<IAppointmentData>, ): Action => ({ type: Appointment_Types.SET_APPOINTMENT_STATE_APPOINTMENTS, payload: appointments, }); export const GetNextAndPreviousAppointmentForConsultation = (): ThunkAction<void, RootState, null, Action> => async (dispatch, getState) => { SetTrackTrace( 'Enter Get Next and Previous Appointment Action', 'GetNextAndPreviousAppointmentForConsultation', SeverityLevel.Information, ); const allAppointments = getState().AppointmentState.appointments; if (allAppointments) { SetTrackTrace( 'Get All Appointments From State Successs: ' + allAppointments.length, 'GetNextAndPreviousAppointmentForConsultation', SeverityLevel.Information, ); } else { SetTrackTrace( 'Get All Appointments From State Failed. ', 'GetNextAndPreviousAppointmentForConsultation', SeverityLevel.Error, ); } const currentAppointment = getState().ConsultationState.Appointment; if (allAppointments) { SetTrackTrace( 'Get Current Appointment From State Successs. ', 'GetNextAndPreviousAppointmentForConsultation', SeverityLevel.Information, ); } else { SetTrackTrace( 'Get Current Appointment From State Failed. ', 'GetNextAndPreviousAppointmentForConsultation', SeverityLevel.Error, ); } const currentAppointmentIndex = getIndexOfAppointment( allAppointments, currentAppointment, ); if (allAppointments) { SetTrackTrace( 'Get Current Appointment Index: ' + currentAppointmentIndex + ' From State Successs. ', 'GetNextAndPreviousAppointmentForConsultation', SeverityLevel.Information, ); } else { SetTrackTrace( 'Get Current Appointment Index Failed. ', 'GetNextAndPreviousAppointmentForConsultation', SeverityLevel.Error, ); } const previousAppointment = allAppointments[currentAppointmentIndex! - 1]; const nextAppointment = allAppointments[currentAppointmentIndex! + 1]; if (previousAppointment) { SetTrackTrace( 'Previous Appointment Exists: ', 'GetNextAndPreviousAppointmentForConsultation', SeverityLevel.Information, ); } else { SetTrackTrace( 'Previous Appointmnt Does Not Exist: ', 'GetNextAndPreviousAppointmentForConsultation', SeverityLevel.Error, ); } if (nextAppointment) { SetTrackTrace( 'Next Appointment Exists: ', 'GetNextAndPreviousAppointmentForConsultation', SeverityLevel.Information, ); } else { SetTrackTrace( 'Next Appointmnt Does Not Exist: ', 'GetNextAndPreviousAppointmentForConsultation', SeverityLevel.Error, ); } //ADD ALL NULL CHECKS FOR INDEX AND OUT OF BOUNDS EXCEPTION dispatch(SetPreviousAppointmentConsultation(previousAppointment)); dispatch(SetNextAppointmentForConsultation(nextAppointment)); };
<?php /** * This is the model class for table "forma_pagamento". * * The followings are the available columns in table 'forma_pagamento': * @property integer $id * @property string $nome * @property integer $ativo */ class FormaPagamento extends CActiveRecord { const _TIPO_DINHEIRO_ = 1; /** * @return string the associated database table name */ public function tableName() { return 'forma_pagamento'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('nome', 'required'), array('ativo', 'numerical', 'integerOnly'=>true), array('nome', 'length', 'max'=>45), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. array('id, nome, ativo', 'safe', 'on'=>'search'), ); } public function scopes() { $alias = $this->getTableAlias(); return array( 'ativos' => array( 'condition' => "{$alias}.ativo = 1", ), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'pedidos' => array(self::HAS_MANY, 'Pedido', 'forma_pagamento_id'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'nome' => 'Nome', 'ativo' => 'Ativo', ); } /** * Retrieves a list of models based on the current search/filter conditions. * * Typical usecase: * - Initialize the model fields with values from filter form. * - Execute this method to get CActiveDataProvider instance which will filter * models according to data in model fields. * - Pass data provider to CGridView, CListView or any similar widget. * * @return CActiveDataProvider the data provider that can return the models * based on the search/filter conditions. */ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('nome',$this->nome,true); $criteria->compare('ativo',$this->ativo); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } /** * Returns the static model of the specified AR class. * Please note that you should have this exact method in all your CActiveRecord descendants! * @param string $className active record class name. * @return FormaPagamento the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } }
# Igor The Igor vendoring tool offers generic vendoring of common fragments of text files that allow comments. This tool is named after a character that appears in several Diskworld novels (my favorite is "Thief of Time"). This character offers a nice metaphor for what this tool tries to provide. An Igor is an assistant who fills a niche. He uses time-tried solutions (like a good jolt of electricity obtained from a lightning bolt) to make his masters project come alive. There are many Igors, but they are quite interchangeable, so they all use the same name. Every Igor has had (and has executed) many surgeries, has many visible scars and talks with a lisp. He isn't pretty, but he does the job. This vendoring tool is similar. It offers inversion-of-control in vendoring dependencies. What is that supposed to mean, you might ask. Well, in a nutshell it works like this: 1. A project declares the niches it wants to be served by an Igor in a directory named `yeth-mathtur` (the strange spelling is caused by the lisp). For each niche there is a subdirectory with a name that matches the name of the niche that contains at least a file named `igor-thettingth.yaml` that specifies the name of the thundercloud project that provides lightning for this niche. File `igor-thettingth.yaml` can also be used to turn features on and off and otherwise change the process. The niche directory may contain additional files that complement or override files and fragments that are injected by Igor. 2. Igor watches thundercloud projects that provide lightning: files and fragments of files that can be injected into projects of mathturs. 3. When files change is thundercloud projects, Igor updates all the projects that declare the corresponding niche (unless opted out in `yeth-mathtur/nicheName/igor-thettingth.yaml`). If the settings file declares a build command, that is also run after the bolt of lightning hit the niche. It is also possible to have Igor apply selected thundercloud projects to a mathturth' project. Filenames in both the thundercloud projects and in the `yeth-mathtur/nicheName` directories of mathturth' projects are qualified with an infix before the last dot to denote their function. * Option: `basename+option-featureName.ext` generates a file `basename.ext` only if the feature is turned on in the settings file * Example: `basename+example-featureName.ext` generates a file `basename.ext` only if the feature is turned on in the settings file and the file does not exist * Overwrite: `basename+overwrite-featureName.ext` signifies that `basename+example-featureName.ext` behaves like an option * Unnamed fragment: `basename+fragment-featureName.ext` replaces placeholders with the ID `featureName` in `basename.ext` only if the feature is turned on in the settings file * Named fragment: `basename+fragment-featureName-placeholderName.ext` replaces placeholders with the ID `featureName-placeholderName` in `basename.ext` only if the feature is turned on in the settings file * Ignore: `basename+ignore-featureName.ext` ignores the instructions for file `basename.ext` in this niche only if the feature is turned on in the settings file (Ignore files are mainly useful in invar) If the basename starts with `dot_`, then this prefix is replaced with a dot (`.`). If the basename starts with `x_`, then this prefix is removed. See the examples below. If the basename is empty, then de hyphen that separates the basename from the infix may be omitted (see the example for `.bashrc` below). A placeholder is either: * One line that contains the substring `==== PLACEHOLDER placeholderId ====` or a block of lines that is delimited by: * One line that contains the substring `==== BEGIN placeholderId ====` * One line that contains the substring `==== END placeholderId ====` The replacement of a placeholder is always a placeholder with the same ID. Special feature `@` is implicitly selected and cannot be turned off. Names like featureName and placeholderName must begin with an alphabetic character or an underscore and may only contain alphabetic characters, underscores and numerical digits. ## Examples Examples of lightning files: * `api-def+option-protobuf.proto` generates `api-def.proto` if feature `proto` is selected * `dot_bashrc+option-bash_config` generates `.bashrc` if feature `bash_config` is selected * `x_dot_slash+option-contrived.md` generates `dot_slash.md` if feature `contrived` is selected * `x_x_x+option-contrived` generates `x_x` if feature `contrived` is selected * `Cargo-fragment+tokio-build_deps.toml` replaces placeholder `build_deps` in `Cargo.toml` if feature `tokio` is selected * `main-ignore+niche.rs` ignores all lightning instructions from this niche for `main.rs` Minimal settings file `yeth-mathtur/async-rust/igor-thettingth.yaml`: ```yaml thundercloud: directory: "{{WORKAREA}}/async-rust-igor-thundercloud" ``` Elaborate settings file `yeth-mathtur/dendrite/igor-thettingth.yaml` ```yaml %YAML 1.2 --- type: name: igor version: v0.1.0 thundercloud: git: remote: "git@github.com:rustigaan/dendrite-igor-thundercloud.git" revision: mathtur on-incoming: warn # update | ignore | warn | fail options: selected: - mongodb # For query models that store data in MongoDB - grpc_ui # For an extra container that provides a web User Interface to call the gRPC backend deselected: - frontend settings: watch: false ```
package com.example.dailycalories.presentation.screens.meal.add_meal import com.example.dailycalories.domain.model.meal.MealFoodProduct sealed class AddMealEvent { data class AddMealProduct( val mealProduct: MealFoodProduct, ) : AddMealEvent() data class ChangeMealProductGrams( val mealProduct: MealFoodProduct, val weight: Float, ) : AddMealEvent() data class DeleteMealProduct(val product: MealFoodProduct) : AddMealEvent() data class ChangeMealName(val name: String) : AddMealEvent() data class ChangeTime(val time: Long) : AddMealEvent() object SaveMeal : AddMealEvent() data class ShowEditProductWeightDialog( val product: MealFoodProduct, ) : AddMealEvent() object HideEditProductWeightDialog : AddMealEvent() data class ShowTimePickerDialog( val show: Boolean, ) : AddMealEvent() }
# htmx sorta A demo project where I learn and play with my "Rust web stack": * Rust * Nix flakes for building and dev shell * [redb](https://github.com/cberner/redb) Rust local key-value store database * [astra](https://github.com/ibraheemdev/astra) Rust web server library * [maud](https://github.com/lambda-fairy/maud) Rust html templating library * [htmx](https://htmx.org/) for dynamic html frontend * [tailwind](https://tailwindcss.com/) via [twind](https://twind.style/) for CSS styling In essence it's a TODO app, and looks like this (click for a video): [![Video Preview](https://i.imgur.com/Q8RfOzf.png)](https://i.imgur.com/ctz2bcJ.mp4) Note: server response slowness is simulated to help improve the UX. The imgur "optimized" the video and now it's slow and laggy, but I have no energy to fight with it right now. In reality things are working just fine. Some of the features: persistent ordered list, with drag'n'drop UX, responsive html, graceful offline handling, rate limiting. I think it might be source of inspiration and example for people that would like to use a similar set of tools for their own projects. ## Running If you're a Nix flake user you can run `nix run github:dpc/htmx-sorta`. Otherwise, proceed like with any other Rust project. ## About the stack I like things simple, small and to the point. Also - it's a bit of a research project, so I'm not afraid to try out things that are not most popular and trendy. I'd like to avoid using async Rust, because it's immature and PITA to use, while blocking IO is perfectly sufficient. That's why I use `astra`, which is very promising blocking IO Rust web framework/library. I don't want any C-binding based dependencies, and that's why I'm using `redb`, which is very promising and lean key value store, in a similar category as e.g. RocksDB. I don't like DSL, especially looking like combination of Python and HTML, so `maud` is my favourite HTML framework. Again - fast, lean, to the point. I'm tired of all the SPAs that are slow heavy and barely work. I'm more of a backend developer than a frontend developer. I think HTMX is the direction that Web should have taken long time ago, instead of betting everything on Javascript. I'm not afraid of adding JS to the code, but it shouldn't be for UX niceness and not the tail wagging the dog. I'm not much of a designer or a web developer, but I've did some web projects over last two decades, and I wholeheartly agree with Tailwind philosophy. Unfortunately it doesn't have a great Rust/maud integration, so I use `twind` as a client-side Tailwind JIT instead. ### Points of Interest Check [maud templates in fragment.rs](https://github.com/dpc/htmx-sorta/blob/c2d300caafa6a3d72eb7eefcb766b669676ca803/src/fragment.rs), acting like web-components for both htmx and tailwind. [Route handlers are in routes.rs](https://github.com/dpc/htmx-sorta/blob/c2d300caafa6a3d72eb7eefcb766b669676ca803/src/routes.rs). They are a bit low level and manual but hopefully `astra` will get some more convenient approach (e.g. like Axum extractors) in the near future. [The developer is working on it](https://github.com/ibraheemdev/astra/issues/8). Go say hello if you're interested. The Nix dev shell I'm using sets up automatically [some cool git hooks](https://github.com/dpc/htmx-sorta/tree/c2d300caafa6a3d72eb7eefcb766b669676ca803/misc/git-hooks). I keep using it in many projects. It includes `semgrep`, `typos` (checking typos), `convco` (conventional commits), linters, and some Rust specific checks. [`mold` is used to speed up linking, with symbol compression enabled](https://github.com/dpc/htmx-sorta/blob/bc77241ca98e06c7a65e768467d34cbf8bfa8b50/.cargo/config.toml) to make the binary smaller (`6.3 MiB` ATM). I've "invented" [a variable-length sorting key approach, that simplifies item sorting.](https://github.com/dpc/htmx-sorta/blob/c2d300caafa6a3d72eb7eefcb766b669676ca803/src/sortid.rs) It makes generating a key between two other keys a simple and infaliable operation. I had an idea for [compact and fast, but imprecise pre-rate-limiter](https://github.com/dpc/htmx-sorta/blob/c2d300caafa6a3d72eb7eefcb766b669676ca803/src/rate_limit/pre.rs) that I think would be very fast. It uses a multi-hash approach with buckets of atomic counters, kind of like bloom/cuckoo filters, to effective take one atomic (relaxed) write on the happy path, and gracefully degrade under heavy load. Did not have time to benchmark it, so 🤷. Maybe it's stupid. The rest is somewhat typical. As of the time of writing this there are some known missing things. It's just an demo/research, don't expect too much. ### License MIT. Feel free to copy, paste and use, no attribution expected.
import 'dart:convert'; import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:provider/provider.dart'; import 'package:safecty/core/navigation/named_route.dart'; import 'package:safecty/feature/home/home_view_model.dart'; import 'package:safecty/feature/home/widget/home_card.dart'; import 'package:safecty/generated/l10n.dart'; import 'package:safecty/theme/app_colors.dart'; import 'package:safecty/theme/spacing.dart'; import 'package:safecty/widgets/loading_widget.dart'; class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); @override State<HomeScreen> createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { @override void initState() { super.initState(); final viewModel = context.read<HomeViewModel>(); SchedulerBinding.instance.addPostFrameCallback( (_) async { await viewModel.getDatesUser(); print(viewModel.user); }, ); } @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return Consumer<HomeViewModel>( builder: ( context, value, __, ) { if (value.state == HomeViewState.loading) { return LoadingWidget( height: size.height, width: size.width, ); } if (value.state == HomeViewState.completed) { return Scaffold( backgroundColor: AppColors.white, appBar: PreferredSize( preferredSize: const Size.fromHeight(10.0), child: AppBar( backgroundColor: Colors.orange, ), ), body: Column( children: [ InkWell( onTap: () => Navigator.of(context).pushNamed(NamedRoute.profileScreen), child: Container( color: AppColors.white, height: size.height * 0.11, width: size.width, padding: const EdgeInsets.all(16.0), child: Stack( alignment: Alignment.center, children: [ // Logo principal Positioned( left: 0.0, child: Container( width: 60.0, height: 60.0, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.grey, image: value.user!.profilePicture == null ? DecorationImage( image: MemoryImage( base64.decode( value.user!.profilePicture!), ), fit: BoxFit.cover, ) : null, ), ), ), Positioned( bottom: 000, right: size.width * 0.7, child: Container( width: 40.0, height: 40.0, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.grey, image: value.workCenter!.companyLogo.isNotEmpty ? DecorationImage( image: MemoryImage( base64.decode( value.workCenter!.companyLogo), ), fit: BoxFit.cover, ) : null, ), ), ), Padding( padding: const EdgeInsets.only( left: Spacing.xLarge + 60.0), child: Center( child: AutoSizeText( value.workCenter!.businessName, style: const TextStyle( fontSize: 16.0, fontWeight: FontWeight.bold, ), minFontSize: 10, stepGranularity: 10, maxLines: 3, overflow: TextOverflow.ellipsis, ), ), ), ], ), ), ), const SizedBox(height: Spacing.medium), Container( height: size.height * 0.75, padding: const EdgeInsets.only( bottom: Spacing.small, left: Spacing.xLarge, right: Spacing.large, ), width: size.width, child: SingleChildScrollView( child: Column( children: [ Row( children: [ HomeCard( icon: Icons.assignment_outlined, onTap: () => Navigator.of(context).pushNamed( NamedRoute.homeScreen, arguments: {"Valor": 1}), title: "Habilidades", ), const SizedBox(width: Spacing.medium), HomeCard( icon: Icons.collections_bookmark, onTap: () => Navigator.of(context) .pushNamed(NamedRoute.homeScreen), title: "Habilidades", ), ], ), const SizedBox(height: Spacing.medium), Row( children: [ HomeCard( icon: Icons.collections_bookmark, onTap: () => Navigator.of(context) .pushNamed(NamedRoute.homeScreen), title: "Habilidades", ), const SizedBox(width: Spacing.medium), HomeCard( icon: Icons.collections_bookmark, onTap: () => Navigator.of(context) .pushNamed(NamedRoute.inspectionPlanScreen), title: AppLocalizations.of(context).inspectionPlan, ), ], ), const SizedBox(height: Spacing.medium), Row( children: [ HomeCard( icon: Icons.collections_bookmark, onTap: () => Navigator.of(context) .pushNamed(NamedRoute.homeScreen), title: "Habilidades", ), const SizedBox(width: Spacing.medium), HomeCard( icon: Icons.collections_bookmark, onTap: () => Navigator.of(context) .pushNamed(NamedRoute.homeScreen), title: "Habilidades", ), ], ) ], ), ), ) ], ), ); } return LoadingWidget( height: size.height, width: size.width, ); }, ); } }
/** * Shows a list of annotations as a cloud in different sizes and colors depending on the size of ... * * @class * @extends Biojs.TagCloud * * @author <a href="mailto:johncar@gmail.com">John Gomez</a> * * @requires <a href="../biojs/css/biojs.AnnotationsCloud.css">AnnotationsCloud CSS</a> * @dependency <link href="../biojs/css/biojs.AnnotationsCloud.css" rel="stylesheet" type="text/css"></link> * * @requires <a href='http://blog.jquery.com/2011/09/12/jquery-1-6-4-released/'>jQuery 1.6.4+</a> * @dependency <script language="JavaScript" type="text/javascript" src="../biojs/dependencies/jquery/jquery-1.6.4.js"></script> * * @requires <a href='../biojs/Biojs.Tooltip.js'>Biojs.Annotations</a> * @dependency <script language="JavaScript" type="text/javascript" src="../biojs/Biojs.Annotations.js"></script> * * @param {Object} options * An object with the options for TagCloud component. * * @option {string} target * Identifier of the DIV tag where the component should be displayed. * * @example * var instance = new Biojs.AnnotationsCloud({ * target: "YourOwnDivId", * proxyUrl: '../biojs/dependencies/proxy/proxy.php', * groupBy: Biojs.Annotations.GROUP_BY_TERM * }); * */ Biojs.AnnotationsCloud = Biojs.TagCloud.extend ( /** @lends Biojs.AnnotationsCloud# */ { constructor: function (options) { this.base(); this._container.addClass('AnnotationsCloud'); this._annotations = new Biojs.Annotations({ sparqlUrl: this.opt.sparqlUrl, proxyUrl: this.opt.proxyUrl, groupBy: this.opt.groupBy, filterBy: this.opt.filterBy }); }, /** * Default values for the options * @name Biojs.AnnotationsCloud-opt */ opt: { target: "YourOwnDivId", sparqlUrl: 'http://biotea.idiginfo.org/sparql', //sparqlUrl: 'http://virtuoso.idiginfo.org/sparql', proxyUrl: 'biojs/dependencies/proxy/proxy.php', groupBy: Biojs.Annotations.GROUP_BY_TERM, filterBy: { field:"topic", value:"uniprot|GO|CHEBI|ICD9|UMLS|fma|MSH|PO|MDDB|NDDF|NDFRT|NCBITaxon" } }, /** * Array containing the supported event names * @name Biojs.AnnotationsCloud-eventTypes */ eventTypes: [ /** * @name Biojs.AnnotationsCloud#onTopicOver * @event * @param {function} actionPerformed A function which receives an {@link Biojs.Event} object as argument. * @eventData {Object} source The component which did triggered the event. * @eventData {string} type The name of the event. * @eventData {string} tagName Name of the clicked tag. * @example * instance.onTopicOver( * function( e ) { * alert("Topic : " + e.topicType + ", Identifier: " + e.topicId ); * } * ); * */ "onTopicOver", "onTopicClicked", "onAnnotationClicked", "onAnnotationOver" ], _initialize: function ( container ) { var opt = this.opt; if ( opt.title !== undefined ) { this._title = jQuery('<div>' + opt.title + '</div>').appendTo( container ); } this._tags = jQuery('<ul class="tags"></ul>').appendTo( container ); }, /** * Filters the current data. It does not a new request for data. * It just filters the already gotten data. * * @param {object} filter It must have both members frequency and topics. * filter.frequency must be an integer which filters by the minimum frequency. * filter.topics must be an array containing the name of topics to avoid. * * @returns {object} Filtered data. * * @example * instance.applyFilter({ frequency: 7, topics: ['uniprot','chebi'] }); * */ applyFilter: function ( filter ) { this._annotations.applyFilter(filter); this.repaint(); }, /** * Request the annotations for an URI resource and fills up the cloud with them. * * @param {string} resourceURI Universal resource identifier * * @example * instance.requestAnnotations("http://biotea.idiginfo.org/pubmedOpenAccess/rdf/PMC3018821"); * * @example * instance.requestAnnotations(["http://biotea.idiginfo.org/pubmedOpenAccess/rdf/PMC3018821","<http://biotea.idiginfo.org/pubmedOpenAccess/rdf/PMC3215666>"]); * */ requestAnnotations: function ( resourceURI, fnCallback ) { //TODO: show loading image var self = this; this.removeAll(); this._container.addClass('loading'); this._annotations.requestAnnotations(resourceURI, function ( data ) { self.repaint(); if (fnCallback) { fnCallback.call(); } }); }, setAnnotations: function ( a ) { var self = this; this.removeAll(); this._container.addClass('loading'); this._annotations = a; this.repaint(); }, cancelRequest: function () { this._annotations.cancelRequest(); }, repaint: function () { var self = this; this.removeAll(); this._paintAnnotations(); this._container.removeClass('loading'); this.onTagOver( function(e) { var annotation = self._getAnnotation(e.tagId); // raising event self.raiseEvent(Biojs.AnnotationsCloud.EVT_ON_ANNOTATION_OVER, { name: annotation.name, freq: annotation.freq, comments: self._getComments(annotation) }); }); }, _getAnnotation: function( key ) { return this._annotations.getItem(key); }, _paintAnnotations: function () { var self = this; var i = this._annotations.iterator(); var a; while ( i.hasNext() ) { a = i.next(); Biojs.console.log("ADDING"); Biojs.console.log( a ); this.addTag({ id: a.id, name: a.name, freq: a.freq }, // Function to be triggered whenever a tag is clicked function ( tagId, tagName, tagValueNode ) { Biojs.console.log("Searching for tag " + tagId); var annot = self._getAnnotation(tagId); Biojs.console.log(annot); // raising event self.raiseEvent(Biojs.AnnotationsCloud.EVT_ON_ANNOTATION_CLICKED, { name: annot.name, freq: annot.freq, comments: self._getComments(annot) }); var topicList = jQuery('<span class="topics"></span>'); var e, anchor; var items = ( self.opt.groupBy == Biojs.Annotations.GROUP_BY_TERM) ? annot.topics : annot.terms; for ( key in items ) { e = items[key].map; anchor = jQuery('<a class="topic ' + key + '">' + key + '</a>') if ( !Biojs.Utils.isEmpty(e) ) { anchor.attr({ href: e.baseUrl, target: '_blank', topicType: e.shortName }) .css('color',e.color) } else { anchor.attr({ topicType: key }) } anchor.appendTo(topicList); } // Draw a tooltip containing the topics of the topicType selected // Example: the identifiers of uniprot var simpleTip = new Biojs.Tooltip({ targetSelector: topicList.children(), cbRender: function( element ) { return self._paintTopics( tagId, jQuery(element).attr('topicType') ); }, arrowType: Biojs.Tooltip.ARROW_TOP_MIDDLE }); return topicList; } ); } }, _paintTopics: function ( tagId, topicType ) { var self = this; var annotation = self._getAnnotation(tagId); var pattern=/(#|_|:|\/)([A-Za-z0-9])*$/g; Biojs.console.log("tagID " + tagId + ", topicType " + topicType); // raising event self.raiseEvent(Biojs.AnnotationsCloud.EVT_ON_ANNOTATION_CLICKED, { name: annotation.name, freq: annotation.freq, comments: self._getComments(annotation) }); var topicList = jQuery('<span class="topics"></span>'); var topic, identifier; var topicsByType = ( this.opt.groupBy == Biojs.Annotations.GROUP_BY_TERM) ? annotation.topics[topicType] : annotation.terms[topicType]; for ( i in topicsByType.entities ) { //topic = topicsByType.map; topic = ( this.opt.groupBy == Biojs.Annotations.GROUP_BY_TERM) ? topicsByType.map : annotation.map; identifier = ( topicsByType.entities[i].match(pattern)[0] ).substr(1); jQuery('<a class="topic ' + topic.shortName + '">' + topic.prefix + identifier + '</a>') .attr({ href: topic.baseUrl + identifier, target: '_blank', topicType: topic.shortName, topicId: identifier }) .css('color',topic.color) .mouseover( function(e){ var target = jQuery(e.target); self.raiseEvent(Biojs.AnnotationsCloud.EVT_ON_TOPIC_OVER, { href: target.attr("href"), topicType: target.attr("topicType"), topicId: target.attr("topicId") }); }) .click(function(e){ // Do not open the href e.preventDefault(); var target = jQuery(e.target); self.raiseEvent(Biojs.AnnotationsCloud.EVT_ON_TOPIC_CLICKED, { href: target.attr("href"), topicType: target.attr("topicType"), topicId: target.attr("topicId") }); }) .appendTo(topicList); } return topicList; }, _getComments: function( annotation ) { var compareTo = 30; var comments = []; var comment; var last=""; var t = annotation.name; for ( var i in annotation.comments ) { if ( ! ( annotation.comments[i][0].slice(0, compareTo) == last ) ) { comment = annotation.comments[i][0].replace( new RegExp( t.toLowerCase(), 'gi' ), "<span class='highlight'>" + t + "</span>" ); comments.push( [ comment ] ); } last = annotation.comments[i][0].slice(0, compareTo); } return comments; } },{ // Events EVT_ON_TOPIC_OVER: "onTopicOver", EVT_ON_TOPIC_CLICKED: "onTopicClicked", EVT_ON_ANNOTATION_CLICKED: "onAnnotationClicked", EVT_ON_ANNOTATION_OVER: "onAnnotationOver" });
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from 'src/app/services/auth.service'; import { Admin } from 'src/app/types/Admin'; import Swal from 'sweetalert2' @Component({ selector: 'app-signup-page', templateUrl: './signup-page.component.html', styleUrls: ['./signup-page.component.css'] }) export class SignupPageComponent implements OnInit { username: string; email: string; password: string; rePassword: string; telecomPass: string; errorMessage: string; constructor(private authService: AuthService, private router: Router) { } ngOnInit() { } resetErrorMsg() { this.errorMessage = '' } validateEmail(mail) { return (/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(mail)) } onSignup() { if (!this.email || !this.username || !this.password || !this.rePassword || !this.telecomPass) return this.errorMessage = 'Fill the whole inputs' if (!this.validateEmail(this.email)) return this.errorMessage = 'Invalid email' if (this.password !== this.rePassword) return this.errorMessage = 'Passwords didnt match' const newUser: Admin = { _id: null, username: this.username, email: this.email, password: this.password, role: 'admin' } this.authService.createUser(newUser, this.telecomPass) .subscribe(() => { Swal.fire( 'Sucess', 'Your account has been created!', 'success' ).then((result) => { if (result.isConfirmed) { this.router.navigate(['login']); } }) }, (err) => { if (err.status === 400) this.errorMessage = 'Telecom password is wrong' else if (err.status === 409) this.errorMessage = 'username or email already in use' else this.errorMessage = 'Connexion error' }) } }
package com.mathiezelat.portfolio.Security.Controller; import java.util.HashSet; import java.util.Set; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.mathiezelat.portfolio.Security.Dto.JwtDto; import com.mathiezelat.portfolio.Security.Dto.LoginUser; import com.mathiezelat.portfolio.Security.Dto.NewUser; import com.mathiezelat.portfolio.Security.Entity.Role; import com.mathiezelat.portfolio.Security.Entity.User; import com.mathiezelat.portfolio.Security.Enums.RoleName; import com.mathiezelat.portfolio.Security.Service.RoleService; import com.mathiezelat.portfolio.Security.Service.UserService; import com.mathiezelat.portfolio.Security.jwt.JwtProvider; @RestController @RequestMapping("/auth") @CrossOrigin(origins = "https://ar-portfolio-mel.web.app") public class AuthController { @Autowired PasswordEncoder passwordEncoder; @Autowired AuthenticationManager authenticationManager; @Autowired UserService userService; @Autowired RoleService roleService; @Autowired JwtProvider jwtProvider; @PostMapping("/register") public ResponseEntity<?> register(@Valid @RequestBody NewUser newUser, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return new ResponseEntity(new Message("Campos mal puestos o email inválido"), HttpStatus.BAD_REQUEST); } if (userService.existsByUsername(newUser.getUsername())) { return new ResponseEntity(new Message("Ese nombre de usuario ya existe"), HttpStatus.BAD_REQUEST); } if (userService.existsByEmail(newUser.getEmail())) { return new ResponseEntity(new Message("Ese email ya existe"), HttpStatus.BAD_REQUEST); } User user = new User(newUser.getName(), newUser.getUsername(), newUser.getEmail(), passwordEncoder.encode(newUser.getPassword())); Set<Role> roles = new HashSet<>(); roles.add(roleService.getByRoleName(RoleName.ROLE_USER).get()); if (newUser.getRoles().contains("admin")) { roles.add(roleService.getByRoleName(RoleName.ROLE_ADMIN).get()); } user.setRoles(roles); userService.save(user); return new ResponseEntity(new Message("Usuario guardado"), HttpStatus.CREATED); } @PostMapping("/login") public ResponseEntity<JwtDto> login(@Valid @RequestBody LoginUser loginUser, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return new ResponseEntity(new Message("Campos mal puestos"), HttpStatus.BAD_REQUEST); } Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtProvider.generateToken(authentication); UserDetails userDetails = (UserDetails) authentication.getPrincipal(); JwtDto jwtDto = new JwtDto(jwt, userDetails.getUsername(), userDetails.getAuthorities()); return new ResponseEntity(jwtDto, HttpStatus.OK); } }
// // RegisterViewController.swift // Assignment 1 Tatiana // // Created by Tatiana Pasechnik on 13/04/23. // import UIKit class RegisterViewController: UIViewController, UITextFieldDelegate{ //outlets @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var addressTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var phoneTextField: UITextField! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var scrollView: UIScrollView! weak var activeField: UITextField? override func viewDidLoad() { super.viewDidLoad() //display password as dotts in ios12+ passwordTextField.textContentType = .oneTimeCode //method to controll when Keyboard shows KeyboardNotificationUtils.registerKeyboardNotifications(for: self, didShow: #selector(keyboardDidShow), willHide: #selector(keyboardWillBeHidden)) } deinit { NotificationCenter.default.removeObserver(self) } // Method to close Keyboard when user finished typing func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // check if text field finished editing func textFieldDidEndEditing(_ textField: UITextField) { activeField = nil } // check if textfield is active func textFieldDidBeginEditing(_ textField: UITextField) { activeField = textField } //Manipulate keyboard to display under the field, where entering text @objc func keyboardDidShow(notification: Notification) { let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue guard let activeField = activeField, let keyboardHeight = keyboardSize?.height else { return } let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardHeight, right: 0.0) scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets let activeRect = activeField.convert(activeField.bounds, to: scrollView) scrollView.scrollRectToVisible(activeRect, animated: true) } @objc func keyboardWillBeHidden(notification: Notification) { let contentInsets = UIEdgeInsets.zero scrollView.contentInset = contentInsets scrollView.scrollIndicatorInsets = contentInsets } // Register new user @IBAction func registerUserBtn(_ sender: UIButton) { let textFieldsArray = [nameTextField,addressTextField, emailTextField, phoneTextField, usernameTextField, passwordTextField] var emptyFieldsArray = [UITextField]() for field in textFieldsArray { if field!.text!.isEmpty { field!.layer.borderColor = UIColor.red.cgColor field!.layer.borderWidth = 1 showMessage(msg: "Attention! Some required information is missing. Please make sure you fill in all the fields before proceeding", controller: self) emptyFieldsArray.append(field!) } else { field!.layer.borderWidth = 0 } } if emptyFieldsArray.isEmpty { let uName = nameTextField.text! let uAddress = addressTextField.text! let uEmail = emailTextField.text! let uPhone = phoneTextField.text! let uUsername = usernameTextField.text! let uPassword = passwordTextField.text! if !(searchUser(username: uUsername)) { let newUser = User(name: uName, address: uAddress, email: uEmail, phone: uPhone, usernmae: uUsername, password: uPassword) users.append(newUser) let data = try! NSKeyedArchiver.archivedData(withRootObject: users, requiringSecureCoding: false) UserDefaults.standard.set(data, forKey: "users") showMessageAndRedirect(msg: "User registered successfully", controller: self) } else { showMessage (msg: "This username already exist, please choose another username or login", controller: self) } } } }
/* Copyright 2022 Savvas Dalkitsis Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.ui import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.seam.actions.ChangeSearchSuggestionsEnabled import com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.seam.actions.ClearRecentSearches import com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.seam.actions.SettingsAction import com.savvasdalkitsis.uhuruphotos.feature.settings.view.implementation.ui.state.SettingsState import com.savvasdalkitsis.uhuruphotos.foundation.icons.api.R.drawable import com.savvasdalkitsis.uhuruphotos.foundation.strings.api.R.string @Composable internal fun SettingsSearch( state: SettingsState, action: (SettingsAction) -> Unit, ) { val checked = state.searchSuggestionsEnabled SettingsCheckBox( text = stringResource(string.enable_suggestions), icon = when { checked -> drawable.ic_lightbulb else -> drawable.ic_lightbulb_off }, isChecked = checked, onCheckedChange = { action(ChangeSearchSuggestionsEnabled(it)) } ) SettingsOutlineButtonRow( buttonText = stringResource(string.clear_recent_searches), icon = drawable.ic_clear_all, ) { action(ClearRecentSearches) } }
from abc import ABC, abstractmethod from pprint import pprint class Gradinita(ABC): @abstractmethod def activitate_practica(self): pass @abstractmethod def ora_de_somn(self): raise NotImplementedError class GradinitaPublica(Gradinita): def activitate_practica(self): print('Copiii invata sa deseneze') def ora_de_somn(self): print('Copiii trebuie sa doarma la ora 5') class GradinitaPrivata(Gradinita, ABC): __elevi={} def _adauga_elevi(self,**kwargs): self.__elevi.update(kwargs) @property def elevi(self): return self.__elevi @elevi.setter def elevi(self,value): self._adauga_elevi(**value) def activitate_practica(self): print('Copiii invata sa modeleze cu plastilina') class GradinitaPrivata11(GradinitaPrivata): def ora_de_somn(self): print('Copiii dorm intre 11:30 si 14:30') class GradinitaPublica25(GradinitaPublica): nr_elevi = 600 _adresa = 'Strada Napoca 12' __fonduri = 300_000 @property def fonduri(self): return self.__fonduri @fonduri.setter def fonduri(self, value): self.__fonduri = value @fonduri.deleter def fonduri(self): self.__fonduri = None def activitate_practica(self): print('Copiii se joaca in curte pe balansoar') def calculeaza_medie_buline_rosii(self, buline): medie = sum(buline) / len(buline) if medie > 5: print('Elevii acestei gradinite sunt foarte neastamparati') def info_elevi(self): elevi = {} while True: nume_elev = input('Introdu numele elevului: ') nume_parinti = input('Introdu nume parinti: ') varsta = input('Introdu varsta: ') activitate = input('Introdu activitatea preferata: ') elevi[nume_elev] = { 'nume_parinti': nume_parinti, 'varsta': varsta, 'activitate': activitate } introduce = input('Doresti sa introduci date in continuare? (y/n): ') if introduce.lower() != 'y': break pprint(elevi) p = GradinitaPublica() p.activitate_practica() # pr = GradinitaPrivata() # da eroare pt ca nu se pot crea obiecte pt clase abstracte p25 = GradinitaPublica25() p25.activitate_practica() p25.ora_de_somn() p25.calculeaza_medie_buline_rosii([1, 2, 3, 4]) p25.calculeaza_medie_buline_rosii([8, 9, 10, 7]) # p25.info_elevi() print(p25.nr_elevi) print(p25.fonduri) p25.fonduri = 250_000 print(p25.fonduri) del p25.fonduri print(p25.fonduri) pr11=GradinitaPrivata11() pr11.elevi={'Andrei': {'varsta': 3,'an_inscriere':2022}} pr11.elevi={'Valentina': {'varsta': 2,'an_inscriere':2023}} pprint(pr11.elevi)
<!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>SB Admin - Bootstrap Admin Template</title> <!-- Bootstrap Core CSS --> <link href="{{ asset('css/bootstrap.min.css')}}" rel="stylesheet"> <!-- Custom CSS --> <link href="{{asset('css/sb-admin.css')}}" rel="stylesheet"> <!-- mon css --> <link href="{{asset('css/default.css?32')}}" rel="stylesheet"> <link href="{{ asset('css/bootstrap-datepicker3.min.css')}}" rel="stylesheet"> <!-- Custom Fonts --> <link href="{{asset('font-awesome-4.7.0/css/font-awesome.min.css')}}" rel="stylesheet" type="text/css"> <script src="{{asset('js/jquery.js')}}"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div id="wrapper"> @include('elements/loader/loader_fullpage') <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{{route('home')}}">Jp Multi service</a> </div> <!-- Top Menu Items --> <ul class="nav navbar-right top-nav"> <!-- <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-envelope"></i> <b class="caret"></b></a> <ul class="dropdown-menu message-dropdown"> <li class="message-preview"> <a href="#"> <div class="media"> <span class="pull-left"> <img class="media-object" src="http://placehold.it/50x50" alt=""> </span> <div class="media-body"> <h5 class="media-heading"><strong>John Smith</strong> </h5> <p class="small text-muted"><i class="fa fa-clock-o"></i> Yesterday at 4:32 PM</p> <p>Lorem ipsum dolor sit amet, consectetur...</p> </div> </div> </a> </li> <li class="message-preview"> <a href="#"> <div class="media"> <span class="pull-left"> <img class="media-object" src="http://placehold.it/50x50" alt=""> </span> <div class="media-body"> <h5 class="media-heading"><strong>John Smith</strong> </h5> <p class="small text-muted"><i class="fa fa-clock-o"></i> Yesterday at 4:32 PM</p> <p>Lorem ipsum dolor sit amet, consectetur...</p> </div> </div> </a> </li> <li class="message-preview"> <a href="#"> <div class="media"> <span class="pull-left"> <img class="media-object" src="http://placehold.it/50x50" alt=""> </span> <div class="media-body"> <h5 class="media-heading"><strong>John Smith</strong> </h5> <p class="small text-muted"><i class="fa fa-clock-o"></i> Yesterday at 4:32 PM</p> <p>Lorem ipsum dolor sit amet, consectetur...</p> </div> </div> </a> </li> <li class="message-footer"> <a href="#">Read All New Messages</a> </li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-bell"></i> <b class="caret"></b></a> <ul class="dropdown-menu alert-dropdown"> <li> <a href="#">Alert Name <span class="label label-default">Alert Badge</span></a> </li> <li> <a href="#">Alert Name <span class="label label-primary">Alert Badge</span></a> </li> <li> <a href="#">Alert Name <span class="label label-success">Alert Badge</span></a> </li> <li> <a href="#">Alert Name <span class="label label-info">Alert Badge</span></a> </li> <li> <a href="#">Alert Name <span class="label label-warning">Alert Badge</span></a> </li> <li> <a href="#">Alert Name <span class="label label-danger">Alert Badge</span></a> </li> <li class="divider"></li> <li> <a href="#">View All</a> </li> </ul> </li>--> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-connectdevelop"></i> {{ \Illuminate\Support\Facades\Auth::check()? \Illuminate\Support\Facades\Auth::user()->name:'' }} <b class="caret"></b> </a> <ul class="dropdown-menu"> <!--<li> <a href="#"><i class="fa fa-fw fa-user"></i> Profile</a> </li> <li> <a href="#"><i class="fa fa-fw fa-envelope"></i> Inbox</a> </li> <li> <a href="#"><i class="fa fa-fw fa-gear"></i> Settings</a> </li>--> <li class="divider"></li> <li class="text-center"> <form method="POST" action="/logout"> {{ csrf_field() }} <button type="submit" class="btn btn-danger"><i class="fa fa-fw fa-power-off"></i>Se déconnecter</button> </form> </li> </ul> </li> </ul> <ul class="nav navbar-right top-nav"> <li class="dropdown"> @if(Session::has('client')) <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-user"></i>&nbsp; {{Session::get('client.fullName')}} <b class="caret"></b> </a> <ul class="dropdown-menu"> <li> <a href="{{route('clients.choixClient')}}"><i class="fa fa-fw fa-list"></i>Changer</a> </li> <li> <a href="{{route('clients.view',Session::get('client.id'))}}"><i class="fa fa-fw fa-search"></i>Voir Client</a> </li> <li> <a href="{{route('clients.edit',Session::get('client.id'))}}"><i class="fa fa-fw fa-gear"></i>modifier Client</a> </li> {{--<li>--}} {{--<a href="#"><i class="fa fa-fw fa-envelope"></i>Email</a>--}} {{--</li>--}} </ul> @else <a href="{{ route('clients.choixClient',['redirect' => 'home']) }}" > <i class="fa fa-user"></i> &nbsp; Choisir un client </a> @endif </li> </ul> <!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens --> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> @include('layouts.nav') </ul> </div> <!-- /.navbar-collapse --> </nav> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> @include('flash') <div class="col-lg-12"> <h1 class="page-header"> @yield('title') </h1> </div> <div class="col-lg-12"> @yield('content') </div> </div> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --> </div> <!-- /#wrapper --> <!-- jQuery --> <!-- Bootstrap Core JavaScript --> <script src="{{asset('js/bootstrap.min.js')}}"defer></script> <script src="{{asset('js/bootstrap-datepicker.min.js')}}"defer></script> <script src="{{asset('js/bootstrap-datepicker.fr.js')}}"defer></script> <script src="{{asset('js/defaut.js')}}"></script> </body> </html>
# Interview--Java基础 精心收录整理互联网笔试面试题,以及自己发布的文章,欢迎各位star!或者关注微信公众号【1024笔记】,免费获取海量学习资源 . 作者:江夏、 . 简书:https://www.jianshu.com/u/b3263fc54bce . 知乎:https://www.zhihu.com/people/qing-ni-chi-you-zi-96 . GitHub:https://github.com/JiangXia-1024?tab=repositories . 博客地址:https://blog.csdn.net/qq_41153943 ------ ### 1、&和&&的区别 &和&&都可以用作逻辑与的运算符,表示逻辑与(and),当运算符两边的表达式的结果都为true 时,整个运算结果才为true,否则,只要有一方为false,则结果为false。 既然存在两个运算符,那么他们之前肯定还是有区别的。&&还具有短路的功能,即如果第一个表达式为false,则不再计算第二个表达式,整个条件都为false。例如, ```cpp int i=0; string g="adb"; if(i!=0 && g.length==0){ ..... } ``` ```cpp int i=0; string g="adb"; if(i!=0 & g.length==0){ ..... } ``` 因为i=0,所以表达式i!=0返回的是false,那么&&后面的表达式便不再执行。整个if条件都为false,如果将&&换成&,虽然i!=0返回的是false,但是表达式g.length==0还是要执行,整个if条件也返回的是false。 &还可以用作位运算符,当&操作符两边的表达式不是boolean类型时,&表示按位与操作,我们通常 使用0x0f来与一个整数进行&运算,来获取该整数的低4个bit位,例如,0x31 & 0x0f的结果为0x01。 ### 2、short s1= 1; s1 = s1+1 和short s1 = 1; s1 += 1;有什么区别 对于short s1= 1; s1 = s1+1因为1是int类型,而等号左边的s1是short类型,由于s1+1运算时会自动提升表达式的类型,所以运算的结果是int型,再赋值给 short类型s1时,编译器将报告需要强制转换类型的错误,所以需要进行强转。 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200509105222272.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200509105311917.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) 对于short s1= 1; s1 += 1;在java中+=的作用包含两个部分,除了基本的加法运算功能之外,还可以隐形转换改变结果的类型,将计算结果的类型转换为“+=”符号左边的对象的类型。所以可以正确编译 ![img](https://img-blog.csdnimg.cn/20200509105757495.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) ### 3、使用final关键字修饰一个变量时,是引用不能变,还是引用的对象不能变 使用final关键字修饰一个变量时,是指引用变量不能变,但是引用变量所指向的对象中的内容还是可以改变的。 ```cpp public class Demo2 { //声明一个final关键字修饰的字符串 public static final StringBuffer sb = new StringBuffer("abc"); public static void main(String[] args) { // TODO Auto-generated method stub //sb指向新的引用对象 sb = new StringBuffer("def"); } } ``` 上述代码报错: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200509143729619.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) ```cpp public class Demo2 { //声明一个final关键字修饰的字符串 public static final StringBuffer sb = new StringBuffer("abc"); public static void main(String[] args) { // TODO Auto-generated method stub //sb指向新的引用对象 //sb = new StringBuffer("def"); System.out.println(sb); //修改sb引用对象的值 sb.append("def"); System.out.println(sb); } } ``` ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200509144014812.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) 其实这个还是跟final关键字的使用有关。final关键字除了可以修饰类和方法以外,final关键字还可以用来修饰变量,其中包括基本数据类型的值变量和引用变量。 final修饰的变量其实就相当于定义了一个常量,无法被修改的变量。 如果final修饰的是一个基本数据类型的值变量,那么这个变量的值就定了,不能变了,比如final int i=10;那么就是在栈内存中对i变量赋值为10,这个值是不能改变的了; 而如果final关键字修饰的是一个引用变量,那么该变量在栈内存中存的是一个内存地址,该地址就不能变了,但是该内存地址所指向的那个对象还是可以变的。 如果拿去买房为例的话,对于基本数据类型的变量,房子的价格就好比是被final修饰的基本数据类型的变量,一旦定死了就不能修改了(虽然现实中可以修改的);而对于引用变量,这个地皮(栈内存地址)一旦规划作为住宅用地了,那么便不可以再做其他用途(引用不能指向其他的对象),但是在这个地址上盖什么样的房子,多少房子是可以改变的(引用对象的内容可以改变) 使用final关键字修饰一个变量时,是指引用变量不能变,但是引用变量所指向的对象中的内容还是可以改变的。 ```cpp public class Demo2 { //声明一个final关键字修饰的字符串 public static final StringBuffer sb = new StringBuffer("abc"); public static void main(String[] args) { // TODO Auto-generated method stub //sb指向新的引用对象 sb = new StringBuffer("def"); } } ``` 上述代码报错: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200509143729619.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) ```cpp public class Demo2 { //声明一个final关键字修饰的字符串 public static final StringBuffer sb = new StringBuffer("abc"); public static void main(String[] args) { // TODO Auto-generated method stub //sb指向新的引用对象 //sb = new StringBuffer("def"); System.out.println(sb); //修改sb引用对象的值 sb.append("def"); System.out.println(sb); } } ``` ![](https://img-blog.csdnimg.cn/20200509151033193.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) ### 4、Integer与int的区别 int是java提供的8种基本数据类型之一。Java为每个基本数据库类型提供了封装类,而Integer就是java为int提供 的封装类。int的默认值为0,而Integer的默认值为null,即Integer可以区分出未赋值和值为0的区别, int则无法表达出未赋值的情况。 例如:要想表达出没有工资和工资为0的区别,则只能使用Integer。在JSP的开发中,Integer的默认为null,所以用el表达式在文本框中显示时,值为空白字符串,而int默认的默认值为0,所以用el表达式在文本框中显示时,结果为0,所以,int不适合作为web层的表单数据的类型。 在Hibernate中,如果将OID定义为Integer类型,那么Hibernate就可以根据其值是否为null而判断一 个对象是否是临时的,如果将OID定义为了int类型,还需要在hbm映射文件中设置其unsaved-value属 性为0。 另外,Integer提供了多个与整数相关的操作方法,例如,将一个字符串转换成整数,Integer中还定 义了表示整数的最大值和最小值的常量。 ### 5、Overload和Override的区别?Overload的方法是否可以改变返回值的类型? #### **5.1、overload** Overload的中文意思是重载,它表示同一个类中可以有多个名称相同的方法,但这些方法的参数列表各不相同,即参数的个数或类型至少有一个不同,但返回值和方法属性必须相同。在调用的时候,VM就会根据不同的参数列表,来执行对应的合适的方法。 比如: ```cpp public class Demo4 { public static void main(String[] args) { Demo4 demo4 = new Demo4(); demo4.say(); demo4.say("你好啊"); demo4.say("张三","你在干嘛"); demo4.say(4, "李四"); demo4.say("李四",5); } public void say() { System.out.println("Hello world"); } public void say(String wordString) { System.out.println("Hello "+ wordString); } public void say(String name,String word) { System.out.println(name+"说:"+word); } public void say(int word,String name) { System.out.println(name+"说:"+word); } public void say(String name,int word) { System.out.println(name+"说:"+word); } } ``` ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200512101442239.png) 上面代码中的方法就是重载。 我看有些文章里面写到对于重载的返回值类型也可以是不同的,还有的说是可以相同,也可以不同。那么我们先看代码: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200512101738391.png) 这里报错完全一样的方法在Demo4中,所以可以看出,参数列表相同,仅仅靠返回值不同,是不能实现重载的。在java中明确声明在一个类中,两个方法的方法名和参数列表一样,返回值类型不同这是不允许的。 有的说在参数列表不同的情况下(已经是重载了),返回值类型可以是相同,可以是不同的。再来看代码: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200512102223457.png) 的确上述的代码,并没有报错。但是我们想想,上面的两个say方法,一个返回的是说的内容(返回值类型是string),一个返回的是说了几句话(返回值类型是int),这两个方法的功能是不一样的。所以他们已经是两个不一样的方法了,只是方法名一样,但是并不是方法的重载(我也不能说我说的都对,只是个人觉得的,目前也没有在一本权威的书本上面看到这类的答案,所以如果有小伙伴觉得不对,或者看到了权威的说法,欢迎指正)。 #### 5.2、Override Override重写(覆盖),表示子类中的方法可以与父类中的某个方法的名称和参数完全相同,通过子类创建的实 例对象调用这个方法时,将调用子类中的定义方法,这相当于把父类中定义的那个完全相同的方法给覆盖了, 这也正是面向对象编程的中多态性的一种表现。子类覆盖父类的方法时,只能比父类抛出更少的异常,或者是抛出父类抛出的异常的子异常,因为子类可以解决父类的一些问题,所以不能比父类有更多的问题。 子类方法的访问权限只能比父类的更大,不能更小。如果父类的方法是private类型,那么子类并不能对父类的private关键字修饰的方法进行覆盖,相当于子类中增加了一个全新的方法。因为我们知道provite关键字修饰的变量或者方法都是只能本类可以访问使用,其他的任何的都不可以。所以 当一个子类继承了父类,那么这个子类其实是拥有父类所有的成员属性和方法,包括父类里有private属性的变量和方法,子类也是继承的,但是子类并不能使用,也就是说,它继承了,但是并没有使用权, 打个比方就好比,你爸的钱虽然都是你的(都可以继承),但是你只能使用你爸放在家里的钱(public修饰的变量方法),你爸存在银行卡里面的钱你并不能使用(private修饰的),但你是可以继承的。 ```cpp public class Demo4 { public String say(String wordString) { return wordString; } private String say(String wordString,int i) { return wordString; } public int say(int wordString) { return wordString; } } ``` ```cpp package Demo1; public class Demo5 extends Demo4 { public static void main(String[] args) { Demo5 demo5 = new Demo5(); String s1 = demo5.say("你好"); int i = demo5.say(23); String s2 = demo5.say("你好",23); System.out.println(s1); System.out.println(i); System.out.println(s2); } public String say(String wordString) { return wordString; } private String say(String wordString,int i) { return wordString; } public int say(int wordString) { return wordString; } } ``` ![在这里插入图片描述](https://img-blog.csdnimg.cn/2020051210532382.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) #### 5.3、overwrite overwrite重写的意思:java官方文档没有该词的出现,所以java中就没有它的存在,但是也有人把overwrite解释为override。 但是在C++中将Override和overwrite进行了区分。 Override:覆盖 是指派生类函数覆盖基类函数,特征是: (1)不同的范围(分别位于派生类与基类); (2)函数名字相同; (3)参数相同; (4)基类函数必须有virtual 关键字。 Overwrite:重写 是指派生类的函数屏蔽了与其同名的基类函数,规则如下: (1)如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无virtual关键字,基类的函数将被隐藏。 (2)如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有virtual关键字。此时,基类的函数被隐藏。 所以如果是java的话根本不需要考虑overwrite,记住overload和override即可。 #### 5.4、总结 override: 1、覆盖的方法的标志必须要和被覆盖的方法的标志完全匹配,才能达到覆盖的效果; 2、覆盖的方法的返回值必须和被覆盖的方法的返回一致; 3、覆盖的方法所抛出的异常必须和被覆盖方法的所抛出的异常一致,或者是其子类; 4、如果某一方法在父类中是访问权限是priavte,那么就不能在子类对其进行覆盖, 否则在其子类中只是新定义了一个方法,并没有对其进行覆盖。 Overload: 1、在使用重载时只能通过不同的参数样式。例如,不同的参数类型,不同的参数个数,不同的参数顺序(注意这里同一方法内的几个参数类型必须不一样,例如可以是fun(int,float),但是不能为 fun(int,int)); 2、不能通过访问权限、返回类型、抛出的异常进行重载; 3、方法的异常类型和数目不会对重载造成影响; 参考:https://stackoverflow.com/questions/837864/java-overloading-vs-overriding ### 6、Java中实现多态的机制是什么? 靠的是父类或接口定义的引用变量可以指向子类或具体实现类的实例对象,而程序调用的方法在运行期才动态绑定,就是引用变量所指向的具体实例对象的方法,也就是内存里正在运行的那个对象的方法,而不是引用变量的类型中定义的方法。 ### 7、接口是否可继承接口?抽象类是否可实现(implements)接口?抽象类是否可继承具体类(concreteclass)?抽象类中是否可以有静态的main方法? 接口可以继承接口。抽象类可以实现(implements)接口,抽象类可以继承具体类。抽象类中可以有静态的main方法。备注:只要明白了接口和抽象类的本质和作用,这些问题都很好回答,你想想,如果你是java语言的设计者,你是否会提供这样的支持,如果不提供的话,有什么理由吗?如果你没有道理不提供,那答案就是肯定的了。只要记住抽象类与普通类的唯一区别就是不能创建实例对象和允许有abstract方法。 ### 8、abstract的method是否可同时是static,是否可同时是native,是否可同时是synchronized? abstract的method不可以是static的,因为抽象的方法是要被子类实现的,而static与子类扯不上关系!native方法表示该方法要用另外一种依赖平台的编程语言实现的,不存在着被子类实现的问题,所以,它也不能是抽象的,不能与abstract混用。例如,FileOutputSteam类要硬件打交道,底层的实现用的是操作系统相关的api实现;例如,在windows用c语言实现的,所以,查看jdk的源代码,可以发现 FileOutputStream的open方法的定义如下: `` private native void open(Stringname) throwsFileNotFoundException; `` 如果我们要用java调用别人写的c语言函数,我们是无法直接调用的,我们需要按照java的要求写一个c语言的函数,又我们的这个c语言函数去调用别人的c语言函数。由于我们的c语言函数是按java的要求来写的,我们这个c语言函数就可以与java对接上,java那边的对接方式就是定义出与我们这个c函数相对应的方法,java中对应的方法不需要写具体的代码,但需要在前面声明native。关于synchronized与abstract合用的问题,我觉得也不行,因为在我几年的学习和开发中,从来没见到过这种情况,并且我觉得synchronized应该是作用在一个具体的方法上才有意义。而且,方法上的synchronized同步所使用的同步锁对象是this,而抽象方法上无法确定this是什么。 ### 9、内部类可以引用它的包含类的成员吗? 可以。如果不是静态内部类,那没有什么限制! 如果你把静态嵌套类当作内部类的一种特例,那在这种情况下不可以访问外部类的普通成员变量,而 只能访问外部类中的静态成员,例如,下面的代码: ```java class Outer { static int x; static class Inner { voidtest() { syso(x); } } } ``` ### 10、String s = "Hello";s = s + "world!";这两行代码执行后,原始的String对象中的内容到底变了没有? 没有。因为String被设计成不可变(immutable)类,所以它的所有对象都是不可变对象。在这段代码中,s原先指向一个String对象,内容是 "Hello",然后我们对s进行了+操作,那么s所指向的那个对象是否发生了改变呢?答案是没有。这时,s不指向原来那个对象了,而指向了另一个 String对象,内容为"Hello world!",原来那个对象还存在于内存之中,只是s这个引用变量不再指向它了。通过上面的说明,我们很容易导出另一个结论,如果经常对字符串进行各种各样的修改,或者说,不可预见的修改,那么使用String来代表字符串的话会引起很大的内存开销。因为String对象建立之后不能再改变,所以对于每一个不同的字符串,都需要一个String对象来表示。这时,应该考虑使用StringBuffer类,它允许修改,而不是每个不同的字符串都要生成一个新的对象。并且,这两种类的对象转换十分容易。 同时,我们还可以知道,如果要使用内容相同的字符串,不必每次都new一个String。例如我们要在构造器中对一个名叫s的String引用变量进行初始化,把它设置为初始值,应当这样做: ```java public class Demo { private String s; ... public Demo { s = "Initial Value"; } ... } 而非 s = new String("Initial Value"); ``` 后者每次都会调用构造器,生成新对象,性能低下且内存开销大,并且没有意义,因为String对象不可改变,所以对于内容相同的字符串,只要一个String对象来表示就可以了。也就说,多次调用上面的构造器创建多个对象,他们的 String类型属性s都指向同一个对象。上面的结论还基于这样一个事实:对于字符串常量,如果内容相同,Java认为它们代表同一个String对象。而用关键字new调用构造器,总是会创建一个新的对象,无论内容是否相同。至于为什么要把String类设计成不可变类,是它的用途决定的。其实不只String,很多Java标准类库中的类都是不可变的。在开发一个系统的时候,我们有时候也需要设计不可变类,来传递一组相关的值,这也是面向对象思想的体现。不可变类有一些优点,比如因为它的对象是只读的,所以多线程并发访问也不会有任何问题。当然也有一些缺点,比如每个不同的状态都要一个对象来代表,可能会造成性能上的问题。所以Java标准类库还提供了一个可变版本,即StringBuffer。 ### 11、ArrayList和Vector的区别 这两个类都实现了List接口(List接口继承了Collection接口),他们都是有序集合,即存储在这两个集合中的元素的位置都是有顺序的,相当于一种动态的数组,我们以后可以按位置索引号取出某个元素,并且其中的数据是允许重复的,这是与HashSet之类的集合的最大不同处,HashSet之类的集合不可以按索引号去检索其中的元素,也不允许有重复的元素。ArrayList与Vector的区别主要包括两个方面:. (1)同步性: Vector是线程安全的,也就是说是它的方法之间是线程同步的,而ArrayList是线程序不安全的,它的方法之间是线程不同步的。如果只有一个线程会访问到集合,那最好是使用ArrayList,因为它不考虑线程安全,效率会高些;如果有多个线程会访问到集合,那最好是使用Vector,因为不需要我们自己再去考虑和编写线程安全的代码。 (2)数据增长: ArrayList与Vector都有一个初始的容量大小,当存储进它们里面的元素的个数超过了容量时,就需要增加ArrayList与Vector的存储空间,每次要增加存储空间时,不是只增加一个存储单元,而是增加多个存储单元,每次增加的存储单元的个数在内存空间利用与程序效率之间要取得一定的平衡。Vector默认增长为原来两倍,而ArrayList的增长策略在文档中没有明确规定(从源代码看到的是增长为原来的1.5倍)。ArrayList与Vector都可以设置初始的空间大小,Vector还可以设置增长的空间大小,而ArrayList没有提供设置增长空间的方法。 总结:即Vector增长原来的一倍,ArrayList增加原来的0.5倍。 ### 12、HashMap和Hashtable的区别 HashMap是Hashtable的轻量级实现(非线程安全的实现),他们都完成了Map接口,主要区别在于HashMap允许空(null)键值(key),由于非线程安全,在只有一个线程访问的情况下,效率要高于Hashtable。HashMap允许将null作为一个entry的key或者value,而Hashtable不允许。HashMap把Hashtable的contains方法去掉了,改成containsvalue和containsKey。因为contains方法容易让人引起误解。Hashtable继承自Dictionary类,而HashMap是Java1.2引进的Map interface的一个实现。最大的不同是,Hashtable的方法是Synchronize的,而HashMap不是,在多个线程访问Hashtable时,不需要自己为它的方法实现同步,而HashMap就必须为之提供同步。 就HashMap与HashTable的区别主要从三方面来说。 一.历史原因:Hashtable是基于陈旧的Dictionary类的,HashMap是Java 1.2引进的Map接口的一个实 现 二.同步性:Hashtable是线程安全的,也就是说是同步的,而HashMap是线程序不安全的,不是同步 的 三.值:只有HashMap可以让你将空值作为一个表的条目的key或value。 ### 13、List和 Map区别? 一个是存储单列数据的集合,另一个是存储键和值这样的双列数据的集合,List中存储的数据是有顺序,并且允许重复;Map中存储的数据是没有顺序的,其键是不能重复的,它的值是可以有重复的。 ### 14、List、Map、Set三个接口,存取元素时,各有什么特点? 首先,List与Set具有相似性,它们都是单列元素的集合,所以,它们有一个共同的父接口,叫 Collection。Set里面不允许有重复的元素,即不能有两个相等(注意,不是仅仅是相同)的对象,即假 设Set集合中有了一个A对象,现在我要向Set集合再存入一个B对象,但B对象与A对象equals相等,则B 对象存储不进去,所以,Set集合的add方法有一个boolean的返回值,当集合中没有某个元素,此时 add方法可成功加入该元素时,则返回true,当集合含有与某个元素equals相等的元素时,此时add方 法无法加入该元素,返回结果为false。Set取元素时,不能细说要取第几个,只能以Iterator接口取得所 有的元素,再逐一遍历各个元素。 List表示有先后顺序的集合,注意,不是那种按年龄、按大小、按价格之类的排序。当我们多次调用 add(Obje)方法时,每次加入的对象就像火车站买票有排队顺序一样,按先来后到的顺序排序。有时 候,也可以插队,即调用add(intindex,Obj e)方法,就可以指定当前对象在集合中的存放位置。一个对 象可以被反复存储进List中,每调用一次add方法,这个对象就被插入进集合中一次,其实,并不是把 这个对象本身存储进了集合中,而是在集合中用一个索引变量指向这个对象,当这个对象被add多次 时,即相当于集合中有多个索引指向了这个对象,如图x所示。List除了可以用Iterator接口取得所有的 元素,再逐一遍历各个元素之外,还可以调用get(index i)来明确说明取第几个。 Map与List和Set不同,它是双列的集合,其中有put方法,定义如下:put(obj key,obj value),每次 存储时,要存储一对key/value,不能存储重复的key,这个重复的规则也是按equals比较相等。取则可 以根据key获得相应的value,即get(Object key)返回值为key所对应的value。另外,也可以获得所有的 key的结合,还可以获得所有的value的结合,还可以获得key和value组合成的Map.Entry对象的集合。 List以特定次序来持有元素,可有重复元素。Set无法拥有重复元素,内部排序。Map保存key-value值, value可多值。 ### 15、ArrayList、Vector、LinkedList的存储性能和特性 ArrayList和Vector都是使用数组方式存储数据,此数组元素数大于实际存储的数据以便增加和插入元素,它们都允许直接按序号索引元素,但是插入元素要涉及数组元素移动等内存操作,所以索引数据快而插入数据慢,Vector由于使用了synchronized方法(线程安全),通常性能上较ArrayList差。而LinkedList使用双向链表实现存储,按序号索引数据需要进行前向或后向遍历,索引就变慢了,但是插入数据时只需要记录本项的前后项即可,所以插入速度较快。LinkedList也是线程不安全的,LinkedList提供了一些方法,使得LinkedList可以被当作堆栈和队列来使用。 ### 16、jsp有哪些内置对象?作用分别是什么 1. request 用户端请求,此请求会包含来自GET/POST请求的参数; request表示HttpServletRequest对象。它包含了有关浏览器请求的信息,并且提供了几个用于获取cookie, header,和session数据的有用的方法。 2. response 网页传回用户端的回应; response表示HttpServletResponse对象,并提供了几个用于设置送回浏览器的响应的方法(如cookies,头信息等) 3. pageContext 网页的属性是在这里管理; pageContext表示一个javax.servlet.jsp.PageContext对象。它是用于方便存取各种范围的名字空间、servlet相关的对象的API,并且包装了通用的 4. out 用来传送回应的输出; out对象是javax.jsp.JspWriter的一个实例,并提供了几个方法使你能用于向浏览器回送输出结果。 ##### servlet相关功能的方法。 5. session 与请求有关的会话期; session表示一个请求的javax.servlet.http.HttpSession对象。Session可以存贮用户的状态信息 6. application servlet 正在执行的内容; applicaton 表示一个javax.servle.ServletContext对象。这有助于查找有关servlet引擎和servlet环境的信息 7. config servlet的构架部件; config表示一个javax.servlet.ServletConfig对象。该对象用于存取servlet实例的初始化参数。 8. page JSP网页本身; page表示从该页面产生的一个servlet实例 9. exception 针对错误网页,未捕捉的例外; #### JSP共有以下6种基本动作 1. jsp:include:在页面被请求的时候引入一个文件。 2. jsp:useBean:寻找或者实例化一个JavaBean。 3. jsp:setProperty:设置JavaBean的属性。 4. jsp:getProperty:输出某个JavaBean的属性。 5. jsp:forward:把请求转到一个新的页面。 6. jsp:plugin:根据浏览器类型为Java插件生成OBJECT或EMBED标记 ### 17、Servlet API中forward()与redirect()的区别 #### 概念 forward()与redirect()是servlet的两种主要的跳转方式。forward又叫转发,redirect叫做重定向。 转发过程:客户浏览器发送http请求——>web服务器接受此请求—>调用内部的一个方法在容器内部完成请求处理和转发动作一>将目标资源发送给客户端; 在这里,转发的路径必须是同一个web容器下的URL,其不能转向到其他的web路径上去,中间传递的 是自己的容器内的request。在客户浏览器路径栏显示的仍然是其第一次访问的路径,也就是说客户是感觉不到服务器做了转发的。转发行为是浏览器只做了一次访问请求。 ![forword转发](https://img-blog.csdnimg.cn/20200514202933727.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) 重定向过程:客户浏览器发送http请求一一>web服务器接受后发送302状态码响及对应新的location给客户浏览器——>客户端浏览器发现是302状态码,会自动再发送一 个新的http请求,请求url是新的location地址一一>服务器根据此请求寻找资源并发送给客户端浏览器在这里location可以重定向到任意URL, 既然是浏览器重新发出了请求,则就没有什么request传递的概念了。在客户浏览器地址栏显示的是其重定向的路径,客户可以观察到地址的变化的。重定向行为是浏览器做了至少两次的访问请求的。 ![redirct重定向](https://img-blog.csdnimg.cn/20200514202710823.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) #### 区别: 1. 从地址栏显示来说: forward是服务器内部的重定向,服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发给浏览器。浏览器根本不知道服务器发送的内容从哪里来的,所以它的地址栏还是原来的地址。 redirect是服务端根据逻辑,发送一个状态码,告诉浏览器重新去请求那个地址。所以地址栏显示的是新的URL。 所以redirect等于客户端向服务器端发出两次request,同时也接受两次response;而forword只有一次请求。 2. 从数据共享来说 forward:forward方法只能在同一个Web应用程序内的资源之间转发请求,是服务器内部的一种操作。由于在整个定向的过程中用的是同一个request,因此forward会将request的信息带到被重定向的jsp或者servlet中使用,所以可以共享数据。 redirect:redirect是服务器通知客户端,让客户端重新发起请求。redirect不仅可以重定向到当前应用程序的其他资源,还可以重定向到同一个站点上的其他应用程序中的资源,甚至是使用绝对URL重定向到其他站点的资源。所以不能共享数据。 3. 从应用场景来说 forward:一般适用于用户登陆的时候,根据角色转发到相应的模块。 redirect:一般适用于用户注销登陆时返回主页面和跳转到其它的网站等. 4. 从效率来说 forward:效率高。 redirect:效率低. 5. 从本质来说: forword转发是服务器上的行为,而redirect重定向是客户端的行为 ### 18、面试题系列之接口是否可继承接口?抽象类是否可实现(implements)接口?抽象类是否可继承具体类?抽象类中是否可以有静态的main方法? 有一个面试四连击的题目:接口是否可继承接口?抽象类是否可实现(implements)接口?抽象类是否可继承具体类?抽象类中是否可以有静态的main方法? 上面这个题目我们来慢慢的剖析一下。先从基本的概念说起。 #### 一、接口 官方解释:Java接口是一系列方法的声明,是一些方法特征的集合,一个接口只有方法的特征没有方法的实现,因此这些方法可以在不同的地方被不同的类实现,而这些实现可以具有不同的行为(功能)。 又到了我最喜欢打比方的环节了:我们身边最常见的接口就是电脑的usb接口了。我们可以想想,我们电脑的usb接口是不是就那么几个但是没有任何的具体的功能?但是当我们把u盘插到usb接口的时候,我们可以进行数据的传输; 当我们把鼠标插入usb接口的时候,我们可以左键打开网页、文件夹等更多的功能;当我们把键盘插入到usb接口的时候我们可以打字,等等。虽然接入不同的设备可以进行不同的操作,但是上述的设备操作都是和电脑的数据交互。 所以电脑在设置usb接口的时候,并没有实现具体的读写数据的功能,而是但不同的设备接入usb接口就可以实现不同的数据读写功能。这就是接口的好处,试想:如果每个接口都有特定的功能,鼠标要插这个接口,键盘插那个接 口。那电脑就全是接口了,大大的浪费了资源,而且还不好看。 接口的特点以及重点: 1、并不能直接去实例化一个接口,因为接口中的方法都是抽象的,是没有方法体的。但是,我们可以使用接口类型的引用指向一个实现了该接口的对象(键盘、鼠标,....),并且可以调用这个接口中的方法。 2、一个类可以实现不止一个接口。键盘可以连接戴尔的接口、华硕的接口、联想的接口。 3、接口也可以继承,并且可以多继承。一个接口可以继承于另一个接口,或者另一些接口。比如现在的很多人电脑的usb接口不够用,所以有了usb接口拓展。 4、接口中所有的方法都是抽象的和public的,所有的属性都是public,static,final的。 5、一个类如果要实现某个接口的话,那么它必须要实现这个接口中的所有方法。我们在使用编辑器编写的时候就会自动提示: ![在这里插入图片描述](https://img-blog.csdnimg.cn/2020052017470116.png) 否则的话会报错: ![在这里插入图片描述](https://img-blog.csdnimg.cn/2020052017485660.png) 接口的实例: ```cpp public interface Demo8 { void say(); int add(); } ``` ```cpp public class Demo7 implements Demo8 { public static void main(String[] args) { Demo7 demo7 = new Demo7(); demo7.say(); System.out.println(demo7.add()); } public void say() { System.out.println("你好啊"); } public int add() { int i=1; int j=2; return i+j; } } ``` ```cpp public interface Demo9 extends Demo8{ void print(String name); } ``` 一个类实现 一个接口,如果这个接口继承了另一个接口,那么这个类除了实现这个接口的所有方法以外,还要实现被继承的那个接口的所有方法: ```cpp public class Demo10 implements Demo9 { public static void main(String[] args) { } @Override public void say() { // TODO Auto-generated method stub } @Override public int add() { // TODO Auto-generated method stub return 0; } @Override public void print(String name) { // TODO Auto-generated method stub } } ``` #### 二、抽象类 在面向对象的概念中,所有的对象都是通过类来描绘的,但是反过来,并不是所有的类都是用来描绘对象的,如果一个类中没有包含足够的信息来描绘一个具体的对象,这样的类就是抽象类。 抽象类除了不能实例化对象之外,类的其它功能依然存在,成员变量、成员方法和构造方法的访问方式和普通类一样。具有抽象方法的类一定为抽象类。 由于抽象类不能实例化对象,所以抽象类必须被继承,才能被使用。也是因为这个原因,通常在设计阶段决定要不要设计抽象类。 父类包含了子类集合的常见的方法,但是由于父类本身是抽象的,所以不能使用这些方法。 在Java中抽象类表示的是一种继承关系,一个类只能继承一个抽象类,而一个类却可以实现多个接口。 抽象类用来描述一种类型应该具备的基本特征与功能, 具体如何去完成这些行为由子类通过方法重写来完成,这点与接口很像,所以它们会被作为一类的面试题进行考察如: 猫科均会吼叫,但属于猫科的猫与老虎、豹子等它们吼叫的声音确实不同。所以猫科这就是一个类,它只规定了猫科这类的动物有吼叫功能,但并不明确吼叫的细节,吼叫的细节的内容应该由猫与老虎这样的猫科子类重写吼叫的方法具体实现。 即抽象方法指只有功能声明,没有功能主体实现的方法,与接口中的方法类似,但是抽象方法中除了可以有抽象方法还可以有具体的方法。 抽象类的实例: ```cpp public abstract class Demo11 { private String name; private String address; private int number; public Demo11(String name, String address, int number) { System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; } public double computePay() { System.out.println("Inside Employee computePay"); return 0.0; } public void mailCheck() { System.out.println("Mailing a check to " + this.name + " " + this.address); } public String toString() { return name + " " + address + " " + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } } ``` 可以看到尽管该类是抽象类,但是它仍然有 3 个成员变量,7 个成员方法和 1 个构造方法。但是如果想实例化该类,则会报错:提示不能实例化Demo11 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200520180905402.png) ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200520181024117.png) 所以抽象类只能通过被继承: ```cpp public class Demo12 extends Demo11 { private double salary; //Annual salary public Demo12(String name, String address, int number, double salary) { super(name, address, number); setSalary(salary); } public void mailCheck() { System.out.println("Within mailCheck of Salary class "); System.out.println("Mailing check to " + getName() + " with salary " + salary); } public double getSalary() { return salary; } public void setSalary(double newSalary) { if(newSalary >= 0.0) { salary = newSalary; } } public double computePay() { System.out.println("Computing salary pay for " + getName()); return salary/52; } } ``` ```cpp package Demo1; public class Demo10 { public static void main(String[] args) { Demo12 demo12 = new Demo12("张三", "北京", 3, 3600.00); Demo11 demo11 = new Demo12("李四", "上海", 2, 2400.00); System.out.println("Call mailCheck using Salary reference --"); demo12.mailCheck(); System.out.println("\n Call mailCheck using Employee reference--"); demo12.mailCheck(); } } ``` ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200520181605164.png) 所以尽管不能实例化一个抽象类,但是可以实例化一个继承了抽象类的子类,然后将抽象类的引用指向子类的对象。 如果一个类中它拥有抽象方法,那么这个类就必须是抽象类,抽象类可以没有抽象方法,但是如果有抽象方法的类,必须被申明为抽象类。 ```cpp public abstract class Demo11 { private String name; private String address; private int number; //抽象方法 public abstract double computePay(); } ``` 如果一个抽象类中有抽象方法,那么任何继承它的子类都必须重写父类的抽象方法,或者子类也可以声明自身为抽象类。但是最终,必须有子类实现该抽象方法,否则,从最初的父类到最终的子类都不能用来实例化对象,那么就没有任何的意义了。 另外构造方法,类方法(用 static 修饰的方法)不能声明为抽象方法。 抽象类可实现接口,并且可以不实现接口中的方法,但是继承抽象类的实体类必须实现接口中的方法。 ```cpp public abstract class Demo11 implements Demo9{ private String name; private String address; private int number; public Demo11(String name, String address, int number) { System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; } public double computePay() { System.out.println("Inside Employee computePay"); return 0.0; } public void mailCheck() { System.out.println("Mailing a check to " + this.name + " " + this.address); } public String toString() { return name + " " + address + " " + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } } ``` ![ ](https://img-blog.csdnimg.cn/20200520182642272.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) 另外抽象类也可以继承实体类: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200520182910987.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTUzOTQz,size_16,color_FFFFFF,t_70) ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200520182924166.png) 抽象类中也可以有静态的main方法。 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200520183059554.png) #### 3、答案 所以接口可以继承接口。抽象类可以实现(implements)接口,抽象类可以继承具体类。抽象类中可以有静态的main方法。 ### 19、char型变量中能不能存贮一个中文汉字?为什么? char型变量是用来存储Unicode编码的字符的,unicode编码字符集中包含了汉字,所以,char型变量中当然可以存储汉字啦。不过,如果某个特殊的汉字没有被包含在unicode编码字符集中,那么,这个char型变量中就不能存储这个特殊汉字。补充说明:unicode编码占用两个字节,所以,char类型的变量也是占用两个字节。 ### 20、用最有效率的方法算出2乘以8等于几? 2<< 3,(左移三位)因为将一个数左移n位,就相当于乘以了2的n次方,那么,一个数乘以8只要将其左移3位即可,而位运算cpu直接支持的,效率最高,所以,2乘以8等於几的最效率的方法是2<< 3。 ### 21、静态变量和实例变量的区别? ###### 在语法定义上的区别: 静态变量前要加static关键字,而实例变量前则不加。 ###### 在程序运行时的区别: 实例变量属于某个对象的属性,必须创建了实例对象,其中的实例变量才会被分配空间,才能使用这个实例变量。静态变量不属于某个实例对象,而是属于类,所以也称为类变量,只要程序加载了类的字节码,不用创建任何实例对象,静态变量就会被分配空间,静态变量就可以被使用了。总之,实例变量必须创建对象后才可以通过这个对象来使用,静态变量则可以直接使用类名来引用。 例如,对于下面的程序,无论创建多少个实例对象,永远都只分配了一个staticVar变量,并且每创建一个实例对象,这个staticVar就会加1;但是,每创建一个实例对象,就会分配一个instanceVar,即可能分配多个instanceVar,并且每个instanceVar的值都只自加了1次。 ```java int arr[][] ={{1,2,3},{4,5,6,7},{9}}; boolean found = false; for(int i=0;i<arr.length&&!found;i++)    {     for(intj=0;j<arr[i].length;j++){        System.out.println(“i=” + i + “,j=” + j);        if(arr[i][j] ==5) {            found =true;            break;       }    } } ``` ### 22、是否可以从一个static方法内部发出对非static方法的调用? 不可以。因为非static方法是要与对象关联在一起的,必须创建一个对象后,才可以在该对象上进行方法调用,而static方法调用时不需要创建对象,可以直接调用。也就是说,当一个static方法被调用时,可能还没有创建任何实例对象,如果从一个static方法中发出对非static方法的调用,那个非static方法是关联到哪个对象上的呢?这个逻辑无法成立,所以,一个static方法内部发出对非static方法的调 用。 ### 23、Integer与int的区别 int是java提供的8种原始数据类型之一。Java为每个原始类型提供了封装类,Integer是java为int提供的封装类。int的默认值为0,而Integer的默认值为null,即Integer可以区分出未赋值和值为0的区别,int则无法表达出未赋值的情况。 例如:要想表达出没有参加考试和考试成绩为0的区别,则只能使用Integer。在JSP开发中,Integer的默认为null,所以用el表达式在文本框中显示时,值为空白字符串,而int默认的默认值为0,所以用el表达式在文本框中显示时,结果为0,所以,int不适合作为web层的表单数据的类型。 在Hibernate中,如果将OID定义为Integer类型,那么Hibernate就可以根据其值是否为null而判断一个对象是否是临时的,如果将OID定义为了int类型,还需要在hbm映射文件中设置其unsaved-value属性为0。 另外,Integer提供了多个与整数相关的操作方法,例如,将一个字符串转换成整数,Integer中还定 义了表示整数的最大值和最小值的常量。 ### 24、Math.round(11.5)等於多少?Math.round(-11.5)等于多少? Math类中提供了三个与取整有关的方法:ceil、floor、round,这些方法的作用与它们的英文名称的含义相对应。 例如,ceil的英文意义是天花板,该方法就表示向上取整,Math.ceil(11.3)的结果为12,Math.ceil(-11.3)的结果是-11; floor的英文意义是地板,该方法就表示向下取整,Math.ceil(11.6)的结果为11,Math.ceil(-11.6)的结果是-12; 最难掌握的是round方法,它表示“四舍五入”,算法为Math.floor(x+0.5),即将原来的数字加上0.5后再向下取整,所以,Math.round(11.5)的结果为12,Math.round(-11.5)的结果为-11。 ### 25、Java中实现多态的机制是什么? Java中的多态靠的是父类或接口定义的引用变量可以指向子类或具体实现类的实例对象,而程序调用的方法在运行期才动态绑定,就是引用变量所指向的具体实例对象的方法,也就是内存里正在运行的那个对象的方法,而不是引用变量的类型中定义的方法。 ### 26、abstractclass和interface语法上有什么区别? 1、抽象类可以有构造方法,接口中不能有构造方法。 2、抽象类中可以有普通成员变量,接口中没有普通成员变量 3、抽象类中可以包含非抽象的普通方法,接口中的所有方法必须都是抽象的,不能有非抽象的普通方 法。 4、抽象类中的抽象方法的访问类型可以是public,protected和(默认类型,虽然eclipse下不报错,但应该也不行),但接口中的抽象方法只能是public类型的,并且默认即为public abstract类型。 5、抽象类中可以包含静态方法,接口中不能包含静态方法 6、抽象类和接口中都可以包含静态成员变量,抽象类中的静态成员变量的访问类型可以任意,但接口中定义的变量只能是public static final类型,并且默认即为public static final类型。 7、一个类可以实现多个接口,但只能继承一个抽象类。 ### 27、abstract的method是否可同时是static,是否可同时是native,是否可同时是synchronized? abstract的method不可以是static的,因为抽象的方法是要被子类实现的,而static与子类扯不上关系! native方法表示该方法要用另外一种依赖平台的编程语言实现的,不存在着被子类实现的问题,所以, 它也不能是抽象的,不能与abstract混用。例如,FileOutputSteam类要硬件打交道,底层的实现用的 是操作系统相关的api实现;例如,在windows用c语言实现的,所以,查看jdk的源代码,可以发现 FileOutputStream的open方法的定义如下: ``` private native void open(Stringname) throws FileNotFoundException; ``` 如果我们要用java调用别人写的c语言函数,我们是无法直接调用的,我们需要按照java的要求写一个c语言的函数,又我们的这个c语言函数去调用别人的c语言函数。由于我们的c语言函数是按java的要求来写的,我们这个c语言函数就可以与java对接上,java那边的对接方式就是定义出与我们这个c函数相对应的方法,java中对应的方法不需要写具体的代码,但需要在前面声明native。 关于synchronized与abstract合用的问题,个人从来没见到过这种情况,并且我觉得synchronized应该是作用在一个具体的方法上才有意义。而且,方法上的synchronized同步所使用的同步锁对象是this,而抽象方法上无法确定this是什么。 ### 28、内部类可以引用它的包含类的成员吗?有没有什么限制? 完全可以。如果不是静态内部类,那没有什么限制! 如果把静态嵌套类当作内部类的一种特例,那在这种情况下不可以访问外部类的普通成员变量,而只能访问外部类中的静态成员。 例如,下面的代码: ```java class Outer { static int x; static class Inner  {     voidtest()    {        syso(x);    }  } } ``` ### 29、如何去掉一个Vector集合中重复的元素? ```java Vector newVector = new Vector(); For (int i=0;i<vector.size();i++) { Object obj = vector.get(i);    if(!newVector.contains(obj);       newVector.add(obj); } ``` 还有一种简单的方式,利用了Set不允许重复元素: ```java HashSetset = new HashSet(vector); ``` ### 30、Collection和Collections的区别 Collection是集合类的上级接口,继承他的接口主要有Set和List。 Collections是针对集合类的一个帮助类,他提供一系列静态方法实现对各种集合的搜索、排序、线程 安全化等操作。 ### 31、Set里的元素是不能重复的,那么用什么方法来区分重复与否呢?是用==还是equals()?它们有何区别? Set里的元素是不能重复的,元素重复与否是使用equals()方法进行判断的。 ### 32、==和equal区别 ==是用来比较两个变量的值是否相等,也就是用于比较变量所对应的内存中所存储的数值是否相同,要比较两个基本类型的数据或两个引用变量是否相等,只能用==操作符。 而equals方法是用于比较两个独立对象的内容是否相同,就好比去比较两个人的长相是否相同,它比较的两个对象是独立的。 比如:两条new语句创建了两个对象,然后用a/b这两个变量分别指向了其中一个对象,这是两个不同的对象,它们的首地址是不同的,即a和b中存储的数值是不相同的,所以,表达式a==b将返回false,而这两个对象中的内容是相同的,所以,表达式a.equals(b)将返回true。 ==操作符专门用来比较两个变量的值是否相等,也就是用于比较变量所对应的内存中所存储的数值是否相同,要比较两个基本类型的数据或两个引用变量是否相等,只能用==操作符。 如果一个变量指向的数据是对象类型的,那么,这时候涉及了两块内存,对象本身占用一块内存(堆内存),变量也占用一块内存,例如Objet obj = new Object();变量obj是一个内存,new Object()是另一个内存,此时,变量obj所对应的内存中存储的数值就是对象占用的那块内存的首地址。对于指向对象类型的变量,如果要比较两个变量是否指向同一个对象,即要看这两个变量所对应的内存中的数值是否相等,这时候就需要用==操作符进行比较。 equals方法是用于比较两个独立对象的内容是否相同,就好比去比较两个人的长相是否相同,它比较的两个对象是独立的。例如,对于下面的代码: ``` String a=new String("foo"); String b=new String("foo"); ``` 两条new语句创建了两个对象,然后用a,b这两个变量分别指向了其中一个对象,这是两个不同的对象,它们的首地址是不同的,即a和b中存储的数值是不相同的,所以,表达式a==b将返回false,而这两个对象中的内容是相同的,所以,表达式a.equals(b)将返回true。 在实际开发中,我们经常要比较传递进行来的字符串内容是否等,例如,String input = …;input.equals(“quit”),许多人稍不注意就使用==进行比较了,这是错误的,随便从网上找几个项目实战的教学视频看看,里面就有大量这样的错误。记住,字符串的比较基本上都是使用equals方法。 如果一个类没有自己定义equals方法,那么它将继承Object类的equals方法,Object类的equals方法的实现代码如下: ``` boolean equals(Object o){ return this==o; } ``` 这说明,如果一个类没有自己定义equals方法,它默认的equals方法(从Object 类继承的)就是使用==操作符,也是在比较两个变量指向的对象是否是同一对象,这时候使用equals和使用==会得到同样的结果,如果比较的是两个独立的对象则总返回false。如果你编写的类希望能够比较该类创建的两个实例对象的内容是否相同,那么你必须覆盖equals方法,由你自己写代码来决定在什么情况即可认为两个对象的内容是相同的。 ### 33、集合类都有哪些?主要方法? 最常用的集合类是 List 和 Map。 List的具体实现包括 ArrayList和 Vector,它们是可变大小的列表,比较适合构建、存储和操作任何类型对象的元素列表。 List适用于按数值索引访问元素的情形。 Map 提供了一个更通用的元素存储方法。 Map集合类用于存储元素对(称作"键"和"值"),其中每个键映射到一个值。它们都有增删改查的方法。 对于set,大概的方法是add,remove, contains等 对于map,大概的方法就是put,remove,contains等 List类会有get(int index)这样的方法,因为它可以按顺序取元素,而set类中没有get(int index)这样的方法。List和set都可以迭代出所有元素,迭代时先要得到一个iterator对象,所以,set和list类都有一个iterator方法,用于返回那个iterator对象。map可以返回三个集合,一个是返回所有的key的集合,另外一个返回的是所有value的集合,再一个返回的key和value组合成的EntrySet对象的集合,map也有 get方法,参数是key,返回值是key对应的value,这个自由发挥,也不是考记方法的能力,这些编程过程中会有提示,结合他们三者的不同说一下用法就行。 ### 34、String s = new String("xyz");创建了几个StringObject?是否可以继承String类? 两个或一个都有可能,”xyz”对应一个对象,这个对象放在字符串常量缓冲区,常量”xyz”不管出现多少遍,都是缓冲区中的那一个。NewString每写一遍,就创建一个新的对象,它使用常量”xyz”对象的内容来创建出一个新String对象。如果以前就用过’xyz’,那么这里就不会创建”xyz”了,直接从缓冲区拿,这时创建了一个StringObject;但如果以前没有用过"xyz",那么此时就会创建一个对象并放入缓冲区,这种情况它创建两个对象。至于String类是否继承,答案是否定的,因为String默认final修饰,是不可继承的。 ### 35、String和StringBuffer的区别 JAVA平台提供了两个类:String和StringBuffer,它们可以储存和操作字符串,即包含多个字符的字符数据。这个String类提供了数值不可改变的字符串。而这个StringBuffer类提供的字符串可以进行修改。当你知道字符数据要改变的时候你就可以使用StringBuffer。典型地,你可以使用StringBuffers来动态构造字符数据。 ### 36、下面这条语句一共创建了多少个对象:Strings="a"+"b"+"c"+"d"; 对于如下代码: ```java String s1 = "a"; String s2 = s1 + "b"; String s3 = "a" + "b"; System.out.println(s2 == "ab"); System.out.println(s3 == "ab"); ``` 第一条语句打印的结果为false,第二条语句打印的结果为true,这说明javac编译可以对字符串常量直接相加的表达式进行优化,不必要等到运行期再去进行加法运算处理,而是在编译时去掉其中的加号,直接将其编译成一个这些常量相连的结果。题目中的第一行代码被编译器在编译时优化后,相当于直接定义了一个”abcd”的字符串,所以,上面的代码应该只创建了一个String对象。 对于如下代码: ``` String s ="a" + "b" +"c" + "d"; System.out.println(s== "abcd"); ``` 最终打印的结果应该为true。 ### 37、try {}里有一个return语句,那么紧跟在这个try后的finally{}里的code会不会被执行,什么时候被执行,在return前还是后? 我们知道finally{}中的语句是一定会执行的,那么这个可能正常脱口而出就是return之前,return之 后可能就出了这个方法了,鬼知道跑哪里去了,但更准确的应该是在return中间执行,请看下面程序代 码的运行结果: ``` public classTest {   public static void main(String[]args) {    System.out.println(newTest().test());;  }   static int test()  {    intx = 1;    try    {      returnx;    }    finally    {      ++x;    }  } } ``` ---------执行结果 --------- 1 运行结果是1,为什么呢?主函数调用子函数并得到结果的过程,好比主函数准备一个空罐子,当子函 数要返回结果时,先把结果放在罐子里,然后再将程序逻辑返回到主函数。所谓返回,就是子函数说, 我不运行了,你主函数继续运行吧,这没什么结果可言,结果是在说这话之前放进罐子里的。 ### 38、final, finally, finalize的区别。 final 用于声明属性,方法和类,分别表示属性不可变,方法不可覆盖,类不可继承。内部类要访问局部变量,局部变量必须定义成final类型。 finally是异常处理语句结构的一部分,表示总是执行。 finalize是Object类的一个方法,在垃圾收集器执行的时候会调用被回收对象的此方法,可以覆盖此方法提供垃圾收集时的其他资源回收,例如关闭文件等。但是JVM不保证此方法总被调用 ### 39、运行时异常与一般异常有何异同? 异常表示程序运行过程中可能出现的非正常状态,运行时异常表示虚拟机的通常操作中可能遇到的异常,是一种常见运行错误。java编译器要求方法必须声明抛出可能发生的非运行时异常,但是并不要求必须声明抛出未被捕获的运行时异常。 ### 40、error和exception有什么区别? error 表示恢复不是不可能但很困难的情况下的一种严重问题。比如说内存溢出。不可能指望程序能处理这样的情况。exception表示一种设计或实现问题。也就是说,它表示如果程序运行正常,从不会发生的情况。 ### 41、简单说说Java中的异常处理机制的简单原理和应用。 异常是指java程序运行时(非编译)所发生的非正常情况或错误,与现实生活中的事件很相似,现实生活中的事件可以包含事件发生的时间、地点、人物、情节等信息,可以用一个对象来表示,Java使用面向对象的方式来处理异常,它把程序中发生的每个异常也都分别封装到一个对象来表示的,该对象中包含有异常的信息。 Java对异常进行了分类,不同类型的异常分别用不同的Java类表示,所有异常的根类为 java.lang.Throwable,Throwable下面又派生了两个子类: Error和Exception,Error表示应用程序本身无法克服和恢复的一种严重问题,程序只有奔溃了,例如,说内存溢出和线程死锁等系统问题。 Exception表示程序还能够克服和恢复的问题,其中又分为系统异常和普通异常:系统异常是软件本身缺陷所导致的问题,也就是软件开发人员考虑不周所导致的问题,软件使用者无法克服和恢复这种问题,但在这种问题下还可以让软件系统继续运行或者让软件挂掉,例如,数组脚本越界(ArrayIndexOutOfBoundsException),空指针异常(NullPointerException)、类转换异常 (ClassCastException); 普通异常是运行环境的变化或异常所导致的问题,是用户能够克服的问题,例如,网络断线,硬盘空间不够,发生这样的异常后,程序不应该死掉。 java为系统异常和普通异常提供了不同的解决方案,编译器强制普通异常必须try..catch处理或用throws声明继续抛给上层调用方法处理,所以普通异常也称为checked异常,而系统异常可以处理也可以不处理,所以,编译器不强制用try..catch处理或用throws声明,所以系统异常也称为unchecked异常。 ### 42、Java 中堆和栈有什么区别? JVM 中堆和栈属于不同的内存区域,使用目的也不同。栈常用于保存方法帧和局部变量,而对象总是在堆上分配。栈通常都比堆小,也不会在多个线程之间共享,而堆被整个 JVM 的所有线程共享。 栈:在函数中定义的一些基本类型的变量和对象的引用变量都是在函数的栈内存中分配,当在一段代码块定义一个变量时,Java 就在栈中为这个变量分配内存空间,当超过变量的作用域后,Java 会自动释放掉为该变量分配的内存空间,该内存空间可以立即被另作它用。 堆:堆内存用来存放由 new 创建的对象和数组,在堆中分配的内存,由 Java 虚拟机的自动垃圾回收器来管理。在堆中产生了一个数组或者对象之后,还可以在栈中定义一个特殊的变量,让栈中的这个变量的取值等于数组或对象在堆内存中的首地址,栈中的这个变量就成了数组或对象的引用变量,以后就可以在程序中使用栈中的引用变量来访问堆中的数组或者对象,引用变量就相当于是为数组或者对象起 的一个名称。 ### 43、能将 int 强制转换为 byte 类型的变量吗?如果该值大于 byte类型的范围,将会出现什么现象? 我们可以做强制转换,但是 Java 中 int 是 32 位的,而 byte 是 8 位的,所以,如果强制转化,int 类型的高 24 位将会被丢弃,因为byte 类型的范围是从 -128 到 128。这里笔误:-128到127 ### 44、**Redis常用的五种数据类型** **1.String(字符串)** String是简单的 key-value 键值对,value 不仅可以是 String,也可以是数字。它是Redis最基本的数据类型,一个redis中字符串value最多可以是512M。 **2.Hash(哈希)** Redis hash 是一个键值对集合,对应Value内部实际就是一个HashMap,Hash特别适合用于存储对象。 **3.List(列表)** Redis 列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素导列表的头部(左边)或者尾部(右边)。 底层实现为一个双向链表,即可以支持反向查找和遍历,更方便操作,不过带来了部分额外的内存开销,Redis内部的很多实现,包括发送缓冲队列等也都是用的这个数据结构。 **4.Set(集合)** Redis的Set是String类型的无序集合,它的内部实现是一个 value永远为null的HashMap,实际就是通过计算hash的方式来快速排重的,这也是set能提供判断一个成员是否在集合内的原因。 **5.zset(有序集合)** Redis zset 和 set 一样也是String类型元素的集合,且不允许重复的成员,不同的是每个元素都会关联一个double类型的分数,用来排序。 ### 45、**接口有什么用** 1、通过接口可以实现不相关类的相同行为,而不需要了解对象所对应的类。 2、通过接口可以指明多个类需要实现的方法。 3、通过接口可以了解对象的交互界面,而不需了解对象所对应的类。 另:Java是单继承,接口可以使其实现多继承的功能。 ### 46、Java中堆内存和栈内存详解 Java把内存分成两种,一种叫做栈内存,一种叫做堆内存。 在函数中定义的一些基本类型的变量和对象的引用变量都是在函数的栈内存中分配。**当在一段代码块中定义一个变量时,java就在栈中为这个变量分配内存空间,当超过变量的作用域后,java会自动释放掉为该变量分配的内存空间,该内存空间可以立刻被另作他用。** **堆内存用于存放由new创建的对象和数组。**在堆中分配的内存,由java虚拟机自动垃圾回收器来管理。在堆中产生了一个数组或者对象后,还可以在栈中定义一个特殊的变量,这个变量的取值等于数组或者对象在堆内存中的首地址,在栈中的这个特殊的变量就变成了数组或者对象的引用变量,以后就可以在程序中使用栈内存中的引用变量来访问堆中的数组或者对象,引用变量相当于为数组或者对象起的一个别名,或者代号。 引用变量是普通变量,定义时在栈中分配内存,引用变量在程序运行到作用域外释放。而数组&对象本身在堆中分配,即使程序运行到使用new产生数组和对象的语句所在地代码块之外,数组和对象本身占用的堆内存也不会被释放,**数组和对象在没有引用变量指向它的时候,才变成垃圾,不能再被使用,但是仍然占着内存,在随后的一个不确定的时间被垃圾回收器释放掉**。这个也是java比较占内存的主要原因,实际上,栈中的变量指向堆内存中的变量,这就是 Java 中的指针! **java中内存分配策略及堆和栈的比较**   **1 内存分配策略**   按照编译原理的观点,程序运行时的内存分配有三种策略,分别是静态的,栈式的,和堆式的.   静态存储分配是指在编译时就能确定每个数据目标在运行时刻的存储空间需求,因而在编译时就可以给他们分配固定的内存空间.这种分配策略要求程序代码中不允许有可变数据结构(比如可变数组)的存在,也不允许有嵌套或者递归的结构出现,因为它们都会导致编译程序无法计算准确的存储空间需求.   栈式存储分配也可称为动态存储分配,是由一个类似于堆栈的运行栈来实现的.和静态存储分配相反,在栈式存储方案中,程序对数据区的需求在编译时是完全未知的,只有到运行的时候才能够知道,但是规定在运行中进入一个程序模块时,必须知道该程序模块所需的数据区大小才能够为其分配内存.和我们在数据结构所熟知的栈一样,栈式存储分配按照先进后出的原则进行分配。   静态存储分配要求在编译时能知道所有变量的存储要求,栈式存储分配要求在过程的入口处必须知道所有的存储要求,而堆式存储分配则专门负责在编译时或运行时模块入口处都无法确定存储要求的数据结构的内存分配,比如可变长度串和对象实例.堆由大片的可利用块或空闲块组成,堆中的内存可以按照任意顺序分配和释放.   **2 堆和栈的比较**   上面的定义从编译原理的教材中总结而来,除静态存储分配之外,都显得很呆板和难以理解,下面撇开静态存储分配,集中比较堆和栈:   从堆和栈的功能和作用来通俗的比较,堆主要用来存放对象的,栈主要是用来执行程序的.而这种不同又主要是由于堆和栈的特点决定的:   在编程中,例如C/C++中,所有的方法调用都是通过栈来进行的,所有的局部变量,形式参数都是从栈中分配内存空间的。实际上也不是什么分配,只是从栈顶向上用就行,就好像工厂中的传送带(conveyor belt)一样,Stack Pointer会自动指引你到放东西的位置,你所要做的只是把东西放下来就行.退出函数的时候,修改栈指针就可以把栈中的内容销毁.这样的模式速度最快, 当然要用来运行程序了.需要注意的是,在分配的时候,比如为一个即将要调用的程序模块分配数据区时,应事先知道这个数据区的大小,也就说是虽然分配是在程序运行时进行的,但是分配的大小多少是确定的,不变的,而这个"大小多少"是在编译时确定的,不是在运行时.   堆是应用程序在运行的时候请求操作系统分配给自己内存,由于从操作系统管理的内存分配,所以在分配和销毁时都要占用时间,因此用堆的效率非常低.但是堆的优点在于,编译器不必知道要从堆里分配多少存储空间,也不必知道存储的数据要在堆里停留多长的时间,因此,用堆保存数据时会得到更大的灵活性。事实上,面向对象的多态性,堆内存分配是必不可少的,因为多态变量所需的存储空间只有在运行时创建了对象之后才能确定.在C++中,要求创建一个对象时,只需用 new命令编制相关的代码即可。执行这些代码时,会在堆里自动进行数据的保存.当然,为达到这种灵活性,必然会付出一定的代价:在堆里分配存储空间时会花掉更长的时间!这也正是导致我们刚才所说的效率低的原因,看来列宁同志说的好,人的优点往往也是人的缺点,人的缺点往往也是人的优点(晕~).   **3 JVM中的堆和栈**   JVM是基于堆栈的虚拟机.JVM为每个新创建的线程都分配一个堆栈.也就是说,对于一个Java程序来说,它的运行就是通过对堆栈的操作来完成的。堆栈以帧为单位保存线程的状态。JVM对堆栈只进行两种操作:以帧为单位的压栈和出栈操作。   我们知道,某个线程正在执行的方法称为此线程的当前方法.我们可能不知道,当前方法使用的帧称为当前帧。当线程激活一个Java方法,JVM就会在线程的 Java堆栈里新压入一个帧。这个帧自然成为了当前帧.在此方法执行期间,这个帧将用来保存参数,局部变量,中间计算过程和其他数据.这个帧在这里和编译原理中的活动纪录的概念是差不多的.   从Java的这种分配机制来看,堆栈又可以这样理解:堆栈(Stack)是操作系统在建立某个进程时或者线程(在支持多线程的操作系统中是线程)为这个线程建立的存储区域,该区域具有先进后出的特性。   每一个Java应用都唯一对应一个JVM实例,每一个实例唯一对应一个堆。应用程序在运行中所创建的所有类实例或数组都放在这个堆中,并由应用所有的线程共享.跟C/C++不同,Java中分配堆内存是自动初始化的。Java中所有对象的存储空间都是在堆中分配的,但是这个对象的引用却是在堆栈中分配,也就是说在建立一个对象时从两个地方都分配内存,在堆中分配的内存实际建立这个对象,而在堆栈中分配的内存只是一个指向这个堆对象的指针(引用)而已。   **4 Java 中的堆和栈**   Java把内存划分成两种:一种是栈内存,一种是堆内存。   在函数中定义的一些基本类型的变量和对象的引用变量都在函数的栈内存中分配。   当在一段代码块定义一个变量时,Java就在栈中为这个变量分配内存空间,当超过变量的作用域后,Java会自动释放掉为该变量所分配的内存空间,该内存空间可以立即被另作他用。   堆内存用来存放由new创建的对象和数组。   在堆中分配的内存,由Java虚拟机的自动垃圾回收器来管理。   在堆中产生了一个数组或对象后,还可以在栈中定义一个特殊的变量,让栈中这个变量的取值等于数组或对象在堆内存中的首地址,栈中的这个变量就成了数组或对象的引用变量。   引用变量就相当于是为数组或对象起的一个名称,以后就可以在程序中使用栈中的引用变量来访问堆中的数组或对象。   具体的说:   **栈与堆都是Java用来在Ram中存放数据的地方。与C++不同,Java自动管理栈和堆,程序员不能直接地设置栈或堆。**   Java的堆是一个运行时数据区,类的(对象从中分配空间。这些对象通过new、newarray、anewarray和multianewarray等指令建立,它们不需要程序代码来显式的释放。堆是由垃圾回收来负责的,堆的优势是可以动态地分配内存大小,生存期也不必事先告诉编译器,因为它是在运行时动态分配内存的,Java的垃圾收集器会自动收走这些不再使用的数据。但缺点是,由于要在运行时动态分配内存,存取速度较慢。   栈的优势是,存取速度比堆要快,仅次于寄存器,栈数据可以共享。但缺点是,存在栈中的数据大小与生存期必须是确定的,缺乏灵活性。栈中主要存放一些基本类型的变量(,int, short, long, byte, float, double, boolean, char)和对象句柄。   栈有一个很重要的特殊性,就是存在栈中的数据可以共享。假设我们同时定义:   int a = 3;   int b = 3;   编译器先处理int a = 3;首先它会在栈中创建一个变量为a的引用,然后查找栈中是否有3这个值,如果没找到,就将3存放进来,然后将a指向3。接着处理int b = 3;在创建完b的引用变量后,因为在栈中已经有3这个值,便将b直接指向3。这样,就出现了a与b同时均指向3的情况。这时,如果再令a=4;那么编译器会重新搜索栈中是否有4值,如果没有,则将4存放进来,并令a指向4;如果已经有了,则直接将a指向这个地址。因此a值的改变不会影响到b的值。要注意这种数据的共享与两个对象的引用同时指向一个对象的这种共享是不同的,因为这种情况a的修改并不会影响到b, 它是由编译器完成的,它有利于节省空间。而一个对象引用变量修改了这个对象的内部状态,会影响到另一个对象引用变量。 ### 47、**List和Set比较,各自的子类比较** **对比一:****Arraylist与LinkedList的比较** 1、ArrayList是实现了基于动态数组的数据结构,因为地址连续,一旦数据存储好了,查询操作效率会比较高(在内存里是连着放的)。 2、因为地址连续, ArrayList要移动数据,所以插入和删除操作效率比较低。 3、LinkedList基于链表的数据结构,地址是任意的,所以在开辟内存空间的时候不需要等一个连续的地址,对于新增和删除操作add和remove,LinedList比较占优势。 4、因为LinkedList要移动指针,所以查询操作性能比较低。 **适用场景分析:** 当需要对数据进行对此访问的情况下选用ArrayList,当需要对数据进行多次增加删除修改时采用LinkedList。 **对比二:****ArrayList与Vector的比较** 1、Vector的方法都是同步的,是线程安全的,而ArrayList的方法不是,由于线程的同步必然要影响性能。因此,ArrayList的性能比Vector好。 2、当Vector或ArrayList中的元素超过它的初始大小时,Vector会将它的容量翻倍,而ArrayList只增加50%的大小,这样。ArrayList就有利于节约内存空间。 3、大多数情况不使用Vector,因为性能不好,但是它支持线程的同步,即某一时刻只有一个线程能够写Vector,避免多线程同时写而引起的不一致性。 4、Vector可以设置增长因子,而ArrayList不可以。 **适用场景分析:** 1、Vector是线程同步的,所以它也是线程安全的,而ArrayList是线程异步的,是不安全的。如果不考虑到线程的安全因素,一般用ArrayList效率比较高。 2、如果集合中的元素的数目大于目前集合数组的长度时,在集合中使用数据量比较大的数据,用Vector有一定的优势。 **对比三:****HashSet与TreeSet的比较** 1.TreeSet 是二叉树实现的,Treeset中的数据是自动排好序的,不允许放入null值 。 2.HashSet 是哈希表实现的,HashSet中的数据是无序的,可以放入null,但只能放入一个null,两者中的值都不能重复,就如数据库中唯一约束 。 3.HashSet要求放入的对象必须实现HashCode()方法,放入的对象,是以hashcode码作为标识的,而具有相同内容的String对象,hashcode是一样,所以放入的内容不能重复。但是同一个类的对象可以放入不同的实例。 **适用场景分析:** HashSet是基于Hash算法实现的,其性能通常都优于TreeSet。我们通常都应该使用HashSet,在我们需要排序的功能时,我们才使用TreeSet。 ### 48、**HashMap和ConcurrentHashMap的区别** 1、HashMap不是线程安全的,而ConcurrentHashMap是线程安全的。 2、ConcurrentHashMap采用锁分段技术,将整个Hash桶进行了分段segment,也就是将这个大的数组分成了几个小的片段segment,而且每个小的片段segment上面都有锁存在,那么在插入元素的时候就需要先找到应该插入到哪一个片段segment,然后再在这个片段上面进行插入,而且这里还需要获取segment锁。 3、ConcurrentHashMap让锁的粒度更精细一些,并发性能更好。 ### 49、**HashTable和ConcurrentHashMap的区别** 它们都可以用于多线程的环境,但是当Hashtable的大小增加到一定的时候,性能会急剧下降,因为迭代时需要被锁定很长的时间。因为ConcurrentHashMap引入了分割(segmentation),不论它变得多么大,仅仅需要锁定map的某个部分,而其它的线程不需要等到迭代完成才能访问map。简而言之,在迭代的过程中,ConcurrentHashMap仅仅锁定map的某个部分,而Hashtable则会锁定整个map。 ### 50、**String,StringBuffer和StringBuilder的区别** 1、运行速度,或者说是执行速度,在这方面运行速度快慢为:StringBuilder > StringBuffer > String。 2、线程安全上,StringBuilder是线程不安全的,而StringBuffer是线程安全的。 **适用场景分析:** String:适用于少量的字符串操作的情况 StringBuilder:适用于单线程下在字符缓冲区进行大量操作的情况 StringBuffer:适用多线程下在字符缓冲区进行大量操作的情况 ### 51、**wait和sleep的区别** 1、sleep()方法是属于Thread类中的,而wait()方法,则是属于Object类中的。 2、sleep()方法导致了程序暂停执行指定的时间,让出cpu给其他线程,但是他的监控状态依然保持着,当指定的时间到了又会自动恢复运行状态。所以在调用sleep()方法的过程中,线程不会释放对象锁。 3、调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。 ### 52、**JVM的内存结构** 根据 JVM 规范,JVM 内存共分为虚拟机栈、堆、方法区、程序计数器、本地方法栈五个部分。 **1、Java虚拟机栈:** 线程私有;每个方法在执行的时候会创建一个栈帧,存储了局部变量表,操作数栈,动态连接,方法返回地址等;每个方法从调用到执行完毕,对应一个栈帧在虚拟机栈中的入栈和出栈。 **2、堆:** 线程共享;被所有线程共享的一块内存区域,在虚拟机启动时创建,用于存放对象实例。 **3、方法区:** 线程共享;被所有线程共享的一块内存区域;用于存储已被虚拟机加载的类信息,常量,静态变量等。 **4、程序计数器:** 线程私有;是当前线程所执行的字节码的行号指示器,每条线程都要有一个独立的程序计数器,这类内存也称为“线程私有”的内存。 **5、本地方法栈:** 线程私有;主要为虚拟机使用到的Native方法服务。 ### 53、**强引用,软引用和弱引用的区别** **强引用:** 只有这个引用被释放之后,对象才会被释放掉,只要引用存在,垃圾回收器永远不会回收,这是最常见的New出来的对象。 **软引用:** 内存溢出之前通过代码回收的引用。软引用主要用户实现类似缓存的功能,在内存足够的情况下直接通过软引用取值,无需从繁忙的真实来源查询数据,提升速度;当内存不足时,自动删除这部分缓存数据,从真正的来源查询这些数据。 **弱引用:** 第二次垃圾回收时回收的引用,短时间内通过弱引用取对应的数据,可以取到,当执行过第二次垃圾回收时,将返回null。弱引用主要用于监控对象是否已经被垃圾回收器标记为即将回收的垃圾,可以通过弱引用的isEnQueued方法返回对象是否被垃圾回收器标记。 ### 54、**数组在内存中如何分配** 1、简单的值类型的数组,每个数组成员是一个引用(指针),引用到栈上的空间(因为值类型变量的内存分配在栈上) 2、引用类型,类类型的数组,每个数组成员仍是一个引用(指针),引用到堆上的空间(因为类的实例的内存分配在堆上) ### 55、**java的多态表现在哪里** **简单的理解多态** 多态,简而言之就是同一个行为具有多个不同表现形式或形态的能力。比如说,有一杯水,我不知道它是温的、冰的还是烫的,但是我一摸我就知道了。我摸水杯这个动作,对于不同温度的水,就会得到不同的结果。这就是多态。 那么,java中是怎么体现多态呢?我们来直接看代码: ```java public class Water { public void showTem(){ System.out.println("我的温度是: 0度"); } } public class IceWater extends Water { public void showTem(){ System.out.println("我的温度是: 0度"); } } public class WarmWater extends Water { public void showTem(){ System.out.println("我的温度是: 40度"); } } public class HotWater extends Water { public void showTem(){ System.out.println("我的温度是: 100度"); } } public class TestWater{ public static void main(String[] args) { Water w = new WarmWater(); w.showTem(); w = new IceWater(); w.showTem(); w = new HotWater(); w.showTem(); } } ``` 运行结果: ```java 我的温度是: 40度 我的温度是: 0度 我的温度是: 100度 ``` 这段代码中最关键的就是这一句 ```java Water w = new WarmWater(); ``` 这句代码体现的就是向上转型。后面我会详细讲解这一知识点。 **多态的分类** 已经简单的认识了多态了,那么我们来看一下多态的分类。 多态一般分为两种:**重写式多态和重载式多态**。重写和重载这两个知识点前面的文章已经详细将结果了,这里就不多说了。 重载式多态,也叫编译时多态。也就是说这种多态再编译时已经确定好了。重载大家都知道,方法名相同而参数列表不同的一组方法就是重载。在调用这种重载的方法时,通过传入不同的参数最后得到不同的结果。 > 但是这里是有歧义的,有的人觉得不应该把重载也算作多态。因为很多人对多态的理解是:**程序中定义的引用变量所指向的具体类型和通过该引用变量发出的方法调用在编程时并不确定,而是在程序运行期间才确定,这种情况叫做多态。** 这个定义中描述的就是我们的第二种多态—重写式多态。并且,重载式多态并不是面向对象编程特有的,而多态却是面向对象三大特性之一(如果我说的不对,记得告诉我。。)。 > > 我觉得大家也没有必要在定义上去深究这些,我的理解是:**同一个行为具有多个不同表现形式或形态的能力**就是多态,所以我认为重载也是一种多态,如果你不同意这种观点,我也接受。 重写式多态,也叫运行时多态。这种多态通过动态绑定(dynamic binding)技术来实现,是指在执行期间判断所引用对象的实际类型,根据其实际的类型调用其相应的方法。也就是说,只有程序运行起来,你才知道调用的是哪个子类的方法。 这种多态通过函数的重写以及向上转型来实现,我们上面代码中的例子就是一个完整的重写式多态。我们接下来讲的所有多态都是重写式多态,因为它才是面向对象编程中真正的多态。 > 动态绑定技术涉及到jvm,暂时不讲(因为我也不懂,哈哈哈哈),感兴趣的可以自己去研究一下,我暂时还没有时间去研究jvm。。 **多态的条件** **继承**。在多态中必须存在有继承关系的子类和父类。 **重写**。子类对父类中某些方法进行重新定义,在调用这些方法时就会调用子类的方法。 **向上转型**。在多态中需要将子类的引用赋给父类对象,只有这样该引用才能够具备技能调用父类的方法和子类的方法。 继承也可以替换为实现接口。 继承和重写之前都说过了,接下来我们来看一下转型是什么。 向上转型与向下转型 **向上转型** 子类引用的对象转换为父类类型称为向上转型。通俗地说就是是将子类对象转为父类对象。此处父类对象可以是接口。 **转型过程中需要注意的问题** 向上转型时,子类单独定义的方法会丢失。比如上面Dog类中定义的run方法,当animal引用指向Dog类实例时是访问不到run方法的,animal.run()会报错。 子类引用不能指向父类对象。Cat c = (Cat)new Animal()这样是不行的。 **向上转型的好处** 减少重复代码,使代码变得简洁。 提高系统扩展性。 **向下转型** 与向上转型相对应的就是向下转型了。向下转型是把父类对象转为子类对象。(请注意!这里是有坑的。) **向下转型注意事项** 向下转型的前提是父类对象指向的是子类对象(也就是说,在向下转型之前,它得先向上转型) 向下转型只能转型为本类对象(猫是不能变成狗的)。 **总结** 1. 多态,简而言之就是同一个行为具有多个不同表现形式或形态的能力。 2. 多态的分类:运行时多态和编译时多态。 3. 运行时多态的前提:继承(实现),重写,向上转型 4. 向上转型与向下转型。 5. 继承链中对象方法的调用的优先级:this.show(O)、super.show(O)、this.show((super)O)、super.show((super)O)。 多态主要有两种表现形式:重载和重写 **重载:** 是发生在同一类中,具有相同的方法名,主要是看参数的个数,类型,顺序不同实现方法的重载的,返回值的类型可以不同。 **重写:** 是发生在两个类中(父类和子类),具有相同的方法名,主要看方法中参数,个数,类型必须相同,返回值的类型必须相同。 ### 56、**BIO、NIO和AIO的区别** Java BIO : 同步并阻塞,服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销,当然可以通过线程池机制改善。 Java NIO : 同步非阻塞,服务器实现模式为一个请求一个线程,即客户端发送的连接请求都会注册到多路复用器上,多路复用器轮询到连接有I/O请求时才启动一个线程进行处理。 Java AIO 异步非阻塞,服务器实现模式为一个有效请求一个线程,客户端的I/O请求都是由OS先完成了再通知服务器应用去启动线程进行处理。 NIO比BIO的改善之处是把一些无效的连接挡在了启动线程之前,减少了这部分资源的浪费(因为我们都知道每创建一个线程,就要为这个线程分配一定的内存空间) AIO比NIO的进一步改善之处是将一些暂时可能无效的请求挡在了启动线程之前,比如在NIO的处理方式中,当一个请求来的话,开启线程进行处理,但这个请求所需要的资源还没有就绪,此时必须等待后端的应用资源,这时线程就被阻塞了。 **适用场景分析:** BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中,JDK1.4以前的唯一选择,但程序直观简单易理解,如之前在Apache中使用。 NIO方式适用于连接数目多且连接比较短(轻操作)的架构,比如聊天服务器,并发局限于应用中,编程比较复杂,JDK1.4开始支持,如在 Nginx,Netty中使用。 AIO方式使用于连接数目多且连接比较长(重操作)的架构,比如相册服务器,充分调用OS参与并发操作,编程比较复杂,JDK7开始支持,在成长中,Netty曾经使用过,后来放弃。 ### 57、**java中常说的堆和栈,分别是什么数据结构;另外,为什么要分为堆和栈来存储数据** 栈是一种具有后进先出性质的数据结构,也就是说后存放的先取,先存放的后取。 堆是一种经过排序的树形数据结构,每个结点都有一个值。通常我们所说的堆的数据结构,是指二叉堆。堆的特点是根结点的值最小(或最大),且根结点的两个子树也是一个堆。由于堆的这个特性,常用来实现优先队列,堆的存取是随意的。 **为什么要划分堆和栈** 1、从软件设计的角度看,栈代表了处理逻辑,而堆代表了数据。这样分开,使得处理逻辑更为清晰。 2、堆与栈的分离,使得堆中的内容可以被多个栈共享。一方面这种共享提供了一种有效的数据交互方式(如:共享内存),另一方面,堆中的共享常量和缓存可以被所有栈访问,节省了空间。 3、栈因为运行时的需要,比如保存系统运行的上下文,需要进行地址段的划分。由于栈只能向上增长,因此就会限制住栈存储内容的能力。而堆不同,堆中的对象是可以根据需要动态增长的,因此栈和堆的拆分,使得动态增长成为可能,相应栈中只需记录堆中的一个地址即可。 4、体现了Java面向对象这一核心特点 ### 58、**为什么要用线程池** **什么是线程池** 线程池是指在初始化一个多线程应用程序过程中创建一个线程集合,然后在需要执行新的任务时重用这些线程而不是新建一个线程。 **使用线程池的好处** 1、线程池改进了一个应用程序的响应时间。由于线程池中的线程已经准备好且等待被分配任务,应用程序可以直接拿来使用而不用新建一个线程。 2、线程池节省了CLR 为每个短生存周期任务创建一个完整的线程的开销并可以在任务完成后回收资源。 3、线程池根据当前在系统中运行的进程来优化线程时间片。 4、线程池允许我们开启多个任务而不用为每个线程设置属性。 5、线程池允许我们为正在执行的任务的程序参数传递一个包含状态信息的对象引用。 6、线程池可以用来解决处理一个特定请求最大线程数量限制问题。 ### 59、**悲观锁和乐观锁的区别,怎么实现** 悲观锁:一段执行逻辑加上悲观锁,不同线程同时执行时,只能有一个线程执行,其他的线程在入口处等待,直到锁被释放。 乐观锁:一段执行逻辑加上乐观锁,不同线程同时执行时,可以同时进入执行,在最后更新数据的时候要检查这些数据是否被其他线程修改了(版本和执行初是否相同),没有修改则进行更新,否则放弃本次操作。 悲观锁的实现: ```java //0.开始事务 begin;/begin work;/start transaction; (三者选一就可以) //1.查询出商品信息 select status from t_goods where id=1 for update; //2.根据商品信息生成订单 insert into t_orders (id,goods_id) values (null,1); //3.修改商品status为2 update t_goods set status=2; //4.提交事务 commit;/commit work; ``` 乐观锁的实现 ```java 1.查询出商品信息 select (status,status,version) from t_goods where id=#{id} 2.根据商品信息生成订单 3.修改商品status为2 update t_goods set status=2,version=version+1 where id=#{id} and version=#{version}; ``` ### 60、进程、线程 #### 进程 狭义:进程是正在运行的程序的实例。 广义:进程是一个具有一定独立功能的程序,关于某个数据集合的一次运行活动。 进程是操作系统动态执行的基本单元,在传统的操作系统中, 进程即是基本的分配单元,也是基本的执行单元。 #### 线程 线程是操作系统能够进行运算调试的最小单位。它被包含在进程中,是进程中的实际动作单位。一个线程指的是进程中的一个单一顺序的控制流,一个进程中可以并发多个线程,每个线程执行不同的任务。 1.1.3 多线程的优点 1. 可以把占据时间较长的任务放到后台去处理 2. 程序的运行速度加快 #### 使用多线程 ##### 继承Thread 步骤: 1. 创建一个类,这个类需要继承Thread 2. 重写Thread类的run方法(业务代码) 3. 实例化创建好的线程类 4. 调用实例化对象的start方法启动线程 ```java package chap1; public class Demo02 { public static void main(String[] args) { Thread t = new Demo02Thread(); t.start(); // 启动线程 System.out.println("运行了main方法"); } } class Demo02Thread extends Thread{ @Override public void run() { System.out.println("运行了run方法"); } } ``` 线程运行具有以下特点 1. 随机性 ```java package chap1; public class Demo03 { public static void main(String[] args) { Thread t = new Demo03Thread(); t.start(); try { for (int i = 0; i < 10; i++) { System.out.println("运行main方法"); Thread.sleep(100); } }catch (InterruptedException e){ e.printStackTrace(); } } } class Demo03Thread extends Thread{ @Override public void run() { try { for (int i = 0; i < 10; i++) { System.out.println("运行run方法"); Thread.sleep(100); } }catch (InterruptedException e){ e.printStackTrace(); } } } ``` 在多线程编程中,代码的执行结果与代码的执行顺序或调用顺序是无关的。线程是一个子任务,CPU以不确定的方式或者是以随机的时间来调用线程中的run方法。 如果直接调用线程对象的run方法,不是启动线程,而是由main主线程来调用run方法。 2. start的执行顺序与线程的启动顺序不一致 ```java package chap1; public class Demo04 { public static void main(String[] args) { Thread t1 = new Demo04Thread(1); Thread t2 = new Demo04Thread(2); Thread t3 = new Demo04Thread(3); Thread t4 = new Demo04Thread(4); Thread t5 = new Demo04Thread(5); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } } class Demo04Thread extends Thread{ private int val; public Demo04Thread(int val){ this.val = val; } @Override public void run() { System.out.println("val=" + val); } } ``` ##### 实现Runnable接口 步骤: 1. 创建一个类,这个类需要实现Runnable接口 2. 重写Runnable接口的run方法 3. 实例化创建的这个类 4. 实例化一个Thread对象,并把第3步创建的对象通过Thread的构造方法进行传递 5. 调用Thread对象的start方法 ```java package chap1; public class Demo05 { public static void main(String[] args) { Runnable r = new Demo05Thread(); Thread t = new Thread(r); t.start(); System.out.println("运行了main方法"); } } class Demo05Thread implements Runnable{ @Override public void run() { System.out.println("运行了run方法"); } } ``` 使用Thread继承的方式开发多线程应用程序是有局限的,Java是单继承,为了改变这种限抽,可以使用Runnable接口方式来实现多线程。 ##### Callable接口 Runnable是执行工作的独立任务,但是它不返回任何值。如果希望任务在完成的同时能够返回一个值,可以通过实现Callable接口。在JDK5.0中引入的Callable接口是一种具有类型参数的泛型,它的类型参数表示从方法call中返回的值的类型。 ``` import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class Demo05 { public static void main(String[] args) throws ExecutionException, InterruptedException { Callable<Integer> callable = new Demo05Callable(); FutureTask<Integer> task = new FutureTask<>(callable); Thread t1 = new Thread(task); t1.start(); System.out.println("线程返回的值是:" + task.get()); } } class Demo05Callable implements Callable<Integer>{ @Override public Integer call() throws Exception { System.out.println(Thread.currentThread().getName() + "调用了callable接口的实现类"); int val = (int)(Math.random() * 10); System.out.println("准备返回的值是:" + val); return val; } } ``` ### 61、在JAVA中如何跳出当前的多重嵌套循环? 在Java中,要想跳出多重循环,可以在外面的循环语句前定义一个标号,然后在里层循环体的代码中使用带有标号的break语句,即可跳出外层循环。比如: ```java for(int i=0;i<10;i++){  for(intj=0;j<10;j++){    System.out.println(“i=” + i + “,j=” + j);    if(j == 5) break ok;  } } ``` 另外还有一个标号的方式,它是让外层的循环条件表达式的结果可以受到里层循环体代码的控制,例如,要在二维数组中查找到某个数字。 ``` int arr[][] ={{1,2,3},{4,5,6,7},{9}}; boolean found = false; for(int i=0;i<arr.length&&!found;i++)    {     for(intj=0;j<arr[i].length;j++){        System.out.println(“i=” + i + “,j=” + j);        if(arr[i][j] ==5) {            found =true;            break;       }    } } ``` ### 62、short s1= 1; s1 = (s1+1是int类型,而等号左边的是short类型,所以需要强转)1 + 1;有什么错? short s1 = 1; s1 += 1;有什么错?(没有错) 对于short s1= 1; s1 = s1 + 1;由于s1+1运算时会自动提升表达式的类型,所以结果是int型,再赋值给short类型s1时,编译器将报告需要强制转换类型的错误。 对于short s1= 1; s1 += 1;由于 +=是java语言规定的运算符,java编译器会对它进行特殊处理,因此可以正确编译。 ### 63、char型变量中能不能存贮一个中文汉字?为什么? char型变量是用来存储Unicode编码的字符的,unicode编码字符集中包含了汉字,所以,char型变量中当然可以存储汉字啦。不过,如果某个特殊的汉字没有被包含在unicode编码字符集中,那么,这个char型变量中就不能存储这个特殊汉字。补充说明:unicode编码占用两个字节,所以,char类型的变量也是占用两个字节。 ### 64、使用final关键字修饰一个变量时,是引用不能变,还是引用的对象不能变? 使用final关键字修饰一个变量时,是指引用变量不能变,引用变量所指向的对象中的内容还是可以改变的。例如,对于如下语句: ``` finalStringBuffer a=new StringBuffer("immutable"); ``` 执行如下语句将报告编译期错误: ``` a=new StringBuffer(""); ``` 但是,执行如下语句则可以通过编译: ``` a.append(" broken!"); ``` 有人在定义方法的参数时,可能想采用如下形式来阻止方法内部修改传进来的参数对象: ``` public void method(final StringBuffer param){ } ``` 实际上,这是办不到的,在该方法内部仍然可以增加如下代码来修改参数对象: ``` param.append("a"); ``` ### 65、静态变量和实例变量的区别? 在语法定义上的区别:静态变量前要加static关键字,而实例变量前则不加。 在程序运行时的区别:实例变量属于某个对象的属性,必须创建了实例对象,其中的实例变量才会被分配空间,才能使用这个实例变量。静态变量不属于某个实例对象,而是属于类,所以也称为类变量,只要程序加载了类的字节码,不用创建任何实例对象,静态变量就会被分配空间,静态变量就可以被使用了。总之,实例变量必须创建对象后才可以通过这个对象来使用,静态变量则可以直接使用类名来引用。 例如,对于下面的程序,无论创建多少个实例对象,永远都只分配了一个staticVar变量,并且每创建一个实例对象,这个staticVar就会加1;但是,每创建一个实例对象,就会分配一个instanceVar,即可能分配多个instanceVar,并且每个instanceVar的值都只自加了1次。 ```java int arr[][] ={{1,2,3},{4,5,6,7},{9}}; boolean found = false; for(int i=0;i<arr.length&&!found;i++)    {     for(intj=0;j<arr[i].length;j++){        System.out.println(“i=” + i + “,j=” + j);        if(arr[i][j] ==5) {            found =true;            break;       }    } } ``` ### 66、是否可以从一个static方法内部发出对非static方法的调用? 不可以。 因为非static方法是要与对象关联在一起的,必须创建一个对象后,才可以在该对象上进行方法调用,而static方法调用时不需要创建对象,可以直接调用。也就是说,当一个static方法被调用时,可能还没有创建任何实例对象,如果从一个static方法中发出对非static方法的调用,那个非static方法是关联到哪个对象上的呢?这个逻辑无法成立,所以,一个static方法内部发出对非static方法的调用。 ### 67、List,Set, Map是否继承自Collection接口? List,Set是,Map不是! ### 68、List、Map、Set三个接口,存取元素时,各有什么特点? 首先,List与Set具有相似性,它们都是单列元素的集合,所以,它们有一个共同的父接口,叫Collection。 Set里面不允许有重复的元素,即不能有两个相等(注意,不是仅仅是相同)的对象,即假设Set集合中有了一个A对象,现在我要向Set集合再存入一个B对象,但B对象与A对象equals相等,则B对象存储不进去,所以,Set集合的add方法有一个boolean的返回值,当集合中没有某个元素,此时add方法可成功加入该元素时,则返回true,当集合含有与某个元素equals相等的元素时,此时add方法无法加入该元素,返回结果为false。Set取元素时,不能细说要取第几个,只能以Iterator接口取得所有的元素,再逐一遍历各个元素。 List表示有先后顺序的集合,注意,不是那种按年龄、按大小、按价格之类的排序。当我们多次调用add(Obje)方法时,每次加入的对象就像火车站买票有排队顺序一样,按先来后到的顺序排序。有时候,也可以插队,即调用add(intindex,Obj e)方法,就可以指定当前对象在集合中的存放位置。一个对象可以被反复存储进List中,每调用一次add方法,这个对象就被插入进集合中一次,其实,并不是把这个对象本身存储进了集合中,而是在集合中用一个索引变量指向这个对象,当这个对象被add多次时,即相当于集合中有多个索引指向了这个对象。List除了可以用Iterator接口取得所有的元素,再逐一遍历各个元素之外,还可以调get(index i)来明确说明取第几个。 Map与List和Set不同,它是双列的集合,其中有put方法,定义如下:put(obj key,obj value),每次存储时,要存储一对key/value,不能存储重复的key,这个重复的规则也是按equals比较相等。取则可以根据key获得相应的value,即get(Object key)返回值为key所对应的value。另外,也可以获得所有的key的结合,还可以获得所有的value的结合,还可以获得key和value组合成的Map.Entry对象的集合。 List以特定次序来持有元素,可有重复元素。Set无法拥有重复元素,内部序。Map保存key-value值,value可多值。 ### 69、ArrayList,Vector,LinkedList的存储性能和特性 ArrayList和Vector都是使用数组方式存储数据,此数组元素数大于实际存储的数据以便增加和插入元素,它们都允许直接按序号索引元素,但是插入元素要涉及数组元素移动等内存操作,所以索引数据快而插入数据慢,Vector由于使用了synchronized方法(线程安全),通常性能上较ArrayList差。而LinkedList使用双向链表实现存储,按序号索引数据需要进行前向或后向遍历,索引就变慢了,但是插入数据时只需要记录本项的前后项即可,所以插入速度较快。LinkedList也是线程不安全的,LinkedList提供了一些方法,使得LinkedList可以被当作堆栈和队列来使用。 ### 70、如何去掉一个Vector集合中重复的元素 ``` Vector newVector = new Vector(); For (int i=0;i<vector.size();i++) { Object obj = vector.get(i); if(!newVector.contains(obj); newVector.add(obj); } ``` 还有一种简单的方式,利用了Set不允许重复元素: ``` HashSetset = new HashSet(vector); ``` ### 71、集合类都有哪些?主要方法? 最常用的集合类是 List 和 Map。 List的具体实现包括 ArrayList和 Vector,它们是可变大小的列表,比较适合构建、存储和操作任何类型对象的元素列表。 List适用于按数值索引访问元素的情形。Map 提供了一个更通用的元素存储方法。 Map集合类用于存储元素对(称作"键"和"值"),其中每个键映射到一个值。它们都有增删改查的方法。 对于set,大概的方法是add,remove, contains等对于map,大概的方法就是put,remove,contains等List类会有get(int index)这样的方法,因为它可以按顺序取元素,而set类中没有get(int index)这样的方法。List和set都可以迭代出所有元素,迭代时先要得到一个iterator对象,所以,set和list类都有一个iterator方法,用于返回那个iterator对象。 map可以返回三个集合,一个是返回所有的key的集合,另外一个返回的是所有value的集合,再一个返回的key和value组合成的EntrySet对象的集合,map也有get方法,参数是key,返回值是key对应的value。 ### 72、a.hashCode() 有什么用?与 a.equals(b) 有什么关系? hashCode() 方法对应对象整型的 hash 值。它常用于基于 hash 的集合类,如 Hashtable、HashMap、LinkedHashMap等等。它与 equals() 方法关系特别紧密。根据 Java 规范,两个使用equal() 方法来判断相等的对象,必须具有相同的 hash code。 ### 73、字节流与字符流的区别 要把一段二进制数据数据逐一输出到某个设备中,或者从某个设备中逐一读取一段二进制数据,不管输入输出设备是什么,我们要用统一的方式来完成这些操作,用一种抽象的方式进行描述,这个抽象描述方式起名为IO流,对应的抽象类为OutputStream和InputStream,不同的实现类就代表不同的输入和输出设备,它们都是针对字节进行操作的。计算机中的一切最终都是二进制的字节形式存在。对于经常用到的中文字符,首先要得到其对应的字节,然后将字节写入到输出流。读取时,首先读到的是字节,可是我们要把它显示为字符,我们需要将字节转换成字符。由于这样的需求很广泛,Java专门提供了字符流包装类。底层设备永远只接受字节数据,有时候要写字符串到底层设备,需要将字符串转成字节再进行写入。字符流是字节流的包装,字符流则是直接接受字符串,它内部将串转成字节,再写入底层设备,这为我们向IO设备写入或读取字符串提供了一点点方便。字符向字节转换时,要注意编码的问题,因为字符串转成字节数组,其实是转成该字符的某种编码的字节形式,读取也是反之的道理 ### 74、什么是java序列化,如何实现java序列化?或者请解释Serializable接口的作用。 我们有时候将一个java对象变成字节流的形式传出去或者从一个字节流中恢复成一个java对象,例如,要将java对象存储到硬盘或者传送给网络上的其他计算机,这个过程我们可以自己写代码去把一个java对象变成某个格式的字节流再传输。但是,jre本身就提供了这种支持,我们可以调用OutputStream的writeObject方法来做,如果要让java帮我们做,要被传输的对象必须实现serializable接口,这样,javac编译时就会进行特殊处理,编译的类才可以被writeObject方法操作,这就是所谓的序列化。需要被序列化的类必须实现Serializable接口,该接口是一个mini接口,其中没有需要实现方法,implements Serializable只是为了标注该对象是可被序列化的。例如,在web开发中,如果对象被保存在了Session中,tomcat在重启时要把Session对象序列化到硬盘,这个对象就必须实现Serializable接口。如果对象要经过分布式系统进行网络传输,被传输的对象就必须实现Serializable接口。 ### 75、**一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制?** 可以有多个类,但只能有一个public的类,并且public的类名必须与文件名相一致。 ### 76、Java有没有goto? java中的保留字,现在没有在java中使用。 ### 77、switch语句能否作用在byte上,能否作用在long上,能否作用在String上? 在switch(expr1)中,expr1只能是一个整数表达式或者枚举常量(更大字体),整数表达式可以是int基本类型或Integer包装类型,由于,byte,short,char都可以隐含转换为int,所以,这些类型以及这些类型的包装类型也是可以的。显然,long和String类型都不符合switch的语法规定,并且不能被隐式转换成int类型,所以,它们不能作用于swtich语句中。 ### 78、静态变量和实例变量的区别? 在语法定义上的区别:静态变量前要加static关键字,而实例变量前则不加。 在程序运行时的区别:实例变量属于某个对象的属性,必须创建了实例对象,其中的实例变量才会被分配空间,才能使用这个实例变量。静态变量不属于某个实例对象,而是属于类,所以也称为类变量,只要程序加载了类的字节码,不用创建任何实例对象,静态变量就会被分配空间,静态变量就可以被使用了。总之,实例变量必须创建对象后才可以通过这个对象来使用,静态变量则可以直接使用类名来引用。 例如,对于下面的程序,无论创建多少个实例对象,永远都只分配了一个staticVar变量,并且每创建一个实例对象,这个staticVar就会加1;但是,每创建一个实例对象,就会分配一个instanceVar,即可能分配多个instanceVar,并且每个instanceVar的值都只自加了1次。 ``` public class VariantTest { public static int staticVar = 0; public int instanceVar = 0; public VariantTest() { staticVar++; instanceVar++; System.out.println(“staticVar=” + staticVar + ”,instanceVar=” + instanceVar); } } ``` ### 79、是否可以从一个static方法内部发出对非static方法的调用? 不可以。因为非static方法是要与对象关联在一起的,必须创建一个对象后,才可以在该对象上进行方法调用,而static方法调用时不需要创建对象,可以直接调用。也就是说,当一个static方法被调用时,可能还没有创建任何实例对象,如果从一个static方法中发出对非static方法的调用,那个非static方法是关联到哪个对象上的呢?这个逻辑无法成立,所以,一个static方法内部发出对非static方法的调用。 ### 80、Integer与int的区别 int是java提供的8种原始数据类型之一。Java为每个原始类型提供了封装类,Integer是java为int提供的封装类。int的默认值为0,而Integer的默认值为null,即Integer可以区分出未赋值和值为0的区别,int则无法表达出未赋值的情况,例如,要想表达出没有参加考试和考试成绩为0的区别,则只能使用Integer。在JSP开发中,Integer的默认为null,所以用el表达式在文本框中显示时,值为空白字符串,而int默认的默认值为0,所以用el表达式在文本框中显示时,结果为0,所以,int不适合作为web层的表单数据的类型。 在Hibernate中,如果将OID定义为Integer类型,那么Hibernate就可以根据其值是否为null而判断一个对象是否是临时的,如果将OID定义为了int类型,还需要在hbm映射文件中设置其unsaved-value属性为0。 另外,Integer提供了多个与整数相关的操作方法,例如,将一个字符串转换成整数,Integer中还定义了表示整数的最大值和最小值的常量。 ### 81、Overload和Override的区别。Overloaded的方法是否可以改变返回值的类型? Overload是重载的意思,Override是覆盖的意思,也就是重写。 重载Overload表示同一个类中可以有多个名称相同的方法,但这些方法的参数列表各不相同(即参数个数或类型不同)。 重写Override表示子类中的方法可以与父类中的某个方法的名称和参数完全相同,通过子类创建的实例对象调用这个方法时,将调用子类中的定义方法,这相当于把父类中定义的那个完全相同的方法给覆盖了,这也是面向对象编程的多态性的一种表现。子类覆盖父类的方法时,只能比父类抛出更少的异常,或者是抛出父类抛出的异常的子异常,因为子类可以解决父类的一些问题,不能比父类有更多的问题。子类方法的访问权限只能比父类的更大,不能更小。如果父类的方法是private类型,那么,子类则不存在覆盖的限制,相当于子类中增加了一个全新的方法。 至于Overloaded的方法是否可以改变返回值的类型这个问题,要看你倒底想问什么呢?这个题目很模糊。如果几个Overloaded的方法的参数列表不一样,它们的返回者类型当然也可以不一样。但我估计你想问的问题是:如果两个方法的参数列表完全一样,是否可以让它们的返回值不同来实现重载Overload。这是不行的,我们可以用反证法来说明这个问题,因为我们有时候调用一个方法时也可以不定义返回结果变量,即不要关心其返回结果,例如,我们调用map.remove(key)方法时,虽然remove方法有返回值,但是我们通常都不会定义接收返回结果的变量,这时候假设该类中有两个名称和参数列表完全相同的方法,仅仅是返回类型不同,java就无法确定编程者倒底是想调用哪个方法了,因为它无法通过返回结果类型来判断。 override可以翻译为覆盖,从字面就可以知道,它是覆盖了一个方法并且对其重写,以求达到不同的作用。对我们来说最熟悉的覆盖就是对接口方法的实现,在接口中一般只是对方法进行了声明,而我们在实现时,就需要实现接口声明的所有方法。除了这个典型的用法以外,我们在继承中也可能会在子类覆盖父类中的方法。在覆盖要注意以下的几点: 1、覆盖的方法的标志必须要和被覆盖的方法的标志完全匹配,才能达到覆盖的效果; 2、覆盖的方法的返回值必须和被覆盖的方法的返回一致; 3、覆盖的方法所抛出的异常必须和被覆盖方法的所抛出的异常一致,或者是其子类; 4、被覆盖的方法不能为private,否则在其子类中只是新定义了一个方法,并没有对其进行覆盖。 overload对我们来说可能比较熟悉,可以翻译为重载,它是指我们可以定义一些名称相同的方法,通过定义不同的输入参数来区分这些方法,然后再调用时,VM就会根据不同的参数样式,来选择合适的方法执行。在使用重载要注意以下的几点: 1、在使用重载时只能通过不同的参数样式。例如,不同的参数类型,不同的参数个数,不同的参数顺序(当然,同一方法内的几个参数类型必须不一样,例如可以是fun(int,float),但是不能为fun(int,int)); 2、不能通过访问权限、返回类型、抛出的异常进行重载; 3、方法的异常类型和数目不会对重载造成影响; 4、对于继承来说,如果某一方法在父类中是访问权限是priavte,那么就不能在子类对其进行重载,如果定义的话,也只是定义了一个新方法,而不会达到重载的效果。 ### 82、构造器Constructor是否可被override? 构造器Constructor不能被继承,因此不能重写Override,但可以被重载Overload。 ### 83、接口是否可继承接口? 抽象类是否可实现(implements)接口? 抽象类是否可继承具体类(concrete class)? 抽象类中是否可以有静态的main方法? 接口可以继承接口。抽象类可以实现(implements)接口,抽象类是否可继承具体类。抽象类中可以有静态的main方法。 只有记住抽象类与普通类的唯一区别就是不能创建实例对象和允许有abstract方法。 ### 84、面向对象的特征有哪些方面 计算机软件系统是现实生活中的业务在计算机中的映射,而现实生活中的业务其实就是一个个对象协作的过程。面向对象编程就是按现实业务一样的方式将程序代码按一个个对象进行组织和编写,让计算机系统能够识别和理解用对象方式组织和编写的程序代码,这样就可以把现实生活中的业务对象映射到计算机系统中。 面向对象的编程语言有封装、继承 、抽象、多态等4个主要的特征。 1、封装: 封装是保证软件部件具有优良的模块性的基础,封装的目标就是要实现软件部件的“高内聚、低耦合”,防止程序相互依赖性而带来的变动影响。在面向对象的编程语言中,对象是封装的最基本单位,面向对象的封装比传统语言的封装更为清晰、更为有力。面向对象的封装就是把描述一个对象的属性和行为的代码封装在一个“模块”中,也就是一个类中,属性用变量定义,行为用方法进行定义,方法可以直接访问同一个对象中的属性。通常情况下,**只要记住让变量和访问这个变量的方法放在一起,将一个类中的成员变量全部定义成私有的,只有这个类自己的方法才可以访问到这些成员变量,这就基本上实现对象的封装,就很容易找出要分配到这个类上的方法了,就基本上算是会面向对象的编程了。把握一个原则:把对同一事物进行操作的方法和相关的方法放在同一个类中,把方法和它操作的数据放在同一个类中。** 例如,人要在黑板上画圆,这一共涉及三个对象:人、黑板、圆,画圆的方法要分配给哪个对象呢?由于画圆需要使用到圆心和半径,圆心和半径显然是圆的属性,如果将它们在类中定义成了私有的成员变量,那么,画圆的方法必须分配给圆,它才能访问到圆心和半径这两个属性,人以后只是调用圆的画圆方法、表示给圆发给消息而已,画圆这个方法不应该分配在人这个对象上,**这就是面向对象的封装性,即将对象封装成一个高度自治和相对封闭的个体,对象状态(属性)由这个对象自己的行为(方法)来读取和改变。**一个更便于理解的例子就是,司机将火车刹住了,刹车的动作是分配给司机,还是分配给火车,显然,应该分配给火车,因为司机自身是不可能有那么大的力气将一个火车给停下来的,只有火车自己才能完成这一动作,火车需要调用内部的离合器和刹车片等多个器件协作才能完成刹车这个动作,司机刹车的过程只是给火车发了一个消息,通知火车要执行刹车动作而已。 2、抽象: 抽象就是找出一些事物的相似和共性之处,然后将这些事物归为一个类,这个类只考虑这些事物的相似和共性之处,并且会忽略与当前主题和目标无关的那些方面,将注意力集中在与当前目标有关的方面。例如,看到一只蚂蚁和大象,你能够想象出它们的相同之处,那就是抽象。抽象包括行为抽象和状态抽象两个方面。例如,定义一个Person类,如下: ``` class Person { String name; int age; } ``` 人本来是很复杂的事物,有很多方面,但因为当前系统只需要了解人的姓名和年龄,所以上面定义的类中只包含姓名和年龄这两个属性,这就是一种抽像,使用抽象可以避免考虑一些与目标无关的细节。我对抽象的理解就是不要用显微镜去看一个事物的所有方面,这样涉及的内容就太多了,而是要善于划分问题的边界,当前系统需要什么,就只考虑什么。 3、继承: 在定义和实现一个类的时候,可以在一个已经存在的类的基础之上来进行,把这个已经存在的类所定义的内容作为自己的内容,并可以加入若干新的内容,或修改原来的方法使之更适合特殊的需要,这就是继承。继承是子类自动共享父类数据和方法的机制,这是类之间的一种关系,提高了软件的可重用性和可扩展性。 4、多态: 多态是指程序中定义的引用变量所指向的具体类型和通过该引用变量发出的方法调用在编程时并不确定,而是在程序运行期间才确定,即一个引用变量倒底会指向哪个类的实例对象,该引用变量发出的方法调用到底是哪个类中实现的方法,必须在由程序运行期间才能决定。因为在程序运行时才确定具体的类,这样,不用修改源程序代码,就可以让引用变量绑定到各种不同的类实现上,从而导致该引用调用的具体方法随之改变,即不修改程序代码就可以改变程序运行时所绑定的具体代码,让程序可以选择多个运行状态,这就是多态性。多态性增强了软件的灵活性和扩展性。例如,下面代码中的UserDao是一个接口,它定义引用变量userDao指向的实例对象由daofactory.getDao()在执行的时候返回,有时候指向的是UserJdbcDao这个实现,有时候指向的是UserHibernateDao这个实现,这样,不用修改源代码,就可以改变userDao指向的具体类实现,从而导致userDao.insertUser()方法调用的具体代码也随之改变,即有时候调用的是UserJdbcDao的insertUser方法,有时候调用的是UserHibernateDao的insertUser方法: ``` UserDao userDao = daofactory.getDao(); userDao.insertUser(user); ``` 比喻:人吃饭,你看到的是左手,还是右手? ### 85、java中实现多态的机制是什么? 靠的是父类或接口定义的引用变量可以指向子类或具体实现类的实例对象,而程序调用的方法在运行期才动态绑定,就是引用变量所指向的具体实例对象的方法,也就是内存里正在运行的那个对象的方法,而不是引用变量的类型中定义的方法。 ### **86、abstract class和interface有什么区别?** 含有abstract修饰符的class即为抽象类,abstract 类不能创建的实例对象。含有abstract方法的类必须定义为abstract class,abstract class类中的方法不必是抽象的。abstract class类中定义抽象方法必须在具体(Concrete)子类中实现,所以,不能有抽象构造方法或抽象静态方法。如果的子类没有实现抽象父类中的所有抽象方法,那么子类也必须定义为abstract类型。 接口(interface)可以说成是抽象类的一种特例,接口中的所有方法都必须是抽象的。接口中的方法定义默认为public abstract类型,接口中的成员变量类型默认为public static final。 **下面比较一下两者的语法区别:** 1.抽象类可以有构造方法,接口中不能有构造方法。 2.抽象类中可以有普通成员变量,接口中没有普通成员变量 3.抽象类中可以包含非抽象的普通方法,接口中的所有方法必须都是抽象的,不能有非抽象的普通方法。 4.抽象类中的抽象方法的访问类型可以是public,protected和(默认类型,虽然 eclipse下不报错,但应该也不行),但接口中的抽象方法只能是public类型的,并且默认即为public abstract类型。 5.抽象类中可以包含静态方法,接口中不能包含静态方法 6.抽象类和接口中都可以包含静态成员变量,抽象类中的静态成员变量的访问类型可以任意,但接口中定义的变量只能是public static final类型,并且默认即为public static final类型。 7.一个类可以实现多个接口,但只能继承一个抽象类。 **下面接着再说说两者在应用上的区别:** 接口更多的是在系统架构设计方法发挥作用,主要用于定义模块之间的通信契约。而抽象类在代码实现方面发挥作用,可以实现代码的重用,例如,模板方法设计模式是抽象类的一个典型应用,假设某个项目的所有Servlet类都要用相同的方式进行权限判断、记录访问日志和处理异常,那么就可以定义一个抽象的基类,让所有的Servlet都继承这个抽象基类,在抽象基类的service方法中完成权限判断、记录访问日志和处理异常的代码,在各个子类中只是完成各自的业务逻辑代码,伪代码如下: ``` public abstract class BaseServlet extends HttpServlet { ​ public final void service(HttpServletRequest request, HttpServletResponse response) throws IOExcetion,ServletException ​ { ​ 记录访问日志 ​ 进行权限判断 if(具有权限) { ​ try ​ { ​ doService(request,response); } ​ catch(Excetpion e) ​ { ​ 记录异常信息 ​ } } ​ } ​ protected abstract void doService(HttpServletRequest request, HttpServletResponse response) throws IOExcetion,ServletException; //注意访问权限定义成protected,显得既专业,又严谨,因为它是专门给子类用的 } public class MyServlet1 extends BaseServlet { protected void doService(HttpServletRequest request, HttpServletResponse response) throws IOExcetion,ServletException ​ { ​ 本Servlet只处理的具体业务逻辑代码 ​ } } ``` 父类方法中间的某段代码不确定,留给子类干,就用模板方法设计模式。 备注:这道题的思路是先从总体解释抽象类和接口的基本概念,然后再比较两者的语法细节,最后再说两者的应用区别。比较两者语法细节区别的条理是:先从一个类中的构造方法、普通成员变量和方法(包括抽象方法),静态变量和方法,继承性等6个方面逐一去比较回答,接着从第三者继承的角度的回答,特别是最后用了一个典型的例子来展现自己深厚的技术功底。 ### **87、abstract的method是否可同时是static,是否可同时是native,是否可同时是synchronized?** abstract的method 不可以是static的,因为抽象的方法是要被子类实现的,而static与子类扯不上关系! native方法表示该方法要用另外一种依赖平台的编程语言实现的,不存在着被子类实现的问题,所以,它也不能是抽象的,不能与abstract混用。例如,FileOutputSteam类要硬件打交道,底层的实现用的是操作系统相关的api实现,例如,在windows用c语言实现的,所以,查看jdk 的源代码,可以发现FileOutputStream的open方法的定义如下: private native void open(String name) throws FileNotFoundException; 如果我们要用java调用别人写的c语言函数,我们是无法直接调用的,我们需要按照java的要求写一个c语言的函数,又我们的这个c语言函数去调用别人的c语言函数。由于我们的c语言函数是按java的要求来写的,我们这个c语言函数就可以与java对接上,java那边的对接方式就是定义出与我们这个c函数相对应的方法,java中对应的方法不需要写具体的代码,但需要在前面声明native。 关于synchronized与abstract合用的问题,我觉得也不行,因为在我几年的学习和开发中,从来没见到过这种情况,并且我觉得synchronized应该是作用在一个具体的方法上才有意义。而且,方法上的synchronized同步所使用的同步锁对象是this,而抽象方法上无法确定this是什么。 ### **88、什么是内部类?Static Nested Class 和 Inner Class的不同。** 内部类就是在一个类的内部定义的类,内部类中不能定义静态成员(静态成员不是对象的特性,只是为了找一个容身之处,所以需要放到一个类中而已,这么一点小事,你还要把它放到类内部的一个类中,过分了啊!提供内部类,不是为让你干这种事情,无聊,不让你干。我想可能是既然静态成员类似c语言的全局变量,而内部类通常是用于创建内部对象用的,所以,把“全局变量”放在内部类中就是毫无意义的事情,既然是毫无意义的事情,就应该被禁止),内部类可以直接访问外部类中的成员变量,内部类可以定义在外部类的方法外面,也可以定义在外部类的方法体中,如下所示: ``` public class Outer { ​ int out_x = 0; ​ public void method() ​ { ​ Inner1 inner1 = new Inner1(); ​ public class Inner2 //在方法体内部定义的内部类 ​ { ​ public method() ​ { ​ out_x = 3; ​ } ​ } ​ Inner2 inner2 = new Inner2(); ​ } ​ public class Inner1 //在方法体外面定义的内部类 ​ { ​ } ​ } ``` 在方法体外面定义的内部类的访问类型可以是public,protecte,默认的,private等4种类型,这就好像类中定义的成员变量有4种访问类型一样,它们决定这个内部类的定义对其他类是否可见;对于这种情况,我们也可以在外面创建内部类的实例对象,创建内部类的实例对象时,一定要先创建外部类的实例对象,然后用这个外部类的实例对象去创建内部类的实例对象,代码如下: Outer outer = new Outer(); Outer.Inner1 inner1 = outer.new Innner1(); 在方法内部定义的内部类前面不能有访问类型修饰符,就好像方法中定义的局部变量一样,但这种内部类的前面可以使用final或abstract修饰符。这种内部类对其他类是不可见的其他类无法引用这种内部类,但是这种内部类创建的实例对象可以传递给其他类访问。这种内部类必须是先定义,后使用,即内部类的定义代码必须出现在使用该类之前,这与方法中的局部变量必须先定义后使用的道理也是一样的。这种内部类可以访问方法体中的局部变量,但是,该局部变量前必须加final修饰符。 对于这些细节,只要在eclipse写代码试试,根据开发工具提示的各类错误信息就可以马上了解到。 在方法体内部还可以采用如下语法来创建一种匿名内部类,即定义某一接口或类的子类的同时,还创建了该子类的实例对象,无需为该子类定义名称: ``` public class Outer { ​ public void start() ​ { ​ new Thread( new Runable(){ ​ public void run(){}; } ).start(); ​ } } ``` 最后,在方法外部定义的内部类前面可以加上static关键字,从而成为Static Nested Class,它不再具有内部类的特性,所有,从狭义上讲,它不是内部类。Static Nested Class与普通类在运行时的行为和功能上没有什么区别,只是在编程引用时的语法上有一些差别,它可以定义成public、protected、默认的、private等多种类型,而普通类只能定义成public和默认的这两种类型。在外面引用Static Nested Class类的名称为“外部类名.内部类名”。在外面不需要创建外部类的实例对象,就可以直接创建Static Nested Class,例如,假设Inner是定义在Outer类中的Static Nested Class,那么可以使用如下语句创建Inner类: Outer.Inner inner = new Outer.Inner(); 由于static Nested Class不依赖于外部类的实例对象,所以,static Nested Class能访问外部类的非static成员变量。当在外部类中访问Static Nested Class时,可以直接使用Static Nested Class的名字,而不需要加上外部类的名字了,在Static Nested Class中也可以直接引用外部类的static的成员变量,不需要加上外部类的名字。 在静态方法中定义的内部类也是Static Nested Class,这时候不能在类前面加static关键字,静态方法中的Static Nested Class与普通方法中的内部类的应用方式很相似,它除了可以直接访问外部类中的static的成员变量,还可以访问静态方法中的局部变量,但是,该局部变量前必须加final修饰符。 备注:首先根据你的印象说出你对内部类的总体方面的特点:例如,在两个地方可以定义,可以访问外部类的成员变量,不能定义静态成员,这是大的特点。然后再说一些细节方面的知识,例如,几种定义方式的语法区别,静态内部类,以及匿名内部类。 ### **89、内部类可以引用它的包含类的成员吗?有没有什么限制?** 完全可以。如果不是静态内部类,那没有什么限制! 如果你把静态嵌套类当作内部类的一种特例,那在这种情况下不可以访问外部类的普通成员变量,而只能访问外部类中的静态成员,例如,下面的代码: ``` class Outer { ​ static int x; ​ static class Inner ​ { ​ void test() ​ { ​ syso(x); ​ } ​ } } ``` 答题时,也要能察言观色,揣摩提问者的心思,显然人家希望你说的是静态内部类不能访问外部类的成员,但你一上来就顶牛,这不好,要先顺着人家,让人家满意,然后再说特殊情况,让人家吃惊。 ### **90、Anonymous Inner Class (匿名内部类) 是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)?** 可以继承其他类或实现其他接口。不仅是可以,而是必须! ### **91、String是最基本的数据类型吗?** 基本数据类型包括byte、int、char、long、float、double、boolean和short。 java.lang.String类是final类型的,因此不可以继承这个类、不能修改这个类。为了提高效率节省空间,我们应该用StringBuffer类 ``` String s = "Hello";s = s + " world!"; ``` 这两行代码执行后,原始的String对象中的内容到底变了没有? 没有。因为String被设计成不可变(immutable)类,所以它的所有对象都是不可变对象。在这段代码中,s原先指向一个String对象,内容是 "Hello",然后我们对s进行了+操作,那么s所指向的那个对象是否发生了改变呢?答案是没有。这时,s不指向原来那个对象了,而指向了另一个 String对象,内容为"Hello world!",原来那个对象还存在于内存之中,只是s这个引用变量不再指向它了。 通过上面的说明,我们很容易导出另一个结论,如果经常对字符串进行各种各样的修改,或者说,不可预见的修改,那么使用String来代表字符串的话会引起很大的内存开销。因为 String对象建立之后不能再改变,所以对于每一个不同的字符串,都需要一个String对象来表示。这时,应该考虑使用StringBuffer类,它允许修改,而不是每个不同的字符串都要生成一个新的对象。并且,这两种类的对象转换十分容易。 同时,我们还可以知道,如果要使用内容相同的字符串,不必每次都new一个String。例如我们要在构造器中对一个名叫s的String引用变量进行初始化,把它设置为初始值,应当这样做: 而非 ``` public class Demo { private String s; ... public Demo { s = "Initial Value"; } ... } ``` 而非 后者每次都会调用构造器,生成新对象,性能低下且内存开销大,并且没有意义,因为String对象不可改变,所以对于内容相同的字符串,只要一个String对象来表示就可以了。也就说,多次调用上面的构造器创建多个对象,他们的String类型属性s都指向同一个对象。 上面的结论还基于这样一个事实:对于字符串常量,如果内容相同,Java认为它们代表同一个String对象。而用关键字new调用构造器,总是会创建一个新的对象,无论内容是否相同。 至于为什么要把String类设计成不可变类,是它的用途决定的。其实不只String,很多Java标准类库中的类都是不可变的。在开发一个系统的时候,我们有时候也需要设计不可变类,来传递一组相关的值,这也是面向对象思想的体现。不可变类有一些优点,比如因为它的对象是只读的,所以多线程并发访问也不会有任何问题。当然也有一些缺点,比如每个不同的状态都要一个对象来代表,可能会造成性能上的问题。所以Java标准类库还提供了一个可变版本,即 StringBuffer。 ``` s = new String("Initial Value"); ``` 后者每次都会调用构造器,生成新对象,性能低下且内存开销大,并且没有意义,因为String对象不可改变,所以对于内容相同的字符串,只要一个String对象来表示就可以了。也就说,多次调用上面的构造器创建多个对象,他们的String类型属性s都指向同一个对象。 上面的结论还基于这样一个事实:对于字符串常量,如果内容相同,Java认为它们代表同一个String对象。而用关键字new调用构造器,总是会创建一个新的对象,无论内容是否相同。 至于为什么要把String类设计成不可变类,是它的用途决定的。其实不只String,很多Java标准类库中的类都是不可变的。在开发一个系统的时候,我们有时候也需要设计不可变类,来传递一组相关的值,这也是面向对象思想的体现。不可变类有一些优点,比如因为它的对象是只读的,所以多线程并发访问也不会有任何问题。当然也有一些缺点,比如每个不同的状态都要一个对象来代表,可能会造成性能上的问题。所以Java标准类库还提供了一个可变版本,即 StringBuffer。 ### **92、String s = new String("xyz");创建了几个String Object? 二者之间有什么区别?** 两个或一个,”xyz”对应一个对象,这个对象放在字符串常量缓冲区,常量”xyz”不管出现多少遍,都是缓冲区中的那一个。New String每写一遍,就创建一个新的对象,它一句那个常量”xyz”对象的内容来创建出一个新String对象。如果以前就用过’xyz’,这句代表就不会创建”xyz”自己了,直接从缓冲区拿。 ### **93、String** **和StringBuffer的区别** JAVA平台提供了两个类:String和StringBuffer,它们可以储存和操作字符串,即包含多个字符的字符数据。String类表示内容不可改变的字符串。而StringBuffer类表示内容可以被修改的字符串。当你知道字符数据要改变的时候你就可以使用StringBuffer。典型地,你可以使用StringBuffers来动态构造字符数据。另外,String实现了equals方法,new String(“abc”).equals(new String(“abc”)的结果为true,而StringBuffer没有实现equals方法,所以,new StringBuffer(“abc”).equals(new StringBuffer(“abc”)的结果为false。 接着要举一个具体的例子来说明,我们要把1到100的所有数字拼起来,组成一个串。 ``` StringBuffer sbf = new StringBuffer(); for(int i=0;i<100;i++) { ​ sbf.append(i); } ``` 上面的代码效率很高,因为只创建了一个StringBuffer对象,而下面的代码效率很低,因为创建了101个对象。 ``` String str = new String(); for(int i=0;i<100;i++) { ​ str = str + i; } ``` 在讲两者区别时,应把循环的次数搞成10000,然后用endTime-beginTime来比较两者执行的时间差异,最后还要讲讲StringBuilder与StringBuffer的区别。 String覆盖了equals方法和hashCode方法,而StringBuffer没有覆盖equals方法和hashCode方法,所以,将StringBuffer对象存储进Java集合类中时会出现问题。 ### **94、StringBuffer与StringBuilder的区别** StringBuffer和StringBuilder类都表示内容可以被修改的字符串,StringBuilder是线程不安全的,运行效率高,如果一个字符串变量是在方法里面定义,这种情况只可能有一个线程访问它,不存在不安全的因素了,则用StringBuilder。如果要在类里面定义成员变量,并且这个类的实例对象会在多线程环境下使用,那么最好用StringBuffer。 ### **95、数组有没有length()这个方法? String有没有length()这个方法?** 数组没有length()这个方法,有length的属性。String有有length()这个方法。 ### **96、下面这条语句一共创建了多少个对象:****String s="a"+"b"+"c"+"****d****";** 答:对于如下代码: ``` String s2 = s1 + "b"; String s3 = "a" + "b"; System.out.println(s2 == "ab"); System.out.println(s3 == "ab"); ``` 第一条语句打印的结果为false,第二条语句打印的结果为true,这说明javac编译可以对字符串常量直接相加的表达式进行优化,不必要等到运行期去进行加法运算处理,而是在编译时去掉其中的加号,直接将其编译成一个这些常量相连的结果。 题目中的第一行代码被编译器在编译时优化后,相当于直接定义了一个”abcd”的字符串,所以,上面的代码应该只创建了一个String对象。写如下两行代码, ``` String s = "a" + "b" + "c" + "d"; System.out.println(s == "abcd"); ``` 最终打印的结果应该为true。 ### **97、try {}里有一个return语句,那么紧跟在这个try后的finally {}里的code会不会被执行,什么时候被执行,在return前还是后?** 也许你的答案是在return之前,但往更细地说,我的答案是在return中间执行,请看下面程序代码的运行结果: ``` public class Test { ​ /** ​ * **@param** args add by zxx ,Dec 9, 2008 ​ */ ​ **public** **static** **void** main(String[] args) { ​ // **TODO** Auto-generated method stub ​ System.*out*.println(**new** Test().test());; ​ } ​ static **int** test() ​ { ​ **int** x = 1; ​ **try** ​ { ​ **return** x; ​ } ​ **finally** ​ { ​ ++x; ​ } ​ } ​ } ``` ---------执行结果 --------- 1 运行结果是1,为什么呢?主函数调用子函数并得到结果的过程,好比主函数准备一个空罐子,当子函数要返回结果时,先把结果放在罐子里,然后再将程序逻辑返回到主函数。所谓返回,就是子函数说,我不运行了,你主函数继续运行吧,这没什么结果可言,结果是在说这话之前放进罐子里的。 ### **98、final, finally, finalize的区别。** final 用于声明属性,方法和类,分别表示属性不可变,方法不可覆盖,类不可继承。 内部类要访问局部变量,局部变量必须定义成final类型,例如,一段代码…… finally是异常处理语句结构的一部分,表示总是执行。 finalize是Object类的一个方法,在垃圾收集器执行的时候会调用被回收对象的此方法,可以覆盖此方法提供垃圾收集时的其他资源回收,例如关闭文件等。JVM不保证此方法总被调用 **99、运行时异常与一般异常有何异同?** 异常表示程序运行过程中可能出现的非正常状态,运行时异常表示虚拟机的通常操作中可能遇到的异常,是一种常见运行错误。java编译器要求方法必须声明抛出可能发生的非运行时异常,但是并不要求必须声明抛出未被捕获的运行时异常。 ### **100、error和exception有什么区别?** error 表示恢复不是不可能但很困难的情况下的一种严重问题。比如说内存溢出。不可能指望程序能处理这样的情况。 exception 表示一种设计或实现问题。也就是说,它表示如果程序运行正常,从不会发生的情况。 ### **101、请写出你最常见到的5个runtime exception。** 这道题主要考你的代码量到底多大,如果你长期写代码的,应该经常都看到过一些系统方面的异常,你不一定真要回答出5个具体的系统异常,但你要能够说出什么是系统异常,以及几个系统异常就可以了,当然,这些异常完全用其英文名称来写是最好的,如果实在写不出,那就用中文吧,有总比没有强! 所谓系统异常,就是…..,它们都是RuntimeException的子类,在jdk doc中查RuntimeException类,就可以看到其所有的子类列表,也就是看到了所有的系统异常。我比较有印象的系统异常有:NullPointerException、ArrayIndexOutOfBoundsException、ClassCastException。 ### **102、sleep() 和 wait() 有什么区别?** (网上的答案:sleep是线程类(Thread)的方法,导致此线程暂停执行指定时间,给执行机会给其他线程,但是监控状态依然保持,到时后会自动恢复。调用sleep不会释放对象锁。 wait是Object类的方法,对此对象调用wait方法导致本线程放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象发出notify方法(或notifyAll)后本线程才进入对象锁定池准备获得对象锁进入运行状态。) sleep就是正在执行的线程主动让出cpu,cpu去执行其他线程,在sleep指定的时间过后,cpu才会回到这个线程上继续往下执行,如果当前线程进入了同步锁,sleep方法并不会释放锁,即使当前线程使用sleep方法让出了cpu,但其他被同步锁挡住了的线程也无法得到执行。wait是指在一个已经进入了同步锁的线程内,让自己暂时让出同步锁,以便其他正在等待此锁的线程可以得到同步锁并运行,只有其他线程调用了notify方法(notify并不释放锁,只是告诉调用过wait方法的线程可以去参与获得锁的竞争了,但不是马上得到锁,因为锁还在别人手里,别人还没释放。如果notify方法后面的代码还有很多,需要这些代码执行完后才会释放锁,可以在notfiy方法后增加一个等待和一些代码,看看效果),调用wait方法的线程就会解除wait状态和程序可以再次得到锁后继续向下运行。对于wait的讲解一定要配合例子代码来说明,才显得自己真明白。 ### **103、同步和异步有何异同,在什么情况下分别使用他们?举例说明。** 如果数据将在线程间共享。例如正在写的数据以后可能被另一个线程读到,或者正在读的数据可能已经被另一个线程写过了,那么这些数据就是共享数据,必须进行同步存取。 当应用程序在对象上调用了一个需要花费很长时间来执行的方法,并且不希望让程序等待方法的返回时,就应该使用异步编程,在很多情况下采用异步途径往往更有效率。 ### **104、启动一个线程是用run()还是start()? .** 启动一个线程是调用start()方法,使线程就绪状态,以后可以被调度为运行状态,一个线程必须关联一些具体的执行代码,run()方法是该线程所关联的执行代码。 ### **105、当一个线程进入一个对象的一个synchronized方法后,其它线程是否可进入此对象的其它方法?** 分几种情况: 1.其他方法前是否加了synchronized关键字,如果没加,则能。 2.如果这个方法内部调用了wait,则可以进入其他synchronized方法。 3.如果其他个方法都加了synchronized关键字,并且内部没有调用wait,则不能。 4.如果其他方法是static,它用的同步锁是当前类的字节码,与非静态的方法不能同步,因为非静态的方法用的是this。 ### **106、简述synchronized和java.util.concurrent.locks.Lock的异同 ?** 主要相同点:Lock能完成synchronized所实现的所有功能 主要不同点:Lock有比synchronized更精确的线程语义和更好的性能。synchronized会自动释放锁,而Lock一定要求程序员手工释放,并且必须在finally从句中释放。Lock还有更强大的功能,例如,它的tryLock方法可以非阻塞方式去拿锁。 ### **107、ArrayList和Vector的区别** 答: 这两个类都实现了List接口(List接口继承了Collection接口),他们都是有序集合,即存储在这两个集合中的元素的位置都是有顺序的,相当于一种动态的数组,我们以后可以按位置索引号取出某个元素,,并且其中的数据是允许重复的,这是HashSet之类的集合的最大不同处,HashSet之类的集合不可以按索引号去检索其中的元素,也不允许有重复的元素(本来题目问的与hashset没有任何关系,但为了说清楚ArrayList与Vector的功能,我们使用对比方式,更有利于说明问题)。 接着才说ArrayList与Vector的区别,这主要包括两个方面:. (1)同步性: ​ Vector是线程安全的,也就是说是它的方法之间是线程同步的,而ArrayList是线程序不安全的,它的方法之间是线程不同步的。如果只有一个线程会访问到集合,那最好是使用ArrayList,因为它不考虑线程安全,效率会高些;如果有多个线程会访问到集合,那最好是使用Vector,因为不需要我们自己再去考虑和编写线程安全的代码。 备注:对于Vector&ArrayList、Hashtable&HashMap,要记住线程安全的问题,记住Vector与Hashtable是旧的,是java一诞生就提供了的,它们是线程安全的,ArrayList与HashMap是java2时才提供的,它们是线程不安全的。所以,我们讲课时先讲老的。 (2)数据增长: ​ ArrayList与Vector都有一个初始的容量大小,当存储进它们里面的元素的个数超过了容量时,就需要增加ArrayList与Vector的存储空间,每次要增加存储空间时,不是只增加一个存储单元,而是增加多个存储单元,每次增加的存储单元的个数在内存空间利用与程序效率之间要取得一定的平衡。Vector默认增长为原来两倍,而ArrayList的增长策略在文档中没有明确规定(从源代码看到的是增长为原来的1.5倍)。ArrayList与Vector都可以设置初始的空间大小,Vector还可以设置增长的空间大小,而ArrayList没有提供设置增长空间的方法。 总结:即Vector增长原来的一倍,ArrayList增加原来的0.5倍。 ### **108、HashMap和Hashtable的区别** HashMap是Hashtable的轻量级实现(非线程安全的实现),他们都完成了Map接口,主要区别在于HashMap允许空(null)键值(key),由于非线程安全,在只有一个线程访问的情况下,效率要高于Hashtable。 HashMap允许将null作为一个entry的key或者value,而Hashtable不允许。 HashMap把Hashtable的contains方法去掉了,改成containsvalue和containsKey。因为contains方法容易让人引起误解。 Hashtable继承自Dictionary类,而HashMap是Java1.2引进的Map interface的一个实现。 最大的不同是,Hashtable的方法是Synchronize的,而HashMap不是,在多个线程访问Hashtable时,不需要自己为它的方法实现同步,而HashMap 就必须为之提供外同步。 Hashtable和HashMap采用的hash/rehash算法都大概一样,所以性能不会有很大的差异。 就HashMap与HashTable主要从三方面来说。 一.历史原因:Hashtable是基于陈旧的Dictionary类的,HashMap是Java 1.2引进的Map接口的一个实现 二.同步性:Hashtable是线程安全的,也就是说是同步的,而HashMap是线程序不安全的,不是同步的 三.值:只有HashMap可以让你将空值作为一个表的条目的key或value ### 109、List 和 Map 区别? 一个是存储单列数据的集合,另一个是存储键和值这样的双列数据的集合,List中存储的数据是有顺序,并且允许重复;Map中存储的数据是没有顺序的,其键是不能重复的,它的值是可以有重复的。 ### 110、List, Set, Map是否继承自Collection接口? List,Set是,Map不是 ### **111、List、Map、Set三个接口,存取元素时,各有什么特点?** 首先,List与Set具有相似性,它们都是单列元素的集合,所以,它们有一个功共同的父接口,叫Collection。Set里面不允许有重复的元素,所谓重复,即不能有两个相等(注意,不是仅仅是相同)的对象 ,即假设Set集合中有了一个A对象,现在我要向Set集合再存入一个B对象,但B对象与A对象equals相等,则B对象存储不进去,所以,Set集合的add方法有一个boolean的返回值,当集合中没有某个元素,此时add方法可成功加入该元素时,则返回true,当集合含有与某个元素equals相等的元素时,此时add方法无法加入该元素,返回结果为false。Set取元素时,没法说取第几个,只能以Iterator接口取得所有的元素,再逐一遍历各个元素。 List表示有先后顺序的集合, 注意,不是那种按年龄、按大小、按价格之类的排序。当我们多次调用add(Obj e)方法时,每次加入的对象就像火车站买票有排队顺序一样,按先来后到的顺序排序。有时候,也可以插队,即调用add(int index,Obj e)方法,就可以指定当前对象在集合中的存放位置。一个对象可以被反复存储进List中,每调用一次add方法,这个对象就被插入进集合中一次,其实,并不是把这个对象本身存储进了集合中,而是在集合中用一个索引变量指向这个对象,当这个对象被add多次时,即相当于集合中有多个索引指向了这个对象,如图x所示。List除了可以以Iterator接口取得所有的元素,再逐一遍历各个元素之外,还可以调用get(index i)来明确说明取第几个。 Map与List和Set不同,它是双列的集合,其中有put方法,定义如下:put(obj key,obj value),每次存储时,要存储一对key/value,不能存储重复的key,这个重复的规则也是按equals比较相等。取则可以根据key获得相应的value,即get(Object key)返回值为key 所对应的value。另外,也可以获得所有的key的结合,还可以获得所有的value的结合,还可以获得key和value组合成的Map.Entry对象的集合。 List 以特定次序来持有元素,可有重复元素。Set 无法拥有重复元素,内部排序。Map 保存key-value值,value可多值。 HashSet按照hashcode值的某种运算方式进行存储,而不是直接按hashCode值的大小进行存储。例如,"abc" ---> 78,"def" ---> 62,"xyz" ---> 65在hashSet中的存储顺序不是62,65,78,这些问题感谢以前一个叫崔健的学员提出,最后通过查看源代码给他解释清楚,看本次培训学员当中有多少能看懂源码。LinkedHashSet按插入的顺序存储,那被存储对象的hashcode方法还有什么作用呢?学员想想!hashset集合比较两个对象是否相等,首先看hashcode方法是否相等,然后看equals方法是否相等。new 两个Student插入到HashSet中,看HashSet的size,实现hashcode和equals方法后再看size。 同一个对象可以在Vector中加入多次。往集合里面加元素,相当于集合里用一根绳子连接到了目标对象。往HashSet中却加不了多次的。 ### **112、说出ArrayList,Vector, LinkedList的存储性能和特性** ArrayList和Vector都是使用数组方式存储数据,此数组元素数大于实际存储的数据以便增加和插入元素,它们都允许直接按序号索引元素,但是插入元素要涉及数组元素移动等内存操作,所以索引数据快而插入数据慢,Vector由于使用了synchronized方法(线程安全),通常性能上较ArrayList差,而LinkedList使用双向链表实现存储,按序号索引数据需要进行前向或后向遍历,但是插入数据时只需要记录本项的前后项即可,所以插入速度较快。 LinkedList也是线程不安全的,LinkedList提供了一些方法,使得LinkedList可以被当作堆栈和队列来使用。 ### **113、去掉一个Vector集合中重复的元素** ``` Vector newVector = new Vector(); For (int i=0;i<vector.size();i++) { Object obj = vector.get(i); ​ if(!newVector.contains(obj); ​ newVector.add(obj); } ``` 还有一种简单的方式, ``` HashSet set = new HashSet(vector); ``` ### **114、Collection 和 Collections的区别。** Collection是集合类的上级接口,继承与他的接口主要有Set 和List. Collections是针对集合类的一个帮助类,他提供一系列静态方法实现对各种集合的搜索、排序、线程安全化等操作。 ### **115、Set里的元素是不能重复的,那么用什么方法来区分重复与否呢? 是用==还是equals()? 它们有何区别?** Set里的元素是不能重复的,元素重复与否是使用equals()方法进行判断的。 equals()和==方法决定引用值是否指向同一对象equals()在类中被覆盖,为的是当两个分离的对象的内容和类型相配的话,返回真值。 ### **116、两个对象值相同(x.equals(y) == true),但却可有不同的hash code,这句话对不对?** 对。 如果对象要保存在HashSet或HashMap中,它们的equals相等,那么,它们的hashcode值就必须相等。 如果不是要保存在HashSet或HashMap,则与hashcode没有什么关系了,这时候hashcode不等是可以的,例如arrayList存储的对象就不用实现hashcode,当然,我们没有理由不实现,通常都会去实现的。 **TreeSet里面放对象,如果同时放入了父类和子类的实例对象,那比较时使用的是父类的compareTo方法,还是使用的子类的compareTo方法,还是抛异常!** (应该是没有针对问题的确切的答案,当前的add方法放入的是哪个对象,就调用哪个对象的compareTo方法,至于这个compareTo方法怎么做,就看当前这个对象的类中是如何编写这个方法的) 实验代码: ``` public class Parent implements Comparable { ​ private int age = 0; ​ public Parent(int age){ ​ this.age = age; ​ } ​ public int compareTo(Object o) { ​ // TODO Auto-generated method stub ​ System.out.println("method of parent"); ​ Parent o1 = (Parent)o; ​ return age>o1.age?1:age<o1.age?-1:0; ​ } } public class Child extends Parent { ​ public Child(){ ​ super(3); ​ } ​ public int compareTo(Object o) { System.out.println("method of child"); Child o1 = (Child)o; return 1; } } **public** **class** TreeSetTest { ​ /** ​ * **@param** args ​ */ ​ **public** **static** **void** main(String[] args) { ​ // **TODO** Auto-generated method stub ​ TreeSet set = **new** TreeSet(); ​ set.add(**new** Parent(3)); ​ set.add(**new** Child()); ​ set.add(**new** Parent(4)); ​ System.*out*.println(set.size()); ​ } } ``` ### **117、说出一些常用的类,包,接口,请各举5个** 要让人家感觉你对java ee开发很熟,所以,不能仅仅只列core java中的那些东西,要多列你在做ssh项目中涉及的那些东西。就写你最近写的那些程序中涉及的那些类。 常用的类:BufferedReader BufferedWriter FileReader FileWirter String Integer java.util.Date,System,Class,List,HashMap 常用的包:java.lang java.io java.util java.sql ,javax.servlet,org.apache.strtuts.action,org.hibernate 常用的接口:Remote List Map Document NodeList ,Servlet,HttpServletRequest,HttpServletResponse,Transaction(Hibernate)、Session(Hibernate),HttpSession ### **118、什么是java序列化,如何实现java序列化?或者请解释Serializable接口的作用。** 我们有时候将一个java对象变成字节流的形式传出去或者从一个字节流中恢复成一个java对象,例如,要将java对象存储到硬盘或者传送给网络上的其他计算机,这个过程我们可以自己写代码去把一个java对象变成某个格式的字节流再传输,但是,jre本身就提供了这种支持,我们可以调用OutputStream的writeObject方法来做,如果要让java 帮我们做,要被传输的对象必须实现serializable接口,这样,javac编译时就会进行特殊处理,编译的类才可以被writeObject方法操作,这就是所谓的序列化。需要被序列化的类必须实现Serializable接口,该接口是一个mini接口,其中没有需要实现的方法,implements Serializable只是为了标注该对象是可被序列化的。 例如,在web开发中,如果对象被保存在了Session中,tomcat在重启时要把Session对象序列化到硬盘,这个对象就必须实现Serializable接口。如果对象要经过分布式系统进行网络传输或通过rmi等远程调用,这就需要在网络上传输对象,被传输的对象就必须实现Serializable接口。 ### **119、**解释一下什么是servlet; 答:servlet有良好的生存期的定义,包括加载和实例化、初始化、处理请求以及服务结束。这个生存期由javax.servlet.Servlet接口的init,service和destroy方法表达。 ### **120、说一说Servlet的生命周期?** 答:servlet有良好的生存期的定义,包括加载和实例化、初始化、处理请求以及服务结束。这个生存期由javax.servlet.Servlet接口的init,service和destroy方法表达。 Servlet被服务器实例化后,容器运行其init方法,请求到达时运行其service方法,service方法自动派遣运行与请求对应的doXXX方法(doGet,doPost)等,当服务器决定将实例销毁的时候调用其destroy方法。 web容器加载servlet,生命周期开始。通过调用servlet的init()方法进行servlet的初始化。通过调用service()方法实现,根据请求的不同调用不同的do***()方法。结束服务,web容器调用servlet的destroy()方法。 ### **121、Servlet的基本架构** ``` public class ServletName extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } } ``` ### **122、SERVLET API中forward() 与redirect()的区别?** 答:前者仅是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址;后者则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接。这样,从浏览器的地址栏中可以看到跳转后的链接地址。所以,前者更加高效,在前者可以满足需要时,尽量使用forward()方法,并且,这样也有助于隐藏实际的链接。在有些情况下,比如,需要跳转到一个其它服务器上的资源,则必须使用sendRedirect()方法。 forward是服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发给浏览器,浏览器根本不知道服务器发送的内容是从哪儿来的,所以它的地址栏中还是原来的地址。 redirect就是服务端根据逻辑,发送一个状态码,告诉浏览器重新去请求那个地址,一般来说浏览器会用刚才请求的所有参数重新请求,所以session,request参数都可以获取。 ### **123、什么情况下调用doGet()和doPost()?** Jsp页面中的FORM标签里的method属性为get时调用doGet(),为post时调用doPost()。 ### 124、**Request对象的主要方法:** setAttribute(String name,Object):设置名字为name的request的参数值 getAttribute(String name):返回由name指定的属性值 getAttributeNames():返回request对象所有属性的名字集合,结果是一个枚举的实例 getCookies():返回客户端的所有Cookie对象,结果是一个Cookie数组 getCharacterEncoding():返回请求中的字符编码方式 getContentLength():返回请求的Body的长度 getHeader(String name):获得HTTP协议定义的文件头信息 getHeaders(String name):返回指定名字的request Header的所有值,结果是一个枚举的实例 getHeaderNames():返回所以request Header的名字,结果是一个枚举的实例 getInputStream():返回请求的输入流,用于获得请求中的数据 getMethod():获得客户端向服务器端传送数据的方法 getParameter(String name):获得客户端传送给服务器端的有name指定的参数值 getParameterNames():获得客户端传送给服务器端的所有参数的名字,结果是一个枚举的实例 getParametervalues(String name):获得有name指定的参数的所有值 getProtocol():获取客户端向服务器端传送数据所依据的协议名称 getQueryString():获得查询字符串 getRequestURI():获取发出请求字符串的客户端地址 getRemoteAddr():获取客户端的IP地址 getRemoteHost():获取客户端的名字 getSession([Boolean create]):返回和请求相关Session getServerName():获取服务器的名字 getServletPath():获取客户端所请求的脚本文件的路径 getServerPort():获取服务器的端口号 removeAttribute(String name):删除请求中的一个属性 ### 125、 **jsp有哪些内置对象?作用分别是什么? 分别有什么方法?** 答:JSP共有以下9个内置的对象: request 用户端请求,此请求会包含来自GET/POST请求的参数 response 网页传回用户端的回应 pageContext 网页的属性是在这里管理 session 与请求有关的会话期 application servlet 正在执行的内容 out 用来传送回应的输出 config servlet的构架部件 page JSP网页本身 exception 针对错误网页,未捕捉的例外 request表示HttpServletRequest对象。它包含了有关浏览器请求的信息,并且提供了几个用于获取cookie, header, 和session数据的有用的方法。 response表示HttpServletResponse对象,并提供了几个用于设置送回 浏览器的响应的方法(如cookies,头信息等) out对象是javax.jsp.JspWriter的一个实例,并提供了几个方法使你能用于向浏览器回送输出结果。 pageContext表示一个javax.servlet.jsp.PageContext对象。它是用于方便存取各种范围的名字空间、servlet相关的对象的API,并且包装了通用的servlet相关功能的方法。 session表示一个请求的javax.servlet.http.HttpSession对象。Session可以存贮用户的状态信息 applicaton 表示一个javax.servle.ServletContext对象。这有助于查找有关servlet引擎和servlet环境的信息 config表示一个javax.servlet.ServletConfig对象。该对象用于存取servlet实例的初始化参数。 page表示从该页面产生的一个servlet实例 ### **126、MVC的各个部分都有那些技术来实现?如何实现?** MVC是Model-View-Controller的简写。Model 代表的是应用的业务逻辑(通过JavaBean,EJB组件实现), View 是应用的表示面(由JSP页面产生),Controller 是提供应用的处理过程控制(一般是一个Servlet),通过这种设计模型把应用逻辑,处理过程和显示逻辑分成不同的组件实现。这些组件可以进行交互和重用。 ### 127、**我们在web应用开发过程中经常遇到输出某种编码的字符,如iso8859-1等,如何输出一个某种编码的字符串?** ``` Public String translate (String str) { String tempStr = ""; try { tempStr = new String(str.getBytes("ISO-8859-1"), "GBK"); tempStr = tempStr.trim(); } catch (Exception e) { System.err.println(e.getMessage()); } return tempStr; } ``` ### 128、**用JDBC如何调用存储过程** ``` package com.huawei.interview.lym; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Types; public class JdbcTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Connection cn = null; CallableStatement cstmt = null; try { //这里最好不要这么干,因为驱动名写死在程序中了 Class.forName("com.mysql.jdbc.Driver"); //实际项目中,这里应用DataSource数据,如果用框架, //这个数据源不需要我们编码创建,我们只需Datasource ds = context.lookup() //cn = ds.getConnection(); cn = DriverManager.getConnection("jdbc:mysql:///test","root","root"); cstmt = cn.prepareCall("{call insert_Student(?,?,?)}"); cstmt.registerOutParameter(3,Types.INTEGER); cstmt.setString(1, "wangwu"); cstmt.setInt(2, 25); cstmt.execute(); //get第几个,不同的数据库不一样,建议不写 System.out.println(cstmt.getString(3)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { /*try{cstmt.close();}catch(Exception e){} try{cn.close();}catch(Exception e){}*/ try { if(cstmt != null) cstmt.close(); if(cn != null) cn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` ### **129、Class.forName的作用?为什么要用?** 答:按参数中指定的字符串形式的类名去搜索并加载相应的类,如果该类字节码已经被加载过,则返回代表该字节码的Class实例对象,否则,按类加载器的委托机制去搜索和加载该类,如果所有的类加载器都无法加载到该类,则抛出ClassNotFoundException。加载完这个Class字节码后,接着就可以使用Class字节码的newInstance方法去创建该类的实例对象了。 有时候,我们程序中所有使用的具体类名在设计时(即开发时)无法确定,只有程序运行时才能确定,这时候就需要使用Class.forName去动态加载该类,这个类名通常是在配置文件中配置的,例如,spring的ioc中每次依赖注入的具体类就是这样配置的,jdbc的驱动类名通常也是通过配置文件来配置的,以便在产品交付使用后不用修改源程序就可以更换驱动类名。
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 22 22:05:35 2019 Description: Generates panel (e) of main Fig. 2, i.e. the Gaussian Process extrapolation results for the static linear decoder, for the PPC manuscript. Unlike Fig. 2d, for this analysis, the "best" subset of size K neurons was chosen based on ranking based on explained variance. Note: The data file (referred to here as "filename") was generated in Matlab, using the function MAEvsN_static_ranked.m, which calls on the function rankedNeurons_explainedVar.m See the /Adrianna PPC ms/Code/Paper_fns subfolder located in the HFSP shared Dropbox for this Matlab function. @author: adrianna """ from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import ConstantKernel from sklearn.gaussian_process.kernels import WhiteKernel, Matern import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.pyplot import figure from matplotlib import rcParams rcParams['font.family'] = 'sans-serif' rcParams['font.sans-serif'] = ['Tahoma'] tableau20 = np.float32([\ ( 31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), ( 44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), (188, 189, 34), (219, 219, 141), ( 23, 190, 207), (158, 218, 229)])/255. def plot_gp(fidx, mu, cov, X, X_train=None, Y_train=None, samples=[], xtitle="", ytitle="", xlimits=range(0, 500, 200), ylimits=range(0, 1)): X = X.ravel() mu = mu.ravel() uncertainty = 1.96 * np.sqrt(np.diag(cov)) ax = plt.subplot(3,3,((fidx-1)*3)+1) # ax = plt.subplot(2,2,fidx) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) plt.fill_between(X, mu + uncertainty, mu - uncertainty, color=tableau20[fidx*5-1], alpha=0.2) plt.plot(X, mu, color="black", lw=2) for i, sample in enumerate(samples): plt.plot(X, sample, lw=1, ls='--', label=f'Sample {i+1}') if X_train is not None: plt.plot(X_train, Y_train, 'x', color=tableau20[6]) # plt.legend() plt.yticks(ylimits, fontsize=14) plt.xticks(xlimits, fontsize=14) plt.ylim(ylimits[0], ylimits[-1]) plt.xlabel(xtitle,fontsize=15) plt.ylabel(ytitle,fontsize=15) def data_loader(filename): df = pd.read_csv(filename, ',', header=None) X_train = df.get(0).values # N values X_train = X_train.reshape(-1, 1) return df, X_train if __name__ == '__main__': figure(num=None, figsize=(7, 7), dpi=80) # Load data filename = "Results/MAEvsN_static_ranked_m04_5.csv" df, X_train = data_loader(filename) # pdb.set_trace() # Define extrapolation points X_extrap = np.array(range(1, 401, 1)) X_extrap = X_extrap.reshape(-1, 1) for i in range(0,3): Y_train = df.get(i+1).values # mean MAE values Y_train = Y_train.reshape(-1, 1) # Define kernel for GP k = ConstantKernel(1.0) * Matern(length_scale=1.0) + WhiteKernel(1.0) gp = GaussianProcessRegressor(kernel=k) gp.fit(X_train, Y_train) # Compute posterior predictive mean and covariance mu_s, cov_s = gp.predict(X_extrap, return_cov=True) # Show optimized kernel parameters print(gp.kernel_) if i==0: xtitle = " " ytitle = "MAE (m)" ylimits = [0.2, 0.9] #range(0,2,1) elif i==1: xtitle = " " ytitle = "MAE (m/s)" ylimits = [0, 0.2] else: xtitle = "# of PPC Neurons" ytitle = "MAE (deg)" ylimits = [7, 14] # Plot plot_gp(i+1, mu_s, cov_s, X_extrap, X_train=X_train, Y_train=Y_train, xtitle=xtitle, ytitle=ytitle,xlimits=[1, 200, 400], ylimits=ylimits) # Hack from MRULE to get axes to match if i==0: plt.ylim(0,1) if i==1: plt.ylim(0,0.15) if i==2: plt.ylim(0,25) plt.savefig("Fig2d.svg")
package at.hannibal2.skyhanni.features.inventory import at.hannibal2.skyhanni.SkyHanniMod import at.hannibal2.skyhanni.api.CollectionAPI import at.hannibal2.skyhanni.events.RenderItemTipEvent import at.hannibal2.skyhanni.utils.InventoryUtils import at.hannibal2.skyhanni.utils.ItemUtils import at.hannibal2.skyhanni.utils.ItemUtils.cleanName import at.hannibal2.skyhanni.utils.ItemUtils.getLore import at.hannibal2.skyhanni.utils.ItemUtils.name import at.hannibal2.skyhanni.utils.LorenzUtils.between import at.hannibal2.skyhanni.utils.NumberUtil.romanToDecimal import at.hannibal2.skyhanni.utils.NumberUtil.romanToDecimalIfNeeded import at.hannibal2.skyhanni.utils.StringUtils.matchMatcher import at.hannibal2.skyhanni.utils.StringUtils.matchRegex import at.hannibal2.skyhanni.utils.StringUtils.removeColor import net.minecraft.item.ItemStack import net.minecraftforge.fml.common.eventhandler.SubscribeEvent class ItemDisplayOverlayFeatures { private val rancherBootsSpeedCapPattern = "§7Current Speed Cap: §a(?<cap>.*)".toPattern() private val petLevelPattern = "\\[Lvl (?<level>.*)] .*".toPattern() @SubscribeEvent fun onRenderItemTip(event: RenderItemTipEvent) { event.stackTip = getStackTip(event.stack) } private fun getStackTip(item: ItemStack): String { val itemName = item.cleanName() if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(0)) { when (itemName) { "First Master Star" -> return "1" "Second Master Star" -> return "2" "Third Master Star" -> return "3" "Fourth Master Star" -> return "4" "Fifth Master Star" -> return "5" } } if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(1) && itemName.matchRegex("(.*)Master Skull - Tier .")) { return itemName.substring(itemName.length - 1) } if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(2) && (itemName.contains("Golden ") || itemName.contains("Diamond "))) { when { itemName.contains("Bonzo") -> return "1" itemName.contains("Scarf") -> return "2" itemName.contains("Professor") -> return "3" itemName.contains("Thorn") -> return "4" itemName.contains("Livid") -> return "5" itemName.contains("Sadan") -> return "6" itemName.contains("Necron") -> return "7" } } if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(3) && itemName.startsWith("New Year Cake (")) { return "§b" + itemName.between("(Year ", ")") } if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(4)) { val chestName = InventoryUtils.openInventoryName() if (!chestName.endsWith("Sea Creature Guide") && ItemUtils.isPet(itemName)) { petLevelPattern.matchMatcher(itemName) { val level = group("level").toInt() if (level != ItemUtils.maxPetLevel(itemName)) { return "$level" } } } } if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(5) && itemName.contains(" Minion ") && item.getLore().any { it.contains("Place this minion") }) { val array = itemName.split(" ") val last = array[array.size - 1] return last.romanToDecimal().toString() } if (SkyHanniMod.feature.inventory.displaySackName && ItemUtils.isSack(item)) { val sackName = grabSackName(itemName) return (if (itemName.contains("Enchanted")) "§5" else "") + sackName.substring(0, 2) } if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(8) && itemName.contains("Kuudra Key")) { return when (itemName) { "Kuudra Key" -> "§a1" "Hot Kuudra Key" -> "§22" "Burning Kuudra Key" -> "§e3" "Fiery Kuudra Key" -> "§64" "Infernal Kuudra Key" -> "§c5" else -> "§4?" } } if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(9) && InventoryUtils.openInventoryName() == "Your Skills" && item.getLore().any { it.contains("Click to view!") }) { if (CollectionAPI.isCollectionTier0(item.getLore())) return "0" val split = itemName.split(" ") if (split.size < 2) return "0" if (!itemName.contains("Dungeon")) { val text = split.last() return "" + text.romanToDecimalIfNeeded() } } if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(10) && InventoryUtils.openInventoryName().endsWith(" Collections")) { val lore = item.getLore() if (lore.any { it.contains("Click to view!") }) { if (CollectionAPI.isCollectionTier0(lore)) return "0" item.name?.let { if (it.startsWith("§e")) { val text = it.split(" ").last() return "" + text.romanToDecimalIfNeeded() } } } } if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(11) && itemName.contains("Rancher's Boots")) { for (line in item.getLore()) { rancherBootsSpeedCapPattern.matchMatcher(line) { return group("cap") } } } if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(12) && itemName.contains("Larva Hook")) { for (line in item.getLore()) { "§7§7You may harvest §6(?<amount>.).*".toPattern().matchMatcher(line) { val amount = group("amount").toInt() return when { amount > 4 -> "§a$amount" amount > 2 -> "§e$amount" else -> "§c$amount" } } } } if (SkyHanniMod.feature.inventory.itemNumberAsStackSize.contains(13) && itemName.startsWith("Dungeon ") && itemName.contains(" Potion")) { item.name?.let { "Dungeon (?<level>.*) Potion".toPattern().matchMatcher(it.removeColor()) { return when (val level = group("level").romanToDecimal()) { in 1..2 -> "§f$level" in 3..4 -> "§a$level" in 5..6 -> "§9$level" else -> "§5$level" } } } } return "" } var done = false private fun grabSackName(name: String): String { val split = name.split(" ") val text = split[0] for (line in arrayOf("Large", "Medium", "Small", "Enchanted")) { if (text == line) return grabSackName(name.substring(text.length + 1)) } return text } }
import "../scss/PostApp.scss"; import React from "react"; import { useDispatch, useSelector } from "react-redux"; import { getPosts } from "../redux/postSlice"; import PostItem from "./PostItem"; const PostApp = () => { const dispatch = useDispatch(); const posts = useSelector((state)=>state.post.posts) return ( <div className="posts-main"> <h2>3.Redux Toolkit Async Thunk</h2> <div className="post-btn"> <button onClick={()=>dispatch(getPosts())} type="submit">GET POSTS</button> </div> <div className="posts"> { posts?.map((post)=>( <PostItem key={post.title} post={post} /> )) } </div> </div> ); }; export default PostApp;
<div class="col-xs-8"> <div class="panel panel-primary heading-gap"> <div class="panel-heading">Item Details</div> <table class="table table-hover"> <thead> <tr> <th style="width:10%;">Action</th> <th style="width:40%;">Name</th> <th style="width:35%;">Description</th> <th style="width:15%;">Price</th> </tr> </thead> <tbody> <tr *ngFor="let item of items" id={{item?.id}}> <td style="width:10%;" class="center-align"> <i class="fa fa-pencil cursor-pointer blue tiny-rightmargin" aria-hidden="true" (click)="editItem(item)"></i> <i class="fa fa-times cursor-pointer red" aria-hidden="true" (click)="deleteItem(item)"></i> </td> <td class="break-all" style="width:40%;">{{item.name}}</td> <td class="break-all" style="width:35%;">{{item.desc}}</td> <td style="width:15%;">{{item.price}}</td> </tr> </tbody> <tfoot> <tr *ngIf="showProgress"> <td colspan="4"> <div class="spinner"> <div class="bounce1"></div> <div class="bounce2"></div> <div class="bounce3"></div> </div> </td> </tr> <tr class="center-align gray" *ngIf="items.length == 0 && showProgress == false"> <td colspan="4">No Record Found</td> </tr> </tfoot> </table> </div> </div> <div class="col-xs-4"> <div class="panel panel-primary heading-gap"> <div class="panel-heading">Add/Edit Item</div> <div class="panel-body"> <form [formGroup]="itemForm" (ngSubmit)="addItem()"> <input type="hidden" [(ngModel)]="item.id" formControlName="id" /> <div class="form-group"> <label for="name">Name</label> <input attr.itemid="{{item?.id}}" type="text" asyncValidator class="form-control" id="name" [(ngModel)]="item.name" formControlName="name" required> <div *ngIf="formErrors.name" class="alert alert-danger"> {{ formErrors.name }} </div> </div> <div class="form-group"> <label for="desc">Description</label> <textarea class="form-control" rows="3" id="desc" [(ngModel)]="item.desc" formControlName="desc"></textarea> </div> <div class="form-group"> <label for="price">Price</label> <input type="number" class="form-control" id="price" min=1 [(ngModel)]="item.price" formControlName="price" required> <div *ngIf="formErrors.price" class="alert alert-danger"> {{ formErrors.price }} </div> </div> <button class="btn btn-success" type="submit" [disabled]="!itemForm.valid">{{addButtonText}}</button> <button class="btn btn-default" type="button" (click)="newForm()">Clear</button> </form> </div> </div> </div>
--- title: Les frameworks web côté serveur slug: Learn/Server-side/Premiers_pas/Web_frameworks tags: - Débutant - Guide - Server - Web translation_of: Learn/Server-side/First_steps/Web_frameworks --- <div><section class="Quick_links" id="Quick_Links"> <ol> <li data-default-state="closed"><a href="/fr/docs/Learn/Getting_started_with_the_web"><strong>Bienvenue aux débutants !</strong></a></li> <li class="toggle"> <details> <summary>Commencer avec le Web</summary> <ol> <li><a href="/fr/docs/Learn/Getting_started_with_the_web">Vue d&apos;ensemble de Commencer avec le Web</a></li> <li><a href="/fr/docs/Learn/Getting_started_with_the_web/Installing_basic_software">Installation des outils de base</a></li> <li><a href="/fr/docs/Learn/Getting_started_with_the_web/What_will_your_website_look_like">Quel sera l&apos;aspect de votre site web ?</a></li> <li><a href="/fr/docs/Learn/Getting_started_with_the_web/Dealing_with_files">Gérer les fichiers</a></li> <li><a href="/fr/docs/Learn/Getting_started_with_the_web/HTML_basics">Les bases de HTML</a></li> <li><a href="/fr/docs/Learn/Getting_started_with_the_web/CSS_basics">Les bases de CSS</a></li> <li><a href="/fr/docs/Learn/Getting_started_with_the_web/JavaScript_basics">Les bases de JavaScript</a></li> <li><a href="/fr/docs/Learn/Getting_started_with_the_web/Publishing_your_website">Publier votre site web</a></li> <li><a href="/fr/docs/Learn/Getting_started_with_the_web/How_the_Web_works">Le fonctionnement du Web</a></li> </ol> </details> </li> <li data-default-state="closed"><a href="/fr/docs/Learn/HTML"><strong>HTML</strong></a></li> <li class="toggle"> <details> <summary>Introduction au HTML</summary> <ol> <li><a href="/fr/docs/Learn/HTML/Introduction_to_HTML">Vue d&apos;ensemble de Introduction au HTML</a></li> <li><a href="/fr/docs/Learn/HTML/Introduction_to_HTML/Getting_started">Commencer avec le HTML</a></li> <li><a href="/fr/docs/Learn/HTML/Introduction_to_HTML/The_head_metadata_in_HTML">Qu&apos;y-a-t-il dans l&apos;en-tête ? Métadonnées en HTML</a></li> <li><a href="/fr/docs/Learn/HTML/Introduction_to_HTML/HTML_text_fundamentals">Fondamentaux du texte en HTML</a></li> <li><a href="/fr/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks">Création d&apos;hyperliens</a></li> <li><a href="/fr/docs/Learn/HTML/Introduction_to_HTML/Advanced_text_formatting">Formatage avancé du texte</a></li> <li><a href="/fr/docs/Learn/HTML/Introduction_to_HTML/Document_and_website_structure">Structure de site web et de document</a></li> <li><a href="/fr/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML">Déboguer en HTML</a></li> <li><a href="/fr/docs/Learn/HTML/Introduction_to_HTML/Marking_up_a_letter">Baliser une lettre</a></li> <li><a href="/fr/docs/Learn/HTML/Introduction_to_HTML/Structuring_a_page_of_content">Structurer une page de contenu</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Multimedia and embedding</summary> <ol> <li><a href="/fr/docs/Learn/HTML/Multimedia_and_embedding">Multimedia and embedding overview</a></li> <li><a href="/fr/docs/Learn/HTML/Multimedia_and_embedding/Images_in_HTML">Images in HTML</a></li> <li><a href="/fr/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content">Video and audio content</a></li> <li><a href="/fr/docs/Learn/HTML/Multimedia_and_embedding/Other_embedding_technologies">From object to iframe — other embedding technologies</a></li> <li><a href="/fr/docs/Learn/HTML/Multimedia_and_embedding/Adding_vector_graphics_to_the_Web">Adding vector graphics to the Web</a></li> <li><a href="/fr/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images">Responsive images</a></li> <li><a href="/fr/docs/Learn/HTML/Multimedia_and_embedding/Mozilla_splash_page">Assessment: Mozilla splash page</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>HTML tables</summary> <ol> <li><a href="/fr/docs/Learn/HTML/Tables">HTML tables overview</a></li> <li><a href="/fr/docs/Learn/HTML/Tables/Basics">HTML table basics</a></li> <li><a href="/fr/docs/Learn/HTML/Tables/Advanced">HTML Table advanced features and accessibility</a></li> <li><a href="/fr/docs/Learn/HTML/Tables/Structuring_planet_data">Assessment: Structuring planet data</a></li> </ol> </details> </li> <li data-default-state="closed"><a href="/fr/docs/Learn/CSS"><strong>CSS — Styling the Web</strong></a></li> <li class="toggle"> <details> <summary>CSS first steps</summary> <ol> <li><a href="/fr/docs/Learn/CSS/First_steps">CSS first steps overview</a></li> <li><a href="/fr/docs/Learn/CSS/First_steps/What_is_CSS">What is CSS?</a></li> <li><a href="/fr/docs/Learn/CSS/First_steps/Getting_started">Getting started with CSS</a></li> <li><a href="/fr/docs/Learn/CSS/First_steps/How_CSS_is_structured">How CSS is structured</a></li> <li><a href="/fr/docs/Learn/CSS/First_steps/How_CSS_works">How CSS works</a></li> <li><a href="/fr/docs/Learn/CSS/First_steps/Using_your_new_knowledge">Using your new knowledge</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>CSS building blocks</summary> <ol> <li><a href="/fr/docs/Learn/CSS/Building_blocks">CSS building blocks overview</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/Cascade_and_inheritance">Cascade and inheritance</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/Selectors">CSS selectors</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/The_box_model">The box model</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders">Backgrounds and borders</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/Handling_different_text_directions">Handling different text directions</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/Overflowing_content">Overflowing content</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/Values_and_units">Values and units</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/Sizing_items_in_CSS">Sizing items in CSS</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/Images_media_form_elements">Images, media, and form elements</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/Styling_tables">Styling tables</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/Debugging_CSS">Debugging CSS</a></li> <li><a href="/fr/docs/Learn/CSS/Building_blocks/Organizing">Organizing your CSS</a></li> </ol></details> </li> <li class="toggle"> <details> <summary>Styling text</summary> <ol> <li><a href="/fr/docs/Learn/CSS/Styling_text">Styling text overview</a></li> <li><a href="/fr/docs/Learn/CSS/Styling_text/Fundamentals">Fundamental text and font styling</a></li> <li><a href="/fr/docs/Learn/CSS/Styling_text/Styling_lists">Styling lists</a></li> <li><a href="/fr/docs/Learn/CSS/Styling_text/Styling_links">Styling links</a></li> <li><a href="/fr/docs/Learn/CSS/Styling_text/Web_fonts">Web fonts</a></li> <li><a href="/fr/docs/Learn/CSS/Styling_text/Typesetting_a_homepage">Assessment: Typesetting a community school homepage</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>CSS layout</summary> <ol> <li><a href="/fr/docs/Learn/CSS/CSS_layout">CSS layout overview</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Introduction">Introduction</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Normal_Flow">Normal Flow</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Flexbox">Flexbox</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Grids">Grids</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Floats">Floats</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Positioning">Positioning</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Multiple-column_Layout">Multiple-column Layout</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Responsive_Design">Responsive design</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Media_queries">Beginner&apos;s guide to media queries</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Legacy_Layout_Methods">Legacy Layout Methods</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Supporting_Older_Browsers">Supporting Older Browsers</a></li> <li><a href="/fr/docs/Learn/CSS/CSS_layout/Fundamental_Layout_Comprehension">Fundamental Layout Comprehension</a></li> </ol> </details> </li> <li data-default-state="closed"><a href="/fr/docs/Learn/JavaScript"><strong>JavaScript — Dynamic client-side scripting</strong></a></li> <li class="toggle"> <details> <summary>JavaScript first steps</summary> <ol> <li><a href="/fr/docs/Learn/JavaScript/First_steps">JavaScript first steps overview</a></li> <li><a href="/fr/docs/Learn/JavaScript/First_steps/What_is_JavaScript">What is JavaScript?</a></li> <li><a href="/fr/docs/Learn/JavaScript/First_steps/A_first_splash">A first splash into JavaScript</a></li> <li><a href="/fr/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a></li> <li><a href="/fr/docs/Learn/JavaScript/First_steps/Variables">Storing the information you need — Variables</a></li> <li><a href="/fr/docs/Learn/JavaScript/First_steps/Math">Basic math in JavaScript — Numbers and operators</a></li> <li><a href="/fr/docs/Learn/JavaScript/First_steps/Strings">Handling text — Strings in JavaScript</a></li> <li><a href="/fr/docs/Learn/JavaScript/First_steps/Useful_string_methods">Useful string methods</a></li> <li><a href="/fr/docs/Learn/JavaScript/First_steps/Arrays">Arrays</a></li> <li><a href="/fr/docs/Learn/JavaScript/First_steps/Silly_story_generator">Assessment: Silly story generator</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>JavaScript building blocks</summary> <ol> <li><a href="/fr/docs/Learn/JavaScript/Building_blocks">JavaScript building blocks overview</a></li> <li><a href="/fr/docs/Learn/JavaScript/Building_blocks/conditionals">Making decisions in your code — Conditionals</a></li> <li><a href="/fr/docs/Learn/JavaScript/Building_blocks/Looping_code">Looping code</a></li> <li><a href="/fr/docs/Learn/JavaScript/Building_blocks/Functions">Functions — Reusable blocks of code</a></li> <li><a href="/fr/docs/Learn/JavaScript/Building_blocks/Build_your_own_function">Build your own function</a></li> <li><a href="/fr/docs/Learn/JavaScript/Building_blocks/Return_values">Function return values</a></li> <li><a href="/fr/docs/Learn/JavaScript/Building_blocks/Events">Introduction to events</a></li> <li><a href="/fr/docs/Learn/JavaScript/Building_blocks/Image_gallery">Assessment: Image gallery</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Introducing JavaScript objects</summary> <ol> <li><a href="/fr/docs/Learn/JavaScript/Objects">Introducing JavaScript objects overview</a></li> <li><a href="/fr/docs/Learn/JavaScript/Objects/Basics">Object basics</a></li> <li><a href="/fr/docs/Learn/JavaScript/Objects/Object-oriented_JS">Object-oriented JavaScript for beginners</a></li> <li><a href="/fr/docs/Learn/JavaScript/Objects/Object_prototypes">Object prototypes</a></li> <li><a href="/fr/docs/Learn/JavaScript/Objects/Inheritance">Inheritance in JavaScript</a></li> <li><a href="/fr/docs/Learn/JavaScript/Objects/JSON">Working with JSON data</a></li> <li><a href="/fr/docs/Learn/JavaScript/Objects/Object_building_practice">Object building practice</a></li> <li><a href="/fr/docs/Learn/JavaScript/Objects/Adding_bouncing_balls_features">Assessment: Adding features to our bouncing balls demo</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Asynchronous JavaScript</summary> <ol> <li><a href="/fr/docs/Learn/JavaScript/Asynchronous">Asynchronous JavaScript overview</a></li> <li><a href="/fr/docs/Learn/JavaScript/Asynchronous/Concepts">General asynchronous programming concepts</a></li> <li><a href="/fr/docs/Learn/JavaScript/Asynchronous/Introducing">Introducing asynchronous JavaScript</a></li> <li><a href="/fr/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals">Cooperative asynchronous Java​Script: Timeouts and intervals</a></li> <li><a href="/fr/docs/Learn/JavaScript/Asynchronous/Promises">Graceful asynchronous programming with Promises</a></li> <li><a href="/fr/docs/Learn/JavaScript/Asynchronous/Async_await">Making asynchronous programming easier with async and await</a></li> <li><a href="/fr/docs/Learn/JavaScript/Asynchronous/Choosing_the_right_approach">Choosing the right approach</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Client-side web APIs</summary> <ol> <li><a href="/fr/docs/Learn/JavaScript/Client-side_web_APIs">Client-side web APIs</a></li> <li><a href="/fr/docs/Learn/JavaScript/Client-side_web_APIs/Introduction">Introduction to web APIs</a></li> <li><a href="/fr/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents">Manipulating documents</a></li> <li><a href="/fr/docs/Learn/JavaScript/Client-side_web_APIs/Fetching_data">Fetching data from the server</a></li> <li><a href="/fr/docs/Learn/JavaScript/Client-side_web_APIs/Third_party_APIs">Third party APIs</a></li> <li><a href="/fr/docs/Learn/JavaScript/Client-side_web_APIs/Drawing_graphics">Drawing graphics</a></li> <li><a href="/fr/docs/Learn/JavaScript/Client-side_web_APIs/Video_and_audio_APIs">Video and audio APIs</a></li> <li><a href="/fr/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage">Client-side storage</a></li> </ol> </details> </li> <li><a href="/fr/docs/Learn/Forms"><strong>Web forms — Working with user data</strong></a></li> <li class="toggle"> <details> <summary>Core forms learning pathway</summary> <ol> <li><a href="/fr/docs/Learn/Forms">Web forms overview</a></li> <li><a href="/fr/docs/Learn/Forms/Your_first_form">Your first form</a></li> <li><a href="/fr/docs/Learn/Forms/How_to_structure_a_web_form">How to structure a web form</a></li> <li><a href="/fr/docs/Learn/Forms/Basic_native_form_controls">Basic native form controls</a></li> <li><a href="/fr/docs/Learn/Forms/HTML5_input_types">The HTML5 input types</a></li> <li><a href="/fr/docs/Learn/Forms/Other_form_controls">Other form controls</a></li> <li><a href="/fr/docs/Learn/Forms/Styling_web_forms">Styling web forms</a></li> <li><a href="/fr/docs/Learn/Forms/Advanced_form_styling">Advanced form styling</a></li> <li><a href="/fr/docs/Learn/Forms/UI_pseudo-classes">UI pseudo-classes</a></li> <li><a href="/fr/docs/Learn/Forms/Form_validation">Client-side form validation</a></li> <li><a href="/fr/docs/Learn/Forms/Sending_and_retrieving_form_data">Sending form data</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Advanced forms articles</summary> <ol> <li><a href="/fr/docs/Learn/Forms/How_to_build_custom_form_controls">How to build custom form controls</a></li> <li><a href="/fr/docs/Learn/Forms/Sending_forms_through_JavaScript">Sending forms through JavaScript</a></li> <li><a href="/fr/docs/Learn/Forms/Property_compatibility_table_for_form_controls">CSS property compatibility table for form controls</a></li> </ol> </details> </li> <li><a href="/fr/docs/Learn/Accessibility"><strong>Accessibility — Make the web usable by everyone</strong></a></li> <li class="toggle"> <details> <summary>Accessibility guides</summary> <ol> <li><a href="/fr/docs/Learn/Accessibility">Accessibility overview</a></li> <li><a href="/fr/docs/Learn/Accessibility/What_is_accessibility">What is accessibility?</a></li> <li><a href="/fr/docs/Learn/Accessibility/HTML">HTML: A good basis for accessibility</a></li> <li><a href="/fr/docs/Learn/Accessibility/CSS_and_JavaScript">CSS and JavaScript accessibility best practices</a></li> <li><a href="/fr/docs/Learn/Accessibility/WAI-ARIA_basics">WAI-ARIA basics</a></li> <li><a href="/fr/docs/Learn/Accessibility/Multimedia">Accessible multimedia</a></li> <li><a href="/fr/docs/Learn/Accessibility/Mobile">Mobile accessibility</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Accessibility assessment</summary> <ol> <li><a href="/fr/docs/Learn/Accessibility/Accessibility_troubleshooting">Assessment: Accessibility troubleshooting</a></li> </ol> </details> </li> <li><a href="/fr/docs/Learn/Tools_and_testing"><strong>Tools and testing</strong></a></li> <li class="toggle"> <details> <summary>Client-side web development tools</summary> <ol> <li><a href="/fr/docs/Learn/Tools_and_testing/Understanding_client-side_tools">Client-side web development tools index</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Overview">Client-side tooling overview</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line">Command line crash course</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Package_management">Package management basics</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain">Introducing a complete toolchain</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Deployment">Deploying our app</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Introduction to client-side frameworks</summary> <ol> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction">Client-side frameworks overview</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features">Framework main features</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>React</summary> <ol> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started">Getting started with React</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning">Beginning our React todo list</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components">Componentizing our React app</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state">React interactivity: Events and state</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering">React interactivity: Editing, filtering, conditional rendering</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility">Accessibility in React</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources">React resources</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Ember</summary> <ol> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started">Getting started with Ember</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization">Ember app structure and componentization</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state">Ember interactivity: Events, classes and state</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer">Ember Interactivity: Footer functionality, conditional rendering</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing">Routing in Ember</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources">Ember resources and troubleshooting</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Vue</summary> <ol> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started">Getting started with Vue</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component">Creating our first Vue component</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists">Rendering a list of Vue components</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models">Adding a new todo form: Vue events, methods, and models</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling">Styling Vue components with CSS</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties">Using Vue computed properties</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering ">Vue conditional rendering: editing existing todos</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management">Focus management with Vue refs</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources">Vue resources</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Git and GitHub</summary> <ol> <li><a href="/fr/docs/Learn/Tools_and_testing/GitHub">Git and GitHub overview</a></li> <li><a href="https://guides.github.com/activities/hello-world/">Hello World</a></li> <li><a href="https://guides.github.com/introduction/git-handbook/">Git Handbook</a></li> <li><a href="https://guides.github.com/activities/forking/">Forking Projects</a></li> <li><a href="https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests">About pull requests</a></li> <li><a href="https://guides.github.com/features/issues/">Mastering Issues</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Cross browser testing</summary> <ol> <li><a href="/fr/docs/Learn/Tools_and_testing/Cross_browser_testing">Cross browser testing overview</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction">Introduction to cross browser testing</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Cross_browser_testing/Testing_strategies">Strategies for carrying out testing</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Cross_browser_testing/HTML_and_CSS">Handling common HTML and CSS problems</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Cross_browser_testing/JavaScript">Handling common JavaScript problems</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility">Handling common accessibility problems</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Cross_browser_testing/Feature_detection">Implementing feature detection</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Cross_browser_testing/Automated_testing">Introduction to automated testing</a></li> <li><a href="/fr/docs/Learn/Tools_and_testing/Cross_browser_testing/Your_own_automation_environment">Setting up your own test automation environment</a></li> </ol> </details> </li> <li data-default-state="open"><a href="/fr/docs/Learn/Server-side"><strong>Server-side website programming</strong></a></li> <li class="toggle"> <details> <summary>First steps</summary> <ol> <li><a href="/fr/docs/Learn/Server-side/First_steps">First steps overview</a></li> <li><a href="/fr/docs/Learn/Server-side/First_steps/Introduction">Introduction to the server-side</a></li> <li><a href="/fr/docs/Learn/Server-side/First_steps/Client-Server_overview">Client-Server overview</a></li> <li><a href="/fr/docs/Learn/Server-side/First_steps/Web_frameworks">Server-side web frameworks</a></li> <li><a href="/fr/docs/Learn/Server-side/First_steps/Website_security">Website security</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Django web framework (Python)</summary> <ol> <li><a href="/fr/docs/Learn/Server-side/Django">Django web framework (Python) overview</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/Introduction">Introduction</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/development_environment">Setting up a development environment</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/Tutorial_local_library_website">Tutorial: The Local Library website</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/skeleton_website">Tutorial Part 2: Creating a skeleton website</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/Models">Tutorial Part 3: Using models</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/Admin_site">Tutorial Part 4: Django admin site</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/Home_page">Tutorial Part 5: Creating our home page</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/Generic_views">Tutorial Part 6: Generic list and detail views</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/Sessions">Tutorial Part 7: Sessions framework</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/Authentication">Tutorial Part 8: User authentication and permissions</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/Forms">Tutorial Part 9: Working with forms</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/Testing">Tutorial Part 10: Testing a Django web application</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/Deployment">Tutorial Part 11: Deploying Django to production</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/web_application_security">Web application security</a></li> <li><a href="/fr/docs/Learn/Server-side/Django/django_assessment_blog">Assessment: DIY mini blog</a></li> </ol> </details> </li> <li class="toggle"> <details> <summary>Express Web Framework (node.js/JavaScript)</summary> <ol> <li><a href="/fr/docs/Learn/Server-side/Express_Nodejs">Express Web Framework (Node.js/JavaScript) overview</a></li> <li><a href="/fr/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> <li><a href="/fr/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> <li><a href="/fr/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express tutorial: The Local Library website</a></li> <li><a href="/fr/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> <li><a href="/fr/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a database (with Mongoose)</a></li> <li><a href="/fr/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> <li><a href="/fr/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> <li><a href="/fr/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> <li><a href="/fr/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> </ol> </details> </li> <li><a href="#"><strong>Further resources</strong></a></li> <li class="toggle"> <details> <summary>Common questions</summary> <ol> <li><a href="/fr/docs/Learn/HTML/Howto">HTML questions</a></li> <li><a href="/fr/docs/Learn/CSS/Howto">CSS questions</a></li> <li><a href="/fr/docs/Learn/JavaScript/Howto">JavaScript questions</a></li> <li><a href="/fr/docs/Learn/Common_questions#How_the_Web_works">Le fonctionnement du Web</a></li> <li><a href="/fr/docs/Learn/Common_questions#Tools_and_setup">Tools and setup</a></li> <li><a href="/fr/docs/Learn/Common_questions#Design_and_accessibility">Design and accessibility</a></li> </ol> </details> </li> <li data-default-state="closed"><a href="/fr/docs/Learn/How_to_contribute">How to contribute</a></li> </ol> </section></div> <div><div class="prevnext"> <a href="/fr/docs/Learn/Server-side/First_steps/Client-Server_overview" class="button"><i class="icon-arrow-left"></i><span class="label"> Précédent </span></a><a href="/fr/docs/Learn/Server-side/First_steps" class="button"><i class="icon-arrow-up"></i> Aperçu : First steps</a><a href="/fr/docs/Learn/Server-side/First_steps/Website_security" class="button"><span class="label"> Suivant </span><i class="icon-arrow-right"></i></a> </div></div> <p class="summary">L&apos;article précédent nous a montré à quoi ressemble la communication entre les clients et les serveurs web, la nature des demandes et des réponses HTTP et ce qu’une application web côté serveur doit faire pour répondre aux demandes d’un navigateur web. Avec ces connaissances en main, il est temps d&apos;explorer comment les frameworks peuvent nous simplifier la tâche.  En chemin, vous comprendrez comment choisir le framework le mieux adapté pour votre première application web côté serveur.</p> <table class="learn-box standard-table"> <tbody> <tr> <th scope="row">Prérequis :</th> <td>Connaissance informatique de base.</td> </tr> <tr> <th scope="row">Objectif :</th> <td>Comprendre comment les frameworks simplifient le développement/la maintenance du code côté serveur et vous faire réfléchir à propos de la sélection d&apos;un framework pour votre propre développement.</td> </tr> </tbody> </table> <p>Les sections suivantes proposent des illustrations avec des fragments de codes utilisés par des frameworks réels. Ne soyez pas inquiété si vous ne comprenez pas tout directement. Les explications viendront au fur et à mesure.</p> <h2 id="Vue_densemble">Vue d&apos;ensemble</h2> <p>Les frameworks web côté serveur (c-à-d &quot;web application frameworks&quot;) facilitent l&apos;écriture, la maintenance et la mise à l&apos;échelle d&apos;applications web. Ils fournissent des outils et des bibliothèques qui simplifient les tâches courantes de développement web, notamment l&apos;acheminement des URL vers les gestionnaires appropriés, l&apos;interaction avec les bases de données, les sessions et l&apos;autorisation des utilisateurs, le formatage de la sortie (HTML, JSON, XML, par exemple) et l&apos;amélioration de la sécurité contre les attaques web.</p> <p>Dans la section suivante, nous allons voir un peu plus de détails comment les frameworks facilite le développement d&apos;applications web. Nous verrons alors les critères utilisés pour choisir un framework adapté.</p> <h2 id="Que_peut_faire_un_framework_web_pour_vous">Que peut faire un framework web pour vous ?</h2> <p>Les frameworks web fournissent des outils et des bibliothèques pour simplifier les opérations de développement web courantes. Utiliser un framework web côté serveur n&apos;est pas obligatoire, mais fortement conseillé... Cela vous facilitera grandement la vie. Cette section présente certaines des fonctionnalités parmi les plus souvent fournies par les frameworks web.</p> <h3 id="Travailler_directement_avec_les_requêtes_et_les_réponses_HTTP">Travailler directement avec les requêtes et les réponses HTTP</h3> <p>Comme nous l&apos;avons vu dans le dernier article, les serveurs web et les navigateurs communiquent via le protocole HTTP — les serveurs attendent les requêtes HTTP du navigateur, puis renvoient des informations dans les réponses HTTP. Les infrastructures web vous permettent d&apos;écrire une syntaxe simplifiée qui générera un code côté serveur pour travailler avec ces demandes et réponses. Cela signifie que vous aurez un travail plus facile, en interagissant avec un code plus facile, de niveau supérieur, plutôt que des primitives de réseau de niveau inférieur.</p> <p>L&apos;exemple ci-dessous montre comment cela fonctionne dans le framework web Django (Python). Chaque fonction &quot;view&quot; (un gestionnaire de demandes) reçoit un objet HttpRequest contenant les informations de la demande et doit renvoyer un objet HttpResponse avec la sortie formatée (dans ce cas une chaîne).</p> <pre class="brush: python notranslate"># Django view function from django.http import HttpResponse def index(request): # Get an HttpRequest (request) # perform operations using information from the request. # Return HttpResponse return HttpResponse(&apos;Output string to return&apos;) </pre> <h3 id="Acheminer_les_requettes_au_gestionnaire_approprié">Acheminer les requettes au gestionnaire approprié</h3> <p>La plupart des sites fournissent un certain nombre de ressources différentes, accessibles via des URL distinctes. Il est difficile de gérer toutes ces fonctions en une seule fois. Par conséquent, les infrastructures web fournissent des mécanismes simples pour mapper les modèles d&apos;URL vers des fonctions de gestionnaire spécifiques. Cette approche présente également des avantages en termes de maintenance, car vous pouvez modifier l&apos;URL utilisée pour fournir une fonctionnalité particulière sans avoir à modifier le code sous-jacent.</p> <p>Différents frameworks utilisent différents mécanismes pour la cartographie. Par exemple, l&apos;infrastructure web Flask (Python) ajoute des itinéraires pour afficher les fonctions à l&apos;aide d&apos;un décorateur.</p> <pre class="brush: python notranslate">@app.route(&quot;/&quot;) def hello(): return &quot;Hello World!&quot;</pre> <p>Alors que Django attend des développeurs qu&apos;ils définissent une liste de mappages d&apos;URL entre un modèle d&apos;URL et une fonction d&apos;affichage.</p> <pre class="brush: python notranslate">urlpatterns = [ url(r&apos;^$&apos;, views.index), # example: /best/myteamname/5/ url(r&apos;^(?P&lt;team_name&gt;\w.+?)/(?P&lt;team_number&gt;[0-9]+)/$&apos;, views.best), ] </pre> <h3 id="Faciliter_laccès_aux_données_via_la_requête">Faciliter l&apos;accès aux données via la requête</h3> <p>Les données peuvent être encodées dans une requête HTTP de différentes manières. Une demande HTTP GET pour obtenir des fichiers ou des données du serveur peut coder les données requises dans les paramètres d&apos;URL ou dans la structure d&apos;URL. Une demande HTTP POST de mise à jour une ressource sur le serveur inclura plutôt les informations de mise à jour en tant que &quot;données POST&quot; dans le corps de la demande. La requête HTTP peut également inclure des informations sur la session ou l&apos;utilisateur en cours dans un cookie côté client. Les frameworks web fournissent des mécanismes appropriés au langage de programmation pour accéder à ces informations. Par exemple, l&apos;objet HttpRequest que Django transmet à chaque fonction d&apos;affichage contient des méthodes et des propriétés permettant d&apos;accéder à l&apos;URL cible, le type de demande (par exemple, un HTTP GET), les paramètres GET ou POST, les données de cookie et de session, etc. Django peut également transmettre informations codées dans la structure de l&apos;URL en définissant des &quot;modèles de capture&quot; dans le mappeur d&apos;URL (voir le dernier fragment de code dans la section ci-dessus).</p> <h3 id="extraction_et_simplification_de_l’accès_à_la_base_de_données">extraction et simplification de l’accès à la base de données</h3> <p>Les sites web utilisent des bases de données pour stocker des informations à partager avec les utilisateurs et sur les utilisateurs. Les infrastructures web fournissent souvent une couche de base de données qui extrait les opérations de lecture, d&apos;écriture, de requête et de suppression de base de données. Cette couche d&apos;extraction est appelée ORM (Object-Relational Mapper).</p> <p>L&apos;utilisation d&apos;un ORM présente deux avantages :   </p> <ol> <li>Vous pouvez remplacer la base de données sous-jacente sans avoir nécessairement besoin de changer le code qui l&apos;utilise. Cela permet aux développeurs d’optimiser les caractéristiques des différentes bases de données en fonction de leur utilisation.   </li> <li>La validation de base des données peut être mise en œuvre avec le framework. Il est ainsi plus facile et plus sûr de vérifier que les données sont stockées dans le type de champ de base de données approprié, qu’elles ont le format correct (par exemple une adresse électronique) et qu’elles ne sont en aucun cas malveillantes (les pirates peuvent utiliser certains modèles de code pour agir mal, telles que la suppression des enregistrements de la base de données).</li> </ol> <p>Par exemple, le framework web Django fournit un ORM et fait référence à l&apos;objet utilisé pour définir la structure d&apos;un enregistrement en tant que modèle. Le modèle spécifie les types de champs à stocker, ce qui peut fournir une validation au niveau du champ sur les informations pouvant être stockées (par exemple, un champ de courrier électronique autoriserait uniquement les adresses de courrier électronique valides). Les définitions de champ peuvent également spécifier leur taille maximale, leurs valeurs par défaut, leurs options de liste de sélection, leur aide pour la documentation, leur libellé pour les formulaires, etc. Le modèle ne spécifie aucune information sur la base de données sous-jacente, il s&apos;agit d&apos;un paramètre de configuration susceptible d&apos;être modifié séparément de notre code.</p> <p>Le premier extrait de code ci-dessous montre un modèle Django très simple pour un objet Team. Ceci stocke le nom et le niveau de l&apos;équipe en tant que champs de caractères et spécifie un nombre maximal de caractères à stocker pour chaque enregistrement. Team_level étant un champ de choix, nous fournissons également un mappage entre les choix à afficher et les données à stocker, ainsi qu&apos;une valeur par défaut.</p> <pre class="brush: python notranslate">#best/models.py from django.db import models class Team(models.Model): team_name = models.CharField(max_length=40) TEAM_LEVELS = ( (&apos;U09&apos;, &apos;Under 09s&apos;), (&apos;U10&apos;, &apos;Under 10s&apos;), (&apos;U11, &apos;Under 11s&apos;), ... #list our other teams ) team_level = models.CharField(max_length=3,choices=TEAM_LEVELS,default=&apos;U11&apos;) </pre> <p>Le modèle Django fournit une API de requête simple pour la recherche dans la base de données. Cela peut correspondre à plusieurs champs à la fois en utilisant différents critères (par exemple, exact, insensible à la casse, supérieur à, etc.), et peut prendre en charge des instructions complexes (par exemple, vous pouvez spécifier une recherche sur les équipes U11 ayant un nom d&apos;equipe (team name) qui commence par &quot;Fr&quot; ou se termine par &quot;al&quot;).</p> <p>Le deuxième extrait de code montre une fonction d&apos;affichage (gestionnaire de ressources) permettant d&apos;afficher toutes nos équipes U09. Dans ce cas, nous spécifions que nous voulons filtrer tous les enregistrements où le champ team_level a exactement le texte &apos;U09&apos; (notez dans l exemple ci dessous comment ce critère est transmis à la fonction filter () sous forme d&apos;argument avec le nom du champ et le type de correspondance séparés par un double. underscores: team_level__exact).</p> <pre class="brush: python notranslate">#best/views.py from django.shortcuts import render from .models import Team def youngest(request): <strong>list_teams = Team.objects.filter(team_level__exact=&quot;U09&quot;)</strong> context = {&apos;youngest_teams&apos;: list_teams} return render(request, &apos;best/index.html&apos;, context) </pre> <dl> </dl> <h3 id="Rendering_data">Rendering data</h3> <p>Les frameworks web fournissent souvent des systèmes de templates. Ceux-ci vous permettent de spécifier la structure d&apos;un document de sortie, en utilisant des espaces réservés pour les données qui seront ajoutées lors de la génération d&apos;une page. Les modèles sont souvent utilisés pour créer du HTML, mais peuvent également créer d&apos;autres types de documents.</p> <p>Les frameworks web fournissent souvent un mécanisme facilitant la génération d&apos;autres formats à partir de données stockées, notamment <a href="/fr/docs/Glossaire/JSON">JSON</a> et <a href="/fr/docs/Glossaire/XML">XML</a>.</p> <p>Par exemple, le système de templates Django vous permet de spécifier des variables en utilisant une syntaxe &quot;double-handlebars&quot; (par exemple,<code>{</code><code>{ <em>variable_name</em> </code><code>}</code><code>}</code> ), qui sera remplacée par les valeurs transmises à partir de la fonction d&apos;affichage lors du rendu d&apos;une page. Le système de templates prend également en charge les expressions (avec la syntaxe:<code>{% <em>expression</em> %}</code> ), qui permettent aux templates d&apos;effectuer des opérations simples, telles que l&apos;itération des valeurs de liste transmises au modèle.</p> <div class="note notecard"> <p><strong>Note </strong>: Many other templating systems use a similar syntax, e.g.: Jinja2 (Python), handlebars (JavaScript), moustache (JavaScript), etc.</p> </div> <p>L&apos;extrait de code ci-dessous montre comment cela fonctionne. En reprenant l&apos;exemple &quot;youngest_teams&quot; de la section précédente, le modèle HTML se voit transmettre par la vue une variable de liste nommée youngest_teams. Dans le squelette HTML, nous avons une expression qui vérifie d&apos;abord si la variable youngest_teams existe, puis itère dans une boucle for. À chaque itération, le modèle affiche la valeur team_name de l&apos;équipe dans un élément de liste.</p> <pre class="brush: html notranslate">#best/templates/best/index.html &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;body&gt; {% if youngest_teams %} &lt;ul&gt; {% for team in youngest_teams %} &lt;li&gt;{{ team.team_name }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% else %} &lt;p&gt;No teams are available.&lt;/p&gt; {% endif %} &lt;/body&gt; &lt;/html&gt; </pre> <h2 id="Comment_choisir_un_framework_web"><span style="background-color: #f5f5f5; color: rgba(0, 0, 0, 0.87); display: inline !important; float: none; font-family: &quot;Roboto&quot;,arial,sans-serif; font-size: 24px; font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration: none; text-indent: 0px; text-transform: none; white-space: pre-wrap;">Comment choisir un framework web</span></h2> <p>Il existe de nombreux frameworks web pour presque tous les langages de programmation que vous souhaitez utiliser (nous énumérons quelques-uns des frameworks les plus populaires dans la section suivante). Avec autant de choix, il peut devenir difficile de déterminer quel framework constitue le meilleur point de départ pour votre nouvelle application web.</p> <p>Certains des facteurs qui peuvent affecter votre décision sont les suivants:</p> <ul> <li><strong>Effort d&apos;apprentissage </strong>: L&apos;effort d&apos;apprentissage d&apos;un framework web dépend de votre familiarité avec le langage de programmation sous-jacent, de la cohérence de son API, de la qualité de sa documentation ainsi que de la taille et de l&apos;activité de sa communauté. Si vous avez peu d&apos;eqperience en programmation, pensez à Django (l’un des plus faciles à apprendre en fonction des critères ci-dessus). Si vous faites partie d&apos;une équipe de développement qui possède déjà une expérience significative avec un framework web ou un langage de programmation particulier, il est logique de s&apos;en tenir à cela.</li> <li><strong>Productivité </strong>: la productivité mesure la rapidité avec laquelle vous pouvez créer de nouvelles fonctionnalités une fois que vous êtes familiarisé avec le framework. Elle inclut à la fois les efforts d&apos;écriture et de maintenance du code (car vous ne pouvez pas écrire de nouvelles fonctionnalités alors que les anciennes sont endommagées). Un grand nombre des facteurs qui affectent la productivité sont similaires à ceux de &quot;Effort d&apos;apprentissage&quot; - par ex. documentation, communauté, expérience en programmation, etc. - les autres facteurs incluent: <ul> <li><em>Objectif / origine du framework </em>: certains frameworks web ont été créés à l&apos;origine pour résoudre certains types de problèmes, et restent meilleurs pour créer des applications web avec des contraintes similaires. Par exemple, Django a été créé pour soutenir le développement d&apos;un site web de journal. Il est donc bon pour les blogs et les autres sites impliquant la publication d&apos;éléments. En revanche, Flask est un cadre beaucoup plus léger et est idéal pour créer des applications web s&apos;exécutant sur des périphériques intégrés.</li> <li><em>Populaire vs Impopulaire</em>: Un framework populaire est un frameqork dans lequel il est recommandé de &quot;meilleures&quot; manières de résoudre un problème particulier. Les frameworks populaire ont tendance à être plus productifs lorsque vous essayez de résoudre des problèmes courants, car ils vous orientent dans la bonne direction, mais ils sont parfois moins flexibles.</li> <li><em>Ressource incluses vs. l&apos;obtenir vous-même </em>: certains frameworks web incluent des outils / bibliothèques qui traitent tous les problèmes que leurs développeurs peuvent penser &quot;par défaut&quot;, tandis que des frameworks plus légers attendent des développeurs web qu&apos;ils choisissent la solution aux problèmes de bibliothèques séparées (Django est un exemple inclue &quot; tout &quot; tandis que  Flask est un exemple de framework très léger). Les frameworks qui incluent tout sont souvent plus faciles à démarrer car vous avez déjà tout ce dont vous avez besoin, et il est probable qu’il soit bien intégré et bien documenté. Cependant, si une structure plus petite contient tout ce dont vous avez besoin (le cas échéant), elle peut alors s&apos;exécuter dans des environnements plus restreints et disposer d&apos;un sous-ensemble de choses plus petites et plus faciles à apprendre.</li> <li><em>Si le framework encourage ou non les bonnes pratiques de développement </em>: par exemple, un cadre qui encourage une architecture Model-View-Controller où on sépare le code en fonctions logiques engendrera un code plus facile à maintenir qu&apos;un code qui n&apos;a pas d&apos;attente de la part des développeurs. De même, la conception de la structure peut avoir un impact important sur la facilité de test et de réutilisation du code.</li> </ul> </li> <li><strong>Performances du framework/langage de programmation </strong>: généralement, la <em>vitesse</em> n’est pas le facteur le plus important dans la sélection car même des exécutions relativement lentes, comme Python, sont plus que <em>suffisantes</em> pour les sites de taille moyenne fonctionnant avec un matériel raisonnablement performant. Les avantages perçus en termes de vitesse par rapport à un autre langage comme C++ ou JavaScript peuvent être compensés par les coûts d’apprentissage et de maintenance.</li> <li><strong>Mise en cache </strong>: la popularité de votre site web grandit, vous constatez peut-être que le serveur ne peut plus gérer toutes les requêtes. À ce stade, vous pouvez envisager d’ajouter un support pour la mise en cache : une optimisation dans laquelle vous stockez tout ou partie de la réponse à une requête web afin qu&apos;il ne soit pas nécessaire de la recalculer la prochaine fois. Retourner la réponse en cache à une requête est beaucoup plus rapide que d&apos;en calculer une. La mise en cache peut être implémentée dans votre code ou sur le serveur (voir proxy inverse). Les infrastructures web auront différents niveaux de prise en charge pour définir le contenu pouvant être mis en cache.</li> <li><strong>Adpatation </strong>: votre site web connaît un succès fantastique, vous avez épuisé les avantages de la mise en cache, vous atteignez même les limites de la mise à l&apos;échelle verticale (exécuter votre application Web sur un matériel plus puissant). À ce stade, il est temps de penser à une mise à l’échelle horizontale (partager la charge en répartissant votre site sur un certain nombre de serveurs web et de bases de données) ou «géographiquement», car certains de vos clients sont très éloignés de votre serveur. L&apos;infrastructure web que vous choisissez peut faire toute la différence en termes de facilité d&apos;adaptation de votre site.</li> <li><strong>Sécurité web </strong>: certains environnements web offrent une meilleure prise en charge de la gestion des attaques web courantes. Django, par exemple, supprime toutes les entrées utilisateur des modèles HTML afin que le code JavaScript saisi par l&apos;utilisateur ne puisse pas être exécuté. D&apos;autres frameworks offrent une protection similaire, mais celle-ci n&apos;est pas toujours activée par défaut.</li> </ul> <p>Il existe de nombreux autres facteurs possibles, y compris les licences, que le cadre soit ou non en cours de développement actif, etc.</p> <p>Si vous débutez en programmation, vous choisirez probablement un framework facile à prendre en main. Une documentation riche et une communauté active sont également des critères pertinents pour votre choix. Pour la suite de ce cours, nous avons choisi Django (Python) et Express (Node/JavaScript) principalement parce que ces frameworks sont faciles à apprendre et bénéficient d&apos;un bon soutien.</p> <div class="note notecard"> <p><strong>Note</strong>: Let&apos;s go to the main websites for <a href="https://www.djangoproject.com/">Django</a> (Python) and <a href="http://expressjs.com/">Express</a> (Node/JavaScript) and check out their documentation and community.</p> <ol> <li>Navigate to the main sites (linked above) <ul> <li>Click on the Documentation menu links (named things like &quot;Documentation, Guide, API Reference, Getting Started&quot;.</li> <li>Can you see topics showing how to set up URL routing, templates, and databases/models?</li> <li>Are the documents clear?</li> </ul> </li> <li>Navigate to mailing lists for each site (accessible from Community links). <ul> <li>How many questions have been posted in the last few days</li> <li>How many have responses?</li> <li>Do they have an active community?</li> </ul> </li> </ol> </div> <h2 id="A_few_good_web_frameworks">A few good web frameworks?</h2> <p>Let&apos;s now move on, and discuss a few specific server-side web frameworks.</p> <p>The server-side frameworks below represent <em>a few </em>of the most popular available at the time of writing. All of them have everything you need to be productive — they are open source, are under active development, have enthusiastic communities creating documentation and helping users on discussion boards, and are used in large numbers of high-profile websites. There are many other great server-side frameworks that you can discover using a basic internet search.</p> <div class="note notecard"> <p><strong>Note</strong>: Descriptions come (partially) from the framework websites!</p> </div> <h3 id="Django_Python">Django (Python)</h3> <p><a href="https://www.djangoproject.com/">Django</a> is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.</p> <p>Django follows the &quot;Batteries included&quot; philosophy and provides almost everything most developers might want to do &quot;out of the box&quot;. Because everything is included, it all works together, follows consistent design principles, and has extensive and up-to-date documentation. It is also fast, secure, and very scalable. Being based on Python, Django code is easy to read and to maintain.</p> <p>Popular sites using Django (from Django home page) include: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic, Open Knowledge Foundation, Pinterest, Open Stack.</p> <h3 id="Flask_Python">Flask (Python)</h3> <p><a href="http://flask.pocoo.org/">Flask</a> is a microframework for Python.</p> <p>While minimalist, Flask can create serious websites out of the box. It contains a development server and debugger, and includes support for <a href="https://github.com/pallets/jinja">Jinja2</a> templating, secure cookies, <a href="https://en.wikipedia.org/wiki/Unit_testing">unit testing</a>, and <a href="http://www.restapitutorial.com/lessons/restfulresourcenaming.html">RESTful</a> request dispatching. It has good documentation and an active community.</p> <p>Flask has become extremely popular, particularly for developers who need to provide web services on small, resource-constrained systems (e.g. running a web server on a <a href="https://www.raspberrypi.org/">Raspberry Pi</a>, <a href="http://blogtarkin.com/drone-definitions-learning-the-drone-lingo/">Drone controllers</a>, etc.)</p> <h3 id="Express_Node.jsJavaScript">Express (Node.js/JavaScript)</h3> <p><a href="http://expressjs.com/">Express</a> is a fast, unopinionated, flexible and minimalist web framework for <a href="https://nodejs.org/en/">Node.js</a> (node is a browserless environment for running JavaScript). It provides a robust set of features for web and mobile applications and delivers useful HTTP utility methods and <a href="/en-US/docs/Glossary/Middleware">middleware</a>.</p> <p>Express is extremely popular, partially because it eases the migration of client-side JavaScript web programmers into server-side development, and partially because it is resource-efficient (the underlying node environment uses lightweight multitasking within a thread rather than spawning separate processes for every new web request).</p> <p>Because Express is a minimalist web framework it does not incorporate every component that you might want to use (for example, database access and support for users and sessions are provided through independent libraries). There are many excellent independent components, but sometimes it can be hard to work out which is the best for a particular purpose!</p> <p>Many popular server-side and full stack frameworks (comprising both server and client-side frameworks) are based on Express, including <a href="http://feathersjs.com/">Feathers</a>, <a href="https://www.itemsapi.com/">ItemsAPI</a>, <a href="http://keystonejs.com/">KeystoneJS</a>, <a href="http://krakenjs.com/">Kraken</a>, <a href="http://loopback.io/">LoopBack</a>, <a href="http://mean.io/">MEAN</a>, and <a href="http://sailsjs.org/">Sails</a>.</p> <p>A lot of high profile companies use Express, including: Uber, Accenture, IBM, etc. (a list is provided <a href="http://expressjs.com/en/resources/companies-using-express.html">here</a>).</p> <h3 id="Ruby_on_Rails_Ruby">Ruby on Rails (Ruby)</h3> <p><a href="http://rubyonrails.org/">Rails</a> (usually referred to as &quot;Ruby on Rails&quot;) is a web framework written for the Ruby programming language.</p> <p>Rails follows a very similar design philosophy to Django. Like Django it provides standard mechanisms for routing URLs, accessing data from a database, generating HTML from templates and formatting data as <a href="/fr/docs/Glossaire/JSON">JSON</a> or <a href="/fr/docs/Glossaire/XML">XML</a>. It similarly encourages the use of design patterns like DRY (&quot;dont repeat yourself&quot; — write code only once if at all possible), MVC (model-view-controller) and a number of others.</p> <p>There are of course many differences due to specific design decisions and the nature of the languages.</p> <p>Rails has been used for high profile sites, including:<strong> </strong><a href="https://basecamp.com/">Basecamp</a>, <a href="https://github.com/">GitHub</a>, <a href="https://shopify.com/">Shopify</a>, <a href="https://airbnb.com/">Airbnb</a>, <a href="https://twitch.tv/">Twitch</a>, <a href="https://soundcloud.com/">SoundCloud</a>, <a href="https://hulu.com/">Hulu</a>, <a href="https://zendesk.com/">Zendesk</a>, <a href="https://square.com/">Square</a>, <a href="https://highrisehq.com/">Highrise</a>.</p> <h3 id="Laravel_PHP">Laravel (PHP)</h3> <p><a href="https://laravel.com/">Laravel</a> is a web application framework with expressive, elegant syntax. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as:</p> <ul> <li><a href="https://laravel.com/docs/routing" rel="nofollow">Simple, fast routing engine</a>.</li> <li><a href="https://laravel.com/docs/container" rel="nofollow">Powerful dependency injection container</a>.</li> <li>Multiple back-ends for <a href="https://laravel.com/docs/session" rel="nofollow">session</a> and <a href="https://laravel.com/docs/cache" rel="nofollow">cache</a> storage.</li> <li>Expressive, intuitive <a href="https://laravel.com/docs/eloquent" rel="nofollow">database ORM</a>.</li> <li>Database agnostic <a href="https://laravel.com/docs/migrations" rel="nofollow">schema migrations</a>.</li> <li><a href="https://laravel.com/docs/queues" rel="nofollow">Robust background job processing</a>.</li> <li><a href="https://laravel.com/docs/broadcasting" rel="nofollow">Real-time event broadcasting</a>.</li> </ul> <p>Laravel is accessible, yet powerful, providing tools needed for large, robust applications.</p> <h3 id="ASP.NET">ASP.NET</h3> <p><a href="http://www.asp.net/">ASP.NET</a> is an open source web framework developed by Microsoft for building modern web applications and services. With ASP.NET you can quickly create web sites based on HTML, CSS, and JavaScript, scale them for use by millions of users and easily add more complex capabilities like Web APIs, forms over data, or real time communications.</p> <p>One of the differentiators for ASP.NET is that it is built on the <a href="https://en.wikipedia.org/wiki/Common_Language_Runtime">Common Language Runtime</a> (CLR), allowing programmers to write ASP.NET code using any supported .NET language (C#, Visual Basic, etc.). Like many Microsoft products it benefits from excellent tools (often free), an active developer community, and well-written documentation.</p> <p>ASP.NET is used by Microsoft, Xbox.com, Stack Overflow, and many others.</p> <h3 id="Mojolicious_Perl">Mojolicious (Perl)</h3> <p><a href="http://mojolicious.org/">Mojolicious</a> is a next generation web framework for the Perl programming language.</p> <p>Back in the early days of the web, many people learned Perl because of a wonderful Perl library called <a href="https://metacpan.org/module/CGI">CGI</a>. It was simple enough to get started without knowing much about the language and powerful enough to keep you going. Mojolicious implements this idea using bleeding edge technologies.</p> <p>Some of the features provided by Mojolicious are: <strong>Real-time web framework</strong>, to easily grow single file prototypes into well-structured MVC web applications; RESTful routes, plugins, commands, Perl-ish templates, content negotiation, session management, form validation, testing framework, static file server, CGI/<a href="http://plackperl.org">PSGI</a> detection, first class Unicode support; Full stack HTTP and WebSocket client/server implementation with IPv6, TLS, SNI, IDNA, HTTP/SOCKS5 proxy, UNIX domain socket, Comet (long polling), keep-alive, connection pooling, timeout, cookie, multipart and gzip compression support; JSON and HTML/XML parsers and generators with CSS selector support; Very clean, portable and object-oriented pure-Perl API with no hidden magic; Fresh code based upon years of experience, free and open source.</p> <h2 id="Summary">Summary</h2> <p>This article has shown that web frameworks can make it easier to develop and maintain server-side code. It has also provided a high level overview of a few popular frameworks, and discussed criteria for choosing a web application framework. You should now have at least an idea of how to choose a web framework for your own server-side development. If not, then don&apos;t worry — later on in the course we&apos;ll give you detailed tutorials on Django and Express to give you some experience of actually working with a web framework.</p> <p>For the next article in this module we&apos;ll change direction slightly and consider web security.</p> <div class="prevnext"> <a href="/fr/docs/Learn/Server-side/First_steps/Client-Server_overview" class="button"><i class="icon-arrow-left"></i><span class="label"> Précédent </span></a><a href="/fr/docs/Learn/Server-side/First_steps" class="button"><i class="icon-arrow-up"></i> Aperçu : First steps</a><a href="/fr/docs/Learn/Server-side/First_steps/Website_security" class="button"><span class="label"> Suivant </span><i class="icon-arrow-right"></i></a> </div> <h2 id="In_this_module">In this module</h2> <ul> <li><a href="/en-US/docs/Learn/Server-side/First_steps/Introduction">Introduction to the server side</a></li> <li><a href="/en-US/docs/Learn/Server-side/First_steps/Client-Server_overview">Client-Server overview</a></li> <li><a href="/en-US/docs/Learn/Server-side/First_steps/Web_frameworks">Server-side web frameworks</a></li> <li><a href="/en-US/docs/Learn/Server-side/First_steps/Website_security">Website security</a></li> </ul>
% FloatShield grey-box identification procedure % % Identification of a first-principles based grey-box model using experimental data. % % This code is part of the AutomationShield hardware and software % ecosystem. Visit http://www.automationshield.com for more % details. This code is licensed under a Creative Commons % Attribution-NonCommercial 4.0 International License. % % Created by Martin Gulan, Gergely Takacs and Peter Chmurciak. startScript; % Clears screen and variables, except allows CI testing %% Data preprocessing load APRBS_R4_2.mat % Read identificaiton results Ts = 0.025; % Sampling period data = iddata(y, u, Ts, 'Name', 'Experiment'); % Create identification data object data = data(600:2000); % Select a relatively stable segment datand=data; data = detrend(data); % Remove offset and linear trends data.InputName = 'Fan Power'; % Input name data.InputUnit = '%'; % Input unit data.OutputName = 'Ball Position'; % Output name data.OutputUnit = 'mm'; % Output unit data.Tstart = 0; % Starting time data.TimeUnit = 's'; % Time unit %% Initial guess of model parameters m = 0.003; % [kg] Weight of the ball r = 0.015; % [m] Radius of the ball cd = 0.47; % [-] Drag coefficient ro = 1.23; % [kg/m3] Density of air % A = pi*r^2; % [m2] Exposed area of the ball; circle's... A = 2 * pi * r^2; % ...or half of a sphere's area g = 9.81; % [m/s2] Gravitataional acceleration vEq = sqrt(m*g/(0.5 * cd * ro * A)); % [m/s] Theoretical equilibrium air velocity k = 7.78; % Fan's gain tau = vEq / (2 * g); % Fan's time constant tau2 = 0.6; % Ball's time constant h0 = data.y(1, 1); % Initial ball position estimate dh0 = (data.y(2, 1) - data.y(1, 1)) / Ts; % Initial ball velocity estimate v0 = 0; % Initial airspeed estimate %% Choose the type of grey-box model to identify % model = 'nonlinear'; % Nonlinear state-space model model = 'linearSS'; % Linear state-space model % model = 'linearTF'; % Linear transfer function switch model case 'nonlinear' % Model structure FileName = 'FloatShield_ODE'; % File describing the model structure Order = [1, 1, 3]; % Model orders [ny nu nx] Parameters = [m; cd; ro; A; g; k; tau]; % Initial values of parameters InitialStates = [h0; dh0; v0]; % Initial values of states Ts = 0; % Time-continuous system % Set identification options nlgr = idnlgrey(FileName, Order, Parameters, InitialStates, Ts, 'Name', 'Nonlinear Grey-box Model'); set(nlgr, 'InputName', 'Fan Power', 'InputUnit', '%', 'OutputName', 'Ball Position', 'OutputUnit', 'mm', 'TimeUnit', 's'); nlgr = setpar(nlgr, 'Name', {'Ball Mass', 'Drag Coefficient', 'Air Density', 'Exposed Area', ... 'Gravitational Acceleration', 'Fan Gain', 'Fan Time Constant'}); nlgr = setinit(nlgr, 'Name', {'Ball Position', 'Ball Speed', 'Air Speed'}); % nlgr.Parameters(1).Minimum = 0.0035; % nlgr.Parameters(1).Maximum = 0.004; nlgr.Parameters(1).Fixed = true; nlgr.Parameters(2).Minimum = 0.3; nlgr.Parameters(2).Maximum = 1.0; % nlgr.Parameters(3).Minimum = 1.0; nlgr.Parameters(3).Fixed = true; % nlgr.Parameters(4).Minimum = 0.0028; % nlgr.Parameters(4).Maximum = 0.0057; nlgr.Parameters(4).Fixed = true; nlgr.Parameters(5).Fixed = true; nlgr.Parameters(6).Minimum = 0; nlgr.Parameters(7).Minimum = 0; nlgr.InitialStates(3).Fixed = false; size(nlgr) % Identify model opt = nlgreyestOptions('Display', 'on', 'EstCovar', true, 'SearchMethod', 'Auto'); %gna opt.SearchOption.MaxIter = 50; % Maximal number of iterations model = nlgreyest(data, nlgr, opt); % Run identification procedure % Save results save FloatShield_GreyboxModel_Nonlinear.mat model case 'linearSS' % Unknown parameters alpha = 1/tau; beta = 1/tau2; gamma = k/tau; % Model structure A = [0 1 0; % State-transition matrix 0 -alpha alpha; 0 0 -beta]; B = [ 0; 0; gamma]; % Input matrix C = [1 0 0]; % Output matrix D = 0; % No direct feed-through K = zeros(3,1); % Disturbance K(2) = 25; % State noise x0 = [h0; dh0; v0]; % Initial condition disp('Initial guess:') sys = idss(A,B,C,D,K,x0,0) % Construct state-space representation % Mark the free parameters sys.Structure.A.Free = [0 0 0; % Free and fixed variables 0 1 1; 0 0 1]; sys.Structure.B.Free = [0 1 0]'; % Free and fixed variables sys.Structure.C.Free = false; % No free parameters sys.DisturbanceModel = 'estimate'; % Estimate disturbance model sys.InitialState = 'estimate'; % Estimate initial states % Set identification options Options = ssestOptions; % State-space estimation options Options.Display = 'on'; % Show progress Options.Focus = 'simulation'; % Focus on simulation % 'stability' Options.InitialState = 'estimate'; % Estimate initial condition Options.SearchMethod = 'lsqnonlin'; % 'auto'/'gn'/'gna'/'lm'/'grad'/'lsqnonlin'/'fmincon' % Identify model model = ssest(data,sys,Options); % Run estimation procedure % Save results save FloatShield_GreyboxModel_LinearSS.mat model case 'linearTF' % Model structure model = idproc('P2I'); % Second order with integrator model.Structure.Kp.Value = k; % Initial gain model.Structure.Kp.Maximum = 10; % Maximal gain model.Structure.Kp.Minimum = 5; % Minimal gain model.Structure.Tp1.Value = tau; % Initial time constant %model.Structure.Tp1.Maximum=0.5; % Maximal time constant model.Structure.Tp1.Minimum = 0; % Minimal time constant model.Structure.Tp2.Value = tau2; % Initial time constant %model.Structure.Tp2.Maximum=0.9; % Maximal time constant model.Structure.Tp2.Minimum = 0; % Minimal time constant % Set identification options Opt = procestOptions; % Estimation options Opt.InitialCondition = 'estimate'; % Estimate the initial condition Opt.DisturbanceModel = 'ARMA2'; % Define noise model Opt.Focus = 'stability'; % Goal is to create a stable model Opt.Display = 'full'; % Full estimation output % Identify model model = procest(data, model, Opt); % Estimate a process model % Save results save FloatShield_GreyboxModel_LinearTF.mat model end compare(datand, model); % Compare data to model model % List model parameters grid on % Turn on grid return
""" Import libraries """ import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec """ Define functions """ # Use trapezoid rule to integrate a function numerically from a to b def integrate(X, Y): N = len(Y) deltax = (X[-1] - X[0])/N return (Y[0] + Y[N-1] + 2*np.sum(Y[1:N-2])) * deltax / 2 # Determine coefficients of Fourier series by numerical integration def fourier(X, Y, N): a, b = [], [] deltax = X[-1] - X[0] for n in range(N): a.append((2/deltax)*integrate(X, Y*np.cos(2*np.pi*n*X/deltax))) b.append((2/deltax)*integrate(X, Y*np.sin(2*np.pi*n*X/deltax))) return a, b def f(x, a, b): period = x[-1] - x[0] func = a[0]/2 * np.ones_like(x) for i in range(1, len(a)): func += a[i] * np.cos(2*np.pi*i*x/period) + b[i] * np.sin(2*np.pi*i*x/period) return func """ Main body """ # Import given wavedata from file and split into X and Y components wavedata = np.loadtxt("wavedata.csv", delimiter = ",") X, Y = wavedata[:, 0], wavedata[:, 1] # Calculate Fourier coefficients up to 5 and up to 10 a5, b5 = fourier(X, Y, 5) a10, b10 = fourier(X, Y, 10) # Input calculated a and b coefficients to obtain Fourier expansion of wave data fourier5 = f(X, a5, b5) fourier10 = f(X, a10, b10) """ Plotting and formatting """ fig = plt.figure(figsize = (15, 9)) gs = gridspec.GridSpec(ncols = 2, nrows = 2, figure = fig) ax1 = fig.add_subplot(gs[0, 0], ylim = (min(a10 + b10) - 1, max(a10 + b10) + 1), xlabel = '${n}$', ylabel = 'Magnitude of corresponding cos term; ${a_n}$', title = r'Magnitude of coefficients of ${\cos\left(\frac{2nπx}{Period}\right)}$ up to ${n=10}$') ax2 = fig.add_subplot(gs[0, 1], ylim = (min(a10 + b10) - 1, max(a10 + b10) + 1), xlabel = '${n}$', ylabel = 'Magnitude of corresponding sin term; ${b_n}$', title = r'Magnitude of coefficients of ${\sin\left(\frac{2nπx}{Period}\right)}$ up to ${n=10}$') ax3 = fig.add_subplot(gs[1, 0], xlabel = 'x', ylabel = 'y', title = 'Fourier reconstruction with terms up to ${n = 5}$') ax4 = fig.add_subplot(gs[1, 1], xlabel = 'x', ylabel = 'y', title = 'Fourier reconstruction with terms up to ${n = 10}$') ax1.bar(np.arange(0, 11, 1), a10 + [0]) ax2.bar(np.arange(0, 11, 1), b10 + [0]) ax3.plot(X, Y, label = 'Plot of input data') ax3.plot(X, fourier5, label = 'Fourier approximation') ax3.legend() ax4.plot(X, Y, label = 'Plot of input data') ax4.plot(X, fourier10, label = 'Fourier approximation') ax4.legend() plt.savefig('fourier.png', dpi = 600) plt.show()
$(document).ready(function(){ $(window).scroll(function(){ /* sticky navbar on scroll script */ if(this.scrollY > 20){ $('.navbar').addClass("sticky"); }else{ $('.navbar').removeClass("sticky"); } /* scroll-up button show/hide script */ if(this.scrollY > 500){ $('.scroll-up-btn').addClass("show"); }else{ $('.scroll-up-btn').removeClass("show"); } }); /* slide-up script */ $('.scroll-up-btn').click(function(){ $('html').animate({scrollTop: 0}); /* removing smooth scroll on slide-up button click */ $('html').css("scrollBehavior", "auto"); }); $('.navbar .menu li a').click(function(){ /* applying again smooth scroll on menu items click */ $('html').css("scrollBehavior", "smooth"); }); /* toggle menu/navbar script */ $('.menu-btn').click(function(){ $('.navbar .menu').toggleClass("active"); $('.menu-btn i').toggleClass("active"); }); /* typing text animation script */ var typed = new Typed(".typing", { strings: ["_ROUND THE CLOCK", "-ROUND THE YEAR", "-ACROSS INDIA"], typeSpeed: 100, backSpeed: 60, loop: true }); var typed = new Typed(".typing-2", { strings: [" is a leading transportation and logistics company with over 15 years of experience. They offer a wide range of services, including road transportation, export consulting, and warehouse rental. Seacon Road Carriers is committed to providing their customers with the highest quality of service at competitive prices."], typeSpeed: 50, backSpeed: 60, loop: false }); /* owl carousel script */ $('.carousel').owlCarousel({ margin: 20, loop: true, autoplay: true, autoplayTimeOut: 2000, autoplayHoverPause: true, responsive: { 0:{ items: 1, nav: false }, 600:{ items: 2, nav: false }, 1000:{ items: 3, nav: false } } }); }); /* Scroll Reveal */ window.addEventListener('scroll', reveal); function reveal(){ var reveals = document.querySelectorAll('.reveal'); for(var i = 0; i < reveals.length; i++){ var windowheight = window.innerHeight; var revealtop = reveals[i].getBoundingClientRect().top; var revealpoint = 100; if(revealtop < windowheight - revealpoint){ reveals[i].classList.add('active'); } else{ reveals[i].classList.remove('active'); } } }
import { Fragment } from 'react' import { Box } from '@intouchg/components' import { ApiTableTitle, ApiTableCell } from './ApiTable' import styleApi from '@/content/apis/style' import { Code } from './Code' const StyleApiTable = ({ themeProperty, ...props }) => ( <Box as="table" width="100%" fontSize={1} marginBottom={6} style={{ borderCollapse: 'collapse' }} {...props} > <Box as="thead" textAlign="left"> <tr> <ApiTableTitle width="260px">Component Prop</ApiTableTitle> <ApiTableTitle width="300px">CSS Property</ApiTableTitle> <ApiTableTitle>Theme Key</ApiTableTitle> </tr> </Box> <Box as="tbody"> {Object.entries(styleApi[themeProperty]).map( ([cssProperty, { componentProps, themeKey }]) => ( <tr key={cssProperty}> <ApiTableCell> {componentProps.map((prop, index) => ( <Fragment key={prop}> <Code>{prop}</Code> {index !== componentProps.length - 1 && ', '} </Fragment> ))} </ApiTableCell> <ApiTableCell>{cssProperty}</ApiTableCell> <ApiTableCell> {themeKey && <Code>{themeKey}</Code>} </ApiTableCell> </tr> ) )} </Box> </Box> ) export { StyleApiTable }
-- luasnip setup local luasnip = require 'luasnip' -- nvim-cmp supports additional completion capabilities local capabilities = vim.lsp.protocol.make_client_capabilities() vim.o.completeopt = 'menuone,noselect' -- Setup nvim-cmp. local cmp = require'cmp' local kind_icons = { Text = "", Method = "", Function = "", Constructor = "", Field = "ﰠ", Variable = "", Class = "", Interface = "", Module = "", Property = "", Unit = "", Value = "", Enum = "", Keyword = "", Snippet = "", Color = "", File = "", Reference = "", Folder = "", EnumMember = "", Constant = "", Struct = "פּ", Event = "", Operator = "", TypeParameter = "", } cmp.setup({ preselect = cmp.PreselectMode.None, formatting = { format = function(entry, vim_item) vim_item.kind = string.format("%s", kind_icons[vim_item.kind]) -- vim_item.menu = ({ -- nvim_lsp = '[LSP]', -- buffer = '[Buf]', -- })[entry.source.name] return vim_item end, }, experimental = { ghost_text = false, }, snippet = { expand = function(args) require('luasnip').lsp_expand(args.body) -- For `luasnip` users. end, }, duplicates = { nvim_lsp = 1, luasnip = 1, buffer = 1, path = 1, }, window = { completion = cmp.config.window.bordered(), documentation = cmp.config.window.bordered(), }, mapping = { ['<C-p>'] = cmp.mapping.select_prev_item(), ['<C-n>'] = cmp.mapping.select_next_item(), ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.close(), ['<CR>'] = cmp.mapping.confirm { behavior = cmp.ConfirmBehavior.Replace, select = false, }, ['<Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expandable() then luasnip.expand() elseif luasnip.expand_or_locally_jumpable() then luasnip.expand_or_jump() else fallback() end end, { "i", "s", }), ['<S-Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jump(-1) else fallback() end end, { "i", "s", })}, sources = cmp.config.sources({ { name = 'nvim_lsp' }, { name = 'luasnip' }, -- For luasnip users. }, { { name = 'buffer' }, }) }) -- Set configuration for specific filetype. cmp.setup.filetype('gitcommit', { sources = cmp.config.sources({ { name = 'cmp_git' }, -- You can specify the `cmp_git` source if you were installed it. }, { { name = 'buffer' }, }) }) -- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline('/', { mapping = cmp.mapping.preset.cmdline(), sources = { { name = 'buffer' } } }) -- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline(':', { mapping = cmp.mapping.preset.cmdline(), sources = cmp.config.sources({ { name = 'path' } }, { { name = 'cmdline' } }) }) -- Setup lspconfig. local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()) -- Replace <YOUR_LSP_SERVER> with each lsp server you've enabled. require('lspconfig')[ 'pyright' ].setup { capabilities = capabilities }
<!-- 5 блочных тегов: <p>, <div>, <form>, <nav>, <ul> - можно создавать структуру веб-страницы 5 семантических тегов: <em>, <small>, <strong>, <s>, <cite> - форматирования текстовых фрагментов 5 одиночный тегов: <br>, <hr>, <img>, <source>, <area> - оперируют с одиночными объектами --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Название веб-страницы</title> </head> <body> <!-- блок с идентичным оформлением, используя для визуализации только теги --> <a href="https://www.google.com/">Белая</a> <strong>береза</strong><br> <em>Под моим окном</em><br> <strong><em>Принакрылась снегом,</em></strong><br> <mark>Точно серебром.</mark><br> <!-- упорядоченный список --> <ol> <li><strong>one</strong></li> <li><em>two</em></li> <li><u>three</u></li> <li><a class="google-link" id="mainlink" href="https://www.google.com/" target="_blank">four</a></li> <li style="color: #ff0000">five</li> </ol> <!-- форма --> <form action="#"> <fieldset> <legend>Contact form</legend> <div> <label>First Name</label> <input type="text"><br> </div> <div> <label>Last Name</label> <input type="text"><br> </div> <div> <label>Password</label> <input type="password"><br> </div> <div> <label>Email</label> <input type="email"><br> <div> <label>Country</label> <select> <option>Ukraine</option> <option>Russia</option> </select><br> </div> <div> <label>Do you know html and css?</label> <label><input name="y/n" type="radio">YES</label> <label><input name="y/n" type="radio">NO</label><br> </div> <input type="submit" value="SUBMIT"> </fieldset> </form> </body> </html>
#pragma once #include "Graphics/GPU/GPUInterface.hpp" /* - none: (default) local read/write memory, or input parameter - const: global compile-time constant, or read-only function parameter, or read-only local variable - in: linkage into shader from previous stage - out: linkage out of a shader to next stage - attribute: same as in for vertex shader - uniform: linkage between a shader, OpenGL, and the application - varying: same as in for vertex shader, same as out for fragment shader */ DECLARE_ENUM(GPUStorage, NONE, "none", IN, "in", OUT, "out", VARYING, "varying", ATTRIBUTE, "attribute", CONST, "const", UNIFORM, "uniform" ); enum class GPUPrimitiveType : u32 { INT = GL_INT, FLOAT = GL_FLOAT, BOOL = GL_BOOL, }; class GPUDataType { public: std::string mName; u32 mTypeSizeInBytes; GPUPrimitiveType mPrimitiveType = GPUPrimitiveType::FLOAT; u32 getPrimitiveTypeSizeInBytes() { u32 primitiveTypeSize = 0; switch (mPrimitiveType) { case GPUPrimitiveType::FLOAT: primitiveTypeSize = sizeof(f32); break; case GPUPrimitiveType::INT: primitiveTypeSize = sizeof(i32); break; case GPUPrimitiveType::BOOL: primitiveTypeSize = sizeof(bool); break; } return primitiveTypeSize; } u32 getSizePrimitiveType() { u32 primitiveTypeSizeInBytes = getPrimitiveTypeSizeInBytes(); u32 sizeInPrimitiveTypes = mTypeSizeInBytes/primitiveTypeSizeInBytes; return sizeInPrimitiveTypes; } }; class GPUVariableData { public: GPUVariableData() = default; GPUVariableData(GPUStorage gpuStorage, const GPUDataType& gpuDataType, const std::string& name): mGPUStorage(gpuStorage), mGPUDataType(gpuDataType), mName(name) {} GPUVariableData(GPUStorage gpuStorage, const GPUVariableData& otherGPUVariableData): mGPUStorage(gpuStorage), mGPUDataType(otherGPUVariableData.mGPUDataType), mName(otherGPUVariableData.mName) {} GPUStorage mGPUStorage = GPUStorage::NONE; GPUDataType mGPUDataType; std::string mName; }; class GPUVariableDefinitionData: public GPUVariableData { public: GPUVariableDefinitionData() = default; GPUVariableDefinitionData(GPUStorage gpuStorage, const GPUDataType& gpuDataType, const std::string& name): GPUVariableData(gpuStorage, gpuDataType, name) {} GPUVariableDefinitionData(const GPUVariableData& gpuVariableData): GPUVariableData(gpuVariableData) {} GPUVariableDefinitionData(const GPUVariableData& gpuVariableData, const std::string& value): GPUVariableData(gpuVariableData), mValue(value) {} GPUVariableDefinitionData(const GPUVariableData& gpuVariableData, const std::string& value, const std::string& arraySize): GPUVariableData(gpuVariableData), mValue(value), mArraySize(arraySize) {} GPUVariableDefinitionData(GPUStorage gpuStorage, const GPUVariableData& gpuVariableData): GPUVariableData(gpuStorage, gpuVariableData) {} std::string mValue; std::string mArraySize; };
package watcher import ( "context" "time" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/log" "github.com/kroma-network/kroma/bindings/bindings" ) type ContractWatcher struct { ctx context.Context backend *ethclient.Client log log.Logger } func NewContractWatcher(ctx context.Context, backend *ethclient.Client, l log.Logger) ContractWatcher { return ContractWatcher{ ctx: ctx, backend: backend, log: l, } } func (cw ContractWatcher) WatchUpgraded(address common.Address, handlerFn func() error) error { proxy, err := bindings.NewProxy(address, cw.backend) if err != nil { return err } err = handlerFn() if err != nil { return err } opts := &bind.WatchOpts{Context: cw.ctx} upgradedCh := make(chan *bindings.ProxyUpgraded) sub := event.ResubscribeErr(time.Second*10, func(ctx context.Context, err error) (event.Subscription, error) { if err != nil { cw.log.Warn("resubscribe contract upgraded event", "err", err) } return proxy.WatchUpgraded(opts, upgradedCh, nil) }) go func() { for { select { case evt := <-upgradedCh: cw.log.Info("received contract upgraded event", "address", address) err := handlerFn() if err != nil { cw.log.Error("failed to update config", "err", err) <-time.After(time.Second) upgradedCh <- evt continue } cw.log.Info("config updated") case <-cw.ctx.Done(): sub.Unsubscribe() close(upgradedCh) return } } }() return nil }
-- creating a stored procedure in MySQL that accepts a year as input and checks whether it is a leap year. DELIMITER $$ CREATE PROCEDURE IsLeapYear(IN year INT) BEGIN DECLARE leapYear BOOLEAN; SET leapYear = FALSE; IF year MOD 4 = 0 THEN IF year MOD 100 = 0 THEN IF year MOD 400 = 0 THEN SET leapYear = TRUE; END IF; ELSE SET leapYear = TRUE; END IF; END IF; IF leapYear = TRUE THEN SELECT year, ' is a leap year.' AS result; ELSE SELECT year, ' is not a leap year.' AS result; END IF; END$$ DELIMITER ; -- calling the stored procedure by using the following code: CALL IsLeapYear(2000); CALL IsLeapYear(2005);
#include <stdio.h> #include <stdbool.h> #include <cstring> // Include for strlen bool validate_string(char *str) { if (*str == '\0') { return true; // Empty string (e) is valid } // Check for production S -> 0S1 if (*str == '0') { int len = strlen(str); if (len > 1 && str[len - 1] == '1') { // Ensure length > 1 and ends with 1 return validate_string(str + 1); // Recursively check the middle part } } // String doesn't follow any production rule return false; } int main() { char str[100]; printf("Enter a string (must start with 0 and end with 1): "); scanf("%s", str); if (validate_string(str)) { printf("String belongs to the language.\n"); } else { printf("String does not belong to the language.\n"); } return 0; }
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 include "../HKDF/HMAC.dfy" include "../Digest.dfy" include "../../Model/AwsCryptographyPrimitivesTypes.dfy" /* * Implementation of the https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-108r1.pdf * Key Derivation in Counter Mode Using Pseudorandom Functions */ module KdfCtr { import opened StandardLibrary import opened Wrappers import opened UInt = StandardLibrary.UInt import UTF8 import Types = AwsCryptographyPrimitivesTypes import HMAC import Digest const SEPARATION_INDICATOR: seq<uint8> := [0x00] const COUNTER_START_VALUE: uint32 := 1 // This implementation of te spec is restricted to only deriving // 32 bytes of key material. We will have to consider the effect of allowing different // key length to the hierarchy keyring. method KdfCounterMode(input: Types.KdfCtrInput) returns (output: Result<seq<uint8>, Types.Error>) ensures output.Success? ==> |output.value| == input.expectedLength as nat { :- Need( // Although KDF can support multiple digests; for our use case we only want // to use SHA 256; we may rethink this if we ever want to support other algorithms // We are requiring the requested length to be 32 bytes since this is only used for the hierarchy // keyring it requires to derive a 32 byte key. && input.digestAlgorithm == Types.DigestAlgorithm.SHA_256 && |input.ikm| == 32 && input.nonce.Some? && |input.nonce.value| == 16 && input.expectedLength == 32 && 0 < ((input.expectedLength as int) * 8) as int < INT32_MAX_LIMIT, Types.AwsCryptographicPrimitivesError(message := "Kdf in Counter Mode input is invalid.") ); var ikm := input.ikm; var label_ := input.purpose.UnwrapOr([]); var info := input.nonce.UnwrapOr([]); var okm := []; // Compute length in bits of the input going into the PRF. var internalLength : uint32 := (4 + |SEPARATION_INDICATOR| + 4) as uint32; :- Need( && internalLength as int + |label_| + |info| < INT32_MAX_LIMIT, Types.AwsCryptographicPrimitivesError(message:= "Input Length exceeds INT32_MAX_LIMIT") ); // Compute length in bits of the output from the PRF. "L" in SP800-108. var lengthBits : seq<uint8> := UInt.UInt32ToSeq((input.expectedLength * 8) as uint32); var explicitInfo := label_ + SEPARATION_INDICATOR + info + lengthBits; :- Need( 4 + |explicitInfo| < INT32_MAX_LIMIT, Types.AwsCryptographicPrimitivesError(message := "PRF input length exceeds INT32_MAX_LIMIT.") ); okm :- RawDerive(ikm, explicitInfo, input.expectedLength, 0); return Success(okm); } method RawDerive(ikm: seq<uint8>, explicitInfo: seq<uint8>, length: int32, offset: int32) returns (output: Result<seq<uint8>, Types.Error>) requires && |ikm| == 32 && length == 32 && 4 + |explicitInfo| < INT32_MAX_LIMIT && length as int + Digest.Length(Types.DigestAlgorithm.SHA_256) < INT32_MAX_LIMIT - 1 ensures output.Success? ==> |output.value| == length as int { // We will only support HMAC_SHA256, so no need to support additional Digests var derivationMac := Types.DigestAlgorithm.SHA_256; var hmac :- HMAC.HMac.Build(derivationMac); hmac.Init(key := ikm); var macLengthBytes := Digest.Length(derivationMac) as int32; // "h" in SP800-108 // Number of iterations required to compose output of required length. var iterations := (length + macLengthBytes - 1) / macLengthBytes; // "n" in SP800-108 var buffer := []; // Counter "i" var i : seq<uint8> := UInt.UInt32ToSeq(COUNTER_START_VALUE); for iteration := 1 to iterations + 1 invariant |i| == 4 invariant hmac.GetKey() == ikm { /* * SP800-108 defines PRF(s,x), the "x" variable is prfInput below. */ // i || label || 0x00 || context (info) || L hmac.Update(i); hmac.Update(explicitInfo); var tmp := hmac.GetResult(); buffer := buffer + tmp; i :- Increment(i); } :- Need( |buffer| >= length as int, Types.AwsCryptographicPrimitivesError(message := "Failed to derive key of requested length") ); return Success(buffer[..length]); } function method Increment(x : seq<uint8>) : (ret : Result<seq<uint8>, Types.Error>) requires |x| == 4 ensures ret.Success? ==> |ret.value| == 4 { // increments the counter x which represents the number of iterations // as a bit sequence if x[3] < 255 then Success([x[0], x[1], x[2], x[3]+1]) else if x[2] < 255 then Success([x[0], x[1], x[2]+1, 0]) else if x[1] < 255 then Success([x[0], x[1]+1, 0, 0]) else if x[0] < 255 then Success([x[0]+1, 0, 0, 0]) else Failure(Types.AwsCryptographicPrimitivesError(message := "Unable to derive key material; may have exceeded limit.")) } }
/** * https://adventofcode.com/2020/day/11 */ import {multiLine} from '../../common/parser.mjs'; // Parse Input let inputFilePath = new URL('./input.txt', import.meta.url); const arrInput = multiLine.toArrayofStrArrays(inputFilePath); // Maybe this isn't needed, but surround the whole thing with floor // Honestly, this might make things a bit confusing when debugging. Shrug. arrInput.unshift(floorRow()); arrInput.push(floorRow()); arrInput.forEach(r => { r.unshift('.'); r.push('.'); }); /** * x ---> * y ###### * | ###### * v ###### * */ const adjacentTransform = [ //{y, x} {y: -1, x: -1}, {y: -1, x: 0}, {y: -1, x: 1}, {y: 0, x: -1}, {y: 0, x: 1}, {y: 1, x: -1}, {y: 1, x: 0}, {y: 1, x: 1}, ]; let seats = JSON.parse(JSON.stringify(arrInput)); let changed; let rounds = 0; let MAX_OCCUPIED = 4; do { rounds++; changed = false; seats = nextState(seats); } while (changed); console.log(`Year 2020 Day 11 Part 1 Solution: ${countOccupied(seats)}`); // Create a map of first visible seats const visibleSeats = new Map(); mapSeatsToFirstVisibleSeats(); // Reset the seats seats = JSON.parse(JSON.stringify(arrInput)); rounds = 0; MAX_OCCUPIED = 5; do { rounds++; changed = false; seats = nextState(seats, true); } while (changed); console.log(`Year 2020 Day 11 Part 2 Solution: ${countOccupied(seats)}`); // Adding bool "useNextVisibleForAdjacent" for Part 2 function nextState(_seats, useNextVisibleForAdjacent) { const nextSeats = JSON.parse(JSON.stringify(_seats)); for (let y = 0; y < _seats.length; y++) { const row = _seats[y]; for (let x = 0; x < row.length; x++) { const seat = _seats[y][x]; const nextSeat = nextSeatState(y, x, useNextVisibleForAdjacent); if (seat !== nextSeat) changed = true; nextSeats[y][x] = nextSeat; } } return nextSeats; } // Adding bool "useNextVisibleForAdjacent" for Part 2 function nextSeatState(y, x, useNextVisibleForAdjacent) { if (seats[y][x] === '.') return '.'; // floor let adjacentSeatCoors; if (useNextVisibleForAdjacent) { adjacentSeatCoors = visibleSeats.get(JSON.stringify({y, x})); } else { adjacentSeatCoors = adjacentTransform.map(t => { return {y: y + t.y, x: x + t.x}; }); } const adjacentSeatStates = adjacentSeatCoors.map(c => { return seats[c.y][c.x]; }); const occupiedCount = adjacentSeatStates.reduce((prev, curr) => { return curr === '#' ? prev + 1 : prev; }, 0); if (seats[y][x] === 'L') { if (occupiedCount === 0) return '#'; return 'L'; } else { // assume # if (occupiedCount >= MAX_OCCUPIED) return 'L'; return '#'; } } function floorRow() { return new Array(arrInput[0].length).fill('.'); } function countOccupied(_seats) { let occupied = 0; for (let y = 0; y < _seats.length; y++) { const row = _seats[y]; for (let x = 0; x < row.length; x++) { if (_seats[y][x] === '#') occupied++; } } return occupied; } // Returns an array of all the first seats visible from a given seat function firstSeatsVisible(y, x) { let visibleSeats = []; if (arrInput[y][x] === '.') return visibleSeats; const seatTEST = seats[y][x]; adjacentTransform.forEach(transform => { let seatVisibleFound = false; let seatTestIndexX = x; let seatTestIndexY = y; let seatTestIndexIsValid = true; function seatIndexValid(_y, _x) { return _y >= 0 && _y < arrInput.length && _x >= 0 && _x < arrInput[0].length; } // apply the transform until a seat is found while (!seatVisibleFound && seatTestIndexIsValid) { //apply transform seatTestIndexX += transform.x; seatTestIndexY += transform.y; seatTestIndexIsValid = seatIndexValid(seatTestIndexY, seatTestIndexX); if (!seatTestIndexIsValid) break; seatVisibleFound = seats[seatTestIndexY][seatTestIndexX] !== '.'; } if (seatVisibleFound) visibleSeats.push({y: seatTestIndexY, x: seatTestIndexX}); }); return visibleSeats; } function mapSeatsToFirstVisibleSeats() { for (let y = 0; y < seats.length; y++) { const row = seats[y]; for (let x = 0; x < row.length; x++) { // Fun fact: You can't use objects as map keys. Boo. visibleSeats.set(JSON.stringify({y, x}), firstSeatsVisible(y, x)); } } } // End Process (gracefully) process.exit(0);
import { TodoActionTypes } from '../actions/todo.actions'; import { TodoTask } from '../models/todo-task.model'; export interface TodoState { list: TodoTask[]; loading: boolean; error: Error; } const initialState: TodoState = { list: [], loading: false, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion error: undefined!, }; export function TodoReducer(state: TodoState = initialState, action: any) { switch (action.type) { case TodoActionTypes.LOAD_ITEM: return { ...state, loading: true, }; case TodoActionTypes.LOAD_ITEM_SUCCESS: return { ...state, list: action.payload, loading: false, }; case TodoActionTypes.LOAD_ITEM_FAILURE: return { ...state, error: action.payload, loading: false, }; case TodoActionTypes.ADD_ITEM: return { ...state, loading: true, }; case TodoActionTypes.ADD_ITEM_SUCCESS: return { ...state, list: [...state.list, { todo: action.payload }], loading: false, }; case TodoActionTypes.ADD_ITEM_FAILURE: return { ...state, error: action.payload, loading: false, }; case TodoActionTypes.DELETE_ITEM: return { ...state, loading: true, }; case TodoActionTypes.DELETE_ITEM_SUCESS: return { ...state, list: state.list.filter((item) => item.id !== action.payload), loading: false, }; case TodoActionTypes.DELETE_ITEM_FAILURE: return { ...state, error: action.payload, loading: false, }; default: return state; } }
"""Contains basic ui elements""" # pylint: disable=R0903 # pylint: disable=R0902 ###### Python Built-in Packages ###### ###### Type Hinting ###### ###### Python Packages ###### ###### My Packages ###### from pyengine.libs.designer.py_base import PyBase from pyengine.libs.designer.py_attributes import Rectangle, Text from pyengine.libs.eventer.eventer import Eventer class PyRect(PyBase, Rectangle, Text): """Define a basic rect shape""" def __init__(self, attributes: dict) -> None: """ Init a new Rect object Attributes: attributes: contains all the rect element data """ PyBase.__init__(self, attributes.get("base_data")) Rectangle.__init__(self, attributes.get("rect_data")) Text.__init__(self, attributes.get("text_data"), self.rect) obj_data = attributes.get("obj_data") self.color = obj_data.get("color") self.opacity = obj_data.get("opacity") class PyCircle(PyBase, Rectangle, Text): """Define a basic circle shape""" def __init__(self, attributes: dict) -> None: """ Init a new circle element object Attributes: attributes: contains all the circle data """ PyBase.__init__(self, attributes.get("base_data")) Rectangle.__init__(self, attributes.get("rect_data")) Text.__init__(self, attributes.get("text_data"), self.rect) obj_data = attributes.get("obj_data") self.radius = obj_data.get("radius") self.rect.size = (self.radius * 2, self.radius * 2) self.color = obj_data.get("color") self.opacity = obj_data.get("opacity") class PyButton(PyBase, Rectangle, Text): """Define a basic button object""" def __init__(self, attributes: dict) -> None: """ Init a new button element object Attributes: attributes: contains all the button data """ PyBase.__init__(self, attributes.get("base_data")) Rectangle.__init__(self, attributes.get("rect_data")) Text.__init__(self, attributes.get("text_data"), self.rect) obj_data = attributes.get("obj_data") self.active = obj_data.get("active") self.disabled = obj_data.get("disabled") self.active_color = self.base_color = obj_data.get("base_color") self.hover_color = obj_data.get("hover_color") self.select_color = obj_data.get("select_color") self.disabled_color = obj_data.get("disabled_color") self.opacity = obj_data.get("opacity") Eventer.add_object_event( self, { "button_hover": { "function_path": "pyengine.libs.eventer.ui_events:ButtonEvents.button_hover", "event_type": "mousein", "args": [], } }, ) Eventer.add_object_event( self, { "button_unhover": { "function_path": "pyengine.libs.eventer.ui_events:ButtonEvents.button_hover", "event_type": "mouseout", "args": [False], } }, ) Eventer.add_object_event( self, { "button_select": { "function_path": "pyengine.libs.eventer.ui_events:ButtonEvents.button_select", "event_type": "down:leftclick", "args": [], } }, )
package com.commerce.inventory.service.saga.helper; import com.commerce.inventory.service.common.DomainComponent; import com.commerce.inventory.service.common.outbox.OutboxStatus; import com.commerce.inventory.service.common.valueobject.InventoryStatus; import com.commerce.inventory.service.common.valueobject.Quantity; import com.commerce.inventory.service.inventory.model.Product; import com.commerce.inventory.service.inventory.port.cache.ProductCachePort; import com.commerce.inventory.service.inventory.port.jpa.ProductDataPort; import com.commerce.inventory.service.inventory.port.json.JsonPort; import com.commerce.inventory.service.inventory.usecase.CachedProduct; import com.commerce.inventory.service.inventory.usecase.InventoryRequest; import com.commerce.inventory.service.inventory.usecase.OrderItem; import com.commerce.inventory.service.inventory.usecase.ProductRetrieve; import com.commerce.inventory.service.outbox.model.OrderOutbox; import com.commerce.inventory.service.outbox.model.OrderOutboxPayload; import com.commerce.inventory.service.outbox.port.jpa.OrderOutboxDataPort; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * @Author mselvi * @Created 19.03.2024 */ @DomainComponent public class InventoryUpdatingHelper { private static final Logger logger = LoggerFactory.getLogger(InventoryUpdatingHelper.class); private final OrderOutboxDataPort orderOutboxDataPort; private final ProductCachePort productCachePort; private final ProductDataPort productDataPort; private final JsonPort jsonPort; public InventoryUpdatingHelper(OrderOutboxDataPort orderOutboxDataPort, ProductCachePort productCachePort, ProductDataPort productDataPort, JsonPort jsonPort) { this.orderOutboxDataPort = orderOutboxDataPort; this.productCachePort = productCachePort; this.productDataPort = productDataPort; this.jsonPort = jsonPort; } @Transactional public List<String> process(InventoryRequest inventoryRequest) { List<OrderItem> items = inventoryRequest.items(); List<String> failureMessages = checkCacheByItems(items); logger.info("Items quantity updating actions started on cache"); InventoryStatus inventoryStatus = updatingActionsOnCache(items, failureMessages); logger.info("Items quantity updating actions finished on cache"); OrderOutbox orderOutbox = buildOrderOutbox(inventoryRequest, inventoryStatus, failureMessages); orderOutboxDataPort.save(orderOutbox); logger.info("OrderOutbox persisted for inventory updating action by sagaId: {}", inventoryRequest.sagaId()); return failureMessages; } private List<String> checkCacheByItems(List<OrderItem> items) { List<String> failureMessages = new ArrayList<>(); items.stream() .filter(orderItem -> { Long productId = orderItem.productId(); Optional<CachedProduct> productOptional = productCachePort.get(productId); return productOptional.isEmpty() || (productOptional.isPresent() && isQuantityNotEnoughForOrderItem(orderItem, productOptional)); }) .map(orderItem -> String.format("Product has already sold by productId: %d", orderItem.productId())) .forEach(failureMessages::add); return failureMessages; } private boolean isQuantityNotEnoughForOrderItem(OrderItem orderItem, Optional<CachedProduct> productOptional) { CachedProduct cachedProduct = productOptional.get(); Quantity baseQuantity = new Quantity(cachedProduct.getBaseQuantity()); return baseQuantity.isLowerThan(orderItem.quantity()); } private InventoryStatus updatingActionsOnCache(List<OrderItem> items, List<String> failureMessages) { if (!failureMessages.isEmpty()) { return InventoryStatus.NON_AVAILABLE; } for (OrderItem item : items) { Long productId = item.productId(); Optional<Product> productOptional = productDataPort.findById(new ProductRetrieve(productId)); if (productOptional.isEmpty()) { String errorMessage = String.format("Product could not find by productId: %d", productId); failureMessages.add(errorMessage); logger.error(errorMessage); break; } Optional<CachedProduct> cachedProductOptional = productCachePort.get(productId); if (cachedProductOptional.isEmpty()) { String errorMessage = String.format("Product has already sold by productId: %d", productId); failureMessages.add(errorMessage); logger.error(errorMessage); break; } Quantity orderQuantity = item.quantity(); Product savedProduct = updateProduct(productOptional.get(), orderQuantity, failureMessages); logger.info("Product updated for inventory updating action by productId: {}", productId); updateCache(cachedProductOptional.get(), savedProduct, orderQuantity, productId); } return failureMessages.isEmpty() ? InventoryStatus.AVAILABLE : InventoryStatus.NON_AVAILABLE; } private Product updateProduct(Product product, Quantity orderQuantity, List<String> failureMessages) { product.decreaseQuantity(orderQuantity, failureMessages); return productDataPort.save(product); } private void updateCache(CachedProduct cachedProduct, Product product, Quantity orderQuantity, Long productId) { Quantity baseQuantity = new Quantity(cachedProduct.getBaseQuantity()); Quantity tempQuantity = new Quantity(cachedProduct.getTempQuantity()); Quantity diffQuantity = baseQuantity.substract(tempQuantity); if (diffQuantity.isEqual(orderQuantity)) { productCachePort.remove(productId); logger.info("Product removed from cache by productId: {}", productId); } else if (diffQuantity.isGreaterThan(orderQuantity)) { cachedProduct.setBaseQuantity(product.getQuantity().value()); productCachePort.put(productId, cachedProduct); logger.info("Product updated on cache by productId: {}", productId); } } @Transactional public List<String> rollback(InventoryRequest inventoryRequest) { List<String> failureMessages = new ArrayList<>(); Long orderId = inventoryRequest.orderId(); logger.info("Product updating action started by orderId: {}", orderId); InventoryStatus inventoryStatus = updateProductsByItems(inventoryRequest.items(), failureMessages); logger.info("Product updating action finished by orderId: {}", orderId); OrderOutbox orderOutbox = buildOrderOutbox(inventoryRequest, inventoryStatus, failureMessages); orderOutboxDataPort.save(orderOutbox); logger.info("OrderOutbox persisted for inventory updating rollback action by sagaId: {}", inventoryRequest.sagaId()); return failureMessages; } private InventoryStatus updateProductsByItems(List<OrderItem> items, List<String> failureMessages) { for (OrderItem item : items) { Long productId = item.productId(); Optional<Product> productOptional = productDataPort.findById(new ProductRetrieve(productId)); if (productOptional.isEmpty()) { String errorMessage = String.format("Product could not be found by product id: %d and order id: %d", productId, item.orderId()); failureMessages.add(errorMessage); logger.error(errorMessage); break; } Product product = productOptional.get(); product.increaseQuantity(item.quantity()); productDataPort.save(product); } return failureMessages.isEmpty() ? InventoryStatus.AVAILABLE : InventoryStatus.NON_AVAILABLE; } private OrderOutbox buildOrderOutbox(InventoryRequest inventoryRequest, InventoryStatus inventoryStatus, List<String> failureMessages) { OrderOutboxPayload orderOutboxPayload = buildPayload(inventoryRequest, inventoryStatus, failureMessages); OrderOutbox orderOutbox = OrderOutbox.builder() .sagaId(inventoryRequest.sagaId()) .payload(jsonPort.convertDataToJson(orderOutboxPayload)) .outboxStatus(OutboxStatus.STARTED) .build(); return orderOutbox; } private OrderOutboxPayload buildPayload(InventoryRequest inventoryRequest, InventoryStatus inventoryStatus, List<String> failureMessages) { return new OrderOutboxPayload(inventoryRequest, inventoryStatus, failureMessages); } }
import GDrive from '../gdrive.js'; import multer from 'multer'; import config from 'config'; const drive = new GDrive(); // Instancia de la clase GDrive const upload = multer({ dest: 'uploads/' }); // Configuración de multer export const listarArchivos = async (req, res) => { try { const { page = 1, pageSize = 10 } = req.query; // Página y tamaño de página const archivos = await drive.obtenerArchivos(config.get('google.driveFolderId')); // Obtener archivos const total = archivos.length; const paginatedFiles = archivos.slice((page - 1) * pageSize, page * pageSize); res.json({ total, archivos: paginatedFiles }); } catch (error) { res.status(500).send(error.message); } }; export const subirArchivo = async (req, res) => { try { const { file } = req; const { mimetype, path: filePath } = file; const fecha = new Date(); const fechaStr = fecha.toISOString().replace(/T/, ' ').replace(/\..+/, ''); // Formatear la fecha a string sin milisegundos const nombreArchivo = `Grabacion ${fechaStr}.wav`; const archivoGuardado = await drive.guardarArchivo(filePath, mimetype, config.get('google.driveFolderId'), nombreArchivo); // Guardar archivo res.json(archivoGuardado); } catch (error) { res.status(500).send(error.message); } }; export const borrarArchivo = async (req, res) => { try { const { id } = req.params; await drive.borrarArchivo(id); res.sendStatus(204); } catch (error) { res.status(500).send(error.message); } }; export const borrarTodasLasGrabaciones = async (req, res) => { try { const archivos = await drive.obtenerArchivos(config.get('google.driveFolderId')); const deletePromises = archivos.map(archivo => drive.borrarArchivo(archivo.id)); await Promise.all(deletePromises); res.sendStatus(204); } catch (error) { res.status(500).send(error.message); } }; export const descargarArchivo = async (req, res) => { try { const { id } = req.params; const archivo = await drive.obtenerArchivo(id); archivo.pipe(res); } catch (error) { res.status(500).send(error.message); } }; export const renombrarArchivo = async (req, res) => { try { const { id } = req.params; const { nombre } = req.body; if (!nombre.endsWith('.wav')) { return res.status(400).send('El nombre del archivo debe terminar con .wav'); } const archivoRenombrado = await drive.renombrarArchivo(id, nombre); res.json(archivoRenombrado); } catch (error) { res.status(500).send(error.message); } };
<script lang="ts"> import Textarea from '$lib/components/Textarea.svelte'; import Send from '$lib/icons/Send.svelte'; export let data; const threadInfo = data.trpc.thread.getThreadEmailList.query( { threadId: data.threadId }, { select(res) { if (res.unread) { $markAsRead.mutate({ threadId: data.threadId }); } return res; } } ); const markAsRead = data.trpc.thread.markThreadAsRead.mutation({ onSuccess() { data.trpc.thread.getThreadList.utils.invalidate({ caseId: data.caseId }); } }); const sendReply = data.trpc.thread.reply.mutation({ onSuccess() { data.trpc.thread.getThreadEmailList.utils.invalidate({ threadId: data.threadId }); } }); let replyMessage = ''; const timeFormatter = new Intl.DateTimeFormat('en', { hourCycle: 'h23', minute: '2-digit', hour: '2-digit', day: '2-digit', month: 'short' }); function formatDate(dateNumber: number | string) { return timeFormatter.format(new Date(dateNumber)); } </script> <div class="root"> {#if $threadInfo.isSuccess} {#each $threadInfo.data.messages .flatMap((x) => x) .filter((data) => data.message.type === 'text') as message (message)} <div class="message {message.from === 'me' ? 'mine' : ''}"> {#if message.from !== 'me'} <div>{message.from}</div> <hr /> {/if} {message.message.content} {#if message.date} <span class="time"> {formatDate(message.date)} </span> {/if} </div> {/each} <form class="form" on:submit|preventDefault={() => { if (!$threadInfo.isSuccess) return; const replyData = $threadInfo.data.replyData; $sendReply.mutate({ to: replyData.to ?? '', cc: replyData.cc ?? '', content: replyMessage, replyId: replyData.replyMessageId ?? '', subject: replyData.subject ?? '', threadId: data.threadId }); replyMessage = ''; }} > <div class="textarea"> <Textarea bind:value={replyMessage} placeholder="Сообщение" /> </div> <button aria-label="send email" class="send"> <Send height="100%" width="100%" /> </button> </form> {/if} </div> <style lang="scss"> hr { border: 0; height: 2px; background-color: white; border-radius: 9999px; } .root { display: flex; flex-direction: column; height: 100%; gap: 0.5rem; padding: 0.25rem; border-radius: 0.25rem; background-color: $lightgray; } .message { width: fit-content; max-width: 358px; padding: 0.5rem 0.75rem; border-radius: 1rem; background: $violet; color: white; word-wrap: break-word; display: flex; flex-direction: column; &.mine { margin-left: auto; + .message:not(.mine) { margin-top: 8px; } background: white; color: black; } } .time { margin-left: 4px; color: white; font-size: 10px; line-height: 12px; align-self: end; } .mine .time { color: rgba(60, 60, 67, 0.6); } .form { display: flex; margin-top: auto; border-top: 2px solid #ddd; padding-top: 0.5rem; gap: 0.5rem; } .textarea { flex-grow: 1; background-color: rgba(118, 118, 128, 0.12); padding: 0.5rem; border-radius: 1rem; color: #7a7a7a; transition: outline-color 200ms; outline: 2px solid; outline-color: transparent; &:focus-within { outline-color: #dddf; } } .send { align-self: end; border: none; height: 2rem; width: 2rem; color: #8fa5fb; } </style>
@extends('layouts.app') {{-- page title --}} @section('seo_title', Str::plural($page->title) ?? '') @section('search-title') {{ $page->title ?? ''}} @endsection {{-- vendor styles --}} @section('vendor-style') @endsection {{-- page style --}} @section('page-style') <link rel="stylesheet" type="text/css" href="{{ asset('admin/css/pages/page-users.css')}}"> @endsection @section('content') @section('breadcrumb') <div class="col s12 m6 l6"><h5 class="breadcrumbs-title"><span>{{ Str::plural($page->title) ?? ''}}</span></h5></div> <div class="col s12 m6 l6 right-align-md"> <ol class="breadcrumbs mb-0"> <li class="breadcrumb-item"><a href="{{ url('/home') }}">Home</a></li> <li class="breadcrumb-item"><a href="{{ url($page->route) }}">{{ Str::plural($page->title) ?? ''}}</a></li> <li class="breadcrumb-item active">List</li> </ol> </div> @endsection <!-- edit profile start --> <div class="section users-edit"> <div class="card"> <div class="card-content"> <!-- <div class="card-body"> --> <ul class="tabs mb-2 row"> <li class="tab"> <a class="display-flex align-items-center active" id="account-tab" href="#account"> <i class="material-icons mr-1">person_outline</i><span>Profile</span> </a> </li> <li class="tab"> <a class="display-flex align-items-center" id="information-tab" href="#information"> <i class="material-icons mr-2">settings</i><span>Account</span> </a> </li> </ul> <div class="divider mb-3"></div> <div class="row"> <div class="col s12" id="account"> <!-- users edit media object start --> <div class="media display-flex align-items-center mb-2"> <a class="mr-2" href="#"> <img src="{{auth()->user()->profile_url}}" id="profilePhoto" alt="users avatar" class="z-depth-4 circle user-profile" height="64" width="64"> </a> <div class="media-body"> <form id="profilePhotoForm" name="profilePhotoForm" action="" method="POST" enctype="multipart/form-data" class="ajax-submit"> {{ csrf_field() }} {!! Form::hidden('oldPhotoURL', auth()->user()->profile_url, ['id' => 'oldPhotoURL'] ); !!} <h5 class="media-heading mt-0">User Profile</h5> <div class="user-edit-btns display-flex"> <a id="select-files" class="btn mr-2"><span>Browse</span></a> <button type="submit" class="btn indigo logo-action-btn" id="uploadLogoBtn">Submit</button> </div> <small>Allowed JPG, JPEG or PNG extension only.</small> <div class="upfilewrapper" style="display:none;"> <input id="profile" type="file" accept="image/png, image/gif, image/jpeg" name="image" class="image" /> </div> </form> </div> </div> <!-- users edit media object ends --> <!-- users edit account form start --> @include('layouts.error') @include('layouts.success') {!! Form::open(['class'=>'ajax-submit', 'id'=> Str::camel($page->title).'Form']) !!} {{ csrf_field() }} {!! Form::hidden('user_id', $user->id ?? '', ['id' => 'user_id'] ); !!} <div class="row"> <div class="col s12 m6"> <div class="row"> <div class="col s12 input-field"> {!! Form::text('name', $user->name ?? '', array('id' => 'name')) !!} <label for="name" class="label-placeholder active"> Name <span class="red-text">*</span></label> </div> <div class="col s12 input-field"> {!! Form::text('email', $user->email ?? '', array('id' => 'email')) !!} <label for="name" class="label-placeholder active"> E-mail <span class="red-text">*</span></label> </div> </div> </div> <div class="col s12 m6"> <div class="row"> <div class="col s12 input-field"> {!! Form::text('last_name', $user->last_name ?? '', array('id' => 'last_name')) !!} <label for="last_name" class="label-placeholder active"> Last Name </label> </div> <div class="col s4 input-field"> {!! Form::select('phone_code', $variants->phoneCode, $user->phone_code ?? '', ['id' => 'phone_code', 'class' => 'select2 browser-default', 'placeholder'=>'Please select phone code']) !!} </div> <div class="col s8 input-field"> {!! Form::text('mobile', $user->mobile ?? '', array('id' => 'mobile')) !!} <label for="name" class="label-placeholder active"> Mobile</label> </div> </div> </div> <div class="col s12 display-flex justify-content-end mt-3"> <button type="submit" class="btn indigo" id="submit-btn"> Save changes</button> <button type="button" class="btn btn-light" id="form-reset-btn">Reset</button> </div> </div> {{ Form::close() }} <!-- users edit account form ends --> </div> <div class="col s12" id="information"> <!-- users edit Info form start --> @include('layouts.error') @include('layouts.success') {!! Form::open(['class'=>'ajax-submit', 'name' => 'updatePasswordForm', 'id'=>'updatePasswordForm']) !!} <div class="row"> <div class="col s12 m8"> <div class="row"> <div class="col s12"><h6 class="mb-4"><i class="material-icons mr-1">lock</i>Manage Password</h6></div> <div class="col s12 input-field"> {!! Form::password('old_password', ['id' => 'old_password']) !!} <label for="old_password"> Old Password <span class="red-text">*</span></label> </div> <div class="col s12 input-field"> {!! Form::password('new_password', ['id' => 'new_password']) !!} <label for="new_password"> New Password <span class="red-text">*</span></label> </div> <div class="col s12 input-field"> {!! Form::password('new_password_confirmation', ['id' => 'new_password_confirmation']) !!} <label for="new_password_confirmation"> Confirm Password <span class="red-text">*</span></label> </div> </div> </div> <div class="col s12 m12"> <div class="row"> <div class="col s12 display-flex justify-content-end mt-3"> <button type="submit" class="btn indigo" id="password-submit-btn"> Save changes</button> <button type="button" class="btn btn-light" id="password-form-reset-btn" onclick="resetChangepasswordForm()">Reset</button> </div> </div> </div> </div> {!! Form::close() !!} <!-- users edit Info form ends --> </div> </div> <!-- </div> --> </div> </div> </div> <!-- users edit ends --> @endsection {{-- vendor scripts --}} @section('vendor-script') @endsection @push('page-scripts') <script> $('#phone_code').select2({ placeholder: "Please select phone code", allowClear: true}); if ($("#{{Str::camel($page->title)}}Form").length > 0) { var validator = $("#{{Str::camel($page->title)}}Form").validate({ rules: { name: { required: true, maxlength: 200 }, mobile: { minlength:3, maxlength:15, // emailFormat:true, Needs confirmation from Sukhesh regarding number format remote: { url: "{{ url('/common/is-unique-mobile') }}", type: "POST", data: { user_id: function () { return $('#user_id').val(); } } }, }, email: { required: true, email: true, emailFormat:true, remote: { url: "{{ url('/common/is-unique-email') }}", type: "POST", data: { user_id: function () { return $('#user_id').val(); } } }, }, }, messages: { name: { required: "Please enter name", maxlength: "Length cannot be more than 200 characters", }, mobile: { maxlength: "Length cannot be more than 15 numbers", minlength: "Length must be 3 numbers", remote: "The Mobile has already been taken" }, email: { required: "Please enter E-mail", email: "Please enter a valid E-mail address", emailFormat: "Please enter a valid E-mail address", remote: "The E-mail has already been taken" }, }, submitHandler: function (form) { disableBtn("submit-btn"); id = $("#user_id").val(); user_id = "" == id ? "" : "/" + id; formMethod = "" == id ? "POST" : "PUT"; var forms = $("#{{Str::camel($page->title)}}Form"); $.ajax({ url: "{{ url($page->route) }}" + user_id, type: formMethod, processData: false, data: forms.serialize(), dataType: "html", }).done(function (a) { enableBtn("submit-btn"); var data = JSON.parse(a); if (data.flagError == false) { showSuccessToaster(data.message); // setTimeout(function () { // window.location.href = "{{ url($page->route) }}"; // }, 2000); } else { showErrorToaster(data.message); printErrorMsg(data.error); } }); }, errorElement : 'div', }) } jQuery.validator.addMethod("emailFormat", function (value, element) { return this.optional(element) || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/igm.test(value); }, "Please enter a valid email address"); $("#form-reset-btn").click(function (){ validator.resetForm(); $("#{{Str::camel($page->title)}}Form").find("input[type=text]").val(""); $("#phone_code").val('').trigger('change'); }); if ($("#updatePasswordForm").length > 0) { var changePasswordFormValidator = $("#updatePasswordForm").validate({ rules: { old_password: { required: true, }, new_password: { required: true, minlength: 6, maxlength: 10, }, new_password_confirmation: { equalTo: "#new_password" }, }, messages: { old_password: { required: "Please enter old password", }, new_password: { required: "Please enter new password", minlength: "Passwords must be at least 6 characters in length", maxlength: "Length cannot be more than 10 characters", }, new_password_confirmation: { equalTo: "Passwords are not matching", } }, submitHandler: function (form) { disableBtn('password-submit-btn'); var forms = $("#updatePasswordForm"); $.ajax({ url: "{{ url('update-password') }}", type: 'POST', processData: false, data: forms.serialize(), dataType: "html", }).done(function (a) { var data = JSON.parse(a); resetPasswordForm(); enableBtn('password-submit-btn'); if (data.flagError == false) { showSuccessToaster(data.message); } else { showErrorToaster(data.message); printErrorMsg(data.error); } }); }, errorElement : 'div', }) } function resetPasswordForm() { changePasswordFormValidator.resetForm(); $('#updatePasswordForm').find("input[type=password]").val(""); $("#updatePasswordForm label").removeClass("error"); $("#updatePasswordForm .label-placeholder").addClass('active'); } $("#select-files").on("click", function () { $("#profile").click(); }) $('#profile').change(function() { var ext = $('#profile').val().split('.').pop().toLowerCase(); if ($.inArray(ext, ['png','jpg','jpeg']) == -1) { showErrorToaster("Invalid format. Allowed JPG, JPEG or PNG."); } else { let reader = new FileReader(); reader.onload = (e) => { $('#profilePhoto').attr('src', e.target.result); } reader.readAsDataURL(this.files[0]); } }); $('#profilePhotoForm').submit(function(e) { disableBtn("uploadLogoBtn"); var formData = new FormData(this); $.ajax({ type: "POST",url: "{{ url('update-profile-photo') }}", data: formData, cache:false, contentType: false, processData: false, success: function(data) { enableBtn("uploadLogoBtn"); if (data.flagError == false) { showSuccessToaster(data.message); $(".user-profile").attr("src", data.url); $(".print-error-msg").hide(); } else { showErrorToaster(data.message); printErrorMsg(data.error); } } }); }); </script> @endpush
// // TweetTableViewCell.swift // Twitter // // Created by Angel Zambrano on 9/26/22. // Copyright © 2022 Dan. All rights reserved. // import UIKit class TweetTableViewCell: UITableViewCell { static let identifier = "TweetTableViewCell" let userImageView: UIImageView = { let imgview = UIImageView() imgview.translatesAutoresizingMaskIntoConstraints = false imgview.contentMode = .scaleToFill return imgview }() var tweetId: Int = -1 var retweeted: Bool = false let username: UILabel = { let label = UILabel() label.numberOfLines = 1 label.font = UIFont.boldSystemFont(ofSize: 18) label.text = "John Doe" label.translatesAutoresizingMaskIntoConstraints = false return label }() let tweetLbl: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 16) label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false label.text = "Tweet Content" label.translatesAutoresizingMaskIntoConstraints = false return label }() // adding buttons to like and retweet let likeButton: UIButton = { let btn = UIButton() // btn.backgroundColor = .red btn.translatesAutoresizingMaskIntoConstraints = false btn.setImage(UIImage(named: "favor-icon-1"), for: .normal) btn.addTarget(self, action: #selector(likeTweet), for: .touchUpInside) return btn }() let retTweetButton: UIButton = { let btn = UIButton() btn.translatesAutoresizingMaskIntoConstraints = false btn.setImage(UIImage(named: "retweet-icon"), for: .normal) btn.addTarget(self, action: #selector(retTweetButtonWasPressed), for: .touchUpInside) return btn }() var favorited: Bool = false func setFavorite(_ isFavorited: Bool) { favorited = isFavorited if favorited { likeButton.setImage(UIImage(named: "favor-icon-red"), for: .normal) } else { likeButton.setImage(UIImage(named: "favor-icon-1"), for: .normal) } } @objc func retTweetButtonWasPressed() { TwitterAPICaller.client?.retweet(tweetId: tweetId, success: { self.setRetweeted(true) }, failure: { error in print("error is retweeting \(error)") }) } func setRetweeted(_ isRetweeted: Bool) { if isRetweeted { retTweetButton.setImage(UIImage(named: "retweet-icon-green"), for: .normal) // retTweetButton.isEnabled = true } else { retTweetButton.setImage(UIImage(named: "retweet-icon"), for: .normal) // retTweetButton.isEnabled = false } } @objc func likeTweet() { let toBeFavorited = !favorited if toBeFavorited { TwitterAPICaller.client?.favotireTweet(tweetId: tweetId, success: { self.setFavorite(true) }, failure: { error in print("favorited did not succeed: \(error.localizedDescription)") }) }else { TwitterAPICaller.client?.unfavoriteTweet(tweetId: tweetId, success: { self.setFavorite(false) }, failure: { error in print("unfavorited: \(error.localizedDescription)") }) } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // self.backgroundColor = .yellow // contentView.backgroundColor = .yellow addSubviews() addConstraints() self.clipsToBounds = true } private func addSubviews() { contentView.addSubview(userImageView) contentView.addSubview(username) contentView.addSubview(tweetLbl) contentView.addSubview(likeButton) contentView.addSubview(retTweetButton) } private func addConstraints() { NSLayoutConstraint.activate([ userImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0), userImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 0), userImageView.widthAnchor.constraint(equalToConstant: 95), userImageView.heightAnchor.constraint(equalToConstant: 95) ]) NSLayoutConstraint.activate([ username.topAnchor.constraint(equalTo: contentView.topAnchor), username.leadingAnchor.constraint(equalTo: userImageView.trailingAnchor, constant: 8) ]) let contet: CGFloat = 252 // username.setContentHuggingPriority(.defaultLow, for: .vertical) // username.contentHuggingPriority(for: .vertical).rawValue = 252 username.setContentHuggingPriority(UILayoutPriority.init(rawValue: 252), for: .vertical) NSLayoutConstraint.activate([ tweetLbl.topAnchor.constraint(equalTo: username.bottomAnchor, constant: 4), tweetLbl.leadingAnchor.constraint(equalTo: userImageView.trailingAnchor, constant: 8), tweetLbl.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), // tweetLbl.bottomAnchor.constraint(equalTo: contentView.bottomAnchor) ]) NSLayoutConstraint.activate([ likeButton.topAnchor.constraint(equalTo: tweetLbl.bottomAnchor, constant: 37), likeButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10), likeButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10) ]) NSLayoutConstraint.activate([ retTweetButton.centerYAnchor.constraint(equalTo: likeButton.centerYAnchor), retTweetButton.trailingAnchor.constraint(equalTo: likeButton.leadingAnchor, constant: -10) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
library(tidyverse) library(ggplot2) #setwd(...) coherence <- read_csv("lobe_averages.csv") # Refactor Categorical Variables --------------------------------------- coherence <- coherence %>% mutate(test_session = fct_relevel(test_session, c("pretest", "posttest")), condition = fct_relevel(condition, c("dance","control")), freq_band = fct_relevel(freq_band, c("delta","theta","alpha","beta","lowgamma","higamma")), activity = fct_relevel(activity, c("baseline","eyegaze","convo","follow","lead","improv")), lobe = fct_relevel(lobe, c("frontal","parietal","temporal","occipital"))) # Delta ------------------------------------------------------------------- delta_values <- filter(coherence, freq_band == "delta") ggplot(delta_values, aes(x = avg_coh, fill = condition)) + geom_histogram(binwidth = 0.01, color="#e9ecef", alpha=0.6, position = 'identity') + labs(title = "Distribution in Coherence in Delta", x = "Average Coherence", y = "Count", fill="Condition") + facet_wrap(vars(test_session,lobe), nrow = 2, ncol = 4) ggsave("delta_distribution.png",path = "plots/histograms/lobes",width = 4000,height = 2160, units = c("px")) # Theta ------------------------------------------------------------------- theta_values <- filter(coherence, freq_band == "theta") ggplot(theta_values, aes(x = avg_coh, fill = condition)) + geom_histogram(binwidth = 0.01, color="#e9ecef", alpha=0.6, position = 'identity') + labs(title = "Distribution in Coherence in Theta", x = "Average Coherence", y = "Count", fill="Condition") + facet_wrap(vars(test_session,lobe), nrow = 2, ncol = 4) ggsave("theta_distribution.png",path = "plots/histograms/lobes",width = 4000,height = 2160, units = c("px")) # Alpha ------------------------------------------------------------------- alpha_values <- filter(coherence, freq_band == "alpha") ggplot(alpha_values, aes(x = avg_coh, fill = condition)) + geom_histogram(binwidth = 0.01, color="#e9ecef", alpha=0.6, position = 'identity') + labs(title = "Distribution in Coherence in Alpha", x = "Average Coherence", y = "Count", fill="Condition") + facet_wrap(vars(test_session,lobe), nrow = 2, ncol = 4) ggsave("alpha_distribution.png",path = "plots/histograms/lobes",width = 4000,height = 2160, units = c("px")) # Beta ------------------------------------------------------------------- beta_values <- filter(coherence, freq_band == "beta") ggplot(beta_values, aes(x = avg_coh, fill = condition)) + geom_histogram(binwidth = 0.01, color="#e9ecef", alpha=0.6, position = 'identity') + labs(title = "Distribution in Coherence in Beta", x = "Average Coherence", y = "Count", fill="Condition") + facet_wrap(vars(test_session,lobe), nrow = 2, ncol = 4) ggsave("beta_distribution.png",path = "plots/histograms/lobes",width = 4000,height = 2160, units = c("px")) # Low Gamma ------------------------------------------------------------------- lowgamma_values <- filter(coherence, freq_band == "lowgamma") ggplot(lowgamma_values, aes(x = avg_coh, fill = condition)) + geom_histogram(binwidth = 0.01, color="#e9ecef", alpha=0.6, position = 'identity') + labs(title = "Distribution in Coherence in Low Gamma", x = "Average Coherence", y = "Count", fill="Condition") + facet_wrap(vars(test_session,lobe), nrow = 2, ncol = 4) ggsave("lowgamma_distribution.png",path = "plots/histograms/lobes",width = 4000,height = 2160, units = c("px")) # High Gamma ------------------------------------------------------------------- higamma_values <- filter(coherence, freq_band == "higamma") ggplot(higamma_values, aes(x = avg_coh, fill = condition)) + geom_histogram(binwidth = 0.01, color="#e9ecef", alpha=0.6, position = 'identity') + labs(title = "Distribution in Coherence in High Gamma", x = "Average Coherence", y = "Count", fill="Condition") + facet_wrap(vars(test_session,lobe), nrow = 2, ncol = 4) ggsave("higamma_distribution.png",path = "plots/histograms/lobes",width = 4000,height = 2160, units = c("px"))
#include "vector.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <search.h> void grow(vector* v){ v->Maxlength += v->toAdd; v->start = realloc(v->start , v->Maxlength*v->elemSize); assert(v != NULL); } void VectorNew(vector *v, int elemSize, VectorFreeFunction freeFn, int initialAllocation){ assert(elemSize > 0); assert(initialAllocation >= 0); if(initialAllocation == 0) initialAllocation = 8; v->Maxlength = initialAllocation; v->toAdd = initialAllocation; v->length = 0; v->elemSize = elemSize; v->freeFn = freeFn; v->start = malloc(initialAllocation * elemSize); assert(v->start != NULL); } void VectorDispose(vector *v){ if(v->freeFn != NULL){ for(int i = 0; i < v->length; i++){ v->freeFn(VectorNth(v , i)); } } free(v->start); } int VectorLength(const vector *v){ return v->length; } void *VectorNth(const vector *v, int position){ assert(position >= 0 && position < v->length); return (void*)((char*)v->start + position*v->elemSize); } void VectorReplace(vector *v, const void *elemAddr, int position){ if(v->length <= position && position < 0) return; if(v->freeFn != NULL) v->freeFn(VectorNth(v , position)); memcpy(VectorNth(v , position) , elemAddr , v->elemSize); } void VectorInsert(vector *v, const void *elemAddr, int position){ assert(position >= 0 && position <= v->length); if(v->length == v->Maxlength) grow(v); if(position == v->length){ VectorAppend(v , elemAddr); return; } void* curr = VectorNth(v , position); void* newPos = (void*)((char*)curr + v->elemSize); memmove(newPos , curr , (v->length - position)*v->elemSize); memcpy(curr , elemAddr , v->elemSize); v->length++; } void VectorAppend(vector *v, const void *elemAddr){ if(v->length == v->Maxlength) grow(v); void* curr = (void*)((char*)v->start + v->length*v->elemSize); memcpy(curr, elemAddr , v->elemSize); v->length++; } void VectorDelete(vector *v, int position){ assert(position >= 0 && position < v->length); void* curr = VectorNth(v , position); if(v->freeFn != NULL) v->freeFn(curr); memmove(curr ,(void*)((char*)curr + v->elemSize) , (v->length - position - 1) * v->elemSize); v->length--; } void VectorSort(vector *v, VectorCompareFunction compare){ assert(compare != NULL); qsort(v->start , v->length , v->elemSize , compare); } void VectorMap(vector *v, VectorMapFunction mapFn, void *auxData){ assert(mapFn != NULL); for(int i = 0; i < v->length; i++){ mapFn(VectorNth(v , i) , auxData); } } static const int kNotFound = -1; int VectorSearch(const vector *v, const void *key, VectorCompareFunction searchFn, int startIndex, bool isSorted){ assert(startIndex >= 0 && startIndex <= v->length); assert(key != NULL && searchFn != NULL); void* res = NULL; int num = v->length - startIndex; if(startIndex != v->length){ if(isSorted){ res = bsearch(key , VectorNth(v , startIndex), num , v->elemSize , searchFn); } else { res = lfind(key , VectorNth(v , startIndex) , &num , v->elemSize , searchFn); } } return res == NULL ? kNotFound : ((char*)res - (char*)v->start)/v->elemSize; }
/* eslint-disable */ import React from 'react'; import { Formik, Form } from 'formik'; import { Link, useLocation, useNavigate } from 'react-router-dom'; import useAuth from '../../hooks/useAuth'; import AuthForm from '../../components/AuthForm/AuthForm'; import FormInput from '../../components/FormInput/FormInput'; import AuthBtn from '../../components/AuthBtn/AuthBtn'; import { loginFormData, initialValues, validate } from './util/LoginFormData'; import axiosInstance from '../../services/AxiosInstance'; import './Login.scss'; function Login() { const navigate = useNavigate(); const location = useLocation(); const auth = useAuth(); const onSubmit = async (values, { setSubmitting, setFieldError }) => { try { const res = await axiosInstance.post('/account/login/', values); auth.login(res.data.Token); if (location.state?.from) navigate(location.state.from); else navigate('/dashboard'); } catch (error) { console.log(error); let message = 'Invalid email or password'; if (!!error.response && !!error.response.data && !!error.response.data.status) { message = error.response.data.status; if (message === 'User not verified') { message = 'Please verify your email first by clicking on the confirmation link sent to your email address during signup.'; } } setFieldError('authentication', message); } setSubmitting(false); }; return ( // eslint-disable-next-line <AuthForm title="Welcome" subtitle="Sign in to continue." to="/signup" text="Don't have an account?" link="Sign up"> <Formik {...{ validate, initialValues, onSubmit }}> {({ isSubmitting, errors }) => ( <Form className="login"> {loginFormData.map(({ label, name, type }, index) => ( <FormInput {...{ name, label, type }} key={index} page="login" /> ))} <Link to="/forgot-password" className="login__button"> <span className="login__button__link">Forgot Password?</span> </Link> <AuthBtn {...{ errors, isSubmitting }} btnText="Sign In" /> </Form> )} </Formik> </AuthForm> ); } export default Login;
// Copyright 2021-2024 FRC 6328 // http://github.com/Mechanical-Advantage // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // version 3 as published by the Free Software Foundation or // available in the root directory of this project. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. package frc.robot.subsystems.drive; import edu.wpi.first.math.MathUtil; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.system.plant.DCMotor; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.simulation.DCMotorSim; import frc.robot.Constants; /** * Physics sim implementation of module IO. * * <p>Uses two flywheel sims for the drive and turn motors, with the absolute position initialized * to a random value. The flywheel sims are not physically accurate, but provide a decent * approximation for the behavior of the module. */ public class ModuleIOSim implements ModuleIO { private DCMotorSim driveSim = new DCMotorSim(DCMotor.getKrakenX60(1), 6.75, 0.025); private DCMotorSim turnSim = new DCMotorSim(DCMotor.getKrakenX60(1), 150.0 / 7.0, 0.004); private final Rotation2d turnAbsoluteInitPosition = new Rotation2d(Math.random() * 2.0 * Math.PI); private double driveAppliedVolts = 0.0; private double turnAppliedVolts = 0.0; @Override public void updateInputs(ModuleIOInputs inputs) { driveSim.update(Constants.LOOP_PERIOD_SECS); turnSim.update(Constants.LOOP_PERIOD_SECS); inputs.drivePositionRad = driveSim.getAngularPositionRad(); inputs.driveVelocityRadPerSec = driveSim.getAngularVelocityRadPerSec(); inputs.driveAppliedVolts = driveAppliedVolts; inputs.driveCurrentAmps = new double[] {Math.abs(driveSim.getCurrentDrawAmps())}; inputs.driveTempCelcius = new double[] {}; inputs.turnAbsolutePosition = new Rotation2d(turnSim.getAngularPositionRad()).plus(turnAbsoluteInitPosition); inputs.turnPosition = new Rotation2d(turnSim.getAngularPositionRad()); inputs.turnVelocityRadPerSec = turnSim.getAngularVelocityRadPerSec(); inputs.turnAppliedVolts = turnAppliedVolts; inputs.turnCurrentAmps = new double[] {Math.abs(turnSim.getCurrentDrawAmps())}; inputs.turnTempCelcius = new double[] {}; inputs.odometryTimestamps = new double[] {Timer.getFPGATimestamp()}; inputs.odometryDrivePositionsRad = new double[] {inputs.drivePositionRad}; inputs.odometryTurnPositions = new Rotation2d[] {inputs.turnPosition}; } @Override public void setDriveVoltage(double volts) { driveAppliedVolts = MathUtil.clamp(volts, -12.0, 12.0); driveSim.setInputVoltage(driveAppliedVolts); } @Override public void setTurnVoltage(double volts) { turnAppliedVolts = MathUtil.clamp(volts, -12.0, 12.0); turnSim.setInputVoltage(turnAppliedVolts); } }
# Design Document (Class Records Database) By _Cyrille C. Cervantes_ Video overview: [Student Records Database - CS50 SQL Project](https://www.youtube.com/watch?v=AXD-8H0x8uE) ## Scope ### Purpose The purpose of the database is to efficiently manage and store students records handled by teachers. This involves creating a robust SQL database capable of housing information such as student scores, grades and relevant data. Essentially, the main goal of the project is to be able to replicate this sample table below where scores and grades of each student are properly managed by the sql database. ![Sample Grading Sheet](grading_sheet.png) ### Inclusions The database encompasses the following entities: * `schools` which includes some basic information about the school; * `teachers` who handles the classes; * `students` attending a certain school and some of their basic information; * `sections` of each grade level in the school where students belong to; * `subjects` offered in the K-12 program and their components needed for computing student's grade; * `classes` offered in the school; * `assessments` given to each class; and * the individual `scores` of students on each respective assessments. On the other hand, the database excludes: - the `demographic` information of the students as only the necessary basic information are included. This design streamlines the database, focusing specifically on the elements directly tied to class records and student performance, while having on mind the end-goal of providing a user-friendly interface for teachers. ## Functional Requirements This database will support * CRUD operations for `schools`, `teachers`, `subjects` and its `components`, `classes`, `grade_sections`, `students`, the schools they have attended, the classes they are enrolled in, the `assessments` given to each classes, and the `scores` of each student on each assessment. The design of the database enable us to do the following: - List all the students enrolled in a certain class; - List all the classes taken by each student; - List all the scores of the students; and lastly - Compute for the grades of each student for each classes they are enrolled in. ## Representation ### Entities Entities are captured in SQLite tables with the following schema. _**Disclaimer**: Most parts of this section were created by ChatGPT since this is a boring and tedious work. So, many thanks to ChatGPT! 😊._ <details> <summary>schools</summary> The `schools` table includes: - `id`, which specifies the unique ID for the school as an `INTEGER`. This identifies the school hence `PRIMARY KEY` constraint is applied. - `name`, which is the official name of the school in `TEXT` form. Appropriate for name fields, `TEXT` is used. - `region`, which specifies which region in the Philippines the school belongs to. The type is specified as `TEXT` since there are regions that contain letters in it. - `division`, which states the division belongs to in `TEXT` type. </details> <details> <summary>teachers</summary> The `teachers` table includes the following. - `id`, which specifies the unique ID for the teacher as an `INTEGER`. This column thus has the `PRIMARY KEY` constraint applied. - `first_name`, which specifies the first name of the teacher as `TEXT`. Appropriate for name fields, `TEXT` is used. - `middle_initial`, which specifies the middle initial of the teacher as `TEXT`. This field is `NULLABLE` since not all people have middle initial. - `last_name`, which specifies the teachers's last name. `TEXT` is used for the same reason as `first_name`.'s last name. `TEXT` is used for the same reason as `first_name`. Normally, this table could only contain one data assuming there is only one teacher who handles a certain class. </details> <details> <summary>subjects</summary> The `subjects` table includes the following. - `id`, which specifies the unique ID for the subject as an `INTEGER`. This column thus has the `PRIMARY KEY` constraint applied. - `name`, which is the official name of the subject in `TEXT` form. Appropriate for name fields, `TEXT` is used. - `level` which specifies the grade level of the subject in `INTEGER`. For non grade school subject, this might correspond to the number in the course name. - `track` which distinguishes the track of the subject, be it belongs to one of the following: _Academic_; _Technical-Vocational-Livelihood_; or _Sports and Arts_. For grade school subjects this is `NULLABLE`. </details> <details> <summary>components</summary> The table `components` are where we store the components of a subject needed for grade computation. The table includes the following: - `id`, which specifies the unique ID for the component as an `INTEGER`. This column thus has the `PRIMARY KEY` constraint applied. - `name`, which is the name of the component in `TEXT` form. Appropriate for name fields, `TEXT` is used. - `percentage`, which specifies the weight of the component in relation to the computation of grades. The data should be in `REAL` type and should be less than or equal to 1.0. </details> <details> <summary>subject_components</summary> This table, `subject_components` is where we store the relationship between the subject and its components. - `subject_id`, which specifies the unique ID for the subject from the `subjects` table. - `component_id`, which specifies the unique ID for the subject from the `components` table. - The pair (`subject_id`, `component_id`) is subjected to `UNIQUE` constraint to avoid repeition of data. </details> <details> <summary>classes</summary> The `classes` table includes the following. - `id`, which specifies the unique ID for the class as an `INTEGER`. This column thus has the `PRIMARY KEY` constraint applied. - `name`, which stores the formatted name of the class in `TEXT` form. Appropriate for name fields, `TEXT` is used. The name should obey the following format: `{subject} {grad_level} {section_name} A.Y. {year} {sem} Sem` - `subject_id`, which specifies the ID from the `subjects` table corresponding to the subject taught in the class. - `teacher_id`, which specifies the ID from the `subjects` table corresponding to the teacher that manages the class. - `school_id`, which specifies the ID from the `schools` table corresponding to the school where the class is taught. - `year`, which is the academic year (the first number in `INTEGER`) the class is taught. - `year`, which is the semester (in `INTEGER`) the class is taught. </details> <details> <summary>grade_sections</summary> The `grade_sections` table comprises the following fields: - `id`: An `INTEGER` representing the unique identifier for each grade section. This field is marked as `NOT NULL` and serves as the `PRIMARY KEY`. - `grade`: An `INTEGER` indicating the academic grade associated with the section. This field is marked as `NOT NULL`. - `name`: A `TEXT` field holding the name of the grade section. This field is marked as `NOT NULL`. - `school_id`: An `INTEGER` specifying the ID from the schools table corresponding to the school where the grade section is located. This field is optional. - `adviser`: A `TEXT` field storing the name or identifier of the adviser for the grade section. This field is optional. - `year`: An `INTEGER` denoting the academic year associated with the grade section. Only the first year is stored. </details> <details> <summary>students</summary> The `students` table is defined by the following fields: - `id`: An `INTEGER` serving as the unique identifier for each student. This field is marked as the `PRIMARY KEY`. - `first_name`: A `TEXT` field representing the first name of the student. This field is marked as `NOT NULL`. - `middle_name`: A `TEXT` field for capturing the middle name of the student. This field is optional since not all students have middle name. - `last_name`: A `TEXT` field holding the last name of the student. This field is marked as NOT NULL. - `birth_date`: A `DATE` field indicating the birth date of the student. This field is optional. - `gender`: An `INTEGER` field representing the gender of the student. </details> <details> <summary>students_schools</summary> The `students_schools` table records the schools that students have attended with the following fields. This table provides information about the schools each student has attended, including start and, if applicable, end dates of attendance. * `id`: An `INTEGER` serving as the unique identifier for each record in the table. This field is marked as the `PRIMARY KEY`. * `student_id`: An `INTEGER` indicating the unique ID of the student associated with the school attendance. This field is marked as `NOT NULL` and is linked to the id field in the `students` table through a foreign key constraint. * `school_id`: An `INTEGER` specifying the unique ID of the school attended by the student. This field is marked as `NOT NULL` and is linked to the id field in the `schools` table through a foreign key constraint. * `start_date`: A `DATE` field indicating the start date when the student began attending the specified school. This field is marked as NOT NULL. * `end_date`: A `DATE` field representing the optional end date when the student concluded attendance at the specified school. </details> <details> <summary>students_sections</summary> The `students_sections` table documents the sections to which students are assigned, featuring the following fields: * `id`: An `INTEGER` acting as the unique identifier for each record in the table. This field is marked as the `PRIMARY KEY`. * `student_id`: An `INTEGER` indicating the unique ID of the student. This field is marked as `NOT NULL` and is linked to the id field in the `students` table through a foreign key constraint. * `section_id`: An `INTEGER` specifying the unique ID of the grade section to which the student is assigned. This field is marked as `NOT NULL` and is linked to the id field in the `grade_sections` table through a foreign key constraint. Unique Constraint: * A `UNIQUE` constraint is applied to the combination of `student_id` and `section_id` fields, ensuring that each student is uniquely associated with a grade section. This table captures the assignments of students to specific grade sections, preventing duplicate entries for the same student and section pair. </details> <details> <summary>students_classes</summary> The `students_classes` table records the classes in which students are enrolled, featuring the following fields: - `student_id`: An `INTEGER` indicating the unique ID of the student. This field is marked as `NOT NULL` and is linked to the id field in the `students` table through a foreign key constraint. - `class_id`: An `INTEGER` specifying the unique ID of the class in which the student is enrolled. This field is marked as `NOT NULL` and is linked to the id field in the `classes` table through a foreign key constraint. Unique Constraint: - A `UNIQUE` constraint is applied to the combination of `student_id` and `class_id` fields, ensuring that each student is uniquely associated with a class. </details> <details> <summary>assessments</summary> The `assessments` table documents assessments under certain `components` with the following fields: * `id`: An `INTEGER` serving as the unique identifier for each assessment. This field is marked as the `PRIMARY KEY`. * `name`: A `TEXT` field representing the name of the assessment. * `max_score`: An `INTEGER` field specifying the maximum achievable score for the assessment. This field is marked as `NOT NULL`. * `subject_id`: An `INTEGER` indicating the ID from the subjects table corresponding to the subject under which the assessment falls. This field is optional. * `component_id`: An `INTEGER` specifying the ID from the components table corresponding to the component under which the assessment is categorized. This field is marked as `NOT NULL` and is very much needed for the grade computaiton. It is linked to the id field in the `components` table through a foreign key constraint. * `quarter`: An `INTEGER` field denoting the quarter during which the assessment is conducted. </details> <details> <summary>class_assessments</summary> The `class_assessments` table captures assessments that are given to a certain class: * `id`: An `INTEGER` serving as the unique identifier for each record in the table. This field is marked as the `PRIMARY KEY`. * `class_id`: An `INTEGER` specifying the unique ID of the class associated with the assessment. This field is marked as `NOT NULL` and is linked to the id field in the `classes` table through a foreign key constraint. * `assessment_id`: An `INTEGER` indicating the unique ID of the assessment conducted within the class. This field is marked as `NOT NULL` and is linked to the id field in the `assessments` table through a foreign key constraint. * `date_given`: A DATE field representing the date on which the assessment was conducted. Unique Constraint: - A `UNIQUE` constraint is applied to the combination of `class_id` and `assessment_id` fields, ensuring that each class is uniquely associated with an assessment. </details> <details> <summary>scores</summary> The `scores` table stores scores of each student on a certain assessment with the following fields: * `id`: An `INTEGER` serving as the unique identifier for each score. This field is marked as the `PRIMARY KEY`. * `student_id`: An `INTEGER` indicating the unique ID of the student for whom the score is recorded. This field is marked as `NOT NUL`L and is linked to the id field in the `students` table through a foreign key constraint. * `assessment_id`: An INTEGER indicating the unique ID of the assessment for which the score is recorded. This field is marked as `NOT NULL` and is linked to the id field in the `assessments` table through a foreign key constraint. * `value`: A `REAL` field representing the score achieved by the student. This field has a default value of 0.0 in case the student fails to take the exam. These tables collectively provide a comprehensive structure for managing information related to student enrollment in classes, assessments, and their respective scores. </details> ### Relationships The entity relationship diagram below illustrates the connections between the entities within the database. ![ER Diagram](Class_Records_Database_ER.png) As outlined by the diagram: * A `school` manages no or multiple `grade_sections`, has no or many `students` and offers no or many `classes`. * A `teacher` can teach many `classes` but a `class` should only have one `teacher`. * `students` could be admitted to many schools as long as there is time conflict. He/she belongs to a certain `grade_section` managed by its current school, is enrolled to one or many `classes` (needs to be enrolled to at least one class to be called a student). * A `class` is taught by a `teacher` in a `school` with a `subject` and should have at least one `student`. A class could give 0 to many `assessments` (zero assessments may mean the class has yet to give an assessment). * A `subject` should at least have one `component` that is need for the grade computation. All the weights of the components should add up to 1.0. * To record the `scores` of the students, a `student` could take many `assessments` of different kind however, one `score` of that assessment is only given to the student. ## Optimizations The use-case of the database is assumed to use "id" as way to search for entities. Hence, there is no need to create indices for other columns. Since, ids as primary keys are automatically created for us by sqlite, I opted to not create indices anymore. In addition, the database is assumed to be small, basing on the generalization that teachers usually handle 4-6 classes, hence, any optimizations could be insignificant. ## Limitations With the current schema, sqlite alone cannot produce in one table the more detailed computation of the grades as there are dynamic numbers of quizzes as well as number of subject components. One work-around could be to use scripting program to overcome this problem.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCouponsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('coupons', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('coupon_code'); $table->string('coupon_value', '10'); $table->string('coupon_owner'); $table->integer('coupon_state'); $table->string('coupon_expiry_date', '70'); $table->timestamp('created_at')->useCurrent(); $table->timestamp('updated_at')->useCurrent(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('coupons'); } }
use std::env; use ansilo_connectors_base::interface::{LoggedQuery, ResultSet}; use ansilo_core::err::Result; use ansilo_e2e::current_dir; use itertools::Itertools; use pretty_assertions::assert_eq; use serial_test::serial; #[test] #[serial] fn test_delete_where_remote() { ansilo_logging::init_for_tests(); let containers = ansilo_e2e::mssql::start_mssql(); let mut mssql = ansilo_e2e::mssql::init_mssql_sql(&containers, current_dir!().join("mssql-sql/*.sql")); let (instance, mut client) = ansilo_e2e::util::main::run_instance(current_dir!().join("config.yml")); let rows = client .execute( r#" DELETE FROM t011__test_tab WHERE id = 2 "#, &[], ) .unwrap(); assert_eq!(rows, 1); // Check data received on mssql end let results = mssql .execute("SELECT * FROM t011__test_tab ORDER BY id", vec![]) .unwrap() .reader() .unwrap() .iter_rows() .collect::<Result<Vec<_>>>() .unwrap(); assert_eq!( results .into_iter() .map(|r| ( r["id"].as_int32().unwrap().clone(), r["name"].as_utf8_string().unwrap().clone() )) .collect_vec(), vec![(1, "John".to_string()), (3, "Mary".to_string()),] ); assert_eq!( instance.log().get_from_memory().unwrap(), vec![ ("mssql".to_string(), LoggedQuery::new_query("BEGIN")), ( "mssql".to_string(), LoggedQuery::new( [ r#"DELETE FROM [dbo].[t011__test_tab] "#, r#"WHERE (([t011__test_tab].[id]) = (?))"#, ] .join(""), vec!["LoggedParam [index=1, method=setInt, value=2]".into(),], Some( [("affected".into(), "Some(1)".into())] .into_iter() .collect() ) ) ), ("mssql".to_string(), LoggedQuery::new_query("COMMIT")), ] ); } #[test] #[serial] fn test_delete_where_remote_with_no_pk() { ansilo_logging::init_for_tests(); let containers = ansilo_e2e::mssql::start_mssql(); let mut mssql = ansilo_e2e::mssql::init_mssql_sql(&containers, current_dir!().join("mssql-sql/*.sql")); let (instance, mut client) = ansilo_e2e::util::main::run_instance(current_dir!().join("config.yml")); let rows = client .execute( r#" DELETE FROM t011__test_tab_no_pk WHERE id = 2 "#, &[], ) .unwrap(); assert_eq!(rows, 1); // Check data received on mssql end let results = mssql .execute("SELECT * FROM t011__test_tab_no_pk ORDER BY id", vec![]) .unwrap() .reader() .unwrap() .iter_rows() .collect::<Result<Vec<_>>>() .unwrap(); assert_eq!( results .into_iter() .map(|r| ( r["id"].as_int32().unwrap().clone(), r["name"].as_utf8_string().unwrap().clone() )) .collect_vec(), vec![(1, "John".to_string()), (3, "Mary".to_string()),] ); assert_eq!( instance.log().get_from_memory().unwrap(), vec![ ("mssql".to_string(), LoggedQuery::new_query("BEGIN")), ( "mssql".to_string(), LoggedQuery::new( [ r#"DELETE FROM [dbo].[t011__test_tab_no_pk] "#, r#"WHERE (([t011__test_tab_no_pk].[id]) = (?))"#, ] .join(""), vec!["LoggedParam [index=1, method=setInt, value=2]".into(),], Some( [("affected".into(), "Some(1)".into())] .into_iter() .collect() ) ) ), ("mssql".to_string(), LoggedQuery::new_query("COMMIT")), ] ); } #[test] #[serial] fn test_delete_where_local() { ansilo_logging::init_for_tests(); let containers = ansilo_e2e::mssql::start_mssql(); let mut mssql = ansilo_e2e::mssql::init_mssql_sql(&containers, current_dir!().join("mssql-sql/*.sql")); let (instance, mut client) = ansilo_e2e::util::main::run_instance(current_dir!().join("config.yml")); let rows = client .execute( r#" DELETE FROM t011__test_tab WHERE MD5(id::text) = MD5('1') "#, &[], ) .unwrap(); assert_eq!(rows, 1); // Check data received on mssql end let results = mssql .execute("SELECT * FROM t011__test_tab ORDER BY id", vec![]) .unwrap() .reader() .unwrap() .iter_rows() .collect::<Result<Vec<_>>>() .unwrap(); assert_eq!( results .into_iter() .map(|r| ( r["id"].as_int32().unwrap().clone(), r["name"].as_utf8_string().unwrap().clone() )) .collect_vec(), vec![(2, "Jane".to_string()), (3, "Mary".to_string()),] ); let query_log = instance.log().get_from_memory().unwrap(); // Delete with local eval should lock remote rows using WITH (UPDLOCK) first assert_eq!( query_log, vec![ ("mssql".to_string(), LoggedQuery::new_query("BEGIN")), ( "mssql".to_string(), LoggedQuery::new( [ r#"SELECT [t1].[id] AS [i0], [t1].[id] AS [c0] "#, r#"FROM [dbo].[t011__test_tab] AS [t1] "#, r#"WITH (UPDLOCK)"#, ] .join(""), vec![], None ) ), ( "mssql".to_string(), LoggedQuery::new( [ r#"DELETE FROM [dbo].[t011__test_tab] "#, r#"WHERE (([t011__test_tab].[id]) = (?))"#, ] .join(""), vec!["LoggedParam [index=1, method=setInt, value=1]".into()], Some( [("affected".into(), "Some(1)".into())] .into_iter() .collect() ) ) ), ("mssql".to_string(), LoggedQuery::new_query("COMMIT")), ] ); } #[test] #[serial] fn test_delete_where_local_with_no_pk_fails() { ansilo_logging::init_for_tests(); let containers = ansilo_e2e::mssql::start_mssql(); let _mssql = ansilo_e2e::mssql::init_mssql_sql(&containers, current_dir!().join("mssql-sql/*.sql")); let (_instance, mut client) = ansilo_e2e::util::main::run_instance(current_dir!().join("config.yml")); let err = client .execute( r#" DELETE FROM t011__test_tab_no_pk WHERE MD5(id::text) = MD5('1') "#, &[], ) .unwrap_err(); dbg!(err.to_string()); assert!(err .to_string() .contains("Cannot perform operation on table without primary keys")); }
import 'package:animated_bottom_navigation_bar/animated_bottom_navigation_bar.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:get/get.dart'; import 'package:myfinance_app/core/services/firebase_messaging_service.dart'; import 'package:myfinance_app/currency/controller/currency_controller.dart'; import 'package:myfinance_app/onboarding/controller/onboarding_controller.dart'; import 'package:myfinance_app/reports/controller/reports_controller.dart'; import 'package:myfinance_app/settings/controller/settings_cntroller.dart'; import 'package:myfinance_app/transactions/controller/edit_transaction_controller.dart'; import 'package:myfinance_app/transactions/controller/transaction_controller.dart'; import 'package:myfinance_app/transactions/view/screens/add_transaction_screen.dart'; import 'package:myfinance_app/transactions/view/screens/transactions_screen.dart'; import 'package:myfinance_app/wallets/controller/wallet_controller.dart'; import 'package:myfinance_app/wallets/view/screens/add_edit_wallet_screen.dart'; import 'package:myfinance_app/wallets/view/screens/wallets_screen.dart'; import 'package:provider/provider.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'auth/controller/auth_controller.dart'; import 'auth/view/screens/auth_screen.dart'; import 'core/ui/theme.dart'; import 'onboarding/view/on_boarding_screen.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); await FirebaseMessagingService.initNotification(); final prefs = await SharedPreferences.getInstance(); SettingsController.init(prefs); runApp(MultiProvider(providers: [ ChangeNotifierProvider<TransactionController>( create: (_) => TransactionController()), ChangeNotifierProvider<WalletController>(create: (_) => WalletController()), ChangeNotifierProvider<AuthController>(create: (_) => AuthController()), ChangeNotifierProvider<ReportsController>( create: (_) => ReportsController()), ChangeNotifierProvider<OnBoardingController>( create: (_) => OnBoardingController(prefs)), ChangeNotifierProvider<CurrencyController>( create: (_) => CurrencyController(prefs)), ChangeNotifierProvider<SettingsController>( create: (_) => SettingsController()), ChangeNotifierProvider<EditTransactionController>(create: (_) => EditTransactionController()), ], child: const MyApp())); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { final controller = Provider.of<OnBoardingController>(context, listen: false); final settingsController = Provider.of<SettingsController>(context); final firstTimeLaunched = controller.firstTimeLaunched() ?? true; return GetMaterialApp( debugShowCheckedModeBanner: false, localizationsDelegates: const [ GlobalMaterialLocalizations.delegate, ], theme: AppTheme.lightTheme, darkTheme: AppTheme.darkTheme, themeMode: settingsController.currentTheme.mode, home: firstTimeLaunched ? OnBoardingScreen(onBoardingEnd: (ctx) { controller.onFirstTimeLaunchedChanged(false); Navigator.pushReplacement( ctx, MaterialPageRoute(builder: (_) => const MyHomePage())); }) : const MyHomePage()); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin { var _selectedIndex = 0; var _isFabVisible = true; late AnimationController _hideBottomBarAnimationController; final tutTargetsKeys = [ GlobalKey(), GlobalKey(), GlobalKey(), ]; bool onScrollNotification(ScrollNotification notification) { if (notification is UserScrollNotification && notification.metrics.axis == Axis.vertical) { switch (notification.direction) { case ScrollDirection.forward: _hideBottomBarAnimationController.reverse(); setState(() => _isFabVisible = true); break; case ScrollDirection.reverse: _hideBottomBarAnimationController.forward(); setState(() => _isFabVisible = false); break; case ScrollDirection.idle: break; } } return false; } @override void initState() { super.initState(); _hideBottomBarAnimationController = AnimationController( duration: const Duration(milliseconds: 500), vsync: this, ); } @override void dispose() { _hideBottomBarAnimationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { // SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle( // statusBarColor: Colors.transparent, // statusBarIconBrightness: // Theme.of(context).brightness == Brightness.light // ? Brightness.light // : Brightness.dark, // )); final bottomNanScreens = [ TransactionsScreen( tutTargetsKeys: tutTargetsKeys , onNavigateToWalletScreen: (){ setState(() => _selectedIndex = 1); Get.to(() => const AddEditWalletScreen()); }, ), const WalletsScreen() ]; return Directionality( textDirection: TextDirection.rtl, child: Scaffold( backgroundColor: Theme.of(context).colorScheme.background, floatingActionButton: StreamBuilder( stream: FirebaseAuth.instance.authStateChanges(), builder: (context, snapshot) { if (snapshot.hasData && snapshot.data!.emailVerified) { return AnimatedContainer( duration: const Duration(milliseconds: 500), height: _isFabVisible ? 60.0 : 0.0, child: FloatingActionButton( key: tutTargetsKeys[2], backgroundColor: orangeyRed, onPressed: () { Get.to(() => _selectedIndex == 0 ? const AddTransactionScreen() : const AddEditWalletScreen()); }, child: Icon(Icons.add, color: Theme.of(context).colorScheme.surface), )); } else { return const SizedBox.shrink(); } }), floatingActionButtonLocation: FloatingActionButtonLocation.miniCenterDocked, bottomNavigationBar: StreamBuilder( stream: FirebaseAuth.instance.authStateChanges(), builder: (context, snapshot) { if (snapshot.hasData && snapshot.data!.emailVerified) { return AnimatedBottomNavigationBar.builder( backgroundColor: Theme.of(context).colorScheme.onPrimaryContainer, itemCount: 2, tabBuilder: (index, isActive) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( index == 0 ? Icons.cached_sharp : Icons.account_balance_wallet_outlined, size: 24, key: tutTargetsKeys[index], color: isActive ? orangeyRed : lightGrey, ), const SizedBox(height: 4), Text( index == 0 ? 'المعاملات' : 'المحفظات', style: TextStyle( fontFamily: 'Tajawal', color: isActive ? orangeyRed : lightGrey, ), ) ], ); }, hideAnimationController: _hideBottomBarAnimationController, gapLocation: GapLocation.center, notchSmoothness: NotchSmoothness.smoothEdge, leftCornerRadius: 32, rightCornerRadius: 32, activeIndex: _selectedIndex, onTap: (index) { setState(() => _selectedIndex = index); }, ); } else { return const SizedBox.shrink(); } }), body: NotificationListener<ScrollNotification>( onNotification: onScrollNotification, child: StreamBuilder( stream: FirebaseAuth.instance.authStateChanges(), builder: (context, snapshot) { if (snapshot.hasData && snapshot.data!.emailVerified) { return bottomNanScreens.elementAt(_selectedIndex); } else { return const AuthScreen(); } }, ), ), ), ); } }
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs'; import { Injectable, UnauthorizedException } from '@nestjs/common'; import { LoginCommand } from './login.command'; import { UserService } from '../../domain/services/user.service'; @Injectable() @CommandHandler(LoginCommand) export class LoginCommandHandler implements ICommandHandler<LoginCommand> { constructor(private readonly userService: UserService) {} async execute(command: LoginCommand): Promise<string> { const { username, password } = command; try { const token = await this.userService.login(username, password); return token; } catch (error) { if (error instanceof UnauthorizedException) { throw error; } throw new UnauthorizedException('Invalid username or password'); } } }
<!doctype html> <html lang="en"> <head> {% load static %} <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <link rel="icon" type="image/x-icon" href="{% static 'favicon.ico' %}" /> <title>cinephile</title> </head> <body style="background: #ccffcc;"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <nav class="navbar fixed-top navbar-expand-lg navbar-light" style="background-color:#74cfbf;"> <a class="navbar-brand" href="#"><b>Cinephile</b></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarText"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'search' %}">Search</a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'review' %}">Reviews</a> </li> <li class="nav-item active"> <a class="nav-link" href="#">Recommendation</a> </li> <li class="nav-item active"> <a class="nav-link" href="#about-sec">About</a> </li> </ul> {% if user.is_authenticated %} <span class="navbar-text"> <h1 class="lead"><a href="/cinephile/profile/{{user.id}}">Hello {{ user.username }}</a></h1><h2 class="lead"><a href="{% url 'logout' %}">signout</a></h2> </span> {% else %} <span class="navbar-text"> <button type="button" class="btn btn-outline-success" onclick="login()" >Login</button> <button type="button" class="btn btn-success" onclick="signup()">signup</button> </span> {% endif %} </div> </nav> </div> </div> </div> <section class="site-section" id="detail-sec"> <div class="row"> <div class="col-md-6" style="margin: 7rem auto 0 auto; text-align: center;"> <span> <h6 class="display-4">{{title}}</h6> {% if user.is_authenticated %} <button type="button" class="btn btn-success" onclick="write_rev()">Write a review</button> <button type="button" class="btn btn-primary" data-toggle="button" aria-pressed="false" autocomplete="off" onClick="addtowatch()"> Watched </button>{% endif %}</span> </div> </div> <div class="container-fluid"> <div class="row" > <div class="col-md-4" style="margin: auto 0; text-align: center;"> <img class="img-fluid" src="{{poster}}" alt="Poster not found" > </div> <div class="col-md-4" style="margin: 2rem auto auto auto;"> <p class="lead"><b>Plot:</b> {{plot}}</p> <p class="lead"><b>Director</b>: {{director}}</p> <p class="lead"><b>Writer:</b> {{writer}}</p> <p class="lead"><b>Cast:</b> {{actors}}</p> <p class="lead"><b>Genre:</b> {{genre}}</p> <p class="lead"><b>Country:</b> {{country}}</p> </div> <div class="col-md-4"style="margin: 2rem auto auto auto;"> <p class="lead"><b>Language: </b>{{language}}</p> <p class="lead"><b>Year: </b>{{Year}}</p> <p class="lead"><b>Released: </b>{{released}}</p> <p class="lead"><b>Runtime: </b>{{runtime}}</p> <p class="lead"><b>Rated: </b>{{rated}}</p> <p class="lead"><b>Awards: </b>{{awards}}</p> </div> </div> </div> </section> <section id="review-sec"> <div class="container-fluid"> <div class="row"> <div class="col-md-6" style="margin: 7rem auto 0 auto; text-align: center;"> <p class="display-4"> Review Section</p> </div> </div> <div class="row"> <div class="col-md-2"style="margin: 3rem 0 auto 1rem;"> </div> <div class="col-md-8" style="margin: 3rem 0 auto 1rem; "> {% for each in user_review %} <blockquote class="blockquote"> <p class="mb-0">{{each.content}}.</p> <footer class="blockquote-footer">{{each.pen_id.user.username}} in <cite title="Movie Title">{{title}}</cite></footer> </blockquote> {% endfor %} </div> </div> </div> </section> {% if user.is_authenticated %} <section id="review_write-sec"> <div class="container-fluid" style="margin: 3rem auto auto;"> <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <form method="POST" action="/cinephile/writereview/{{movie_id}}/{{user.id}}"> {% csrf_token %} <div class="mb-3"> <textarea class="form-control" name="content" id="content" rows="4" placeholder="Write your review here"></textarea> </div> <div class="mb-3"> <button type="submit" class="btn btn-info">Post</button> </div> </form> </div> </div> </div> </section> {% endif %} <div class="container-fluid" style="margin-bottom: 10rem;"> <div class="row"> <footer class="fixed-bottom navbar-light" style="background-color:#74cfbf;"> <div class="container"> <div class="row md-5"> <p class="col-12 text-center" > <br> Copyright &copy; <script>document.write(new Date().getFullYear());</script> All rights reserved | Made with <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-heart-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M8 1.314C12.438-3.248 23.534 4.735 8 15-7.534 4.736 3.562-3.248 8 1.314z"/> </svg> from <a href="https://github.com/halfwitted" target="_blank" class="text-primary">Abhishek</a> </p> </div> </div> </footer> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> <script> function login(){ window.location = "{% url 'login' %}"; } function signup(){ window.location = "{% url 'register' %}"; } function write_rev(){ window.location = "#review_write-sec"; } function addtowatch(){ window.location = "/cinephile/recommend/{{movie_id}}/{{user.id}}"; } </script> </body> </html>
package com.miniproject335b.app.controller; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.miniproject335b.app.model.MRole; import com.miniproject335b.app.repository.MRoleRepository; @RestController @CrossOrigin("*") @RequestMapping("/role/") public class MRoleController { @Autowired private MRoleRepository mRoleRepository; private Integer pageSize = 3; private Integer currentPage = 0; private Long totalItems = 0L; private Integer totalPages = 0; private Map<String, Object> response(String status, String message, Object data) { Map<String, Object> response = new HashMap<>(); response.put("status", status); response.put("message", message); response.put("pageSize", this.pageSize); response.put("currentPage", this.currentPage); response.put("totalItems", this.totalItems); response.put("totalPages", this.totalPages); response.put("data", data); return response; } @GetMapping("showall") public ResponseEntity<Map<String, Object>> getAllMRole() { try { List<MRole> listMRole = this.mRoleRepository.findByIsDelete(false); if (listMRole.isEmpty()) { return new ResponseEntity<>(response("success", "No Data", listMRole), HttpStatus.OK); } else { return new ResponseEntity<>(response("success", "Success Fetch Data", listMRole), HttpStatus.OK); } } catch (Exception e) { return new ResponseEntity<>(response("failed", "Failed Fetch Data", new ArrayList<>()), HttpStatus.OK); } } @GetMapping("showpage") public ResponseEntity<Map<String, Object>> getMRolePageable( @RequestParam(defaultValue = "0") Integer pageNumber, @RequestParam(defaultValue = "3") Integer pageSize, @RequestParam(defaultValue = "asc") String order) { try { Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by("name").ascending()); if (order.equals("desc")) { pageable = PageRequest.of(pageNumber, pageSize, Sort.by("name").descending()); } Page<MRole> page = this.mRoleRepository.getMRoleByPageable(pageable); List<MRole> mRole = page.getContent(); if (mRole.isEmpty()) { return new ResponseEntity<>(response("failed", "Failed Fetch Data", mRole), HttpStatus.OK); } else { this.pageSize = page.getSize(); this.currentPage = page.getNumber(); this.totalItems = page.getTotalElements(); this.totalPages = page.getTotalPages(); return new ResponseEntity<>(response("success", "Success Fetch Data", mRole), HttpStatus.OK); } } catch (Exception e) { return new ResponseEntity<>(response("failed", "Failed Fetch Data", new ArrayList<>()), HttpStatus.OK); } } @GetMapping("show/search") public ResponseEntity<Map<String, Object>> getMRoleBySearch(@RequestParam("name") String name){ try { List<MRole> listMRole = this.mRoleRepository.findBySearch(name); if (listMRole.isEmpty()) { return new ResponseEntity<>(response("success", "No Data", listMRole), HttpStatus.OK); } else { return new ResponseEntity<>(response("success", "Success Fetch Data", listMRole), HttpStatus.OK); } } catch (Exception e) { return new ResponseEntity<>(response("failed", "Failed Fetch Data", new ArrayList<>()), HttpStatus.OK); } } @GetMapping("showpage/search") public ResponseEntity<Map<String, Object>> getMRoleSearchPageable( @RequestParam(defaultValue = "0") Integer pageNumber, @RequestParam(defaultValue = "3") Integer pageSize, @RequestParam(defaultValue = "asc") String order, @RequestParam("name") String name) { try { Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by("name").ascending()); if (order.equals("desc")) { pageable = PageRequest.of(pageNumber, pageSize, Sort.by("name").descending()); } Page<MRole> page = this.mRoleRepository.findBySearchPageable(name,pageable); List<MRole> mRole = page.getContent(); if (mRole.isEmpty()) { return new ResponseEntity<>(response("failed", "Failed Fetch Data", mRole), HttpStatus.OK); } else { this.pageSize = page.getSize(); this.currentPage = page.getNumber(); this.totalItems = page.getTotalElements(); this.totalPages = page.getTotalPages(); return new ResponseEntity<>(response("success", "Success Fetch Data", mRole), HttpStatus.OK); } } catch (Exception e) { return new ResponseEntity<>(response("failed", "Failed Fetch Data", new ArrayList<>()), HttpStatus.OK); } } @PostMapping("add/{user}") public ResponseEntity<Map<String, Object>> createMRole(@RequestBody MRole mRole, @PathVariable("user") Long user) { try { // menghilangkan spasi di awal dan di akhir dari data mPaymentMethod pada field name mRole.setName(mRole.getName().trim()); // cek apakah nama tidak null if (mRole.getName() == "" || mRole.getName() == null) { return new ResponseEntity<>(response("failed", "Name Cannot Be Null", new ArrayList<>()),HttpStatus.OK); } // menghilangkan spasi di awal dan di akhir dari data mRole pada field name mRole.setCode(mRole.getCode().trim()); // cek apakah nama tidak null if (mRole.getCode() == "" || mRole.getCode() == null) { return new ResponseEntity<>(response("failed", "Code Cannot Be Null", new ArrayList<>()),HttpStatus.OK); } // cek apakah nama dengan isDelete=false sudah ada di database List<MRole> listMRole = this.mRoleRepository.findByIsDelete(false); for (MRole role : listMRole) { if (role.getName().equals(mRole.getName())) { return new ResponseEntity<>(response("failed", "Name Already Exist", new ArrayList<>()),HttpStatus.OK); } if (role.getCode().equals(mRole.getCode())) { return new ResponseEntity<>(response("failed", "Code Already Exist", new ArrayList<>()),HttpStatus.OK); } } mRole.setCreatedBy(user); mRole.setCreatedOn(new Date()); mRole.setIsDelete(false); MRole mRoleSaved = this.mRoleRepository.save(mRole); if (mRole.equals(mRoleSaved)) { return new ResponseEntity<>(response("success", "Saved Success", mRoleSaved), HttpStatus.CREATED); } else { return new ResponseEntity<>(response("failed", "Saved Failed", mRoleSaved), HttpStatus.OK); } } catch (Exception e) { return new ResponseEntity<>(response("failed", "Saved Failed", new ArrayList<>()), HttpStatus.OK); } } @GetMapping("show/{id}") public ResponseEntity<Map<String, Object>> getMRoleById(@PathVariable("id") Long id) { try { MRole mRole = this.mRoleRepository.findById(id).orElse(null); if (mRole == null) { return new ResponseEntity<>(response("success", "No Data", mRole), HttpStatus.OK); } else { return new ResponseEntity<>(response("success", "Success Fetch Data", mRole), HttpStatus.OK); } } catch (Exception e) { return new ResponseEntity<>(response("failed", "Failed Fetch Data", new ArrayList<>()), HttpStatus.OK); } } @PutMapping("edit/{id}/{user}") public ResponseEntity<Map<String, Object>> updateMRole(@PathVariable("id") Long id, @RequestBody MRole mRole, @PathVariable("user") Long user) { // menghilangkan spasi di awal dan di akhir dari data mPaymentMethod pada field name mRole.setName(mRole.getName().trim()); // cek apakah nama tidak null if (mRole.getName() == "" || mRole.getName() == null) { return new ResponseEntity<>(response("failed", "Name Cannot Be Null", new ArrayList<>()),HttpStatus.OK); } // menghilangkan spasi di awal dan di akhir dari data mRole pada field name mRole.setCode(mRole.getCode().trim()); // cek apakah nama tidak null if (mRole.getCode() == "" || mRole.getCode() == null) { return new ResponseEntity<>(response("failed", "Code Cannot Be Null", new ArrayList<>()),HttpStatus.OK); } // cek apakah nama dengan isDelete=false sudah ada di database List<MRole> listMRole = this.mRoleRepository.findByIsDelete(false); for (MRole role : listMRole) { if (role.getName().equals(mRole.getName())) { return new ResponseEntity<>(response("failed", "Name Already Exist", new ArrayList<>()),HttpStatus.OK); } if (role.getCode().equals(mRole.getCode())) { return new ResponseEntity<>(response("failed", "Code Already Exist", new ArrayList<>()),HttpStatus.OK); } } MRole mRoleUpdate = this.mRoleRepository.findById(id).orElse(null); if (mRoleUpdate != null) { mRoleUpdate.setName(mRole.getName()); mRoleUpdate.setCode(mRole.getCode()); mRoleUpdate.setModifiedBy(user); mRoleUpdate.setModifiedOn(new Date()); MRole mRoleSaved = this.mRoleRepository.save(mRoleUpdate); if (mRoleSaved.equals(mRoleUpdate)) { return new ResponseEntity<>(response("success", "Modified Success", mRoleSaved), HttpStatus.CREATED); } else { return new ResponseEntity<>(response("failed", "Modified Failed", mRoleSaved), HttpStatus.OK); } } else { return new ResponseEntity<>(response("failed", "Modified Failed", new ArrayList<>()), HttpStatus.OK); } } @PutMapping("delete/{id}/{user}") public ResponseEntity<Map<String, Object>> deleteMPaymentMethod(@PathVariable("id") Long id, @PathVariable("user") Long user) { MRole mRoleDelete = this.mRoleRepository.findById(id).orElse(null); if (mRoleDelete != null) { mRoleDelete.setIsDelete(true); mRoleDelete.setDeletedBy(user); mRoleDelete.setDeletedOn(new Date()); MRole mRoleSaved = this.mRoleRepository.save(mRoleDelete); if (mRoleSaved.equals(mRoleDelete)) { return new ResponseEntity<>(response("success", "Deleted Success", mRoleSaved), HttpStatus.CREATED); } else { return new ResponseEntity<>(response("failed", "Deleted Failed", mRoleSaved), HttpStatus.OK); } } else { return new ResponseEntity<>(response("failed", "Deleted Failed", new ArrayList<>()), HttpStatus.OK); } } }
import numpy as np from typing import Tuple class AbstractSteeringModel: @property def beta(self): raise NotImplementedError def reset(self): raise NotImplementedError def integrate(self, control, dt): raise NotImplementedError class DirectSteeringModel(AbstractSteeringModel): def __init__(self, beta_max: float): self.beta_max = beta_max self._beta = 0. @property def beta(self): return self._beta def reset(self): self._beta = 0. def integrate(self, control, dt): self._beta = np.clip(control * self.beta_max, -self.beta_max, self.beta_max) class RateLimitedSteeringModel(AbstractSteeringModel): def __init__(self, beta_max: float, beta_rate: float): self.beta_max = beta_max self.beta_rate = beta_rate self._beta = 0. @property def beta(self): return self._beta def reset(self): self._beta = 0. def integrate(self, control, dt): assert np.shape(control) == () beta_target = np.clip(control * self.beta_max, -self.beta_max, self.beta_max) d_beta = np.sign(beta_target - self._beta) * self.beta_rate new_beta = np.clip(self._beta + dt * d_beta, -self.beta_max, self.beta_max) zero_crossing = np.sign(beta_target - self._beta) != np.sign(beta_target - new_beta) if zero_crossing: new_beta = beta_target self._beta = new_beta
from typing import Optional from .tag import SelfClosingTag from .types import ContextBase class img(SelfClosingTag): """ Represents the 'img' HTML tag, a self-closing element used to embed an image into a webpage. This tag requires a source URL specified via the 'src' attribute to function correctly and may include an 'alt' attribute to provide alternative text which describes the image if it cannot be displayed. Example usage: image = img() image.set_attribute("src", "path/to/image.jpg") image.set_attribute("alt", "Description of the image") """ def __init__(self, ctx: ContextBase, src: Optional[str], *args, **kwargs): super().__init__(ctx, self.__class__.__name__, *args, **kwargs) if src: self.set_attribute("src", src)
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using HaberPortal.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using HaberPortal.ViewModels; using Microsoft.Extensions.FileProviders; using AspNetCoreHero.ToastNotification.Abstractions; namespace HaberPortal.Controllers { public class NewsController : Controller { private readonly AppDbContext _context; private readonly IFileProvider _fileProvider; private readonly INotyfService _notify; public NewsController(AppDbContext context, IFileProvider fileProvider, INotyfService notify) { _context = context; _fileProvider = fileProvider; _notify = notify; } [Authorize(Roles = "Admin")] public async Task<IActionResult> Index() { return _context.News != null ? View(await _context.News.ToListAsync()) : Problem("Entity set 'AppDbContext.News' is null."); } public async Task<IActionResult> Scan(string searchString) { if (_context.News == null) { return Problem("News is null."); } var news = from n in _context.News select n; if (!String.IsNullOrEmpty(searchString)) { news = news.Where(s => s.Title!.Contains(searchString)); } return View(await news.ToListAsync()); } public async Task<IActionResult> Economy() { return _context.News != null ? View(await _context.News.ToListAsync()) : Problem("Entity set 'AppDbContext.News' is null."); } public async Task<IActionResult> Politics() { return _context.News != null ? View(await _context.News.ToListAsync()) : Problem("Entity set 'AppDbContext.News' is null."); } public async Task<IActionResult> Sport() { return _context.News != null ? View(await _context.News.ToListAsync()) : Problem("Entity set 'AppDbContext.News' is null."); } public async Task<IActionResult> Global() { return _context.News != null ? View(await _context.News.ToListAsync()) : Problem("Entity set 'AppDbContext.News' is null."); } public async Task<IActionResult> Nation() { return _context.News != null ? View(await _context.News.ToListAsync()) : Problem("Entity set 'AppDbContext.News' is null."); } public async Task<IActionResult> Details(int? id) { if (id == null || _context.News == null) { return NotFound(); } var news = await _context.News .FirstOrDefaultAsync(m => m.Id == id); if (news == null) { return NotFound(); } return View(news); } [Authorize(Roles = "Admin")] public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create(NewsModel newNews) { var rootFolder = _fileProvider.GetDirectoryContents("wwwroot"); var photoUrl = "-"; if (newNews.PhotoFile != null) { var filename = Path.GetFileName(newNews.PhotoFile.FileName); var photoPath = Path.Combine(rootFolder.First(x => x.Name == "newsPhotos").PhysicalPath, filename); using var stream = new FileStream(photoPath, FileMode.Create); newNews.PhotoFile.CopyTo(stream); photoUrl = filename; } var news = new News { Title = newNews.Title, Content = newNews.Content, Description = newNews.Description, Tag = newNews.Tag, PhotoUrl = photoUrl }; _context.News.Add(news); _context.SaveChanges(); _notify.Success("Haber Başarıyla Eklendi."); return View(newNews); } [Authorize(Roles = "Admin")] public async Task<IActionResult> Edit(int? id) { if (id == null || _context.News == null) { return NotFound(); } var news = await _context.News.FindAsync(id); if (news == null) { return NotFound(); } NewsModel newNews = new() { Id = news.Id, Content = news.Content, Tag = news.Tag, Description = news.Description, Title = news.Title, PhotoFile = null }; return View(newNews); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(NewsModel newNews) { try { var rootFolder = _fileProvider.GetDirectoryContents("wwwroot"); var photoUrl = "-"; if (newNews.PhotoFile != null) { var filename = Path.GetFileName(newNews.PhotoFile.FileName); var photoPath = Path.Combine(rootFolder.First(x => x.Name == "newsPhotos").PhysicalPath, filename); using var stream = new FileStream(photoPath, FileMode.Create); newNews.PhotoFile.CopyTo(stream); photoUrl = filename; } var news = _context.News.FirstOrDefault(n => n.Id == newNews.Id); news.Title = newNews.Title; news.Content = newNews.Content; news.Description = newNews.Description; news.Tag = newNews.Tag; news.PhotoUrl = photoUrl; await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!NewsExists(newNews.Id)) { return NotFound(); } throw; } return RedirectToAction(nameof(Index)); } [Authorize(Roles = "Admin")] public async Task<IActionResult> Delete(int? id) { if (id == null || _context.News == null) { return NotFound(); } var news = await _context.News .FirstOrDefaultAsync(m => m.Id == id); if (news == null) { return NotFound(); } return View(news); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { if (_context.News == null) { return Problem("Entity set 'AppDbContext.News' is null."); } var news = await _context.News.FindAsync(id); if (news == null) { return Problem("Data not found."); } var rootFolder = _fileProvider.GetDirectoryContents("wwwroot"); if (news.PhotoUrl != null && news.PhotoUrl.Length > 1) { var filename = Path.GetFileName(news.PhotoUrl); var photoPath = Path.Combine(rootFolder.First(x => x.Name == "newsPhotos").PhysicalPath, filename); System.IO.File.Delete(photoPath); } _context.News.Remove(news); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool NewsExists(int id) { return (_context.News?.Any(e => e.Id == id)).GetValueOrDefault(); } } }