text
stringlengths
184
4.48M
"use strict"; /* console.log(document.querySelector(".message").textContent); document.querySelector('.message').textContent = 'Correct Number!'; console.log(document.querySelector(".message").textContent); document.querySelector('.number').textContent = 13; document.querySelector('.score').textContent = 10; document.querySelector('.guess').value=23; */ let secretnumber = Math.trunc(Math.random() * 20) + 1; let score = 20; let highscore=0; document.querySelector(".check").addEventListener("click", function () { const guess = Number(document.querySelector(".guess").value); console.log(guess, typeof guess); // When there is no input if (!guess) { document.querySelector(".message").textContent = "😡No Number!"; } // When Player Wins else if (guess === secretnumber) { document.querySelector(".message").textContent = "🎉Correct Number!"; document.querySelector(".number").textContent = secretnumber; document.querySelector("body").style.backgroundColor = "#60b347"; document.querySelector(".number").style.width = "30rem"; if(score>highscore){ highscore=score; document.querySelector(".highscore").textContent=highscore; } } // when guess is too high else if (guess > secretnumber) { if (score > 1) { document.querySelector(".message").textContent = "Too High"; score--; document.querySelector(".score").textContent = score; } else { document.querySelector(".message").textContent = "⛔You lost the game"; } } // when the guess is too low else if (guess < secretnumber) { if (score > 1) { document.querySelector(".message").textContent = "Too low"; score--; document.querySelector(".score").textContent = score; } else { document.querySelector(".message").textContent = "⛔You lost the game"; } } document.querySelector(".again").addEventListener("click", function () { score = 20; secretnumber = Math.trunc(Math.random() * 20) + 1; document.querySelector(".message").textContent = "Start Guessing..."; document.querySelector(".score").textContent = score; document.querySelector(".number").textContent = "?"; document.querySelector(".guess").value = " "; document.querySelector("body").style.backgroundColor = "#222"; document.querySelector(".number").style.width = "15rem"; }); });
/*! \page Skin_Timers Skin Timers \brief **Programatic time-based resources for Skins** \tableofcontents -------------------------------------------------------------------------------- \section Skin_Timers_sect1 Description Skin timers are skin resources that are dependent on time and can be fully controlled from skins either using \link page_List_of_built_in_functions **Builtin functions**\endlink or \link modules__infolabels_boolean_conditions **Infolabels and Boolean conditions**\endlink. One can see them as stopwatches that can be activated and deactivated automatically depending on the value of info expressions or simply activated/deactivated manually from builtins. The framework was created to allow skins to control the visibility of windows (and controls) depending on the elapsed time of timers the skin defines. Skin timers allow multiple use cases in skins, previously only available via the execution of python scripts: - Closing a specific window after x seconds have elapsed - Controlling the visibility of a group (or triggering an animation) depending on the elapsed time of a given timer - Defining a buffer time window that is kept activated for a short period of time (e.g. keep controls visible for x seconds after a player seek) - Executing timed actions (on timer stop or timer start) - etc Skin timers are defined in the `Timers.xml` file within the xml directory of the skin. The file has the following "schema": ~~~~~~~~~~~~~{.xml} <timers> <timer>...</timer> <timer>...</timer> </timers> ~~~~~~~~~~~~~ see \link Skin_Timers_sect2 the examples section\endlink and \link Skin_Timers_sect3 the list of available tags\endlink for concrete details. \skinning_v20 Added skin timers -------------------------------------------------------------------------------- \section Skin_Timers_sect2 Examples The following example illustrates the simplest possible skin timer. This timer is completely manual (it has to be manually started and stopped): ~~~~~~~~~~~~~{.xml} <timer> <name>mymanualtimer</name> <description>100% manual timer</description> </timer> ~~~~~~~~~~~~~ This timer can be controlled from your skin by executing the \link Builtin_SkinStartTimer `Skin.TimerStart(mymanualtimer)` builtin\endlink or \link Builtin_SkinStopTimer `Skin.TimerStop(mymanualtimer)` builtin\endlink. You can define the visibility of skin elements based on the internal properties of the timer, such as the fact that the timer is active/running using \link Skin_TimerIsRunning `Skin.TimerIsRunning(mymanualtimer)` info\endlink or depending on the elapsed time (e.g. 5 seconds) using the \link Skin_TimerElapsedSecs Integer.IsGreaterOrEqual(Skin.TimerElapsedSecs(mymanualtimer),5) info\endlink. The following timer is a variation of the previous timer but with the added ability of being automatically stopped by the skinning engine after a maximum of elapsed 5 seconds without having to issue the `Skin.TimerStop(mymanualtimer)` builtin: ~~~~~~~~~~~~~{.xml} <timer> <name>mymanualautocloseabletimer</name> <description>100% manual autocloseable timer</description> <stop>Integer.IsGreaterOrEqual(Skin.TimerElapsedSecs(mymanualautocloseabletimer),5)</stop> </timer> ~~~~~~~~~~~~~ This type of timer is particularly useful if you want to automatically close a specific window (or triggering a close animation) after x time has elapsed, while guaranteeing the timer is also stopped. See the example below: ~~~~~~~~~~~~~{.xml} <?xml version="1.0" encoding="utf-8"?> <window type="dialog" id="1109"> <onload>Skin.TimerStart(mymanualautocloseabletimer)</onload> ... <controls> <control type="group"> <animation effect="slide" start="0,0" end="0,-80" time="300" condition="Integer.IsGreaterOrEqual(Skin.TimerElapsedSecs(mymanualautocloseabletimer),5)">Conditional</animation> ... </control> </controls> </window> ~~~~~~~~~~~~~ The following timer presents a notification (for 1 sec) whenever the timer is activated or deactivated: ~~~~~~~~~~~~~{.xml} <timer> <name>manualtimerwithactions</name> <description>100% manual timer with actions</description> <onstart>Notification(skintimer, My timer was started, 1000)</onstart> <onstop>Notification(skintimer, My timer was stopped, 1000)</onstop> </timer> ~~~~~~~~~~~~~ The following timer is an example of a completely automatic timer. The timer is automatically activated or deactivated based on the value of boolean info expressions. In this particular example, the timer is automatically started whenever the Player is playing a file (if not already running). It is stopped if there is no file being played (and of course if previously running). Since the timer can be activated/deactivated multiple times, `reset="true"` ensures the timer is always reset to 0 on each start operation. Whenever the timer is started or stopped, notifications are issued. ~~~~~~~~~~~~~{.xml} <timer> <name>myautomatictimer</name> <description>Player state checker</description> <start reset="true">Player.Playing</start> <stop>!Player.Playing</stop> <onstart>Notification(skintimer, Player has started playing a file, 1000)</onstart> <onstop>Notification(skintimer, Player is no longer playing a file, 1000)</onstop> </timer> ~~~~~~~~~~~~~ In certain situations you might want to reset your timer without having to stop and start. For instance, if you want to stop the timer after 5 seconds but have the timer resetting to 0 seconds if the user provides some input to Kodi. For such cases the `<reset/>` condition can be used: ~~~~~~~~~~~~~{.xml} <timer> <name>windowtimer</name> <description>Reset on idle</description> <start reset="true">Window.IsActive(mywindow)</start> <reset>Window.IsActive(mywindow) + !System.IdleTime(1) + Integer.IsGreaterOrEqual(Skin.TimerElapsedSecs(windowtimer), 1)</reset> <stop>!Window.IsActive(mywindow) + Integer.IsGreaterOrEqual(Skin.TimerElapsedSecs(windowtimer), 5)</stop> <onstop>Dialog.Close(mywindow)</onstop> </timer> ~~~~~~~~~~~~~ Finer conditional granularity can also be applied to the `onstop` or `onstart` actions. This allows the skinner to create generic timers which respect a limited set of conditions but trigger different actions depending on a condition applied only to the action. The following timer plays the trailer of a given item when the user is in the videos window, the item has a trailer, the player is not playing and the global idle time is greater than 3 seconds. As you can see, the first action (notification) is triggered for any item. The actual playback, on the other hand, will only play if the focused item has the label "MyAwesomeMovie". ~~~~~~~~~~~~~{.xml} <timer> <name>trailer_autoplay_idle_timer</name> <start reset="true">System.IdleTime(3) + Window.IsVisible(videos) + !Player.HasMedia + !String.IsEmpty(ListItem.Trailer)</start> <onstart>Notification(skintimer try play, $INFO[ListItem.Trailer], 1000)</onstart> <onstart condition="String.IsEqual(ListItem.Label,MyAwesomeMovie)">PlayMedia($INFO[ListItem.Trailer],1,noresume)</onstart> </timer> ~~~~~~~~~~~~~ -------------------------------------------------------------------------------- \section Skin_Timers_sect3 Available tags Skin timers have the following available tags: | Tag | Description | |--------------:|:--------------------------------------------------------------| | name | The unique name of the timer. The name is used as the id of the timer, hence needs to be unique. <b>(required)</b> | description | The description of the timer, a helper string. <b>(optional)</b> | start | An info bool expression that the skinning engine should use to automatically start the timer <b>(optional)</b> | reset | An info bool expression that the skinning engine should use to automatically reset the timer <b>(optional)</b> | stop | An info bool expression that the skinning engine should use to automatically stop the timer <b>(optional)</b> | onstart | A builtin function that the skinning engine should execute when the timer is started <b>(optional)</b><b>(can be repeated)</b>. Supports an additional `"condition"` as element attribute. | onstop | A builtin function that the skinning engine should execute when the timer is stopped <b>(optional)</b><b>(can be repeated)</b>. Supports an additional `"condition"` as element attribute. @note If multiple onstart or onstop actions exist, their execution is triggered sequentially. @note Both onstart and onstop actions support fine-grained conditional granularity by specifying a "condition" attribute (see the examples above). -------------------------------------------------------------------------------- \section Skin_Timers_sect4 See also #### Development: - [Skinning](http://kodi.wiki/view/Skinning) */
{# started.twig #} {% extends "layout.twig" %} {% block subHeader %} <h2 class="sub-header-tit">GET STARTED</h2> <div class="sub-header-content"> <p class="sub-header-txt">XEIcon 사용방법은 매우 간단합니다. 자신의 웹사이트에 단 두 줄만 추가하는 것으로 바로 사용할 수 있습니다.<br>XEIcon과 함께라면 더욱 멋지고 빠르게 프로젝트를 완성할 수 있습니다.</p> </div> <img src="assets/img/img_started.png" class="sub-spot-img"> {% endblock %} {% block page %} <div class="container sub-contents-container"> <div class="sub-section sub-started"> <h3 class="sub-section-tit" id="installation">설치(Installation)</h3> <hr class="half-rule"> <h4 class="sub-section-sub-tit" id="cdn">가장 쉬운 방법(Easiest) : CDN by jsDelivr</h4> <p class="sub-section-info">CDN을 사용하면 한 줄의 코드로 XEIcon을 사용할 수 있습니다. 파일을 다운로드하거나 설치할 필요가 없습니다.</p> <ul class="desc-box"> <li> <ol> <li> <p class="desc-txt">1. 사이트 <span class="deco-box">&lt;head&gt;</span> 태그 안에 아래의 코드를 붙입니다.</p> <div class="desc-code-box"> <p class="desc-code"><code>&lt;link rel=&quot;stylesheet&quot; href=&quot;//cdn.jsdelivr.net/gh/xpressengine/xeicon@{{ versions[0] }}/xeicon.min.css&quot;&gt;</code></p> </div> </li> <li> <p>2. <a href="examples.html">examples</a>페이지를 참조하여 XEIcon을 웹페이지에 적용합니다.</p> </li> </ol> </li> <li> <ol> <li> <p class="desc-txt">1. Paste the following code into the <span class="deco-box">&lt;head&gt;</span> section of your site&rsquo;s HTML.</p> <div class="desc-code-box"> <p class="desc-code"><code>&lt;link rel=&quot;stylesheet&quot; href=&quot;//cdn.jsdelivr.net/gh/xpressengine/xeicon@{{ versions[0] }}/xeicon.min.css&quot;&gt;</code></p> </div> </li> <li> <p>2. check out the <a href="examples.html">examples</a> to start using XEIcon!</p> </li> </ol> </li> </ul> <h4 class="sub-section-sub-tit">쉬운 방법(Easy) : Import CSS</h4> <p class="sub-section-info">폰트를 다운받아 해당 버전의 XEIcon CSS를 사용하는 방법입니다.</p> <ul class="desc-box"> <li> <ol> <li> <p class="desc-txt">1. XEIcon 홈페이지에서 XEIcon을 다운로드 받습니다.</p> </li> <li> <p class="desc-txt">2. XEIcon이라는 폴더명으로 자신의 웹사이트에 복사합니다.</p> </li> <li> <p class="desc-txt">3. html <span class="deco-box">&lt;head&gt;</span> 태그 안에 xeicon.min.css 파일 위치를 아래와 같이 가져옵니다.</p> <div class="desc-code-box"> <p class="desc-code"><code>&lt;link =&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;path/to/xeicon/xeicon.min.css&quot;&gt;</code></p> </div> </li> <li> <p class="desc-txt">4. <a href="library_common.html">XEIcon 라이브러리</a>를 사용해서 XEIcon을 프로젝트에 적용합니다.</p> </li> </ol> </li> <li> <ol> <li> <p class="desc-txt">1. Copy the entire XEIcon directory into your project.</p> </li> <li> <p class="desc-txt">2. In the of your html, reference the location to your xeicon.min.css.</p> <div class="desc-code-box"> <p class="desc-code"><code>&lt;link =&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;path/to/xeicon/xeicon.min.css&quot;&gt;</code></p> </div> </li> <li> <p class="desc-txt">3. check out the <a href="library_common.html">XEIcon Library</a> to start using XEIcon!</p> </li> </ol> </li> </ul> <h4 class="sub-section-sub-tit" id="bower">Bower를 통한 설치 : Install with Bower</h4> <ul class="desc-box"> <li> <ol> <li> <p class="desc-txt">1. 웹 패키지 관리도구 Bower 사용자 설치 방법입니다. 터미널에 아래 명령어를 입력하여 인스톨할 수 있습니다.</p> <div class="desc-code-box"> <p class="desc-code"><code>bower install xeicon</code><br><code>bower install xeicon#&lt;version&gt;</code></p> </div> </li> <li> <p class="desc-txt">2. 자세한 설치방법은 <a href="http://bower.io/docs/api/#install" target="_blank">Bower 홈페이지</a>를 참고하시기 바랍니다.</p> </li> </ol> </li> <li> <ol>c <li> <p class="desc-txt">1. Once you have bower installed, open up Terminal (or Command Prompt) and enter the following command:</p> <div class="desc-code-box"> <p class="desc-code"><code>bower install xeicon</code><br><code>bower install xeicon#&lt;version&gt;</code></p> </div> </li> <li> <p class="desc-txt">2. You can read more about installation on <a href="http://bower.io/docs/api/#install" target="_blank">Bower homepage</a>.</p> </li> </ol> </li> </ul> </div> <div class="sub-section sub-started"> <h3 class="sub-section-tit" id="use">사용방법(How to use)</h3> <hr class="half-rule"> <p>XEIcon은 두가지 방법으로 웹에 적용할 수 있습니다. 적용과 설정 방법은 아래와 같습니다.</p> <h4 class="sub-section-sub-tit" id="tag">Html tag</h4> <ul class="desc-box"> <li> <p class="desc-txt">간단하게 <span class="deco-box">&lt;i&gt;</span> 태그를 웹페이지에 써서 쓸 수 있습니다.</p> <div class="desc-code-box"> <p class="desc-code"><code>&lt;i class=&quot;xi-xpressengine&quot;&gt;&lt;/i&gt; = <i class="xi-xpressengine"></i></code></p> </div> </li> <li> <p class="desc-txt">You can use a simple <span class="deco-box">&lt;i&gt;</span> tag to place an icon in your page, like this:</p> <div class="desc-code-box"> <p class="desc-code"><code>&lt;i class=&quot;xi-xpressengine&quot;&gt;&lt;/i&gt; = <i class="xi-xpressengine"></i></code></p> </div> </li> </ul> <h4 class="sub-section-sub-tit" id="unicode">Unicode HTML Entity</h4> <p class="sub-section-info">폰트를 다운받아 해당 버전의 XEIcon CSS를 사용하는 방법입니다.</p> <ul class="desc-box"> <li> <ol> <li> <p class="desc-txt">1. 유니코드로 XEIcon을 적용하려면, CSS에서 XEIcon을 불러와야 합니다.</p> <div class="desc-code-box"> <p class="desc-code"><code>span.icon {font-family : xeicon;}</code></p> </div> </li> <li> <p class="desc-txt">2. 다음으로 html에 유니코드를 삽입합니다.</p> <div class="desc-code-box"> <p class="desc-code"><code>&lt;span class=&quot;icon&quot;&gt;&amp;#ec2e;&lt;/span&gt;</code></p> </div> </li> </ol> </li> <li> <ol> <li> <p class="desc-txt">1. Specifying the xeicon web-font in a CSS rule with <span class="deco-box">&lt;font-family&gt;</span></p> <div class="desc-code-box"> <p class="desc-code"><code>span.icon {font-family : xeicon;}</code></p> </div> </li> <li> <p class="desc-txt">2. Using the Unicode HTML Entity to display the icon</p> <div class="desc-code-box"> <p class="desc-code"><code>&lt;span class=&quot;icon&quot;&gt;&amp;#ec2e;&lt;/span&gt;</code></p> </div> </li> </ol> </li> </ul> <div class="notice-txt-area"> <p>Note : 이 방법은 더 유연하게 사용할 수 있습니다. 예를들어, &lt;div&gt;, &lt;span&gt;과 같은 태그를 &lt;i&gt;태그 대신에 쓸 수 있습니다.</p> <p>Note : This method may offer you more flexibility. for example, you could use a &lt;div&gt; or &lt;span&gt; tags instead of a &lt;i&gt;tag.</p> </div> </div> </div> {% endblock %}
/*{ "type": "action", "targets": ["omnifocus"], "author": "Niels van Hoorn", "identifier": "nl.zekerwaar.omnifocus.paklijst", "version": "1.0", "description": "Creates a project of single-actions used as a packing list.", "label": "Paklijst", "paletteLabel": "Packing List" }*/ (() => { var action = new PlugIn.Action(function (selection, sender) { var template = projectNamed("[Paklijst Template]"); console.log("template", template.children); var inputForm = new Form(); var dateFormat = Formatter.Date.Style.Short; var dateFormatter = Formatter.Date.withStyle(dateFormat, dateFormat); var taskNameField = new Form.Field.String("tripTitle", "Title", "Vakantie"); const now = new Date(); const from = new Date(now.getTime() + 24 * 3600 * 1000); const to = new Date(from.getTime() + 24 * 3 * 3600 * 1000); var departureDateField = new Form.Field.Date( "departureDate", "Leave", from, dateFormatter ); var returnDateField = new Form.Field.Date( "returnDate", "Return", to, dateFormatter ); inputForm.addField(taskNameField); inputForm.addField(departureDateField); inputForm.addField(returnDateField); const categoryNames = []; const categoryOptions = []; const categorySelection = []; for (const category of template.children) { if (category.dropDate !== null) { continue; } categoryOptions.push(category); categoryNames.push(category.name); if (category.flagged) { categorySelection.push(category); } } const categories = new Form.Field.MultipleOptions( "categories", "Type reis", categoryOptions, categoryNames, categorySelection ); inputForm.addField(categories); var formPromise = inputForm.show( "Enter the trip title and travel dates:", "Continue" ); inputForm.validate = function (formObject) { currentDateTime = new Date(); departureDateObject = formObject.values["departureDate"]; departureDateStatus = departureDateObject && departureDateObject > currentDateTime ? true : false; returnDateObject = formObject.values["returnDate"]; returnDateStatus = returnDateObject && returnDateObject > departureDateObject ? true : false; textValue = formObject.values["tripTitle"]; textStatus = textValue && textValue.length > 0 ? true : false; categoriesObject = formObject.values["categories"]; categoriesStatus = categoriesObject.length > 0 ? true : false; validation = textStatus && departureDateStatus && returnDateStatus && categoriesStatus ? true : false; return validation; }; formPromise.then(function (formObject) { try { var tripTitle = formObject.values["tripTitle"]; var StartDate = formObject.values["departureDate"]; var EndDate = formObject.values["returnDate"]; var tripDuration = parseInt((EndDate - StartDate) / 86400000); var projectName = "Paklijst " + tripTitle; var project = new Project(projectName); project.status = Project.Status.Active; project.containsSingletonActions = true; // project.dueDate = StartDate; categoriesObject = formObject.values["categories"]; const duplicatedTasks = duplicateTasks(categoriesObject, project); const uniqueNames = new Map(); duplicatedTasks.map((t) => t.apply((task) => { task.flagged = false; if (!task.hasChildren) { // Remove duplicates if (uniqueNames.has(task.name)) { const original = uniqueNames.get(task.name); // Copy tasks to original task task.tags.map((tag) => { original.addTag(tag); }); deleteObject(task); } else { uniqueNames.set(task.name, task); // process amounts const matches = task.name.match(/{([^}]+)}/); if (matches) { console.log(matches[1]); try { const result = Function( `days`, `return Math.ceil(${matches[1]})` )(tripDuration); if (typeof result === "number") { task.name = task.name.replace(matches[0], result); } } catch (e) { console.error(e); } } } } }) ); var projID = project.id.primaryKey; URL.fromString("omnifocus:///task/" + projID).open(); } catch (err) { console.error(err); } }); formPromise.catch(function (err) { console.log("form cancelled", err.message); }); }); action.validate = function (selection, sender) { // validation code return true; }; return action; })();
# Step 5: Add Search This is fine for a small number of tracks, but the original iPod could store one thousand songs! Just listing them out wouldn't be manageable. We're going to add search, and in the process we'll touch on applying functional programming in python. ## Objectives Learn to: * Use Python Lambdas. ## Filtering ### In the Functional Style Our basic task is to filter a list of tracks so we only get the ones we want. If we've just bought Weezer's back catalogue but we really want to listen to CAKE, we'll want to filter through our library for just songs with the artist CAKE. So let's look at a few ways to filter lists. We'll use the example of trying to get only the odd numbers out of a list of numbers. Here's one way: ```python numbers = [1, 2, 3, 4, 5] odd_numbers = [] for number in numbers: if number % 2 == 1: # Remember `%` means 'remainder when divided by' (modulo) odd_numbers.append(number) print(odd_numbers) # => [1, 3, 5] ``` The above program is written in an _imperative_ style. That means it works by using loops and ifs to change the state (variables) of the program until it produces the correct result. In this case, the program loops over `numbers` and changes the contents of `odd_numbers`. ### In the Functional Style Here's another approach: ```python numbers = [1, 2, 3, 4, 5] # We'll use the `filter` function. # It takes two arguments, a lambda and a list. odd_numbers = filter( lambda number: number % 2 == 1, # A Lambda is a small function with no name. # In this case, it takes a number as an # argument and returns True if it is odd or # False if it is even. numbers, # And here's our list of numbers. ) # `filter` will # 1. Execute the lambda for each number in the list # 2. If the lambda returns True, it will keep the item # 3. If the lambda returns False, it will discard the item # 4. It will return a new list* with all the kept items. # This could have been on one line too, I just broke it out for you to read. print(list(odd_numbers)) # => [1, 3, 5] # Note: `filter` actually returns an iterable, which acts very similarly to a # list. We need to convert it into a list in order to print it properly. # We do this with `list()`. You won't need to do this most of the time. ``` The above is in a more _functional_ style. It does its job by creating and applying functions — in this case a lambda function. ### Using List Comprehensions <!-- OMITTED --> Here's another way: ```python numbers = [1, 2, 3, 4, 5] odd_numbers = [number for number in numbers if number % 2 == 1] print(odd_numbers) ``` This is also a typical functional approach, but it uses a Python feature called _list comprehensions._ We won't dig too much into those just now, but it's important you can recognise them when you encounter them. Here's a brief schematic: ```python def square_all_odd_numbers(numbers): return [ # Create a list by: number**2 # Evaluating this expression for number # For every item, which we'll call `number` in numbers # In the list called `numbers` if number % 2 == 1 # Where that number is odd ] print(square_all_odd_numbers([1, 2, 3, 4, 5])) # => [1, 9, 25] ``` The python [docs](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) describe this syntax as 'concise and readable'. We can certainly see that it is concise — readable depends on what you're used to. When you get used to this syntax you will probably find it very readable — in any case, it is widely used in Python and so worth learning. ## Implementing Search We're going to use a functional approach to implement our search. Why? Let's first talk about the specification based on the latest user interface. ```shell # We want to implement the ability to search our music library by title, artist, # file, or all of the above depending on what the user chooses. ; python -m ui Welcome to your music library! # Add some tracks etc Enter: a: to add a track p: to play a track d: to delete a track l: to list your tracks s: to search your tracks q: to quit What do you pick? s Search by: t: title a: artist f: file *: anything What do you want to search by? t What do you want to search for? letter 1. Friend Is A Four Letter Word by CAKE @ friend.mp3 2. Dead Letters by P.S. Eliot @ dl.mp3 3. Letters '98 by Havergal @ 98.mp3 ``` And let's try a naïve imperative implementation: ```python class MusicLibrary: def __init__(self): self._tracks = [] # ... omitted other methods def search(self, field, query): query = query.lower() found = [] for track in self._tracks: if field == "title" and query in track.title.lower(): # ^^ # The 'substring in string' operator returns true if `substring` exists # within `string`. So: # 'cat' in 'a cat is nice' is True, whereas # 'dog' in 'a cat is nice' is False found.append(track) elif field == "artist" and query in track.artist.lower(): found.append(track) elif field == "file" and query in track.file.lower(): found.append(track) elif ( field == "any" and (query in track.title.lower()) or (query in track.artist.lower()) or (query in track.file.lower()) ): found.append(track) return found # Usage: lib = MusicLibrary() lib.add(Track("Dead Letters", "P.S. Eliot", "dl.mp3")) lib.add(Track("Friend Is A Four Letter Word", "CAKE", "friend.mp3")) lib.add(Track("Letters '98", "Havergal", "98.mp3")) lib.search("title", "Dead") ``` This has a few disadvantages: 1. It's pretty long and unwieldy. 2. If we want to add more criteria, this string of else ifs will get longer and longer. If you've ever done the Gilded Rose exercise, you'll know the result. 3. We're passing strings around to dictate the type of query, which will be harder to refactor since if you need to change the format, you'll need to search the codebase for `"title"` and hope you catch them all. Let's try using a list comprehension: ```python def search(self, field, query): query = query.lower() if field == "title": return [track for track in self._tracks if query in track.title.lower()] elif field == "artist": return [track for track in self._tracks if query in track.artist.lower()] elif field == "file": return [track for track in self._tracks if query in track.file.lower()] elif field == "any": return [ track for track in self._tracks if (query in track.title.lower()) or (query in track.artist.lower()) or (query in track.file.lower()) ] ``` Or `filter`? ```python def search(self, field, query): query = query.lower() if field == "title": return filter(lambda track: query in track.title.lower(), self._tracks) elif field == "artist": return filter(lambda track: query in track.artist.lower(), self._tracks) elif field == "file": return filter(lambda track: query in track.file.lower(), self._tracks) elif field == "any": return filter( lambda track: (query in track.title.lower()) or (query in track.artist.lower()) or (query in track.file.lower()), self._tracks, ) ``` Are either of those better? Only marginally. They're a tiny bit shorter, but both still have all of the above problems. A seasoned functional programmer would notice that there are only a few things that really differentiate the branches: 1. The field string, which we don't really like anyway. 2. The contents of the lambda. If, instead of this, we pass in a lambda to do the filtering, we get: ```python def search(self, condition): return filter(condition, self._tracks) # Usage: from player.music_library import MusicLibrary, Track lib = MusicLibrary() lib.add(Track("Dead Letters", "P.S. Eliot", "dl.mp3")) lib.add(Track("Friend Is A Four Letter Word", "CAKE", "friend.mp3")) lib.add(Track("Letters '98", "Havergal", "98.mp3")) lib.search(lambda track: "dead" in track.title.lower()) ``` What a result! The advantages: 1. The `search` method is much more concise and readable. 2. It's also much less likely to need to change, meaning less work for the devs. 3. And it's much more powerful. Users of `MusicLibrary` can now get it to search case sensitively, by totally new fields yet to be invented, or whatever they like. There is one disadvantage, which is that you may find custom lambdas popping up all over the code. Any ideas what could improve that? You'll have the opportunity to improve that later in the module. ## Exercise Good news! Kez has won the lottery and is off on a round-the-world cruise. That means the user interface is now yours to maintain. Kez did leave you with some pointers though. Copy in [`interfaces/step_05/ui`](./interfaces/step_05) to your project and get started. ### Part One Test-drive a new `search` method in `MusicLibrary` that takes a lambda as an argument and uses it to filter the tracks as above. Don't touch the UI yet. ### Part Two Open up `ui/interface.py`. You'll see some `TODO` markers. Implement those. Kez has already written some tests for you. Once you've implemented the functionality effectively throughout, the interface tests should pass: ```shell python -m unittest discover ui ..... ---------------------------------------------------------------------- Ran 5 tests in 0.001s OK ``` ### Part Three List comprehensions are considered to be more [idiomatic](https://softwareengineering.stackexchange.com/questions/94563/what-is-idiomatic) than `filter` in Python. Refactor `MusicLibrary#search` to use a list comprehension instead of `filter`. ## Done? [Go to the next challenge](./step_06.md) <!-- BEGIN GENERATED SECTION DO NOT EDIT --> --- **How was this resource?** [😫](https://airtable.com/shrUJ3t7KLMqVRFKR?prefill_Repository=makersacademy/python-data-engineering-challenges&prefill_File=step_05.md&prefill_Sentiment=😫) [😕](https://airtable.com/shrUJ3t7KLMqVRFKR?prefill_Repository=makersacademy/python-data-engineering-challenges&prefill_File=step_05.md&prefill_Sentiment=😕) [😐](https://airtable.com/shrUJ3t7KLMqVRFKR?prefill_Repository=makersacademy/python-data-engineering-challenges&prefill_File=step_05.md&prefill_Sentiment=😐) [🙂](https://airtable.com/shrUJ3t7KLMqVRFKR?prefill_Repository=makersacademy/python-data-engineering-challenges&prefill_File=step_05.md&prefill_Sentiment=🙂) [😀](https://airtable.com/shrUJ3t7KLMqVRFKR?prefill_Repository=makersacademy/python-data-engineering-challenges&prefill_File=step_05.md&prefill_Sentiment=😀) Click an emoji to tell us. <!-- END GENERATED SECTION DO NOT EDIT -->
import { Map, Set } from 'immutable'; import { State } from '../types/store-types'; import { NONE_TAG_ID, NONE_TAG } from '../util/tag-util'; /** * The initial state of the app. * This state is dummy. It needs to be patched by the data from the backend ASAP. * @type {State} */ export const initialState: State = { tags: Map({ [NONE_TAG_ID]: NONE_TAG }), tasks: Map(), dateTaskMap: Map(), groupTaskMap: Map(), repeatedTaskSet: Set(), groupTaskSet: Set(), settings: { canvasCalendar: null, completedOnboarding: true, theme: 'light' }, bannerMessageStatus: {}, courses: Map(), groups: Map(), groupInvites: Map(), }; /** * The initial state setup for testing. * It contains some random values so that snapshot tests can be more meaningful. * @type {State} */ export const initialStateForTesting: State = { tags: Map({ [NONE_TAG_ID]: NONE_TAG, foo: { id: 'foo', order: 1, name: 'Foo', color: 'red', classId: null }, bar: { id: 'bar', order: 2, name: 'Bar', color: 'blue', classId: null }, baz: { id: 'baz', order: 3, name: 'Baz: Baz', color: 'green', classId: '2112' }, }), tasks: Map({ foo: { id: 'foo', order: 1, owner: ['foo'], name: 'Foo', tag: 'foo', complete: true, inFocus: false, children: [{ order: 1, name: 'Foo', complete: true, inFocus: false }], metadata: { type: 'ONE_TIME', date: new Date('2030-01-01'), }, }, bar: { id: 'bar', order: 2, owner: ['foo'], name: 'Bar', tag: 'bar', complete: false, inFocus: true, children: [{ order: 2, name: 'Bar', complete: false, inFocus: true }], metadata: { type: 'ONE_TIME', date: new Date('2030-01-01'), }, }, baz: { id: 'baz', order: 3, owner: ['foo'], name: 'Baz', tag: 'baz', complete: true, inFocus: true, children: [{ order: 3, name: 'Baz', complete: true, inFocus: true }], metadata: { type: 'ONE_TIME', date: new Date('2030-01-01'), }, }, }), dateTaskMap: Map({ [new Date('2030-01-01').toDateString()]: Set(['foo']), [new Date('2031-01-01').toDateString()]: Set(['bar', 'baz']), [new Date('2032-01-01').toDateString()]: Set(), }), groupTaskMap: Map({ groupId1: Set(['foo']), groupId2: Set(['bar', 'baz']), groupId3: Set(), }), repeatedTaskSet: Set(), groupTaskSet: Set(), settings: { canvasCalendar: null, completedOnboarding: true, theme: 'light' }, bannerMessageStatus: {}, courses: Map({ CS2112: [ { courseId: 42, subject: 'CS', courseNumber: '2112', title: 'OO Design Data Structs Honors', examTimes: [ { type: 'final', time: 1576332000000 }, { type: 'prelim', time: 1570145400000 }, ], }, ], }), groups: Map(), groupInvites: Map(), };
import PropTypes from 'prop-types'; import { useNavigate } from 'react-router-dom'; import Button from '../Button/Button'; import Checkbox from '../Checkbox/Checkbox'; function TableRow(props) { const { cols } = props; const navigate = useNavigate(); const status = cols.filter((col) => col.status && col.status === true).length > 0; const action = cols.filter((col) => col.action && col.action === true).length > 0; const checkbox = cols.filter((col) => col.checkbox && col.checkbox === true).length > 0; console.log(cols, props.data); return ( <tr onClick={() => navigate(`${props.data['order id']}`, { state: { data: props.data } }) } > {Object.entries(props.data).map( ([key, value], id) => cols.some((col) => col.name === key) && ( <> {console.log(key)} {status && (key === 'status' || key === 'drink status') ? ( <td key={id}> {value === 'Success' && ( <Button variant='outline' size='xm' type='success'> {value.toUpperCase()} </Button> )} {value === 'Failure' && ( <Button variant='outline' size='xm' type='danger'> {value.toUpperCase()} </Button> )} {value === 'Pending' && ( <Button variant='outline' size='xm' type='warning'> {value.toUpperCase()} </Button> )} {value === 'Sent' && ( <Button variant='outline' size='xm' type='sent'> {value.toUpperCase()} </Button> )} {value === 'Refund Initiated' && ( <Button variant='outline' size='xm' type='blue'> {value.toUpperCase().substring(0, value.length - 1)} </Button> )} {value === 'Refund Completed' && ( <Button variant='outline' size='xm' type='purple'> {value.toUpperCase().substring(0, value.length - 2)} </Button> )} </td> ) : action && key === 'action' ? ( <td key={id}> <Button variant='primary'>Refund</Button> </td> ) : checkbox && key === 'selection' ? ( <td key={id}> <Checkbox /> </td> ) : ( <td key={id}>{value}</td> )} </> ) )} </tr> ); } TableRow.propTypes = { data: PropTypes.object, cols: PropTypes.arrayOf(PropTypes.string), }; export default TableRow;
import React from 'react'; import LoadingIcon from './LoadingIcon'; import CreditCardIcon from '@material-ui/icons/CreditCard'; import DescriptionIcon from '@material-ui/icons/Description'; import AccountCircleIcon from '@material-ui/icons/AccountCircle'; import ExitToAppIcon from '@material-ui/icons/ExitToApp'; import MailIcon from '@material-ui/icons/Mail'; import HomeIcon from '@material-ui/icons/Home'; import DashboardIcon from '@material-ui/icons/Dashboard'; import AssessmentIcon from '@material-ui/icons/Assessment'; import EventIcon from '@material-ui/icons/Event'; import PaymentIcon from '@material-ui/icons/Payment'; import CloudUploadIcon from '@material-ui/icons/CloudUpload'; import CloudDownloadIcon from '@material-ui/icons/CloudDownload'; import CheckCircleIcon from '@material-ui/icons/CheckCircle'; import DoneIcon from '@material-ui/icons/Done'; import ErrorIcon from '@material-ui/icons/Error'; import InfoIcon from '@material-ui/icons/Info'; import CloseIcon from '@material-ui/icons/Close'; import AddIcon from '@material-ui/icons/Add'; import RemoveIcon from '@material-ui/icons/Remove'; import RemoveCircleIcon from '@material-ui/icons/RemoveCircle'; import DeleteIcon from '@material-ui/icons/Delete'; import EditIcon from '@material-ui/icons/Edit'; import GroupIcon from '@material-ui/icons/Group'; import PhotoIcon from '@material-ui/icons/Photo'; import PhotoCameraIcon from '@material-ui/icons/PhotoCamera'; import AddCommentIcon from '@material-ui/icons/AddComment'; import CommentIcon from '@material-ui/icons/ModeComment'; import SendIcon from '@material-ui/icons/Send'; import LikeIcon from '@material-ui/icons/ThumbUp'; import MoreHorizIcon from '@material-ui/icons/MoreHoriz'; import MoreVertIcon from '@material-ui/icons/MoreVert'; import PieChartIcon from '@material-ui/icons/PieChart'; import LineChartIcon from '@material-ui/icons/ShowChart'; import SearchIcon from '@material-ui/icons/Search'; import ViewCarouselIcon from '@material-ui/icons/ViewCarousel'; import StorageIcon from '@material-ui/icons/Storage'; import BuildIcon from '@material-ui/icons/Build'; import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; import ChevronRightIcon from '@material-ui/icons/ChevronRight'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import ExpandLessIcon from '@material-ui/icons/ExpandLess'; import AppsIcon from '@material-ui/icons/Apps'; import TimelineIcon from '@material-ui/icons/Timeline'; import ProcessorIcon from '@material-ui/icons/Memory'; import ViewCompactIcon from '@material-ui/icons/ViewCompact'; import ViewQuiltIcon from '@material-ui/icons/ViewQuilt'; import HighlightIcon from '@material-ui/icons/Highlight'; import LayersIcon from '@material-ui/icons/Layers'; import FullScreenIcon from '@material-ui/icons/Fullscreen'; import FullScreenExitIcon from '@material-ui/icons/FullscreenExit'; import ExploreIcon from '@material-ui/icons/Explore'; import CreateNewFolderIcon from '@material-ui/icons/CreateNewFolder'; import RefreshIcon from '@material-ui/icons/Refresh'; import SaveIcon from '@material-ui/icons/Save'; import SortAlphaIcon from '@material-ui/icons/SortByAlpha'; import SortIcon from '@material-ui/icons/Sort'; import ShareIcon from '@material-ui/icons/Share'; import TiltShiftIcon from '@material-ui/icons/FilterTiltShift'; import CameraIcon from '@material-ui/icons/Camera'; import ViewModuleIcon from '@material-ui/icons/ViewModule'; import VisibilityIcon from '@material-ui/icons/Visibility'; import BarChartIcon from '@material-ui/icons/BarChart'; import TuneIcon from '@material-ui/icons/Tune'; import TransformIcon from '@material-ui/icons/Transform'; import StraightenIcon from '@material-ui/icons/Straighten'; import GridOnIcon from '@material-ui/icons/GridOn'; import GridOffIcon from '@material-ui/icons/GridOff'; import FolderIcon from '@material-ui/icons/Folder'; import PersonIcon from '@material-ui/icons/Person'; import PeopleIcon from '@material-ui/icons/People'; import HelpIcon from '@material-ui/icons/Help'; import MenuBookIcon from '@material-ui/icons/MenuBook'; import ArrowLeftIcon from '@material-ui/icons/ArrowLeft'; import ArrowRightIcon from '@material-ui/icons/ArrowRight'; import ErrorOutlineIcon from '@material-ui/icons/ErrorOutline'; import FirstPageIcon from '@material-ui/icons/FirstPage'; import LastPageIcon from '@material-ui/icons/LastPage'; import CancelIcon from '@material-ui/icons/Cancel'; import WarningIcon from '@material-ui/icons/Warning'; import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown'; import ArrowDropUpIcon from '@material-ui/icons/ArrowDropUp'; import AssignmentIcon from '@material-ui/icons/Assignment'; import LocalBarIcon from '@material-ui/icons/LocalBar'; import LinearScaleIcon from '@material-ui/icons/LinearScale'; import ShoppingCartIcon from '@material-ui/icons/ShoppingCart'; import PersonAddIcon from '@material-ui/icons/PersonAdd'; import GroupAddIcon from '@material-ui/icons/GroupAdd'; import NotificationsIcon from '@material-ui/icons/Notifications'; import MoodIcon from '@material-ui/icons/Mood'; import GifIcon from '@material-ui/icons/Gif'; import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import ArrowForwardIcon from '@material-ui/icons/ArrowForward'; import NavigationIcon from '@material-ui/icons/Navigation'; import SettingsIcon from '@material-ui/icons/Settings'; import UndoIcon from '@material-ui/icons/Undo'; import StyleIcon from '@material-ui/icons/Style'; const customIconTypes = { loading: LoadingIcon, }; const muiIconTypes = { accountCircle: AccountCircleIcon, add: AddIcon, addComment: AddCommentIcon, apps: AppsIcon, arrowBack: ArrowBackIcon, arrowDropDown: ArrowDropDownIcon, arrowDropUp: ArrowDropUpIcon, arrowForward: ArrowForwardIcon, arrowLeft: ArrowLeftIcon, arrowRight: ArrowRightIcon, assessment: AssessmentIcon, assignment: AssignmentIcon, barChart: BarChartIcon, build: BuildIcon, cancel: CancelIcon, camera: PhotoCameraIcon, cameraLens: CameraIcon, checkCircle: CheckCircleIcon, close: CloseIcon, comment: CommentIcon, compass: ExploreIcon, createFolder: CreateNewFolderIcon, creditCard: CreditCardIcon, dashboard: DashboardIcon, delete: DeleteIcon, description: DescriptionIcon, done: DoneIcon, down: ExpandMoreIcon, download: CloudDownloadIcon, edit: EditIcon, error: ErrorIcon, errorOutline: ErrorOutlineIcon, event: EventIcon, exitToApp: ExitToAppIcon, firstPage: FirstPageIcon, folder: FolderIcon, fullscreen: FullScreenIcon, fullscreenExit: FullScreenExitIcon, gif: GifIcon, gridOn: GridOnIcon, gridOff: GridOffIcon, group: GroupIcon, groupAdd: GroupAddIcon, help: HelpIcon, highlight: HighlightIcon, home: HomeIcon, info: InfoIcon, lastPage: LastPageIcon, layers: LayersIcon, left: ChevronLeftIcon, like: LikeIcon, linearScale: LinearScaleIcon, lineChart: LineChartIcon, localBar: LocalBarIcon, mail: MailIcon, menuBook: MenuBookIcon, mood: MoodIcon, moreHoriz: MoreHorizIcon, moreVert: MoreVertIcon, navigation: NavigationIcon, notifications: NotificationsIcon, payment: PaymentIcon, person: PersonIcon, personAdd: PersonAddIcon, photo: PhotoIcon, pieChart: PieChartIcon, processor: ProcessorIcon, refresh: RefreshIcon, remove: RemoveIcon, removeCircle: RemoveCircleIcon, right: ChevronRightIcon, save: SaveIcon, search: SearchIcon, send: SendIcon, settings: SettingsIcon, share: ShareIcon, shoppingCart: ShoppingCartIcon, sortAlpha: SortAlphaIcon, sort: SortIcon, storage: StorageIcon, straighten: StraightenIcon, style: StyleIcon, team: PeopleIcon, tiltShift: TiltShiftIcon, timeline: TimelineIcon, transform: TransformIcon, tune: TuneIcon, undo: UndoIcon, up: ExpandLessIcon, upload: CloudUploadIcon, user: PersonIcon, viewCarousel: ViewCarouselIcon, viewCompact: ViewCompactIcon, viewQuilt: ViewQuiltIcon, viewModule: ViewModuleIcon, visibility: VisibilityIcon, warning: WarningIcon, }; const Icon = (props) => { const { type, ...rest } = props; if (type in customIconTypes) { const CustomIcon = customIconTypes[type]; return <CustomIcon {...rest} />; } else if (type in muiIconTypes) { const MuiIcon = muiIconTypes[type]; return <MuiIcon {...rest} />; } else { // eslint-disable-next-line no-console console.error(`Unsupported Icon type: ${type}`); return null; } }; export default Icon;
<mat-vertical-stepper [linear]="isLinear" #stepper> <mat-step [stepControl]="firstFormGroup"> <ng-template matStepLabel>Personal Info</ng-template> <form [formGroup]="firstFormGroup"> <mat-form-field> <mat-label>Name</mat-label> <input matInput placeholder="Name" formControlName="name" required> </mat-form-field> <br> <mat-form-field> <mat-label>Email Address</mat-label> <input matInput placeholder="Email" formControlName="email" required> </mat-form-field> <br> <mat-form-field> <mat-label>Phone Number</mat-label> <input matInput placeholder="Phone Number" formControlName="phone" required> </mat-form-field> <div> <button mat-button matStepperNext>Next</button> </div> </form> </mat-step> <mat-step [stepControl]="secondFormGroup"> <ng-template matStepLabel>Select Your Plan</ng-template> <form [formGroup]="secondFormGroup"> <mat-radio-group class="options" formControlName="plan"> <mat-radio-button value="arcade">Arcade</mat-radio-button> <mat-radio-button value="advanced">Advanced</mat-radio-button> <mat-radio-button value="pro">Pro</mat-radio-button> </mat-radio-group> <div> <button mat-button matStepperNext>Next</button> </div> </form> </mat-step> <mat-step [stepControl]="thirdFormGroup"> <ng-template matStepLabel>Pick Add-ons</ng-template> <form [formGroup]="thirdFormGroup"> <mat-radio-group class="options" formControlName="addons"> <mat-radio-button value="onlineservice">Online Service</mat-radio-button> <mat-radio-button value="largerstorage">Large Storage</mat-radio-button> <mat-radio-button value="customizableprofile">Customizable Profile</mat-radio-button> </mat-radio-group> <div> <button mat-button matStepperNext>Next</button> </div> </form> </mat-step> <mat-step> <ng-template matStepLabel>Done</ng-template> <p>You are now done.</p> <div> <button mat-button matStepperPrevious>Back</button> <button mat-button (click)="stepper.reset()">Reset</button> <button mat-button (click)="submit()">Submit</button> </div> </mat-step> </mat-vertical-stepper>
<?php /* Plugin Name: XML Sitemaps Plugin URI: http://www.semiologic.com/software/xml-sitemaps/ Description: Automatically generates XML Sitemaps for your site and notifies search engines when they're updated. Version: 2.4 Author: Denis de Bernardy & Mike Koepke Author URI: http://www.getsemiologic.com Text Domain: xml-sitemaps Domain Path: /lang License: Dual licensed under the MIT and GPLv2 licenses */ /* Terms of use ------------ This software is copyright Denis de Bernardy & Mike Koepke, and is distributed under the terms of the MIT and GPLv2 licenses. **/ define('xml_sitemaps_version', '2.4'); if ( !defined('xml_sitemaps_debug') ) define('xml_sitemaps_debug', false); if ( !defined('xml_sitemaps_paged') ) define('xml_sitemaps_paged', false); /** * xml_sitemaps * * @package XML Sitemaps **/ class xml_sitemaps { /** * Plugin instance. * * @see get_instance() * @type object */ protected static $instance = NULL; /** * URL to this plugin's directory. * * @type string */ public $plugin_url = ''; /** * Path to this plugin's directory. * * @type string */ public $plugin_path = ''; /** * Access this plugin’s working instance * * @wp-hook plugins_loaded * @return object of this class */ public static function get_instance() { NULL === self::$instance and self::$instance = new self; return self::$instance; } /** * Loads translation file. * * Accessible to other classes to load different language files (admin and * front-end for example). * * @wp-hook init * @param string $domain * @return void */ public function load_language( $domain ) { load_plugin_textdomain( $domain, FALSE, dirname(plugin_basename(__FILE__)) . '/lang' ); } /** * Constructor. * * */ public function __construct() { $this->plugin_url = plugins_url( '/', __FILE__ ); $this->plugin_path = plugin_dir_path( __FILE__ ); $this->load_language( 'xml-sitemaps' ); add_action( 'plugins_loaded', array ( $this, 'init' ) ); } /** * init() * * @return void **/ function init() { // more stuff: register actions and filters register_activation_hook(__FILE__, array($this, 'activate')); register_deactivation_hook(__FILE__, array($this, 'deactivate')); if ( intval(get_option('xml_sitemaps')) ) { if ( !xml_sitemaps_debug ) add_filter('mod_rewrite_rules', array($this, 'rewrite_rules')); xml_sitemaps::get_options(); add_action('template_redirect', array($this, 'template_redirect')); add_action('save_post', array($this, 'save_post')); add_action('xml_sitemaps_ping', array($this, 'ping')); add_action('do_robots', array($this, 'do_robots')); } else { add_action('admin_notices', array($this, 'inactive_notice')); } add_action('update_option_permalink_structure', array($this, 'reactivate')); add_action('update_option_blog_public', array($this, 'reactivate')); add_action('update_option_active_plugins', array($this, 'reactivate')); add_action('after_db_upgrade', array($this, 'reactivate')); add_action('flush_cache', array($this, 'reactivate')); add_action('wp_upgrade', array($this, 'reactivate')); if ( is_admin() ) { add_action('admin_menu', array($this, 'admin_menu')); add_action('load-settings_page_xml-sitemaps', array($this, 'xml_sitemaps_admin')); } } /** * xml_sitemaps_admin() * * @return void **/ function xml_sitemaps_admin() { include_once $this->plugin_path . '/xml-sitemaps-admin.php'; } /** * do_robots() * * @return void **/ function do_robots() { if ( !intval(get_option('blog_public')) ) return; $file = WP_CONTENT_DIR . '/sitemaps/sitemap.xml'; if ( !file_exists($file) && !xml_sitemaps::generate() ) return; if ( file_exists($file . '.gz') ) $file = trailingslashit(get_option('home')) . 'sitemap.xml.gz'; elseif ( file_exists($file) ) $file = trailingslashit(get_option('home')) . 'sitemap.xml'; else return; echo "\n\n" . 'Sitemap: ' . $file; } # do_robots() /** * ping() * * @return void **/ function ping() { wp_clear_scheduled_hook('xml_sitemaps_ping'); if ( $_SERVER['HTTP_HOST'] == 'localhost' || !intval(get_option('blog_public')) || !intval(get_option('xml_sitemaps_ping')) ) return; $file = WP_CONTENT_DIR . '/sitemaps/sitemap.xml'; if ( !xml_sitemaps::generate() ) return; if ( file_exists($file . '.gz') ) $file = trailingslashit(get_option('home')) . 'sitemap.xml.gz'; elseif ( file_exists($file) ) $file = trailingslashit(get_option('home')) . 'sitemap.xml'; else return; $file = urlencode($file); foreach ( array( 'http://www.google.com/webmasters/sitemaps/ping?sitemap=', 'http://http://www.bing.com/webmaster/ping.aspx?siteMap=', 'http://submissions.ask.com/ping?sitemap=' ) as $service ) wp_remote_fopen($file); } # ping() /** * save_post() * * @param $post_id * @return void */ function save_post($post_id) { if ( wp_is_post_revision($post_id) || !current_user_can('edit_post', $post_id) ) return; $post_id = (int) $post_id; $post = get_post($post_id); # ignore non-published data and password protected data if ( ($post->post_status == 'publish' || $post->post_status == 'trash') && $post->post_password == '' ) { xml_sitemaps::clean(WP_CONTENT_DIR . '/sitemaps'); if ( !wp_next_scheduled('xml_sitemaps_ping') ) wp_schedule_single_event(time() + 600, 'xml_sitemaps_ping'); // 10 minutes } } # save_post() /** * generate() * * @return bool $success **/ function generate() { if ( function_exists('memory_get_usage') && ( (int) @ini_get('memory_limit') < 256 ) ) @ini_set('memory_limit', '256M'); include_once dirname(__FILE__) . '/xml-sitemaps-utils.php'; # disable persistent groups, so as to not pollute memcached wp_cache_add_non_persistent_groups(array('posts', 'post_meta')); # only keep fields involved in permalinks add_filter('posts_fields_request', array($this, 'kill_query_fields')); # sitemap.xml $sitemap = new sitemap_xml; $return = $sitemap->generate(); # restore fields remove_filter('posts_fields_request', array($this, 'kill_query_fields')); return $return; } # generate() /** * template_redirect() * * @return void **/ function template_redirect() { $home_path = parse_url(get_option('home')); $home_path = isset($home_path['path']) ? rtrim($home_path['path'], '/') : ''; if ( in_array( $_SERVER['REQUEST_URI'], array($home_path . '/sitemap.xml', $home_path . '/sitemap.xml.gz') ) && strpos($_SERVER['HTTP_HOST'], '/') === false ) { $dir = WP_CONTENT_DIR . '/sitemaps'; if ( defined('SUBDOMAIN_INSTALL') && SUBDOMAIN_INSTALL ) $dir .= '/' . $_SERVER['HTTP_HOST']; $dir .= $home_path; if ( !xml_sitemaps::clean($dir) ) return; $sitemap = $dir . '/' . basename($_SERVER['REQUEST_URI']); if ( xml_sitemaps_debug || !file_exists($sitemap) ) { if ( !xml_sitemaps::generate() ) return; } # Reset WP $levels = ob_get_level(); for ( $i = 0; $i < $levels; $i++ ) ob_end_clean(); status_header(200); if ( strpos($sitemap, '.gz') !== false ) { header('Content-Type: application/x-gzip'); } else { header('Content-Type:text/xml; charset=utf-8'); } readfile($sitemap); die; } } # template_redirect() /** * rewrite_rules() * * @param array $rules * @return array $rules **/ function rewrite_rules($rules) { $sitemaps_path = WP_CONTENT_DIR . '/sitemaps'; $sitemaps_url = parse_url(WP_CONTENT_URL . '/sitemaps'); $sitemaps_url = $sitemaps_url['path']; $extra = <<<EOS RewriteCond $sitemaps_path%{REQUEST_URI} -f RewriteRule \.xml(\.gz)?$ $sitemaps_url%{REQUEST_URI} [L] EOS; if ( preg_match("/RewriteBase.+\n*/i", $rules, $rewrite_base) ) { $rewrite_base = end($rewrite_base); $new_rewrite_base = trim($rewrite_base) . "\n\n" . trim($extra) . "\n\n"; $rules = str_replace($rewrite_base, $new_rewrite_base, $rules); } return $rules; } # rewrite_rules() /** * save_rewrite_rules() * * @return bool $success **/ function save_rewrite_rules() { if ( !isset($GLOBALS['wp_rewrite']) ) $GLOBALS['wp_rewrite'] = new WP_Rewrite; if ( !function_exists('save_mod_rewrite_rules') || !function_exists('get_home_path') ) { include_once ABSPATH . 'wp-admin/includes/admin.php'; } if ( !get_option('permalink_structure') || !intval(get_option('blog_public')) ) remove_filter('mod_rewrite_rules', array($this, 'rewrite_rules')); return save_mod_rewrite_rules() && get_option('permalink_structure') && intval(get_option('blog_public')); } # save_rewrite_rules() /** * inactive_notice() * * @return void **/ function inactive_notice() { if ( !current_user_can('manage_options') ) return; if ( !xml_sitemaps::activate() ) { global $wpdb; if ( version_compare($wpdb->db_version(), '4.1.1', '<') ) { echo '<div class="error">' . '<p>' . __('XML Sitemaps requires MySQL 4.1.1 or later. It\'s time to <a href="http://www.semiologic.com/resources/wp-basics/wordpress-server-requirements/">change hosts</a> if yours doesn\'t want to upgrade.', 'xml-sitemaps') . '</p>' . "\n" . '</div>' . "\n\n"; } elseif ( ( @ini_get('safe_mode') || @ini_get('open_basedir') ) && !wp_mkdir_p(WP_CONTENT_DIR . '/sitemaps') ) { echo '<div class="error">' . '<p>' . __('Safe mode or open_basedir restriction on your server prevents XML Sitemaps from creating the folders that it needs. It\'s time to <a href="http://www.semiologic.com/resources/wp-basics/wordpress-server-requirements/">change hosts</a> if yours doesn\'t want to upgrade.', 'xml-sitemaps') . '</p>' . "\n" . '</div>' . "\n\n"; } elseif ( !get_option('permalink_structure') ) { if ( strpos($_SERVER['REQUEST_URI'], 'wp-admin/options-permalink.php') === false ) { echo '<div class="error">' . '<p>' . sprintf(__('XML Sitemaps requires that you enable a fancy url structure, under <a href="%s">Settings / Permalinks</a>.', 'xml-sitemaps'), 'options-permalink.php') . '</p>' . "\n" . '</div>' . "\n\n"; } } elseif ( !intval(get_option('blog_public')) ) { // since WP 3.5 if ( class_exists( 'WP_Image_Editor' ) ) { if ( strpos($_SERVER['REQUEST_URI'], 'wp-admin/options-reading.php') === false ) { echo '<div class="error">' . '<p>' . sprintf(__('XML Sitemaps is not active on your site because of your site\'s Search Engine Visibility Settings (<a href="%s">Settings / Reading</a>).', 'xml-sitemaps'), 'options-reading.php') . '</p>' . "\n" . '</div>' . "\n\n"; } } else { if ( strpos($_SERVER['REQUEST_URI'], 'wp-admin/options-privacy.php') === false ) { echo '<div class="error">' . '<p>' . sprintf(__('XML Sitemaps is not active on your site because of your site\'s Privacy Settings (<a href="%s">Settings / Privacy</a>).', 'xml-sitemaps'), 'options-privacy.php') . '</p>' . "\n" . '</div>' . "\n\n"; } } } elseif ( !xml_sitemaps::clean(WP_CONTENT_DIR . '/sitemaps') || !is_writable(ABSPATH . '.htaccess') ){ echo '<div class="error">' . '<p>' . __('XML Sitemaps is not active on your site. Please make the following file and folder writable by the server:', 'xml-sitemaps') . '</p>' . "\n" . '<ul style="margin-left: 1.5em; list-style: square;">' . "\n" . '<li>' . '.htaccess (chmod 666)' . '</li>' . "\n" . '<li>' . 'wp-content (chmod 777)' . '</li>' . "\n" . '</ul>' . "\n" . '</div>' . "\n\n"; } } } # inactive_notice() /** * activate() * * @return bool $success **/ function activate() { # reset status $active = true; # check mysql version global $wpdb; if ( version_compare($wpdb->db_version(), '4.1.1', '<') ) { $active = false; } elseif ( ( @ini_get('safe_mode') || @ini_get('open_basedir') ) && !wp_mkdir_p(WP_CONTENT_DIR . '/sitemaps') ) { $active = false; } else { # clean up $active &= xml_sitemaps::clean(WP_CONTENT_DIR . '/sitemaps'); # insert rewrite rules if ( $active && !xml_sitemaps_debug ) add_filter('mod_rewrite_rules', array($this, 'rewrite_rules')); $active &= xml_sitemaps::save_rewrite_rules(); } if ( !$active ) remove_filter('mod_rewrite_rules', array($this, 'rewrite_rules')); # set options on initial activation xml_sitemaps::init_options(); return $active; } # activate() /** * reactivate() * * @param mixed $in * @return mixed $in **/ function reactivate($in = null) { xml_sitemaps::activate(); return $in; } # reactivate() /** * deactivate() * * @return void **/ function deactivate() { # clean up xml_sitemaps::rm(WP_CONTENT_DIR . '/sitemaps'); # drop rewrite rules remove_filter('mod_rewrite_rules', array($this, 'rewrite_rules')); xml_sitemaps::save_rewrite_rules(); # reset status update_option('xml_sitemaps', 0); } # deactivate() /** * mkdir() * * @param $dir * @return bool $success */ static function mkdir($dir) { return wp_mkdir_p(rtrim($dir, '/')); } # mkdir() /** * rm() * * @param $dir * @return bool $success */ static function rm($dir) { $dir = rtrim($dir, '/'); if ( !file_exists($dir) ) return true; if ( is_file($dir) ) return unlink($dir); return xml_sitemaps::clean($dir) && @rmdir($dir); } # rm() /** * clean() * * @param string $dir * @return bool success **/ static function clean($dir) { if ( !file_exists($dir) ) return xml_sitemaps::mkdir($dir); elseif ( !is_dir($dir) ) return false; if ( !( $handle = opendir($dir) ) ) return false; while ( ( $file = readdir($handle) ) !== false ) { if ( in_array($file, array('.', '..')) ) continue; if ( !xml_sitemaps::rm("$dir/$file") ) { closedir($handle); return false; } } closedir($handle); return true; } # clean() /** * kill_query_fields() * * @param string $fields * @return string $fields **/ function kill_query_fields($fields) { global $wpdb; return "$wpdb->posts.ID, $wpdb->posts.post_author, $wpdb->posts.post_name, $wpdb->posts.post_type, $wpdb->posts.post_status, $wpdb->posts.post_parent, $wpdb->posts.post_date, $wpdb->posts.post_modified"; } # kill_query_fields() /** * kill_query() * * @param $in * @internal param string $where * @return string $where */ static function kill_query($in) { return ' AND ( 1 = 0 ) '; } /** * get_options() * * @return array $options **/ static function get_options() { static $o; if ( !is_admin() && isset($o) ) return $o; $o = get_option('xml_sitemaps'); if ( $o === false || !is_array($o) ) { $o = xml_sitemaps::init_options(); } elseif ( !isset($o['version']) || version_compare( xml_sitemaps_version, $o['version'], '>' ) ) $o = xml_sitemaps::init_options(); return $o; } # get_options() /** * init_options() * * @return array $options **/ static function init_options() { $defaults = array( 'inc_authors' => true, 'inc_categories' => true, 'inc_tags' => true, 'inc_archives' => true, 'exclude_pages' => '', 'mobile_sitemap' => false, 'version' => xml_sitemaps_version, 'empty_author' => false, 'ortho_defaults_set' => false, ); $o = get_option('xml_sitemaps'); if ( $o === false || !is_array($o) ) $updated_opts = $defaults; else $updated_opts = wp_parse_args($o, $defaults); if ( !isset( $o['version'] )) { xml_sitemaps::clean(WP_CONTENT_DIR . '/sitemaps'); } $hostname = php_uname( 'n' ); if ( $updated_opts['ortho_defaults_set'] == false && in_array( $hostname, array('orthohost.com', 'vps.orthohosting.com')) ) { $updated_opts['inc_authors'] = false; $updated_opts['inc_categories'] = false; $updated_opts['inc_tags'] = false; $updated_opts['inc_archives'] = false; $updated_opts['ortho_defaults_set'] = true; xml_sitemaps::clean(WP_CONTENT_DIR . '/sitemaps'); } $updated_opts['version'] = xml_sitemaps_version; update_option('xml_sitemaps', $updated_opts); return $updated_opts; } # init_options() /** * admin_menu() * * @return void **/ function admin_menu() { add_options_page( __('XML Sitemaps', 'xml-sitemaps'), __('XML Sitemaps', 'xml-sitemaps'), 'manage_options', 'xml-sitemaps', array('xml_sitemaps_admin', 'edit_options') ); } # admin_menu() } # xml_sitemaps $xml_sitemaps = xml_sitemaps::get_instance();
import {useState} from 'react'; import './App.css'; import {formatDate} from './lib/utils'; function App() { // State const [msg, setMsg] = useState(null); const [runTrends, setRunTrends] = useState(null); // Methods const fetchFromDate = async date => { let isoDate = `${new Date(date).toISOString().split('.')[0]}Z`; try { /** Fetch runs at the selected Date */ const fetchRuns = await fetch( `https://test-backend.i.datapred.com/without-auth/flows/1/runs?production_date=${isoDate}`, { headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, method: 'GET', }, ); if (fetchRuns.ok) { let run = (await fetchRuns.json()).results[0]; if (run.complete) { setMsg(null); /** If a run is find and complete retrieve the outputs' run */ const fetchOutputs = await fetch( `https://test-backend.i.datapred.com/without-auth/flows/1/runs/${run.id}/outputs`, { headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, method: 'GET', }, ); if (fetchOutputs.ok) { /** An output is found, fetch for the trends */ let output = (await fetchOutputs.json()).results[0]; let fetchTrends = await fetch( `https://test-backend.i.datapred.com/without-auth/flows/1/runs/${run.id}/outputs/${output.id}/trends`, { headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, method: 'GET', }, ); if (fetchTrends.ok) { /** Trends are found and set to the state */ let trends = await fetchTrends.json(); setRunTrends(trends.results); } else { /** Trends are not found */ setMsg('No complete run for this date'); } } } else { /** A run is found but not complete */ setMsg('No complete run for this date'); } } else { /** No run found */ setMsg('No run available for this date'); } } catch (error) { console.log(error); setMsg('An error has occurred when loading data'); } }; return ( <div className="App"> <div className="App-header"> <div className="form"> <label htmlFor="datepicker">Choose a date:</label> <input id="datepicker" type="date" onChange={e => fetchFromDate(e.currentTarget.value)} /> </div> {msg && <div>{msg}</div>} {runTrends && !msg && ( <> <table> <thead> <tr> <th>Horizon Date</th> <th>Horizon Name</th> <th>Trend</th> </tr> </thead> <tbody> {runTrends.map(trend => ( <tr key={trend.id}> <td>{formatDate(trend.horizon_date)}</td> <td>{trend.horizon_name}</td> <td>{trend.trend}</td> </tr> ))} </tbody> </table> </> )} </div> </div> ); } export default App;
# Nicholas Ducharme-Barth # 04/14/2022 # Combine research_fishing_dt and camera_dt data sets into a single analysis ready data set # Copyright (c) 2022 Nicholas Ducharme-Barth # You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. #_____________________________________________________________________________________________________________________________ # load packages library(data.table) library(magrittr) #_____________________________________________________________________________________________________________________________ # set working directory proj.dir = "D:/HOME/SAP/2024_Deep7/" #_____________________________________________________________________________________________________________________________ # define data_flag # data_flag = "" # only loads data up through 2020 data_flag = "2021_" # includes data through 2021 #_____________________________________________________________________________________________________________________________ # bring in data load(file=paste0(proj.dir,"Data/",data_flag,"camera_dt.RData")) load(file=paste0(proj.dir,"Data/",data_flag,"research_fishing_dt.RData")) #_____________________________________________________________________________________________________________________________ # define common columns # id: sample_id # strata: psu, island, strata, strata_2020, substrate, slope, depth_strata, depth_strata_2020, complexity, hardness # temporal: date, year, season, month, jd, year_continuous # spatial: lon, lat # covar: depth, time, lunar_phase # q_covar: gear_type, platform, bait_type # catch: etco, etca, prsi, prfi, przo, hyqu, apru #_____________________________________________________________________________________________________________________________ # format camera_dt to have common columns common_camera_dt = camera_dt %>% .[,gear_type:="camera"] %>% .[,bait_type:="C"] %>% .[,season:="fall"] %>% .[MONTH %in% c("02","03"),season:="spring"] %>% # rename variables setnames(.,c("DROP_CD", "PSU","Island","STRATA","STRATA_2020","substrate","slope","depth_strata","depth_strata_2020","complexity","hardness", "SAMPLE_DATE","YEAR","season","MONTH","JD","YEAR_continuous", "OBS_LON","OBS_LAT", "OFFICIAL_DEPTH_M","DROP_TIME_HST","LUNAR_PHASE", "gear_type", "VESSEL", "bait_type", "ETCO","ETCA","PRSI","PRFI","PRZO","HYQU","APRU"), c("sample_id", "psu", "island", "strata", "strata_2020", "substrate", "slope", "depth_strata", "depth_strata_2020", "complexity", "hardness", "date", "year","season", "month", "jd", "year_continuous", "lon", "lat", "depth", "time", "lunar_phase", "gear_type", "platform", "bait_type", "etco", "etca", "prsi", "prfi", "przo", "hyqu", "apru")) %>% # select proper columns .[,.(sample_id,psu, island, strata, strata_2020, substrate, slope, depth_strata, depth_strata_2020, complexity, hardness,date, year, season, month, jd, year_continuous,lon, lat,depth, time, lunar_phase,gear_type, platform, bait_type,etco, etca, prsi, prfi, przo, hyqu, apru)] #_____________________________________________________________________________________________________________________________ # format research_fishing_dt to have common columns common_research_fishing_dt = research_fishing_dt %>% .[,gear_type:="research_fishing"] %>% .[,season:="fall"] %>% .[MONTH %in% c("02","03"),season:="spring"] %>% # anonymize vessel designation .[,VESSEL:=LETTERS[as.numeric(as.factor(VESSEL))]] %>% # rename variables setnames(.,c("SAMPLE_ID", "PSU","Island","STRATA","STRATA_2020","substrate","slope","depth_strata","depth_strata_2020","complexity","hardness", "SAMPLE_DATE","YEAR","season","MONTH","JD","YEAR_continuous", "LON","LAT", "DEPTH_M","TIME_MIN","LUNAR_PHASE", "gear_type", "VESSEL", "BAIT_CD", "ETCO","ETCA","PRSI","PRFI","PRZO","HYQU","APRU"), c("sample_id", "psu", "island", "strata", "strata_2020", "substrate", "slope", "depth_strata", "depth_strata_2020", "complexity", "hardness", "date", "year","season", "month", "jd", "year_continuous", "lon", "lat", "depth", "time", "lunar_phase", "gear_type", "platform", "bait_type", "etco", "etca", "prsi", "prfi", "przo", "hyqu", "apru")) %>% # select proper columns .[,.(sample_id,psu, island, strata, strata_2020, substrate, slope, depth_strata, depth_strata_2020, complexity, hardness,date, year, season, month, jd, year_continuous,lon, lat,depth, time, lunar_phase,gear_type, platform, bait_type,etco, etca, prsi, prfi, przo, hyqu, apru)] #_____________________________________________________________________________________________________________________________ # combine bfish_combined_wide_dt = rbind(common_camera_dt,common_research_fishing_dt) %>% .[order(year_continuous,gear_type,psu)] bfish_combined_long_dt = bfish_combined_wide_dt %>% melt(.,id.vars=c("sample_id", "psu", "island", "strata", "strata_2020", "substrate", "slope", "depth_strata", "depth_strata_2020", "complexity", "hardness", "date", "year", "season", "month", "jd", "year_continuous", "lon", "lat", "depth", "time", "lunar_phase", "gear_type", "platform", "bait_type")) %>% setnames(.,c("variable","value"),c("species_cd","weight_kg")) #_____________________________________________________________________________________________________________________________ # save formatted data save(common_camera_dt,file=paste0(proj.dir,"Data/",data_flag,"common_camera_dt.RData")) save(common_research_fishing_dt,file=paste0(proj.dir,"Data/",data_flag,"common_research_fishing_dt.RData")) save(bfish_combined_wide_dt,file=paste0(proj.dir,"Data/",data_flag,"bfish_combined_wide_dt.RData")) save(bfish_combined_long_dt,file=paste0(proj.dir,"Data/",data_flag,"bfish_combined_long_dt.RData"))
// // Copyright 2021 The Project Oak Authors // // 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. // #include <fcntl.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/mman.h> #include "wasm_c_api.h" // Ownership indicator as used by the wasm-c-api code. #define own enum ExportFuncs { FN_MALLOC, FN_SET_SHARED, FN_VERIFY_SHARED, FN_FILL_MEMORY, FN_CLEAR_MEMORY, FN_WRITE_RW, FN_READ_RW, FN_WRITE_RO, FN_FORCE_ERROR, }; const char *kExportFuncNames[] = { "malloc", "set_shared", "verify_shared", "fill_memory", "clear_memory", "write_rw", "read_rw", "write_ro", "force_error", }; #define N_FUNCS (sizeof(kExportFuncNames) / sizeof(*kExportFuncNames)) typedef struct { char label; int read_fd; int write_fd; // Engine components own wasm_engine_t *engine; own wasm_store_t *store; own wasm_module_t *module; own wasm_instance_t *instance; own wasm_exporttype_vec_t module_exports; own wasm_extern_vec_t instance_exports; // Export references wasm_memory_t *memory; wasm_func_t *funcs[N_FUNCS]; // Shared buffers own unsigned char *ro_buf; const char *ro_name; int ro_size; own unsigned char *rw_buf; const char *rw_name; int rw_size; } WasmComponents; WasmComponents wc = { 0 }; // Aligns to next largest page boundary, unless p is already aligned. void *page_align(void *p, size_t page_size) { return (void *)((((size_t)p - 1) & ~(page_size - 1)) + page_size); } void info(const char *fmt, ...) { char msg[500]; va_list ap; va_start(ap, fmt); vsnprintf(msg, 500, fmt, ap); va_end(ap); printf("[%c] %s\n", wc.label, msg); } bool error(const char *fmt, ...) { char msg[500]; va_list ap; va_start(ap, fmt); vsnprintf(msg, 500, fmt, ap); va_end(ap); fprintf(stderr, "[%c] >> %s\n", wc.label, msg); return false; } const char *kind_str(enum wasm_externkind_enum kind) { switch (kind) { case WASM_EXTERN_FUNC: return "WASM_EXTERN_FUNC"; case WASM_EXTERN_GLOBAL: return "WASM_EXTERN_GLOBAL"; case WASM_EXTERN_TABLE: return "WASM_EXTERN_TABLE"; case WASM_EXTERN_MEMORY: return "WASM_EXTERN_MEMORY"; default: return "(unknown kind)"; } } typedef struct { bool ok; int val; } FuncResult; // Wraps the cumbersome wasm_func_call API. Assumes args and return value, where present, are i32. FuncResult fn_call(int index, ...) { wasm_func_t *fn = wc.funcs[index]; int arity = wasm_func_param_arity(fn); bool has_result = wasm_func_result_arity(fn); const char *name = kExportFuncNames[index]; // Args vector; capacity of 10 but reset current number to 0. wasm_val_t args[10] = { 0 }; wasm_val_vec_t args_vec = WASM_ARRAY_VEC(args); args_vec.num_elems = 0; assert(arity <= args_vec.size); // Process varags to fill in required number of elements in args/args_vec. char buf[500]; char *p = buf; p += sprintf(p, " -- calling %s(", name); va_list ap; va_start(ap, index); for (int i = 0; i < arity; i++) { int val = va_arg(ap, int); args[i].kind = WASM_I32; args[i].of.i32 = val; args_vec.num_elems++; p += sprintf(p, "%s%d", i ? ", " : "", val); } va_end(ap); info("%s)", buf); // Call the wasm function. FuncResult result = { false, 0 }; wasm_val_t res[1] = { WASM_INIT_VAL }; wasm_val_vec_t res_vec = WASM_ARRAY_VEC(res); own wasm_trap_t *trap = wasm_func_call(fn, arity ? &args_vec : NULL, has_result ? &res_vec : NULL); if (trap == NULL) { // Success - extract the result if required. if (has_result) { result.val = res[0].of.i32; } result.ok = true; } else { // Failure - display the error message. own wasm_message_t msg; wasm_trap_message(trap, &msg); error("Error calling '%s': %s", name, msg.data); wasm_byte_vec_delete(&msg); wasm_trap_delete(trap); } return result; } bool init_module() { info("Loading wasm file"); FILE *file = fopen("module.wasm", "r"); if (file == NULL) { return error("Error loading wasm file"); } fseek(file, 0, SEEK_END); wasm_byte_vec_t wasm_bytes; wasm_bytes.size = ftell(file); wasm_bytes.data = malloc(wasm_bytes.size); fseek(file, 0, SEEK_SET); fread(wasm_bytes.data, 1, wasm_bytes.size, file); fclose(file); info("Creating the store"); wc.engine = wasm_engine_new(); wc.store = wasm_store_new(wc.engine); info("Compiling module"); wc.module = wasm_module_new(wc.store, &wasm_bytes); if (wc.module == NULL) { return error("Error compiling module"); } free(wasm_bytes.data); info("Checking module imports"); own wasm_importtype_vec_t expected_imports; wasm_module_imports(wc.module, &expected_imports); if (expected_imports.size > 0) { return error("Module expects %d imports", expected_imports.size); } wasm_importtype_vec_delete(&expected_imports); info("Instantiating module"); wc.instance = wasm_instance_new(wc.store, wc.module, NULL, NULL); if (wc.instance == NULL) { return error("Error instantiating module"); } info("Retrieving module exports"); wasm_module_exports(wc.module, &wc.module_exports); wasm_instance_exports(wc.instance, &wc.instance_exports); assert(wc.module_exports.size == wc.instance_exports.size); for (int i = 0; i < wc.module_exports.size; i++) { wasm_exporttype_t *export_type = wc.module_exports.data[i]; const wasm_name_t *name = wasm_exporttype_name(export_type); const wasm_externkind_t kind = wasm_externtype_kind(wasm_exporttype_type(export_type)); char buf[100] = { 0 }; memcpy(buf, name->data, name->size); info(" %-30s %s", buf, kind_str(kind)); wasm_extern_t *instance_extern = wc.instance_exports.data[i]; if (strcmp("memory", buf) == 0) { assert(wasm_extern_kind(instance_extern) == WASM_EXTERN_MEMORY); wc.memory = wasm_extern_as_memory(instance_extern); } else { for (int j = 0; j < N_FUNCS; j++) { if (strcmp(kExportFuncNames[j], buf) == 0) { assert(wasm_extern_kind(instance_extern) == WASM_EXTERN_FUNC); wc.funcs[j] = wasm_extern_as_func(instance_extern); break; } } } } if (wc.memory == NULL) { return error("'memory' export not found"); } for (int i = 0; i < N_FUNCS; i++) { if (wc.funcs[i] == NULL) { return error("Function export '%s' not found", kExportFuncNames[i]); } } return true; } bool init_shared_bufs() { info("Allocating shared buffer space in wasm"); int page_size = sysconf(_SC_PAGESIZE); // Call wasm.malloc to reserve enough space for the shared buffers plus alignment concerns. int wasm_alloc_size = wc.ro_size + wc.rw_size + 3 * page_size; info(" wasm_alloc_size: %d", wasm_alloc_size); FuncResult malloc_res = fn_call(FN_MALLOC, wasm_alloc_size); if (!malloc_res.ok) { return false; } // Get the location of wasm's linear memory buffer in our address space. void *wasm_memory_base = wasm_memory_data(wc.memory); info(" wasm_memory_base: %p", wasm_memory_base); // Convert the reserve alloc's linear address to our address space. void *wasm_alloc_ptr = wasm_memory_base + malloc_res.val; info(" wasm_alloc_index: %d", malloc_res.val); info(" wasm_alloc_ptr: %p", wasm_alloc_ptr); // Align the shared buffers inside wasm's linear memory against our page boundaries. void *aligned_ro = page_align(wasm_alloc_ptr, page_size); void *aligned_rw = page_align(aligned_ro + wc.ro_size, page_size); info(" aligned_ro: %p", aligned_ro); info(" aligned_rw: %p", aligned_rw); // Verify that our overall mmapped size will be safely contained in the wasm allocation. void *end = page_align(aligned_rw + wc.rw_size, page_size); int aligned_size = end - wasm_alloc_ptr; info(" aligned_size: %d", aligned_size); assert(aligned_size <= wasm_alloc_size); info("Mapping read-only buffer"); int flags = MAP_SHARED | MAP_FIXED; int ro_fd = shm_open(wc.ro_name, O_RDONLY, S_IRUSR | S_IWUSR); if (ro_fd == -1) { return error("Error calling shm_open"); } wc.ro_buf = mmap(aligned_ro, wc.ro_size, PROT_READ, flags, ro_fd, 0); assert(wc.ro_buf == aligned_ro); info("Mapping read-write buffer"); int rw_fd = shm_open(wc.rw_name, O_RDWR, S_IRUSR | S_IWUSR); if (rw_fd == -1) { return error("Error calling shm_open"); } wc.rw_buf = mmap(aligned_rw, wc.rw_size, PROT_READ | PROT_WRITE, flags, rw_fd, 0); assert(wc.rw_buf == aligned_rw); // We don't need the file descriptors once the buffers have been mapped. assert(close(rw_fd) != -1 && close(ro_fd) != -1); // Inform the wasm module of the aligned shared buffer location in linear memory. int shift_ro = (void *)wc.ro_buf - wasm_memory_base; int shift_rw = (void *)wc.rw_buf - wasm_memory_base; info(" shift_ro: %d", shift_ro); info(" shift_rw: %d", shift_rw); return fn_call(FN_SET_SHARED, shift_ro, wc.ro_size, shift_rw, wc.rw_size).ok; } void destroy() { if (wc.rw_buf != NULL) { assert(munmap(wc.rw_buf, wc.rw_size) != -1); } if (wc.ro_buf != NULL) { assert(munmap(wc.ro_buf, wc.ro_size) != -1); } if (wc.instance_exports.data != NULL) { wasm_extern_vec_delete(&wc.instance_exports); } if (wc.module_exports.data != NULL) { wasm_exporttype_vec_delete(&wc.module_exports); } if (wc.instance != NULL) { wasm_instance_delete(wc.instance); } if (wc.module != NULL) { wasm_module_delete(wc.module); } if (wc.store != NULL) { wasm_store_delete(wc.store); } if (wc.engine != NULL) { wasm_engine_delete(wc.engine); } } bool verify_shared_bufs() { info("Verifying shared buffers"); FuncResult res = fn_call(FN_VERIFY_SHARED); assert(res.ok); switch (res.val) { case 0: return true; case 1: return error("failed: prefix token not matched"); case 2: return error("failed: suffix token not matched"); default: return error("failed: incorrect value at index %d", res.val); } } void scan_memory() { unsigned char *p = wasm_memory_data(wc.memory); size_t size = wasm_memory_data_size(wc.memory); size_t non_zero = 0; size_t filled = 0; for (size_t i = 0; i < size; i++, p++) { if (*p != 0) non_zero++; if (*p == 181) filled++; } info(" %.1lf%% non-zero, %.1lf%% filled", (100.0 * non_zero) / size, (100.0 * filled) / size); } bool test_memory_alloc() { info("Performing memory allocation test"); scan_memory(); FuncResult res = fn_call(FN_FILL_MEMORY); assert(res.ok); info(" malloc failed on iteration %d", res.val); scan_memory(); assert(fn_call(FN_CLEAR_MEMORY).ok); scan_memory(); return true; } bool write_to_rw() { info("Writing to read-write buffer"); // Write 10 values of 20,21,22... from index 3. assert(fn_call(FN_WRITE_RW, 3, 20, 10).ok); return true; } bool read_from_rw() { info("Reading from read-write buffer"); FuncResult res = fn_call(FN_READ_RW, 3, 20, 10); assert(res.ok); if (res.val != 0) return error("failed"); return true; } void write_to_ro() { info("Attempting a write to read-only buffer"); fn_call(FN_WRITE_RO); info("-- should not be reached --"); } bool test_error_handling() { info("Testing container error handling in wasm function call"); return !fn_call(FN_FORCE_ERROR).ok; } void send(char code) { assert(write(wc.write_fd, &code, 1) == 1); } // Commands: // i: initialise // v: verify shared memory contents // m: test memory allocation // w: write to read-write buffer // r: read from read-write buffer // q: write to read-only buffer (will crash) // e: test container's handling of errors in wasm function calls // x: exit void command_loop() { bool ok = true; while (ok) { char cmd = '-'; assert(read(wc.read_fd, &cmd, 1) == 1); printf("\n"); info("<cmd> %c", cmd); switch (cmd) { case 'i': ok = init_module() && init_shared_bufs(); break; case 'v': ok = verify_shared_bufs(); break; case 'm': ok = test_memory_alloc(); break; case 'w': ok = write_to_rw(); break; case 'r': ok = read_from_rw(); break; case 'q': write_to_ro(); // crashes! break; case 'e': ok = test_error_handling(); break; case 'x': send(cmd); return; default: info(" ?? unknown command code"); break; } if (ok) { info(" success"); // Send ack to host. send(cmd); } else { // Send failure signal to host. send('*'); } } } int main(int argc, const char *argv[]) { assert(argc == 8); wc.label = *argv[1]; wc.read_fd = atoi(argv[2]); wc.write_fd = atoi(argv[3]); wc.ro_name = argv[4]; wc.ro_size = atoi(argv[5]); wc.rw_name = argv[6]; wc.rw_size = atoi(argv[7]); info("Container started; pid %d", getpid()); // Send ready signal to host. send('@'); // Process commands from host. command_loop(); info("Shutting down"); destroy(); }
// As seen in the previous exercise, the time of day can be represented as the number of minutes before or after midnight. If the number of minutes is positive, the time is after midnight. If the number of minutes is negative, the time is before midnight. // Write two functions that each take a time of day in 24 hour format, and return the number of minutes before and after midnight, respectively. Both functions should return a value in the range 0..1439. // You may not use javascript's Date class methods. // Understanding the problem: // Input: string // Output: number // Instructions: // - convert a string representation of 24 hour format to minutes // - return a positive number if time is after midnight or negative if time before midnight // Algorithm: // - slice input string first two characters and assignt result to hours // - slice input string and assign result to minutes // - coherce both minutes and hours to number type // - multiply hours by 60 and assign the result to minutesFromHours // - add minutesFromHours to minutes // - return negative for function beforeMidnight and positive for function afterMidnight function beforeMidnight(str) { const MINUTES_IN_A_DAY = 1440; const hours = Number(str.slice(0, 2)); const hoursToMinutes = hours * 60; const minutes = Number(str.slice(3, 5)); const totalMinutes = hoursToMinutes - minutes; return totalMinutes >= MINUTES_IN_A_DAY ? totalMinutes - MINUTES_IN_A_DAY : totalMinutes; } function afterMidnight(str) { const MINUTES_IN_A_DAY = 1440; const hours = Number(str.slice(0, 2)); const hoursToMinutes = hours * 60; const minutes = Number(str.slice(3, 5)); const totalMinutes = hoursToMinutes + minutes; return totalMinutes >= MINUTES_IN_A_DAY ? totalMinutes - MINUTES_IN_A_DAY : totalMinutes; } console.log(afterMidnight("00:00") === 0); console.log(beforeMidnight("00:00") === 0); console.log(afterMidnight("12:34") === 754); console.log(beforeMidnight("12:34") === 686); console.log(afterMidnight("24:00") === 0); console.log(beforeMidnight("24:00") === 0); // The tests above should log true. // Disregard Daylight Savings and Standard Time and other irregularities.
import {Board} from './Board'; import {Turn} from './Turn'; import {Coordinate} from './Coordinate'; import {Color, colorGetInitialColor} from './Color'; import {Piece} from './Piece'; import {Pawn} from './Pawn'; import {Error} from './Error'; import {Draught} from './Draught'; export class Game { private board: Board; private turn: Turn; constructor() { this.board = new Board(); this.turn = new Turn(); this.reset(); } reset() { for (let i = 0; i < Coordinate.getDimension(); i++) { for (let j = 0; j < Coordinate.getDimension(); j++) { let coordinate: Coordinate = new Coordinate(i, j); let color: Color = colorGetInitialColor(coordinate); let piece: Piece = null; if (color != null) { piece = new Pawn(color); } this.board.put(coordinate, piece); } } if (this.turn.getColor() !== Color.RED) { this.turn.change(); } } move(coordinates: Array<Coordinate>): Error { let error: Error = null; let removedCoordinates: Array<Coordinate> = new Array<Coordinate>(); let pair: number = 0; do { error = this.isCorrectPairMove(pair, coordinates); if (error == null) { this.pairMove(removedCoordinates, pair, coordinates); pair++; } } while (pair < coordinates.length - 1 && error == null); error = this.isCorrectGlobalMove(error, removedCoordinates, coordinates); if (error == null) { this.turn.change(); } else { this.unMovesUntilPair(removedCoordinates, pair, coordinates); } return error; } private isCorrectPairMove(pair: number, coordinates: Array<Coordinate>): Error { if (coordinates[pair] === null || coordinates[pair + 1] === null) { return Error.BAD_FORMAT; } if (this.board.isEmpty(coordinates[pair])) { return Error.EMPTY_ORIGIN; } if (this.turn.getOppositeColor() === this.board.getColor(coordinates[pair])) { return Error.OPPOSITE_PIECE; } if (!this.board.isEmpty(coordinates[pair + 1])) { return Error.NOT_EMPTY_TARGET; } let betweenDiagonalPieces: Array<Piece> = this.board.getBetweenDiagonalPieces(coordinates[pair], coordinates[pair + 1]); return this.board.getPiece(coordinates[pair]).isCorrectMovement(betweenDiagonalPieces, pair, coordinates); } private pairMove(removedCoordinates: Array<Coordinate>, pair: number, coordinates: Array<Coordinate>) { let forRemoving: Coordinate = this.getBetweenDiagonalPiece(pair, coordinates); if (forRemoving !== null) { removedCoordinates.unshift(forRemoving); this.board.remove(forRemoving); } this.board.move(coordinates[pair], coordinates[pair + 1]); if (this.board.getPiece(coordinates[pair + 1]).isLimit(coordinates[pair + 1])) { let color: Color = this.board.getColor(coordinates[pair + 1]); this.board.remove(coordinates[pair + 1]); this.board.put(coordinates[pair + 1], new Draught(color)); } } private getBetweenDiagonalPiece(pair: number, coordinates: Array<Coordinate>): Coordinate { if (!coordinates[pair].isOnDiagonal(coordinates[pair + 1])) { return null; } let betweenCoordinates: Array<Coordinate> = coordinates[pair].getBetweenDiagonalCoordinates(coordinates[pair + 1]); if (betweenCoordinates.length === 0) { return null; } for (let coordinate of betweenCoordinates) { if (this.getPiece(coordinate) !== null) { return coordinate; } } return null; } private isCorrectGlobalMove(error: Error, removedCoordinates: Array<Coordinate>, coordinates: Array<Coordinate>): Error { if (error !== null) { return error; } if (coordinates.length > 2 && coordinates.length > removedCoordinates.length + 1) { return Error.TOO_MUCH_JUMPS; } return null; } private unMovesUntilPair(removedCoordinates: Array<Coordinate>, pair: number, coordinates: Array<Coordinate>) { for (let j = pair; j > 0; j--) { this.board.move(coordinates[j], coordinates[j - 1]); } for (let removedPiece of removedCoordinates) { this.board.put(removedPiece, new Pawn(this.getOppositeTurnColor())); } } public isBlocked(): boolean { for (let coordinate of this.getCoordinatesWithActualColor()) { if (!this.isBlockedCoordinate(coordinate)) { return false; } } return true; } private getCoordinatesWithActualColor(): Array<Coordinate> { let coordinates: Array<Coordinate> = new Array<Coordinate>(); for (let i = 0; i < this.getDimension(); i++) { for (let j = 0; j < this.getDimension(); j++) { let coordinate: Coordinate = new Coordinate(i, j); let piece: Piece = this.getPiece(coordinate); if (piece != null && piece.getColor() == this.getTurnColor()) { coordinates.push(coordinate); } } } return coordinates; } private isBlockedCoordinate(coordinate: Coordinate): boolean { for (let i = 1; i <= 2; i++) { for (let target of coordinate.getDiagonalCoordinates(i)) { if (this.isCorrectPairMove(0, [coordinate, target]) === null) { return false; } } } return true; } public cancel() { for (let coordinate of this.getCoordinatesWithActualColor()) { this.board.remove(coordinate); } this.turn.change(); } public getColor(coordinate: Coordinate): Color { if (coordinate === null) { return null; } return this.board.getColor(coordinate); } public getTurnColor(): Color { return this.turn.getColor(); } public resetTurn(){ this.turn.resetColor() } public getOppositeTurnColor(): Color { return this.turn.getOppositeColor(); } public getPiece(coordinate: Coordinate): Piece { if (coordinate === null) { return null; } return this.board.getPiece(coordinate); } public isMultiJumpPossible(coordinate: Coordinate) { if (this.board.getAvailablePiecesToJump(coordinate).length === 0) { return false; } return true; } public getNumberOfPieces(color: Color): number { return this.board.getNumberOfPieces(color); } public getDimension(): number { return Coordinate.getDimension(); } public changeTurnToAllowMultiJump(){ this.turn.change(); } public changePiece(piece: Piece, row: number, column: number){ this.board.setPiece(piece, row, column); } public imprimir(){ this.board.impresion(); } }
--- title: 'ECS integration troubleshooting: No data appears' type: troubleshooting tags: - Integrations - Elastic Container Service integration - Troubleshooting metaDescription: Troubleshooting tips for when New Relic's on-host Amazon ECS integration is not reporting data. redirects: - /docs/ecs-integration-no-data-appears --- ## Problem You installed our [on-host ECS integration](/docs/introduction-amazon-ecs-integration) and waited a few minutes, but your cluster is not showing in the explorer. <Callout variant="important"> We have two ECS integrations: a [cloud-based integration](/docs/integrations/amazon-integrations/aws-integrations-list/aws-ecsecr-monitoring-integration) and an on-host integration. This document is about the on-host integration. </Callout> ## Solution If your New Relic account had previously installed the infrastructure agent or an infrastructure on-host integration, your data should appear in [the UI](/docs/ecs-integration-understand-use-data) within a few minutes. If your account had not previously done either of those things before installing the on-host ECS integration, it may take tens of minutes for data to appear in the UI. In that case, we recommend waiting up to an hour before doing the following troubleshooting steps or contacting support. There are several options for troubleshooting no data appearing: * [Troubleshoot via the awscli tool](#awscli) (recommended when talking to New Relic technical support) * [Troubleshoot via the UI](#ui) For information about stopped tasks, see [Stopped tasks reasons](#stopped-tasks). ### Troubleshoot via awscli [#awscli] When interacting with New Relic support, use this method and send the generated files with your support request: 1. Retrieve the information related to the `newrelic-infra` service or the Fargate service that contains a task with a `newrelic-infra` sidecar: ``` aws ecs describe-services --cluster <var>YOUR_CLUSTER_NAME</var> --service newrelic-infra > newrelic-infra-service.json ``` ``` aws ecs describe-services --cluster <var>YOUR_CLUSTER_NAME</var> --service <var>YOUR_FARGATE_SERVICE_WITH_NEW_RELIC_SIDECAR</var> > newrelic-infra-sidecar-service.json ``` 2. The `failures` attribute details any errors for the services. 3. Under `services` is the `status` attribute. It says `ACTIVE` if the service has no issues. 4. The `desiredCount` should match the `runningCount`. This is the number of tasks the service is handling. Because we use the daemon service type, there should be one task per container instance in your cluster. The `pendingCount` attribute should be zero, because all tasks should be running. 5. Inspect the `events` attribute of `services` to check for issues with scheduling or starting the tasks. For example: if the service is unable to start tasks successfully, it will display a message like: ``` { "id": "5295a13c-34e6-41e1-96dd-8364c42cc7a9", "createdAt": "2020-04-06T15:28:18.298000+02:00", "message": "(service newrelic-ifnra) is unable to consistently start tasks successfully. For more information, see the Troubleshooting section of the Amazon ECS Developer Guide." } ``` 6. In the same section, you can also see which tasks were started by the service from the events: ``` { "id": "1c0a6ce2-de2e-49b2-b0ac-6458a804d0f0", "createdAt": "2020-04-06T15:27:49.614000+02:00", "message": "(service fargate-fail) has started 1 tasks: (task <var>YOUR_TASK_ID</var>)." } ``` 7. Retrieve the information related to the task with this command: ``` aws ecs describe-tasks --tasks <var>YOUR_TASK_ID</var> --cluster <var>YOUR_CLUSTER_NAME</var> > newrelic-infra-task.json ``` 8. The `desiredStatus` and `lastStatus` should be `RUNNING`. If the task couldn't start normally, it will have a `STOPPED` status. 9. Inspect the `stopCode` and `stoppedReason`. One reason example: a task that couldn't be started because the task execution role doesn't have the appropriate permissions to download the license-key-containing secret would have the following output: ``` "stopCode": "TaskFailedToStart", "stoppedAt": "2020-04-06T15:28:54.725000+02:00", "stoppedReason": "Fetching secret data from AWS Secrets Manager in region <var>YOUR_AWS_REGION</var>: secret arn:aws:secretsmanager:<var>YOUR_AWS_REGION</var>:<var>YOUR_AWS_ACCOUNT</var>:secret:NewRelicLicenseKeySecret-Dh2dLkgV8VyJ-80RAHS-fail: AccessDeniedException: User: arn:aws:sts::<var>YOUR_AWS_ACCOUNT</var>:assumed-role/NewRelicECSIntegration-Ne-NewRelicECSTaskExecution-1C0ODHVT4HDNT/8637b461f0f94d649e9247e2f14c3803 is not authorized to perform: secretsmanager:GetSecretValue on resource: arn:aws:secretsmanager:<var>YOUR_AWS_REGION</var>:<var>YOUR_AWS_ACCOUNT</var>:secret:NewRelicLicenseKeySecret-Dh2dLkgV8VyJ-80RAHS-fail-DmLHfs status code: 400, request id: 9cf1881e-14d7-4257-b4a8-be9b56e09e3c", "stoppingAt": "2020-04-06T15:28:10.953000+02:00", ``` 10. If the task is running but you’re still not seeing data, generate [verbose logs](/docs/infrastructure/infrastructure-troubleshooting/troubleshoot-logs/infrastructure-agent-logging-behavior) and examine them for errors. For details about reasons for stopped tasks, see [Stopped tasks](#stopped-tasks). ### Troubleshoot in the UI [#ui] To use the UI to troubleshoot: 1. Log in to your AWS Console and navigate to the EC2 Container Service section. 2. Click on the cluster where you installed the New Relic ECS integration. 3. On the **Services** tab, use the filter to search for the integration service. If you used the automatic install script, the name of the service will be `newrelic-infra`. If you are using Fargate, it will be the name of your monitored service. Once found, click on the name. 4. The service page shows the **Status** of the service. It says `ACTIVE` if the service has no issues. 5. On the same page, the **Desired** count should match the **Running** count. This is the number of tasks the service is handling. Because we use the daemon service type, there should be one task per container instance in your cluster. Pending count should be zero, because all tasks should be running. 6. Inspect the **Events** tab to check for issues with scheduling or starting the tasks. 7. In the **Tasks** tab of your service, you can inspect the running tasks and the stopped tasks by clicking on the **Task status** selector. Containers that failed to start are shown when you select the **Stopped** status. 8. Click on a task to go to the task details page. Under **Stopped reason**, it displays a message explaining why the task was stopped. 9. If the task is running but you’re still not seeing data, generate [verbose logs](/docs/infrastructure/infrastructure-troubleshooting/troubleshoot-logs/infrastructure-agent-logging-behavior) and examine them for errors. For details about reasons for stopped tasks, see [Stopped tasks](#stopped-tasks). ### Reasons for stopped tasks [#stopped-tasks] In the [AWS ECS troubleshooting documentation](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/troubleshooting.html) you can find information on common causes of errors related to running tasks and services. See below for details about some reasons for stopped tasks. **Task stopped with reason:** ``` Fetching secret data from AWS Secrets Manager in region <var>YOUR_AWS_REGION</var>: secret arn:aws:secretsmanager:<var>YOUR_AWS_REGION</var>:<var>YOUR_AWS_ACCOUNT</var>:secret:<var>YOUR_SECRET_NAME</var>: AccessDeniedException: User: arn:aws:sts::<var>YOUR_AWS_ACCOUNT</var>:assumed-role/<var>YOUR_ROLE_NAME</var> is not authorized to perform: secretsmanager:GetSecretValue on resource: arn:aws:secretsmanager:<var>YOUR_AWS_REGION</var>:<var>YOUR_AWS_ACCOUNT</var>:secret:<var>YOUR_SECRET_NAME</var> status code: 400, request id: 9cf1881e-14d7-4257-b4a8-be9b56e09e3c" ``` This means that the IAM role specified using `executionRoleArn` in the task definition doesn't have access to the secret used for the `NRIA_LICENSE_KEY`. The execution role should have a policy attached that grants it access to read the secret. 1. Get the execution role of your task: ``` aws ecs describe-task-definition --task-definition newrelic-infra --output text --query taskDefinition.executionRoleArn ``` You can replace the `--task-definition newrelic-infra` with the name of your fargate task that includes the sidecar container. ``` aws ecs describe-task-definition --task-definition <var>YOUR_FARGATE_TASK_NAME</var> --output text --query taskDefinition.executionRoleArn ``` 2. List the policies attached to role: ``` aws iam list-attached-role-policies --role-name <var>YOUR_EXECUTION_ROLE_NAME</var> ``` This should return 3 policies `AmazonECSTaskExecutionRolePolicy`, `AmazonEC2ContainerServiceforEC2Role` and a third one that should grant read access to the license key. In the following example the policy it's named `NewRelicLicenseKeySecretReadAccess`. ``` { "AttachedPolicies": [ { "PolicyName": "AmazonECSTaskExecutionRolePolicy", "PolicyArn": "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy" }, { "PolicyName": "AmazonEC2ContainerServiceforEC2Role", "PolicyArn": "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role" }, { "PolicyName": "<var>YOUR_POLICY_NAME</var>", "PolicyArn": "arn:aws:iam::<var>YOUR_AWS_ACCOUNT</var>:policy/<var>YOUR_POLICY_NAME</var>" } ] } ``` 3. Retrieve the default policy version: ``` aws iam get-policy-version --policy-arn arn:aws:iam::<var>YOUR_AWS_ACCOUNT</var>:policy/<var>YOUR_POLICY_NAME</var> --version-id $(aws iam get-policy --policy-arn arn:aws:iam::<var>YOUR_AWS_ACCOUNT</var>:policy/<var>YOUR_POLICY_NAME</var> --output text --query Policy.DefaultVersionId) ``` This retrieves the policy permissions. There should be an entry for Action`secretsmanager:GetSecretValue` if you used AWS Secrets Manager to store your license key, or an entry for `ssm:GetParameters`if you used AWS Systems Manager Parameter Store: <CollapserGroup> <Collapser id="aws-secrets-manager" title="AWS Secrets Manager" > ``` { "PolicyVersion": { "Document": { "Version": "2012-10-17", "Statement": [ { "Action": "secretsmanager:GetSecretValue", "Resource": "arn:aws:secretsmanager:<var>YOUR_AWS_REGION</var>:<var>YOUR_AWS_ACCOUNT</var>:secret:<var>YOUR_SECRET_NAME</var>", "Effect": "Allow" } ] }, "VersionId": "v1", "IsDefaultVersion": true, "CreateDate": "2020-03-31T13:47:07+00:00" } } ``` </Collapser> <Collapser id="aws-systems-manager-parameter-store" title="AWS Systems Manager Parameter Store" > ``` { "Version": "2012-10-17", "Statement": [ { "Action": "ssm:GetParameters", "Resource": [ "arn:aws:ssm:<var>YOUR_AWS_REGION</var>:<var>YOUR_AWS_ACCOUNT</var>:parameter/<var>YOUR_SECRET_NAME</var>" ], "Effect": "Allow" } ] } ``` </Collapser> </CollapserGroup>
--- createdAt: 2023-10-03T12:15:05.061Z title: Document Field slug: fields/document --- This field is used to store markdown content. When used in a collection schema, Rescribe will render a markdown editor. The editor supports markdown shortcuts and some rich-text shortcuts. You can create a document field in your collection schema using the `document()` method in the Field API. ```javascript blog: collection({ // other options schema: { // other fields content: fields.document(), }, }), ``` ## Editor The `document()` field will render a markdown editor. The editor is powered by `@i4o/oh-hi-markdown` which is a fork of another (now archived) markdown editor called [rich-markdown-editor](https://github.com/outline/rich-markdown-editor). For the time being, I’ve disabled many of the features that come out of the box in the editor. The editor will be refactored to better suit the Rescribe project. I also have plans to integrate the editor into the Rescribe project but this may not happen. If you want to report issues or request features for the editor, please submit an issue on the [editor’s issues page](https://github.com/i4o-oss/oh-hi-markdown/issues). Rescribe will render the `content` field — which is required in the schema — front and center along with the `title` field (also required). This is so you have a minimal writing environment without all the other fields cluttering up the UI. All other fields apart from `title` and `content` can be accessed via the right panel button on the top right of the editor page.
import logging from colorama import Fore, Style class ColoredFormatter(logging.Formatter): COLORS = { 'DEBUG': Fore.CYAN, 'INFO': Fore.GREEN, 'WARNING': Fore.YELLOW, 'ERROR': Fore.RED, 'CRITICAL': Fore.RED + Style.BRIGHT, } def format(self, record): timestamp = self.formatTime(record, datefmt="%H:%M:%S") log_message = super(ColoredFormatter, self).format(record) return f"{self.COLORS.get(record.levelname, '')} {timestamp} - {record.filename}:{record.lineno} - {record.levelname} - {record.getMessage()}{Style.RESET_ALL}" class CustomLogger: def __init__(self, name, log_file=None): self.logger = logging.getLogger(name) self.logger.setLevel(logging.DEBUG) formatter = ColoredFormatter('%(asctime)s') # Create a console handler console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) self.logger.addHandler(console_handler) # Optionally, create a file handler if log_file: file_handler = logging.FileHandler(log_file) file_handler.setFormatter(formatter) self.logger.addHandler(file_handler) def debug(self, message): self.logger.debug(message) def info(self, message): self.logger.info(message) def warning(self, message): self.logger.warning(message) def error(self, message): self.logger.error(message) def critical(self, message): self.logger.critical(message) # Example usage: if __name__ == "__main__": custom_logger = CustomLogger("my_logger", log_file="example.log") custom_logger.debug("Debug message") custom_logger.info("Info message") custom_logger.warning("Warning message") custom_logger.error("Error message") custom_logger.critical("Critical message")
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="2.0" xml:lang="en" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:dml="http://purl.oclc.org/NET/dml/1.0/" xmlns:pml="http://purl.oclc.org/NET/pml/1.0/" xmlns:dct="http://purl.org/dc/terms/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:df="dml:functions" exclude-result-prefixes="xs dml pml df rdf"> <xsl:import href="functions/common.xsl"/> <xsl:import href="modules/params.xsl"/> <xsl:import href="modules/common.xsl"/> <xsl:import href="modules/inline.xsl"/> <xsl:import href="modules/block.xsl"/> <xsl:import href="modules/table.xsl"/> <xsl:import href="modules/toc.xsl"/> <xsl:import href="modules/metadata.xsl"/> <xsl:import href="modules/pml2html.xsl"/> <dml:note> <dml:list> <dml:item property="dct:creator">Arnau Siches</dml:item> <dml:item property="dct:created">2009-09-28</dml:item> <dml:item property="dct:modified">2009-12-17</dml:item> <dml:item property="dct:description"> <p>Transforms a DML source to HTML.</p> </dml:item> <dml:item property="dct:rights">Copyright 2009 Arnau Siches</dml:item> <dml:item property="dct:license"> This file is part of dml2html. dml2html is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. dml2html 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. You should have received a copy of the GNU General Public License along with dml2html. If not, see http://www.gnu.org/licenses/. </dml:item> </dml:list> </dml:note> <xsl:output method="xhtml" version="1.0" encoding="utf-8" indent="yes" media-type="application/xhtml+xml" omit-xml-declaration="yes" doctype-public="-//W3C//DTD XHTML+RDFa 1.0//EN" doctype-system="http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"/> <xsl:variable name="program.name">dml2html</xsl:variable> <xsl:variable name="program.version">0.9</xsl:variable> <xsl:strip-space elements="dml:dml dml:section"/> <xsl:template match="/"> <xsl:apply-templates/> </xsl:template> <xsl:template match="dml:dml | /dml:note"> <html> <xsl:call-template name="common.attributes"/> <xsl:call-template name="head"/> <xsl:call-template name="body"/> </html> </xsl:template> <xsl:template name="head"> <head profile="http://dublincore.org/documents/2008/08/04/dc-html/"> <xsl:call-template name="metadata"/> <xsl:call-template name="link.stylesheet"/> </head> </xsl:template> <xsl:template name="body"> <body> <xsl:if test="$toc and ($toc.position eq -1)"> <xsl:call-template name="toc"/> </xsl:if> <xsl:apply-templates mode="self"/> <xsl:sequence select="df:message('Footnotes are experimental and only visibles with $debug = true', 'warning')"/> <xsl:if test="$debug"> <xsl:call-template name="set.footnotes"/> </xsl:if> <xsl:if test="$toc and ($toc.position eq 1)"> <xsl:call-template name="toc"/> </xsl:if> <xsl:call-template name="license"/> </body> </xsl:template> <xsl:template name="link.stylesheet"> <link href="{$link.stylesheet.all}" media="all" rel="stylesheet" type="text/css" /> </xsl:template> <xsl:template match="dml:metadata"> <xsl:if test="$metadata.section"> <!-- <xsl:call-template name="common.attributes.and.children"/> --> <dl class="metadata"> <xsl:sequence select="df:set.metadata(df:literal.constructor('document.issued.label'), $document.issued, 'dct:issued')"/> <xsl:sequence select="df:set.metadata(df:literal.constructor('document.editor.label'), $document.creator, 'dct:creator')"/> <!-- <xsl:sequence select="df:set.metadata(df:literal.constructor('document.editor.label'), string-join(($document.creator, $document.publisher), ', '))"/> --> <xsl:sequence select="df:set.metadata(df:literal.constructor('document.version.label'), $document.identifier, 'dct:identifier')"/> </dl> </xsl:if> </xsl:template> <xsl:template name="license"> <xsl:if test="$license.section and exists($document.rights)"> <div id="footer" property="dct:rights"> <xsl:apply-templates select="$document.rights"/> </div> </xsl:if> </xsl:template> </xsl:stylesheet>
package com.example.weichen.bookstore2.asyncTasd; /** * Created by Administrator on 2017/04/02. */ import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.example.weichen.bookstore2.activity.BookInfo_Activity; import com.example.weichen.bookstore2.activity.CustomerBookInfo_Activity; import com.example.weichen.bookstore2.adapter.BookList_Adm_ListView_Adapter; import com.example.weichen.bookstore2.adapter.CustomerList_Adm_ListView_Adapter; import org.json.JSONArray; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GetCustomerList_Admin_AsyncTask extends AsyncTask<String, Void, String> { private Context context; private int byGetOrPost = 0; private ListView lv; Map<String, String> map = null; List<Map<String, String>> list = new ArrayList<Map<String, String>>(); // Flag 0 means GET and 1 means POST. (By default it is GET.) public GetCustomerList_Admin_AsyncTask(Context context, ListView lv, int flag) { this.context = context; this.lv = lv; byGetOrPost = flag; } protected void onPreExecute() { } @Override // which performs a computation on a background thread // It invoked on the background thread immediately after onPreExecute finishes executing. This step is used to // perform background computation that can take a long time. The specified parameters are the parameters // passed to execute(Params...) by the caller of this task. The result of the computation must be returned // by this step and will be passed back to the last step. protected String doInBackground(String... arg0) { String key ="false"; try { // String searchParam = (String) arg0[0]; // String username = (String) arg0[0]; // String password = (String) arg0[1]; String link = "http://people.cs.und.edu/~wchen/457/2/"; // String link = "http://wenchen.cs.und.edu/course/457/11/Android/"; // String link = "http://10.0.2.2/"; // String link = "http://192.168.1.105/"; // Complete the URL. if (byGetOrPost == 0) { // Get method link += "android_getAllCustomerList.php"; // Translates a string into application/x-www-form-urlencoded format using the specific encoding scheme UTF-8. // link += "&password=" + URLEncoder.encode( password, "UTF-8" ); } else { // Post method } // Connect to the server. URL url = new URL(link); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(15 * 1000); conn.setRequestMethod("GET"); conn.setDoOutput(true); InputStream is = conn.getInputStream(); // 获取输入流 byte[] data = readStream(is); // 把输入流转换成字符串组 String json = new String(data); // 把字符串组转换成字符串 if(json !=null && json.indexOf("null")==-1) { // 数据形式:{"total":2,"success":true,"arrayData":[{"id":1,"name":"张三"},{"id":2,"name":"李斯"}]} JSONObject jsonObject = new JSONObject(json); // 返回的数据形式是一个Object类型,所以可以直接转换成一个Object // int total = jsonObject.getInt("count"); // String keywords = jsonObject.getString("keywords"); // 里面有一个数组数据,可以用getJSONArray获取数组 JSONArray jsonArray = jsonObject.getJSONArray("data"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject item = jsonArray.getJSONObject(i); // 得到每个对象 int customerId = item.getInt("customerId"); String amount = item.getString("amount"); String name = item.getString("name"); map = new HashMap<String, String>(); map.put("customerId", customerId + ""); map.put("amount", amount); map.put("name", name); list.add(map); } } key = "success"; } catch (Exception e) { e.printStackTrace(); } return key; } private static byte[] readStream(InputStream inputStream) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { bout.write(buffer, 0, len); } bout.close(); inputStream.close(); return bout.toByteArray(); } @Override // which runs on the UI thread after doInBackground. // Runs on the UI thread after doInBackground(Params...). The specified result is the value returned by // doInBackground(Params...). protected void onPostExecute(String result) { if ("success".equals(result)) { //use baseAdapter to fill listView with data(the follow method' list) CustomerList_Adm_ListView_Adapter mAdapter = new CustomerList_Adm_ListView_Adapter(context, list);//得到一个MyAdapter对象 //TODO:创建listView‘item’点击事件,连接数本详细信息 /*为ListView添加点击事件*/ lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position,long id) { // Intent intent = new Intent(context,BookInfo_Activity.class); // intent.putExtra("title",list.get(position).get("title") ); // context.startActivity(intent); expressitemClick(position); } }); lv.setAdapter(mAdapter);// 为ListView绑定Adapter } } public void expressitemClick(int position){ Intent intent = new Intent(context,CustomerBookInfo_Activity.class); intent.putExtra("customerId",list.get(position).get("customerId") ); context.startActivity(intent); // finish();//看你需不需要返回当前界面,如果点返回需要返回到当前界面,就不用这个 } }
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <!DOCTYPE html> <html> <head> <link href="webjars/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet"> <link href="webjars/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.standalone.min.css" rel="stylesheet"> <meta charset="ISO-8859-1"> <title>Add Todo Page</title> </head> <body> <%@ include file="common/navigation.jspf"%> <div class="container"> <h1>Enter todo detail</h1> <form:form method="post" modelAttribute="todo"> <!-- Description: --> <%-- <form:input type="text" path="description" required="required" /> <form:errors path="description" cssClass="text-warning" /> --%> <form:input type="hidden" path="id" /> <%-- <form:input type="text" path="targetDate" /> --%> <fieldset class="mb-3"> <form:label path="description">Description</form:label> <form:input type="text" path="description" required="required" /> <form:errors path="description" cssClass="text-warning" /> </fieldset> <fieldset class="mb-3"> <form:label path="targetDate">Target Date</form:label> <form:input type="text" path="targetDate" required="required" /> <form:errors path="targetDate" cssClass="text-warning" /> </fieldset> <fieldset class="mb-3"> <form:label path="done">Done</form:label> <form:checkbox path="done" /> <form:errors path="done" cssClass="text-warning" /> </fieldset> <%-- <form:input type="text" path="done" /> --%> <input type="submit" class="btn btn-success" /> </form:form> </div> <script src="webjars/bootstrap/5.1.3/js/bootstrap.min.js"></script> <script src="webjars/jquery/3.6.0/jquery.min.js"></script> <script src="webjars/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script> <script type="text/javascript"> $('#targetDate').datepicker({ format : 'yyyy-mm-dd' }); </script> </body> </html>
--- title: Konversi VSS ke PDF linktitle: Konversi VSS ke PDF second_title: GroupDocs.Konversi .NET API description: Konversikan file VSS ke PDF dengan mudah menggunakan GroupDocs.Conversion untuk .NET. Konversi batch, opsi yang dapat disesuaikan, dan integrasi yang lancar. type: docs weight: 11 url: /id/net/converting-file-types-to-pdf/convert-vss-to-pdf/ --- ## Perkenalan Di era digital saat ini, kemampuan untuk mengkonversi file dengan lancar dari satu format ke format lainnya adalah hal yang terpenting. Baik untuk berbagi dokumen, mengarsipkan data, atau sekadar memastikan kompatibilitas di berbagai platform, memiliki alat konversi file yang andal sangatlah penting. Dalam tutorial ini, kita akan mempelajari proses mengonversi file VSS ke format PDF menggunakan GroupDocs.Conversion untuk .NET. ## Prasyarat Sebelum kita mulai, pastikan Anda memiliki prasyarat berikut: 1. GroupDocs.Conversion for .NET: Pastikan Anda telah mengunduh dan menginstal GroupDocs.Conversion for .NET. Anda dapat mengunduhnya dari[Di Sini](https://releases.groupdocs.com/conversion/net/). 2. Contoh File VSS: Siapkan contoh file VSS untuk dikonversi. Anda dapat menggunakan file VSS apa pun untuk tutorial ini. ## Impor Namespace Sebelum mendalami proses konversi, impor namespace yang diperlukan ke proyek Anda: ```csharp using System; using System.IO; using GroupDocs.Conversion.Options.Convert; ``` ## Langkah 1: Tentukan Folder Keluaran dan Nama File Pertama, tentukan folder keluaran tempat file PDF yang dikonversi akan disimpan, dan tentukan nama file keluaran: ```csharp string outputFolder = "Your Document Directory"; string outputFile = Path.Combine(outputFolder, "vss-converted-to.pdf"); ``` Pastikan untuk mengganti`"Your Document Directory"` dengan jalur ke direktori keluaran yang Anda inginkan. ## Langkah 2: Muat File VSS Sumber Sekarang, kita perlu memuat file sumber VSS menggunakan`Converter` kelas yang disediakan oleh GroupDocs.Conversion: ```csharp using (var converter = new GroupDocs.Conversion.Converter(Constants.SAMPLE_VSS)) { // Kode konversi akan ditambahkan di sini } ``` Mengganti`Constants.SAMPLE_VSS` dengan jalur ke file VSS Anda. ## Langkah 3: Tentukan Opsi Konversi Tentukan opsi konversi, dalam hal ini, untuk mengonversi ke format PDF: ```csharp var options = new PdfConvertOptions(); ``` ## Langkah 4: Lakukan Konversi Jalankan proses konversi dan simpan file PDF yang dikonversi menggunakan opsi yang ditentukan: ```csharp converter.Convert(outputFile, options); ``` ## Langkah 5: Tampilkan Pesan Sukses Terakhir, beri tahu pengguna bahwa proses konversi telah berhasil diselesaikan dan tampilkan jalur ke folder keluaran: ```csharp Console.WriteLine("\nConversion to PDF completed successfully.\nCheck output in {0}", outputFolder); ``` ## Kesimpulan Kesimpulannya, GroupDocs.Conversion untuk .NET memberikan solusi tangguh untuk mengonversi file VSS ke format PDF dengan lancar. Dengan mengikuti langkah-langkah yang diuraikan dalam tutorial ini, Anda dapat mengonversi file VSS Anda secara efisien dengan mudah. ## FAQ ### Bisakah saya mengonversi beberapa file VSS secara bersamaan menggunakan GroupDocs.Conversion untuk .NET? Ya, GroupDocs.Conversion for .NET mendukung konversi batch, memungkinkan Anda mengonversi beberapa file VSS sekaligus. ### Apakah ada batasan ukuran file VSS yang dapat dikonversi? GroupDocs.Conversion for .NET dapat menangani file VSS dengan berbagai ukuran, namun disarankan untuk memastikan bahwa sistem Anda memenuhi persyaratan sumber daya yang diperlukan untuk file yang lebih besar. ### Dapatkah saya menyesuaikan opsi konversi untuk kebutuhan spesifik saya? Tentu saja, GroupDocs.Conversion for .NET menawarkan berbagai opsi penyesuaian, memungkinkan Anda menyesuaikan proses konversi sesuai kebutuhan Anda. ### Apakah GroupDocs.Conversion for .NET mendukung konversi ke format lain selain PDF? Ya, GroupDocs.Conversion for .NET mendukung konversi ke berbagai format termasuk DOCX, XLSX, HTML, dan banyak lagi. ### Apakah dukungan teknis tersedia untuk GroupDocs.Conversion untuk .NET? Ya, Anda dapat memanfaatkan dukungan teknis untuk GroupDocs.Conversion untuk .NET melalui forum dukungan[Di Sini](https://forum.groupdocs.com/c/conversion/11).
import { useEffect, useState } from "react"; //member APIs import { getBanners, getRecentBooks, addToBookBag, reserveBook, } from "../../Utils/MemberApis"; import Banner from "../../Components/Banner/Banner"; import BookCard from "../../Components/Cards/BookCard"; import RecentBooksCard from "../../Components/Cards/RecentBooksCard"; import { toast } from "react-toastify"; function Home() { const [banner, setBanner] = useState([]); const [recentBooks, setRecentBooks] = useState([]); const [update, setUpdate] = useState(false); useEffect(() => { getBanners().then((response) => { if (response.data) { setBanner(response.data.bannerData); } }); // getRecentBooks().then((response) => { // if (response.data.recentBooks) { // setRecentBooks(response.data.recentBooks); // } // }); }, []); useEffect(() => { getRecentBooks().then((response) => { if (response.data.recentBooks) { setRecentBooks(response.data.recentBooks); } }); } , [update]) const handleAddtoBag = (bookId) => { addToBookBag(bookId) .then((response) => { if (response.data.message) { toast.success(response.data.message); setUpdate((prev => !prev)) } }) .catch((err) => { toast.error(err.response.data.error); }); }; const handleBookReserve = (bookId) => { reserveBook(bookId) .then((response) => { if(response.data.message) { toast.success(response.data.message) setUpdate((prev => !prev)) } }) .catch((err) => { if(err.response.data.error) { toast.error(err.response.data.error) } }) } return ( <div className="container mx-auto px-4 md:px-6"> {/*Hero style="background: linear-gradient(90deg, #2b4554 0%, #767ba2 100%)" */} <div className="lg:h-[450px] bg-cover bg-no-repeat bg-fixed rounded-xl border-2" style={{ backgroundImage: // "url(https://media.vanityfair.com/photos/5ce426151c0b0773cacd1121/master/pass/star-wars-feature-vf-2019-summer-embed-05.jpg)", "url(https://images.unsplash.com/photo-1577985051167-0d49eec21977?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1189&q=80)", }} > <div className="bg-black/40 h-full flex rounded-xl "> <div className="container m-auto text-center px-6"> <h2 className="text-5xl font-bold mb-2 font-nunito text-[#ffff]"> "Discover the Magic of Books." </h2> <h3 className="text-2xl mb-8 text-[#ffff]"> "Dive into a world of imagination and knowledge. Explore our vast collection today." </h3> <button className="bg-white font-bold rounded-full py-4 px-8 shadow-lg uppercase tracking-wider hover:border-transparent hover:text-blue-500 hover:bg-gray-800 transition-all"> "Start your reading adventure now!" </button> </div> </div> </div> {/* Banners */} <section className="container mx-auto py-4 mt-12 lg:mt-14"> <h2 className="text-2xl md:text-3xl lg:text-4xl font-extrabold mx-auto text-white text-center mb-7 lg:mb-8"> Your Gateway to Knowledge and Imagination!! </h2> {banner && banner.map((banner, i) => { return <Banner key={i} bannerData={banner} />; })} </section> {/* Recently added books */} <section className="bg-gray-100 rounded-md md:px-6 "> <div className="container mx-auto py-10"> <h2 className="text-xl sm:text-2xl md:text-2xl lg:text-3xl font-bold text-center text-gray-800 mb-8"> Recently added books </h2> <div className="mx-auto grid sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-x-5 md:gap-x-0 gap-y-6"> {recentBooks && recentBooks.map((book, i) => { return ( <RecentBooksCard key={i} bookData={book} handleAddtoBag={handleAddtoBag} handleBookReserve={handleBookReserve} /> ); })} </div> </div> </section> {/* <section style={{ backgroundColor: "#667eea" }}> <div className="container mx-auto px-6 text-center py-20"> <h2 className="mb-6 text-4xl font-bold text-center text-white"> Headquarters personnel </h2> <h3 className="my-4 text-2xl text-white"> Report to command center. Take it easy. </h3> <button className="bg-white font-bold rounded-full mt-6 py-4 px-8 shadow-lg uppercase tracking-wider hover:border-red hover:text-white hover:bg-red-600"> Report </button> </div> </section> */} </div> ); } export default Home;
// Copyright 2021 Optiver Asia Pacific Pty. Ltd. // // This file is part of Ready Trader Go. // // Ready Trader Go is free software: you can redistribute it and/or // modify it under the terms of the GNU Affero General Public License // as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. // // Ready Trader Go 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public // License along with Ready Trader Go. If not, see // <https://www.gnu.org/licenses/>. #ifndef CPPREADY_TRADER_GO_LIBS_READY_TRADER_GO_BASEAUTOTRADER_H #define CPPREADY_TRADER_GO_LIBS_READY_TRADER_GO_BASEAUTOTRADER_H #include <array> #include <cstddef> #include <memory> #include <string> #include <utility> #include <vector> #include <boost/asio/io_context.hpp> #include "connectivitytypes.h" #include "protocol.h" #include "types.h" namespace ReadyTraderGo { class BaseAutoTrader { public: explicit BaseAutoTrader(boost::asio::io_context& context) : mContext(context) {}; virtual void SendAmendOrder(unsigned long clientOrderId, unsigned long volume); virtual void SendCancelOrder(unsigned long clientOrderId); virtual void SendHedgeOrder(unsigned long clientOrderId, Side side, unsigned long price, unsigned long volume); virtual void SendInsertOrder(unsigned long clientOrderId, Side side, unsigned long price, unsigned long volume, Lifespan lifespan); virtual void SetExecutionConnection(std::unique_ptr<IConnection>&& connection); virtual void SetInformationSubscription(std::shared_ptr<ISubscription>&& subscription); virtual void SetLoginDetails(std::string teamName, std::string secret); protected: boost::asio::io_context& mContext; std::unique_ptr<IConnection> mExecutionConnection = nullptr; std::shared_ptr<ISubscription> mInformationSubscription = nullptr; std::string mTeamName; std::string mSecret; virtual void DisconnectHandler(); virtual void MessageHandler(IConnection*, unsigned char, unsigned char const*, std::size_t); virtual void MessageHandler(ISubscription* subscription, unsigned char messageType, unsigned char const* data, std::size_t size); // Message callbacks virtual void ErrorMessageHandler(unsigned long clientOrderId, const std::string& errorMessage) {}; virtual void HedgeFilledMessageHandler(unsigned long clientOrderId, unsigned long price, unsigned long volume) {}; virtual void OrderBookMessageHandler(Instrument instrument, unsigned long sequenceNumber, const std::array<unsigned long, TOP_LEVEL_COUNT>& askPrices, const std::array<unsigned long, TOP_LEVEL_COUNT>& askVolumes, const std::array<unsigned long, TOP_LEVEL_COUNT>& bidPrices, const std::array<unsigned long, TOP_LEVEL_COUNT>& bidVolumes) {}; virtual void OrderFilledMessageHandler(unsigned long clientOrderId, unsigned long price, unsigned long volume) {}; virtual void OrderStatusMessageHandler(unsigned long clientOrderId, unsigned long fillVolume, unsigned long remainingVolume, signed long fees) {}; virtual void TradeTicksMessageHandler(Instrument instrument, unsigned long sequenceNumber, const std::array<unsigned long, TOP_LEVEL_COUNT>& askPrices, const std::array<unsigned long, TOP_LEVEL_COUNT>& askVolumes, const std::array<unsigned long, TOP_LEVEL_COUNT>& bidPrices, const std::array<unsigned long, TOP_LEVEL_COUNT>& bidVolumes) {}; }; inline void BaseAutoTrader::DisconnectHandler() { mContext.stop(); } inline void BaseAutoTrader::SetInformationSubscription(std::shared_ptr<ISubscription>&& subscription) { mInformationSubscription = std::move(subscription); mInformationSubscription->SetName("Info"); mInformationSubscription->MessageReceived = [this](ISubscription* s, unsigned char t, unsigned char const* d, std::size_t z) { MessageHandler(s, t, d, z); }; mInformationSubscription->AsyncReceive(); } inline void BaseAutoTrader::SendAmendOrder(unsigned long clientOrderId, unsigned long volume) { mExecutionConnection->SendMessage(MessageType::AMEND_ORDER, AmendMessage{clientOrderId, volume}); } inline void BaseAutoTrader::SendCancelOrder(unsigned long clientOrderId) { mExecutionConnection->SendMessage(MessageType::CANCEL_ORDER, CancelMessage{clientOrderId}); } inline void BaseAutoTrader::SendHedgeOrder(unsigned long clientOrderId, Side side, unsigned long price, unsigned long volume) { mExecutionConnection->SendMessage(MessageType::HEDGE_ORDER, HedgeMessage{clientOrderId, side, price, volume}); } inline void BaseAutoTrader::SendInsertOrder(unsigned long clientOrderId, Side side, unsigned long price, unsigned long volume, Lifespan lifespan) { mExecutionConnection->SendMessage(MessageType::INSERT_ORDER, InsertMessage{clientOrderId, side, price, volume, lifespan}); } inline void BaseAutoTrader::SetLoginDetails(std::string teamName, std::string secret) { mTeamName = std::move(teamName); mSecret = std::move(secret); } } #endif //CPPREADY_TRADER_GO_LIBS_READY_TRADER_GO_BASEAUTOTRADER_H
import { useEffect, memo, useMemo } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import ItemContact from './ItemContact'; import { contactsActions } from '../../redux/contacts'; import { contactsSelectors } from '../../redux/contacts'; import s from './ContactList.module.css'; const ContactList = () => { const contacts = useSelector(contactsSelectors.getContacts); const filter = useSelector(contactsSelectors.getFilter); const dispatch = useDispatch(); useEffect(() => { if (contacts.length === 1) { dispatch(contactsActions.changeFilter('')); } }, [contacts.length, dispatch]); const filterContacts = useMemo(() => { const normalizedData = filter.toLowerCase(); const array = contacts.filter(item => { const normName = item.name.toLowerCase(); return normName.includes(normalizedData); }); return array; }, [contacts, filter]); return ( <ul className={s.list}> {filterContacts.map(({ id, name, number }) => { return <ItemContact id={id} key={id} name={name} number={number} />; })} </ul> ); }; export default memo(ContactList);
const { ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js'); const fs = require('fs'); async function send_giveaway(client, giveaway) { // # 好欸,有抽獎欸 // ## 誰辦的? 👉 感謝拔拔 <@971730686685880322> // ## 抽幾個人? 👉 抽 100 個人 // ## 什麼時候開獎? 👉 <t:1716182040:F> 準時開獎! // ## 備註 👉 這是一個很棒的抽獎 // ## 要怎麼參加? // ### - 您需要有身分組 <@&1178612139905261608> // ### - 您不可有身分組 <@&1225108686263816252> // ### - 符合上述條件,按底下的按鈕 ( ❤️ ) 即可參加抽獎 // let giveaway = { // message_id: null, // prize: interaction.options.getString("prize"), // winners: interaction.options.getInteger("winners"), // duration: interaction.options.getInteger("duration"), // start_time: Math.floor(Date.now() / 1000), // channel: interaction.options.getChannel("channel").id, // host: interaction.options.getUser("host") || interaction.user, // role: interaction.options.getRole("include_role") || null, // excluded_role: interaction.options.getRole("excluded_role") || null, // description: interaction.options.getString("description") || null, // entries: [], // ended: false // } let description = giveaway.description ? `## 備註 👉 ${giveaway.description}\n` : ''; let exclude_role = giveaway.exclude_role ? `### - 您不可有身分組 ${giveaway.exclude_role}\n` : ''; let require_role = giveaway.require_role ? `### - 您需要有身分組 ${giveaway.require_role}\n` : ''; let message = ( `# 好欸,有抽獎欸\n` + `## 抽什麼? 👉 ${giveaway.prize} 個綠寶石\n` + `## 誰辦的? 👉 ${giveaway.host}\n` + `## 抽幾個人? 👉 抽 ${giveaway.winners} 個人\n` + `## 什麼時候開獎? 👉 <t:${giveaway.duration + Math.floor(Date.now() / 1000)}:F> 準時開獎!\n` + `${description}` + `## 要怎麼參加?\n` + `${require_role}` + `${exclude_role}` + `### - 符合上述條件,按底下的按鈕 ( ❤️ ) 即可參加抽獎` ) //create button const join = new ButtonBuilder() .setCustomId('giveaway_join') .setLabel('參加抽獎') .setStyle(ButtonStyle.Primary); const total = new ButtonBuilder() .setCustomId('giveaway_total') .setLabel('參加人數 0') .setStyle(ButtonStyle.Secondary) const actionRow = new ActionRowBuilder() .addComponents(join) .addComponents(total); const channel = await client.channels.fetch(giveaway.channel); await channel.send({ content: message, components: [actionRow] }).then(msg => { giveaway.message_id = msg.id; }); let giveaways = JSON.parse(fs.readFileSync(`${process.cwd()}/data/giveaways.json`)); giveaways[giveaway.message_id] = giveaway; fs.writeFileSync(`${process.cwd()}/data/giveaways.json`, JSON.stringify(giveaways, null, 4)); } module.exports = { send_giveaway }
/* cmplx.c * * Complex number arithmetic * * * * SYNOPSIS: * * typedef struct { * double r; real part * double i; imaginary part * }cmplx; * * cmplx *a, *b, *c; * * cadd( a, b, c ); c = b + a * csub( a, b, c ); c = b - a * cmul( a, b, c ); c = b * a * cdiv( a, b, c ); c = b / a * cneg( c ); c = -c * cmov( b, c ); c = b * * * * DESCRIPTION: * * Addition: * c.r = b.r + a.r * c.i = b.i + a.i * * Subtraction: * c.r = b.r - a.r * c.i = b.i - a.i * * Multiplication: * c.r = b.r * a.r - b.i * a.i * c.i = b.r * a.i + b.i * a.r * * Division: * d = a.r * a.r + a.i * a.i * c.r = (b.r * a.r + b.i * a.i)/d * c.i = (b.i * a.r - b.r * a.i)/d * ACCURACY: * * In DEC arithmetic, the test (1/z) * z = 1 had peak relative * error 3.1e-17, rms 1.2e-17. The test (y/z) * (z/y) = 1 had * peak relative error 8.3e-17, rms 2.1e-17. * * Tests in the rectangle {-10,+10}: * Relative error: * arithmetic function # trials peak rms * DEC cadd 10000 1.4e-17 3.4e-18 * IEEE cadd 100000 1.1e-16 2.7e-17 * DEC csub 10000 1.4e-17 4.5e-18 * IEEE csub 100000 1.1e-16 3.4e-17 * DEC cmul 3000 2.3e-17 8.7e-18 * IEEE cmul 100000 2.1e-16 6.9e-17 * DEC cdiv 18000 4.9e-17 1.3e-17 * IEEE cdiv 100000 3.7e-16 1.1e-16 */ /* cmplx.c * complex number arithmetic */ /* Cephes Math Library Release 2.8: June, 2000 Copyright 1984, 1995, 2000 by Stephen L. Moshier */ #include "mconf.h" #ifdef ANSIPROT extern double fabs ( double ); extern double cabs ( cmplx * ); extern double sqrt ( double ); extern double atan2 ( double, double ); extern double cos ( double ); extern double sin ( double ); extern double sqrt ( double ); extern double frexp ( double, int * ); extern double ldexp ( double, int ); int isnan ( double ); void cdiv ( cmplx *, cmplx *, cmplx * ); void cadd ( cmplx *, cmplx *, cmplx * ); #else double fabs(), cabs(), sqrt(), atan2(), cos(), sin(); double sqrt(), frexp(), ldexp(); int isnan(); void cdiv(), cadd(); #endif extern double MAXNUM, MACHEP, PI, PIO2, INFINITY, NAN; /* typedef struct { double r; double i; }cmplx; */ cmplx czero = {0.0, 0.0}; extern cmplx czero; cmplx cone = {1.0, 0.0}; extern cmplx cone; /* c = b + a */ void cadd( a, b, c ) register cmplx *a, *b; cmplx *c; { c->r = b->r + a->r; c->i = b->i + a->i; } /* c = b - a */ void csub( a, b, c ) register cmplx *a, *b; cmplx *c; { c->r = b->r - a->r; c->i = b->i - a->i; } /* c = b * a */ void cmul( a, b, c ) register cmplx *a, *b; cmplx *c; { double y; y = b->r * a->r - b->i * a->i; c->i = b->r * a->i + b->i * a->r; c->r = y; } /* c = b / a */ void cdiv( a, b, c ) register cmplx *a, *b; cmplx *c; { double y, p, q, w; y = a->r * a->r + a->i * a->i; p = b->r * a->r + b->i * a->i; q = b->i * a->r - b->r * a->i; if( y < 1.0 ) { w = MAXNUM * y; if( (fabs(p) > w) || (fabs(q) > w) || (y == 0.0) ) { c->r = MAXNUM; c->i = MAXNUM; mtherr( "cdiv", OVERFLOW ); return; } } c->r = p/y; c->i = q/y; } /* b = a Caution, a `short' is assumed to be 16 bits wide. */ void cmov( a, b ) void *a, *b; { register short *pa, *pb; int i; pa = (short *) a; pb = (short *) b; i = 8; do *pb++ = *pa++; while( --i ); } void cneg( a ) register cmplx *a; { a->r = -a->r; a->i = -a->i; } /* cabs() * * Complex absolute value * * * * SYNOPSIS: * * double cabs(); * cmplx z; * double a; * * a = cabs( &z ); * * * * DESCRIPTION: * * * If z = x + iy * * then * * a = sqrt( x**2 + y**2 ). * * Overflow and underflow are avoided by testing the magnitudes * of x and y before squaring. If either is outside half of * the floating point full scale range, both are rescaled. * * * ACCURACY: * * Relative error: * arithmetic domain # trials peak rms * DEC -30,+30 30000 3.2e-17 9.2e-18 * IEEE -10,+10 100000 2.7e-16 6.9e-17 */ /* Cephes Math Library Release 2.1: January, 1989 Copyright 1984, 1987, 1989 by Stephen L. Moshier Direct inquiries to 30 Frost Street, Cambridge, MA 02140 */ /* typedef struct { double r; double i; }cmplx; */ #ifdef UNK #define PREC 27 #define MAXEXP 1024 #define MINEXP -1077 #endif #ifdef DEC #define PREC 29 #define MAXEXP 128 #define MINEXP -128 #endif #ifdef IBMPC #define PREC 27 #define MAXEXP 1024 #define MINEXP -1077 #endif #ifdef MIEEE #define PREC 27 #define MAXEXP 1024 #define MINEXP -1077 #endif double cabs( z ) register cmplx *z; { double x, y, b, re, im; int ex, ey, e; #ifdef INFINITIES /* Note, cabs(INFINITY,NAN) = INFINITY. */ if( z->r == INFINITY || z->i == INFINITY || z->r == -INFINITY || z->i == -INFINITY ) return( INFINITY ); #endif #ifdef NANS if( isnan(z->r) ) return(z->r); if( isnan(z->i) ) return(z->i); #endif re = fabs( z->r ); im = fabs( z->i ); if( re == 0.0 ) return( im ); if( im == 0.0 ) return( re ); /* Get the exponents of the numbers */ x = frexp( re, &ex ); y = frexp( im, &ey ); /* Check if one number is tiny compared to the other */ e = ex - ey; if( e > PREC ) return( re ); if( e < -PREC ) return( im ); /* Find approximate exponent e of the geometric mean. */ e = (ex + ey) >> 1; /* Rescale so mean is about 1 */ x = ldexp( re, -e ); y = ldexp( im, -e ); /* Hypotenuse of the right triangle */ b = sqrt( x * x + y * y ); /* Compute the exponent of the answer. */ y = frexp( b, &ey ); ey = e + ey; /* Check it for overflow and underflow. */ if( ey > MAXEXP ) { mtherr( "cabs", OVERFLOW ); return( INFINITY ); } if( ey < MINEXP ) return(0.0); /* Undo the scaling */ b = ldexp( b, e ); return( b ); } /* csqrt() * * Complex square root * * * * SYNOPSIS: * * void csqrt(); * cmplx z, w; * * csqrt( &z, &w ); * * * * DESCRIPTION: * * * If z = x + iy, r = |z|, then * * 1/2 * Im w = [ (r - x)/2 ] , * * Re w = y / 2 Im w. * * * Note that -w is also a square root of z. The root chosen * is always in the upper half plane. * * Because of the potential for cancellation error in r - x, * the result is sharpened by doing a Heron iteration * (see sqrt.c) in complex arithmetic. * * * * ACCURACY: * * Relative error: * arithmetic domain # trials peak rms * DEC -10,+10 25000 3.2e-17 9.6e-18 * IEEE -10,+10 100000 3.2e-16 7.7e-17 * * 2 * Also tested by csqrt( z ) = z, and tested by arguments * close to the real axis. */ void csqrt( z, w ) cmplx *z, *w; { cmplx q, s; double x, y, r, t; x = z->r; y = z->i; if( y == 0.0 ) { if( x < 0.0 ) { w->r = 0.0; w->i = sqrt(-x); return; } else { w->r = sqrt(x); w->i = 0.0; return; } } if( x == 0.0 ) { r = fabs(y); r = sqrt(0.5*r); if( y > 0 ) w->r = r; else w->r = -r; w->i = r; return; } /* Approximate sqrt(x^2+y^2) - x = y^2/2x - y^4/24x^3 + ... . * The relative error in the first term is approximately y^2/12x^2 . */ if( (fabs(y) < 2.e-4 * fabs(x)) && (x > 0) ) { t = 0.25*y*(y/x); } else { r = cabs(z); t = 0.5*(r - x); } r = sqrt(t); q.i = r; q.r = y/(2.0*r); /* Heron iteration in complex arithmetic */ cdiv( &q, z, &s ); cadd( &q, &s, w ); w->r *= 0.5; w->i *= 0.5; } double hypot( x, y ) double x, y; { cmplx z; z.r = x; z.i = y; return( cabs(&z) ); }
<!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"> <!-- Link to CSS File --> <link rel="stylesheet" href="palindrome.css"> <!-- Link to Js File --> <script type="text/javascript" src="Palindrome.js"></script> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="crossorigin"> <link href="https://fonts.googleapis.com/css2?family=Oswald&display=swap" rel="stylesheet"> <title>WEB 330 – Enterprise JavaScript II</title> </head> <body> <div class="top-container" id="app-header"> <h1 class="app-header">Welcome to the Palindrome App!</h1> </div> <!-- Upper Card --> <div class="card"> <div class="container"> <!-- Card Title --> <h2 id="topCardTitle">Palindrome Checker</h2> <!-- Card label and input --> <label id="topCardLabel" for="input-text">Phase Value:</label> <input type="text" id="cardInput" name="textInput"> <!-- Card Submit Button with onclick attached --> <div class="submit"> <input type="submit" value="Check Phase" id="btnDisplayPhase" onclick="clickFunction()"> </div> </div> </div> <!-- Lower Card Start--> <div class="cardResult"> <div class="containerResult"> <div id="resultCard"> <!-- Card Title --> <h2 id="resultTitle">Palindrome Results</h2> <!-- JavaScript Output P tag --> <div id="datadiv"> <p id="date"></p> <p id="original"></p> <p id="reversed"></p> <p id="length"></p> </div> <h3 id="result"></h3> <!-- Return Home to Landing Page --> <a id="returnConversion" class="return-home" href="https://justinlyost.github.io/Web-330/Week-1/index.html">Return</a> <!-- Palindrome JavaScript Removed and added to external file --> <!-- <script> function clickFunction() { var x = document.getElementById("cardInput").value; var low = x.toLowerCase(); var str = low.split(""); var rev = str.reverse(); var join = rev.join(""); var p = (low +" is a palindrome!"); var n = (low +" is not a palindrome!"); //Thanks for the help: https://www.freecodecamp.org/news/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb/ // IF ELSE STATEMENTS if(x.length <= 0){ document.getElementById("result").innerHTML= "You need to enter something! Maybe nothing is still a Palindrome!"; }else if(low !== join){ document.getElementById("result").innerHTML= n; }else if(low == join){ document.getElementById("result").innerHTML= p; } // date part of app var date = new Date(); var nexDate = date.toDateString(); var today = ("Date: "+ nexDate); document.getElementById("date").innerHTML= today; // Original Phase printout var oPhase = ('Original Phase: '+ low) document.getElementById("original").innerHTML= oPhase; // Reversed Phase Printout var rPhase = ('Reversed Phase: '+ join) document.getElementById("reversed").innerHTML= rPhase; // Length Printout var len = low.length; var nPhase = ('Phase Length: '+ len) document.getElementById("length").innerHTML= nPhase; } </script> --> </div> </div> </div> </body> </html>
package appointments; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; public class DocCalendar { private List<PatientAppointment> appointments; private LocalDate today; public DocCalendar(LocalDate today) { this.appointments = new ArrayList<>(); this.today = today; } public void addAppointment(String patientFirstName, String patientLastName, String doctorKey, String dateTime) { Doctor doc = Doctor.valueOf(doctorKey.toLowerCase()); LocalDateTime localDateTime = convertToDateFromString(dateTime); PatientAppointment appointment = new PatientAppointment(patientFirstName, patientLastName, localDateTime, doc); appointments.add(appointment); } private LocalDateTime convertToDateFromString(String dateTime) { LocalDateTime localDateTime; try { if (dateTime.toLowerCase().startsWith("today")) { String[] parts = dateTime.split(" ", 2); LocalTime time = LocalTime.parse(parts[1].toUpperCase(), DateTimeFormatter.ofPattern("h:mm a", Locale.US)); localDateTime = LocalDateTime.of(today, time); } else { localDateTime = LocalDateTime.parse(dateTime.toUpperCase(), DateTimeFormatter.ofPattern("M/d/yyyy h:mm a", Locale.US)); } } catch (Throwable t) { throw new RuntimeException("Unable to create date time from: [" + dateTime + "], please enter with format [M/d/yyyy h:mm a], " + t.getMessage()); } return localDateTime; } public List<PatientAppointment> getAppointments() { return this.appointments; } public List<PatientAppointment> getTodayAppointments() { return appointments.stream().filter(appt -> appt.getAppointmentDateTime().toLocalDate().equals(today)) .collect(Collectors.toList()); } public boolean hasAppointment(LocalDate date) { return appointments.stream().anyMatch(appt -> appt.getAppointmentDateTime().toLocalDate().equals(date)); } }
--- title: What's New in the Mobile, Multiplayer, & More update (version 1.18.45) date: 2022-02-24T18:46:02Z updated: 2024-05-22T23:15:37Z categories: Product link: https://educommunity.minecraft.net/hc/en-us/articles/4484636118420-What-s-New-in-the-Mobile-Multiplayer-More-update-version-1-18-45 hash: h_01HYH9BZF73ZCRYVZCN5E9QKM9: url-allow-list-changes h_01HYH9BZF74SXGFYWF28MKQTZK: "" h_01HYH9BZF75KDAPKHBPZXSHT8F: update-011723---hotfix--rebrand-version-11845 h_01HYH9BZF7DJ59NSX7HD00C6MG: update-102522---hotfix-version-11842 h_01HYH9BZF7SNRPBJJPF0BF9446: "-1" h_01HYH9BZF742TGV8Y943C0R900: from-the-caves-and-cliffs-part-2-update h_01HYH9BZF7V3NE3EXZEMGCX9X5: mobile-support h_01HYH9BZF7WYYY80Y6JK8H577A: improved-multiplayer-experience h_01HYH9BZF7EF92J3ARWWYXAMRJ: new-npc-skins h_01HYH9BZF744W0ENT8FTSRFJRZ: improved-graphics-performance-technical h_01HYH9BZF73WJCQ7MYMAJVA8Q8: coding-and-websocket-updates-technical h_01HYH9BZF7062Z638R9QE59AQK: known-issues --- Welcome to the Mobile, Multiplayer & More update (version 1.18.45)! Minecraft Education is now available for iPhones and Android phones and tablets! In addition to mobile availability, the new update offers an improved multiplayer experience, updates to in-game coding with Code Builder, and brings the mountain and cave biomes of Caves and Cliffs: Part II to Minecraft Education.   <table style="border-collapse: collapse; width: 100%;" data-border="1" data-cellpadding="15"> <colgroup> <col style="width: 100%" /> </colgroup> <tbody> <tr> <td style="width: 100%"><h3>URL Allow List Changes </h3> <p>From the 1.18.31 beta and newer updates there are changes to the URLs which must be added to the allow list by your IT Admin to permit multiplayer connections. </p> <p>Read more about <a href="../Administration-and-License-Management/FAQ-IT-Admin-Guide.md">URL allow listing for Minecraft Education</a>. </p></td> </tr> </tbody> </table>   ###   ### Update 01/17/23 - Hotfix & Rebrand (version 1.18.45) - Minecraft: Education Edition will be known as Minecraft Education going forward. New name, new logo, new app icons.  - (Screen hanging/crashing on Red Mojang screen) - Chromebook fix  ### Update 10/25/22 - Hotfix (version 1.18.42) Our hotfix contains the following changes: - Multiplayer Improvements - Improved proxy support for multiplayer services - Greater connection reliability in multiplayer sessions  - Searching content across our entire in-game Library is easier than ever with our new Library Search Bar - Coding window now defaults to full screen on mobile devices - Various bug fixes in addition to performance and stability improvements ###   ### From the Caves and Cliffs Part 2 Update Version 1.18 brings some exciting features and changes to worlds. Here are the highlights: - Expanded world height (-64 to 320) - New cave generation with new areas (aquifers, lush caves, dripstone caves, amethyst geodes) - Taller mountains with new biomes (meadows, groves, snowy slopes, jagged peaks, frozen peaks, stony peaks) - Pre-1.18 worlds updated to blend old and new chunks and support deeper caves   ### Mobile Support - Minecraft Education is now available on mobile devices, including iOS phones and Android phones and tablets! - We’ve made updates to how some windows and pages are displayed to make them easier to use on smaller mobile screens - You can adjust where Minecraft displays on the screen so it doesn’t appear in the notch of mobile devices - View the [System Requirements a](../Get-Started/System-Requirements.md)rticle for the minimum required specs for mobile devices   ### Improved Multiplayer Experience - Joining multiplayer worlds should now be easier, requiring less network configuration to successfully connect - *Join by IP Address* has been replaced with *Join by Connection Id*. We still recommend using join codes or sharing a join link as the easiest way to join a multiplayer session.  - View the [URL Allow List](../Administration-and-License-Management/FAQ-IT-Admin-Guide.md) article for important configuration information required to use the new multiplayer experience - Our multiplayer connections now utilize UDP connections (port 3478)  ### New NPC Skins - 20 new skins for nonplayable characters (NPCs) have been added to the game to help spice up your worlds. This update includes skins for agriculture, business mobs, everyday business, and kiosks & robots. - Learn more about using NPCs with the [Tutorial 6. NPCs](https://education.minecraft.net/trainings/tutorial-6-6-npcs) lesson and the [Adding Non-Player Characters (NPCs)](https://aka.ms/MEEAddNPCs) ![Picture1.png](https://educommunity.minecraft.net/hc/article_attachments/8278627181716)![Picture2.png](https://educommunity.minecraft.net/hc/article_attachments/8278627104916)![Picture3.png](https://educommunity.minecraft.net/hc/article_attachments/8278627105044)![Picture4.png](https://educommunity.minecraft.net/hc/article_attachments/8278590146580)   ### Improved Graphics Performance (technical)   - The new Minecraft rendering engine, RenderDragon, is now included in Minecraft Education - This technical update shouldn't impact gameplay, but you should see improved performance   ### Coding and WebSocket updates (technical)  - JSON format for events sent from websocket server and Code Builder APIs have been updated to the hierarchical JSON format.   - Less useful properties removed. Block and item IDs switched to name-based format instead of numerical format.  - Agent commands in websockets moved to new "action:agent" format. All commands are queued and include unique ids to correlate responses.  - Any future breaking changes to websocket and Code Builder APIs will now result in the "protocolVersion" being incremented.     ### Known Issues  Some users may encounter these issues. If you do, [reach out to our support team](https://aka.ms/MEE_New_Request) and we can help.     Coding:  - Code Builder may have unexpected shapes, blocks and discoloration over the coding window on the latest versions of Chromebook Mobile:  - If Minecraft isn't displaying well on your mobile device, you can first try changing the "safe area" by going to **Settings \> Video \> Change Screen Safe Area** and adjusting the size of the playable area. This control lets you define the space in which Minecraft will draw interactive elements of the game. - Even after changing your screen safe area, there may be some on-screen buttons or windows that just don’t display correctly on smaller phone screens and tablets. If you see anything strange or unusable, please take a picture and report it to us. Content: The 1.18 release included updates which require corresponding key content updates in our computer science subject kit and Hour of Code 2019, 2020 and 2021. We are currently addressing these changes and hope to minimize any disruption or impact. The updated content is anticipated to be available soon. Impacted content: - HOC19 - HOC20 - HOC21 - Seymour Islands - Python Islands - Python Tutorials - Reference guide Other:  - Switching from the beta (1.18.30) back to a previous build (1.17.32) can cause Minecraft to crash when loading a world. Manually deleting the options.txt file in the Minecraft Application Data folder will resolve this.  - On Windows, the options.txt can be found at %appdata%\Minecraft Education Edition\games\com.mojang\minecraftpe\options.txt which for most users is "C:\Users\\USERNAME\]\AppData\Roaming\\.." **Windows 7 Users:** While Minecraft Education version 1.18 supports Windows 7, starting in December 2022, you will need to be using Windows 8 or newer to ensure Minecraft Education works correctly on your Windows device. View our [System Requirements article](../Get-Started/System-Requirements.md) for more info.
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; //panggil validator untuk memvalidasi inputan use App\Models\Product; //panggil model Product.php class ProductController extends Controller { // menambahkan data ke database public function store (Request $request) { //menvalidasi inputan $validator = Validator::make($request->all(),[ 'product_name' => 'required|max:50', 'product_type' => 'required|in:snack,drink,fruit,drug,groceries,cigarette,make-up,cigarette', 'product_price' => 'required|numeric', 'expired_at' => 'required|date' ]); //kondisi apabila inputan yang diinginkan tidak sesuai if($validator->fails()) { //response json akan dikirim jika ada inputan yang salah return response()->json($validator->messages())->setStatusCode(422); } $payLoad = $validator->validated(); //masukkan inputan yang benar ke database (table product) Product::create([ 'product_name' => $payLoad['product_name'], 'product_type' => $payLoad['product_type'], 'product_price' => $payLoad['product_price'], 'expired_at' => $payLoad['expired_at'] ]); //response json akan dikirim jika inputan benar return response()->json([ 'msg' => 'Data produk berhasil disimpan' ],201); } function showAll(){ //panggil semua data produk dari tabel product $products = Product::all(); //kirim response json return response()->json([ 'msg' => 'Data produk keseluruhan', 'data' => $products ],200); } function showById($id){ //mencari data berdasarkan ID produk $products = Product::where('id',$id)->first(); //kondisi apabila data dengan ID ada if($products) { //respon ketika data ada return response()->json([ 'msg' => 'Data produk dengan ID: '.$id, 'data' => $products ],200); } //response ketika data tidak ada return response()->json([ 'msg' => 'Data produk dengan ID: '.$id.' tidak ditemukan', ],404); } function showByName($product_name){ //cari data berdasarkan produk yang mirip $product = Product::where('product_name','LIKE','%'.$product_name.'%')->get(); //apabila daa produk ada if($product->count() > 0) { return response()->json([ 'msg'=> 'Data produk dengan nama yang mirip: '.$product_name, 'data' => $product ],200); } //response ketika data tidak ada return response()->json([ 'msg' => 'Data produk dengan nama mirip: '.$product_name.' tidak diterima', ],404); } public function update(Request $request,$id) { //memvalidasi inputan $validator = Validator::make($request->all(),[ 'product_name' => 'required|max:50', 'product_type' => 'required|in:snack,drink,fruit,drug,groceries,cigarette,make-up,cigarette', 'product_price' => 'required|numeric', 'expired_at' => 'required|date' ]); if($validator->fails()) { //response json akan dikirim jika ada inputan yang salah return response()->json($validator->messages())->setStatusCode(422); } $payLoad = $validator->validated(); //sunting inputan yang benar kedatabase (table product) Product::where('id',$id)->update([ 'product_name' => $payLoad['product_name'], 'product_type' => $payLoad['product_type'], 'product_price' => $payLoad['product_price'], 'expired_at' => $payLoad['expired_at'] ]); //response json akan dikirim jika inputan benar return response()->json([ 'msg' => 'Data produk berhasil diubah' ],201); } public function delete($id) { $product = Product::where('id',$id)->get(); if($product) { Product::where('id',$id)->delete(); //response json akan dikirim return response()->json([ 'msg' => 'Data produk dengan ID: '.$id.' berhasil dihapus' ],200); } //response json akan jika ID tidak ada return response()->json([ 'msg' => 'Data produk dengan ID: '.$id.' tidak ditemukan' ],404); } }
import { LockOutlined, Visibility, VisibilityOff } from "@mui/icons-material"; import { LoadingButton } from "@mui/lab"; import { Container, Paper, Avatar, Typography, Box, TextField, Grid, InputAdornment, IconButton } from "@mui/material"; import { Link, useLocation, useNavigate } from "react-router-dom"; import { FieldValues, useForm } from "react-hook-form"; import { useAppDispatch } from "../../app/store/configureStore"; import { signInUser } from "./accountSlice"; import { useState } from "react"; const Login = () => { const navigate = useNavigate(); const location = useLocation(); const dispatch = useAppDispatch(); const { register, handleSubmit, formState: { isSubmitting, errors, isValid }, } = useForm({ mode: "onTouched" }); const [showPassword, setShowPassword] = useState(false); const submitForm = async (data: FieldValues) => { try { await dispatch(signInUser(data)); navigate(location.state?.from || "/catalog"); } catch (error) { console.log(error); } }; return ( <Container component={Paper} maxWidth="sm" sx={{ p: 4, display: "flex", flexDirection: "column", alignItems: "center" }} > <Avatar sx={{ m: 1, bgcolor: "secondary.main" }}> <LockOutlined /> </Avatar> <Typography component="h1" variant="h5"> Sign in </Typography> <Box component="form" onSubmit={handleSubmit(submitForm)} noValidate sx={{ mt: 1 }}> <TextField {...register("email", { required: "Email is required", pattern: /^\S+@\S+\.\S+$/i })} error={!!errors.email} helperText={errors?.email?.message as string} margin="normal" fullWidth label="Email" autoComplete="email" autoFocus /> <TextField {...register("password", { required: "Password is required" })} error={!!errors.password} helperText={errors?.password?.message as string} margin="normal" fullWidth label="Password" type={showPassword ? "text" : "password"} autoComplete="current-password" InputProps={{ endAdornment: ( <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={() => setShowPassword(!showPassword)}> {showPassword ? <Visibility /> : <VisibilityOff />} </IconButton> </InputAdornment> ), }} /> <LoadingButton loading={isSubmitting} disabled={!isValid} type="submit" fullWidth variant="contained" sx={{ mt: 3, mb: 2 }} > Sign In </LoadingButton> <Grid container> <Grid item> <Link to="/register" style={{ textDecoration: "none" }}> {"Don't have an account? Sign Up"} </Link> </Grid> </Grid> </Box> </Container> ); }; export default Login;
# 快速入门 为了方便开发者入门,我们部署了 [web3infra.dev](http://web3infra.dev) 方便开发者永存数据。快速入门将介绍如何使用 arseeding-js 将数据存通过 [web3infra.dev](http://web3infra.dev) 存储到 Arweave 网络。 # 准备 为了快速完成数据上传,你需要提前准备: 1. node.js 开发环境 2. 拥有一个 MetaMask 钱包。 3. 该钱包拥有在 everPay 上任意一种资产。 如果还没做好准备,请查看:[everPay 充值指南](../other/2.getAR.md#swapdeposit) # 创建项目 打开终端,创建一个空文件夹来存放项目, 通过 `npm init` 创建 `package.json` 进行包管理。 ```bash mkdir arseeding-demo cd arseeding-demo npm init ``` # 安装 通过编译器 打开 `arseeding-demo` 文件, 打开终端通过以下代码安装 `arseeding-js`。 ```bash npm i arseeding-js ``` # 上传数据 安装完成后,在目录下创建 `index.js`,将以下代码复制到 `index.js`: ```jsx const { genNodeAPI } = require('arseeding-js') const run = async () => { const instance = genNodeAPI('YOUR PRIVATE KEY') const arseedUrl = 'https://arseed.web3infra.dev' const data = Buffer.from('........') const payCurrencyTag = 'ethereum-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' // everPay 支持的 token tag (chainType-symbol-id) const options = { tags: [{ name: 'Content-Type', value: 'image/png' }] } const res = await instance.sendAndPay(arseedUrl, data, payCurrencyTag, options) console.log('res', res) } run() ``` :::tip 若您喜欢以下导入 arseeding-js, 则需要在 **package.json** 文件中添加 **type:"module"**。 ```js import { genNodeAPI, getTokenTagByEver } from 'arseeding-js' ``` ::: 配置说明: - 将你的 MetaMask 密钥填充到 `YOUR PRIVATE KEY`。确保 PRV KEY 对应的钱包在 everPay 拥有资产。 - arseedUrl 是需要配置的 Arseeding 后端服务地址,这里我们使用 permadao 提供的 Arseed 服务,URL 为:https://arseed.web3infra.dev 。 - data 里需要填充你想要上传的二进制数据,开发者可以采用 file io 从硬盘上读取对应的文件。 - payCurrencyTag 是需要选择的支付 `Token tag`,如果你的 MetaMask 地址在 everPay 持有的是 usdc,可通过 `getTokenTagByEver('usdc')`,获取 usdc 的 `tag`,如果持有的是其他代币,请填写其他代币的名称。具体查看[getTokenTagByEver](../sdk/arseeding-js/9.getTokenTag.md)。 - options 里可以配置你的 Arweave Tags,什么是 Arweave Tags 参考:[这里](../other/tags.md)。 - tags 中的 Content-Type 需要基于你上传的内容进行配置,例如 上传的 png 格式的图片,则配置为 `image/png`,详细说明参考 [Content-Type](../other/tags.md#content-type)。 在准备好配置后,调用 await instance.sendAndPay(arseedUrl, data, payCurrencyTag, ops) 就可以将你的数据上传到 web3infra 的 Arseeding 节点。 在终端执行以下命令进行文件上传: ```bash node index.js ``` 正确执行后终端将返回: ```bash res { everHash: '0xf88033873d3bfc525d9333ec51b60f3f3dc03f822a9a73f66a10ebbd944b29c6', order: { itemId: '2bpKpp0dtfFZE82-P0lOmeI5x4m2ynatFzdjBmCWd4k', size: 192, bundler: 'uDA8ZblC-lyEFfsYXKewpwaX-kkNDDw8az3IW9bDL68', currency: 'USDC', decimals: 6, fee: '1141', paymentExpiredTime: 1690702235, expectedBlock: 1210331, tag: 'ethereum-usdc-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' } } ``` 最终这些数据将打包到 Arweave 网络,永存并不可篡改。 # 下载数据 在返回的结果中可以找到 `res.order.itemId` ,上文中 itemId 为 `2bpKpp0dtfFZE82-P0lOmeI5x4m2ynatFzdjBmCWd4k` 。 可以使用 curl 下载数据: ```bash curl --location --request GET 'https://arseed.web3infra.dev/2bpKpp0dtfFZE82-P0lOmeI5x4m2ynatFzdjBmCWd4k' ``` 更深入的学习 Arseeding 和 web3infra 请查看: - [详细指南](1.detail.md) - [API 文档](../api/0.intro.md) - SDK 文档([golang](../sdk/arseeding-go/1.intro.md), [js](../sdk/arseeding-js/1.intro.md), [python](../sdk/arseeding-py.md))
/* eslint-disable no-unused-vars */ import { useFormik } from "formik"; import { loginSchema } from "../../schemas"; import { Request } from "../../requests/request"; import { ToastContainer, toast } from "react-toastify"; import { useNavigate } from "react-router-dom"; import { SignInChoose, LoginWrapper } from "./LoginStyle"; import { FormStyle } from "../SignUp/SignUpStyle"; import { DarkBrownBox } from "./LoginStyle"; import { RoyalBlueBox } from "./LoginStyle"; import Button from "../Button/Button"; const Login = () => { const navigate = useNavigate(); const request = new Request(); const onSubmit = () => { let obj = { email: values.email, password: values.password, }; request.signInUser(obj).then((res) => { if (res === true) { toast.success("Login Successfull!"); setTimeout(() => { navigate("/", { replace: true }); }, 1500); } if (res === "incorrect-password") { toast.warn("You entered the wrong password!"); } if (res === "no-user") { toast.warn("There is no registered user with that e-mail"); } }); }; const { values, errors, isSubmitting, handleChange, handleSubmit } = useFormik({ initialValues: { email: "", password: "", }, validationSchema: loginSchema, onSubmit, }); return ( <LoginWrapper> <DarkBrownBox /> <div className="h-100"> <div className="container h-100 d-flex align-items-center "> <div className="col-7 mx-auto rounded-2 loginForm"> <SignInChoose className="mb-2"> <div className="text-center signTitle mt-2 mb-3 text-white pt-2"> Sign In With </div> <div className="d-lg-flex px-3 mb-1"> <div className="col-12 col-lg-4 marks signChoose text-dark"> <i style={{ color: "#dd4b39 " }} className="fa-brands fa-google-plus-g fa-xl signMarks" ></i> <span> with Google</span> </div> <div className="col-12 col-lg-4 marks signChoose text-dark"> <i className="fa-brands fa-github fa-xl signMarks"></i> <span> with Github</span> </div> <div className="col-12 col-lg-4 marks signChoose text-dark"> <i style={{ color: "#1877F2" }} className="fa-brands fa-facebook fa-xl signMarks" ></i> <span> with Facebook</span> </div> </div> </SignInChoose> <FormStyle style={{ backgroundColor: "#003459", border: "none" }}> <form onSubmit={handleSubmit}> <div className="form-group d-flex flex-column mb-3"> <label className="formTitle text-white" htmlFor="email"> Email address </label> <input type="email" value={values.email} onChange={handleChange} className={errors.email ? "input-error input" : "input"} id="email" aria-describedby="emailHelp" placeholder="Enter E-mail" /> {errors.email && <p className="error">{errors.email}</p>} </div> <div className="form-group d-flex flex-column mb-3"> <label className="formTitle text-white" htmlFor="password"> Password </label> <input type="password" value={values.password} onChange={handleChange} id="password" className={errors.password ? "input-error input" : " input"} placeholder="Password" /> {errors.password && ( <p className="error">{errors.password}</p> )} </div> <div className="d-flex justify-content-center"> <Button disabled={isSubmitting} type="submit" className="btn btn-primary mt-3 w-25" title="Sign Up !" background={"#fdfdfd"} border={"1px solid #fdfdfd"} color={"#003459"} /> </div> </form> </FormStyle> </div> <ToastContainer /> </div> </div> <RoyalBlueBox /> </LoginWrapper> ); }; export default Login;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="https://cdn.bootcss.com/sql.js/0.5.0/js/sql-optimized.js"></script> <script type="text/javascript" src="sqlite.js"></script> </head> <body> <div id=""> </div> </body> </html> <script type="text/javascript"> // 方案1: // function loadBinaryFile(path, success) { // var xhr = new XMLHttpRequest(); // xhr.open("GET", path, true); // xhr.overrideMimeType("application/text"); // xhr.responseType = "arraybuffer"; // xhr.onload = function() { // var data = new Uint8Array(xhr.response); // var arr = new Array(); // for (var i = 0; i != data.length; ++i) { // arr[i] = String.fromCharCode(data[i]); // }; // success(arr.join("")); // }; // xhr.send(null); // }; // // loadBinaryFile('./test1.db', function(data) { // var sqldb = new window.SQL.Database(data); // var res = sqldb.exec("SELECT * FROM MyNewTable"); // console.log('✅' + JSON.stringify(res)); // }); // // 方案2: // 读取数据库数据 axios.get("test1.db", { responseType: 'arraybuffer' }) .then(function(response) { let db = new window.SQL.Database(new Uint8Array(response.data)); console.log('db✅ ' + JSON.stringify(db)); // 执行查询 let s = new Date().getTime(); let r = db.exec("SELECT * FROM MyNewTable WHERE id = 1;"); let e = new Date().getTime(); console.info("查询数据耗时:" + (e - s) + "ms"); // 解析数据 let obj = dbToObj(r); // console.info(obj); console.log('✅ ' + JSON.stringify(obj)); }) .catch(function(error) { console.info(error); }); // 方法传入两个数组,第一个数组为key,第二个数组对应位置为value,此方法在Python中为zip()函数。 const ArraytoObj = (keys = [], values = []) => { if (keys.length === 0 || values.length === 0) return {}; const len = keys.length > values.length ? values.length : keys.length; const obj = {}; for (let i = 0; i < len; ++i) { obj[keys[i]] = values[i] } return obj; }; // 转驼峰表示:func.camel('USER_ROLE',true) => UserRole // 转驼峰表示:func.camel('USER_ROLE',false) => userRole const camel = (str, firstUpper = false) => { let ret = str.toLowerCase(); ret = ret.replace(/_([\w+])/g, function(all, letter) { return letter.toUpperCase(); }); if (firstUpper) { ret = ret.replace(/\b(\w)(\w*)/g, function($0, $1, $2) { return $1.toUpperCase() + $2; }); } return ret; }; // 把数组里面的所有转化为驼峰命名 const camelArr = (arrs = []) => { let _arrs = []; arrs.map(function(item) { _arrs.push(camel(item)); }); return _arrs; }; // 读取数据库 // 1.把columns转化为驼峰; // 2.把columns和values进行组合; const dbToObj = (_data = {}) => { let _res = []; _data.map(function(item) { let _columns = camelArr(item.columns); item.values.map(function(values) { _res.push(ArraytoObj(_columns, values)); }); }); return _res; }; </script>
import { createSlice, PayloadAction } from "@reduxjs/toolkit"; type sort = { name: string; sortProperty: string; }; interface DataState { sort: sort; choiceItem: string; searchValue: string; } const initialState: DataState = { sort: { name: "популярности", sortProperty: "rating", }, choiceItem: "phones", searchValue: "", }; export const filterSlice = createSlice({ name: "filter", initialState, reducers: { setSort(state, action: PayloadAction<sort>) { state.sort = action.payload; }, setChoiceItem(state, action: PayloadAction<string>) { state.choiceItem = action.payload; }, setSearchValue(state, action: PayloadAction<string>) { state.searchValue = action.payload; }, }, }); export const { setSort, setChoiceItem, setSearchValue } = filterSlice.actions; export default filterSlice.reducer;
import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import Navbar from "./Navbar"; import InputMask from "react-input-mask"; import Patients from "./Patients"; const Home = () => { const navigate = useNavigate(); const [searchText, setSearchText] = useState(''); const [loading, setLoading] = useState(false); const refresh = localStorage.getItem("refresh"); const access = localStorage.getItem("access"); const userDataString = localStorage.getItem("user"); const userData = userDataString ? JSON.parse(userDataString) : null; const [addPatient, setAddPatient] = useState(false); const [patientData, setPatientData] = useState({ name: "", phone: "", cnic: "", fee: "", disorder: "", attendant: "", address: "", }); const submitHandler = async (e) => { e.preventDefault(); try { setLoading(true); const formData = new FormData(); formData.append("name", patientData.name); formData.append("phone", patientData.phone); formData.append("cnic", patientData.cnic); formData.append("fee_paid", patientData.fee); formData.append("disorder", patientData.disorder); formData.append("attendant", patientData.attendant); formData.append("address", patientData.address); const response = await fetch( `${process.env.REACT_APP_BACKEND_URL}patients/create_patient`, { method: "POST", body: formData, } ); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const responseData = await response.json(); console.log(responseData); } catch (error) { console.log(error); } finally { setLoading(false); setPatientData({ name: "", phone: "", cnic: "", fee: "", disorder: "", attendant: "", address: "", }); setAddPatient(false); } }; useEffect(() => { if (!refresh || !access || !userData) { navigate("/login"); } }, [navigate, refresh, access, userData]); const [patients, setPatients] = useState([]); const fetchPatientData = async () => { const response = await fetch( `${process.env.REACT_APP_BACKEND_URL}patients/get_patients` ); const data = await response.json(); setPatients(data); }; useEffect(() => { fetchPatientData(); }, [loading]); const handleSearch = (e) =>{ setSearchText(e.target.value) } return ( <div className=""> <Navbar /> <div className="flex items-center justify-between px-7 mt-4"> <button className="bg-blue-500 py-2 px-3 rounded text-white" onClick={() => setAddPatient(true)} > Add Patient </button> <input type="text" onChange={(e)=>setSearchText(e.target.value)} placeholder="Search Here" name="" id="" className="border-[1px] border-solid border-gray-200 rounded py-2 px-3 outline-blue-500" /> </div> {addPatient && ( <div className="h-screen w-screen overflow-scroll fixed top-0 left-0 flex items-center justify-center opacity-95 bg-gray-200"> <div className="min-w-[300px] md:w-[500px] max-w-[500px]: border-[1px] border-solid border-gray-300 opacity-100 p-5 bg-white rounded-lg"> <div className="py-1"> <h2 className="text-xl">Add a Patient</h2> <hr /> </div> <form action="" onSubmit={submitHandler}> <div className="grid grid-cols-1 md:grid-cols-2 gap-3 "> <div className=""> <label htmlFor="name">Name</label> <input onChange={handleSearch} type="text" name="name" id="name" className="w-full border-solid border-[1px] border-gray-300 p-2 rounded outline-blue-500" /> </div> <div className="block"> <label htmlFor="phone">Phone</label> <InputMask mask="0399-9999999" id="phoneNumber" maskChar="_" onChange={(e) => setPatientData({ ...patientData, phone: e.target.value }) } className="w-full border-solid border-[1px] border-gray-300 p-2 rounded outline-blue-500" /> </div> </div> <div className="grid grid-cols-1 md:grid-cols-2 gap-3"> <div className="block"> <label htmlFor="cnic">CNIC</label> <InputMask mask="99999-9999999-9" maskChar="_" onChange={(e) => setPatientData({ ...patientData, cnic: e.target.value }) } type="text" name="cnic" id="cnic" className="w-full border-solid border-[1px] border-gray-300 p-2 rounded outline-blue-500" /> </div> <div className="block"> <label htmlFor="fee">Fee paid</label> <InputMask mask="9999.00" maskChar="_" onChange={(e) => setPatientData({ ...patientData, fee: e.target.value }) } type="text" name="fee" id="fee" className="w-full border-solid border-[1px] border-gray-300 p-2 rounded outline-blue-500" /> </div> </div> <div className="grid grid-cols-1 md:grid-cols-2 gap-3"> <div className="block"> <label htmlFor="disorder">Disorder</label> <select onChange={(e) => setPatientData({ ...patientData, disorder: e.target.value, }) } name="disorder" id="disorder" className="w-full border-solid border-[1px] border-gray-300 p-2 rounded outline-blue-500" > <option value="">-----</option> <option value="generalCheckup">General Checkup</option> <option value="diabetes">Diabetes</option> <option value="Blood Pressure">Blood Pressure</option> <option value="fever">Fever</option> <option value="accident">Accident</option> <option value="other">Other</option> </select> </div> <div className="block"> <label htmlFor="attendant">Attendant</label> <select onChange={(e) => setPatientData({ ...patientData, attendant: e.target.value, }) } name="attendant" id="attendant" className="w-full border-solid border-[1px] border-gray-300 p-2 rounded outline-blue-500" > <option value="">-----</option> <option value="Brother">Brother</option> <option value="Sister">Sister</option> <option value="Mother">Mother</option> <option value="Father">Father</option> <option value="Son">Son</option> <option value="Daughter">Daughter</option> <option value="Friend">Friend</option> <option value="Cousin">Cousin</option> <option value="Others">Others</option> </select>{" "} </div> </div> <div className="grid grid-cols-1"> <label htmlFor="">Address</label> <textarea onChange={(e) => setPatientData({ ...patientData, address: e.target.value }) } name="address" id="address" className="resize-none w-full border-solid border-[1px] border-gray-300 p-2 rounded outline-blue-500" ></textarea> </div> <div className="flex items-center justify-end gap-3 mt-4"> <button className="py-1 px-3 bg-gray-200 rounded" onClick={() => setAddPatient(false)} > Cancel </button> <button id='submit' type="submit" className="p-1 px-2 text-white bg-blue-500 rounded" > {loading ? <div>loading</div> : <div>OK</div>} </button> </div> </form> </div> </div> )} <Patients patients={patients} searchText={searchText} /> </div> ); }; export default Home;
import * as cfn from '@aws-cdk/aws-cloudformation'; import { NestedStackProps } from '@aws-cdk/aws-cloudformation'; import { Construct, Duration } from '@aws-cdk/core'; import * as sqs from '@aws-cdk/aws-sqs'; import * as lambda from '@aws-cdk/aws-lambda'; import * as kms from '@aws-cdk/aws-kms'; import * as cdk from '@aws-cdk/core'; import * as sns from '@aws-cdk/aws-sns'; import * as snsSubscription from '@aws-cdk/aws-sns-subscriptions' import { SqsEventSource } from '@aws-cdk/aws-lambda-event-sources'; import CommonNestedStack from './commonNestedStack'; export interface CommonStackObject { sqsQueue: sqs.Queue; handlers: Array<lambda.Function>; } export class FifoQueueLambdaStack extends CommonNestedStack { public readonly commonStackOutpu: CommonStackObject; public readonly handlers: Array<lambda.Function> = []; constructor(scope: Construct, id: string, props?: NestedStackProps, additionalProps?: any) { super(scope, id); const ENV_NAME = this.node.tryGetContext("ENV_NAME"); const SERVICE_NAME = this.node.tryGetContext("SERVICE_NAME"); //Need Fifo queue const queue = new sqs.Queue(this, `${ENV_NAME}-${SERVICE_NAME}-fifo-sqs`, { queueName: `${ENV_NAME}-${SERVICE_NAME}-workshop.fifo`, fifo: true, encryption: sqs.QueueEncryption.KMS }); this.cfnOutput(`${ENV_NAME}-${SERVICE_NAME}-workshop-06-queue-output-name`, queue.queueName, `${ENV_NAME}-${SERVICE_NAME}-workshop-06-name`, `queue name export for ${ENV_NAME}-${SERVICE_NAME}-workshop`); this.cfnOutput(`${ENV_NAME}-${SERVICE_NAME}-workshop-queue-06-output-arn`, queue.queueArn, `${ENV_NAME}-${SERVICE_NAME}-workshop-06-arn`, `queue arn export for ${ENV_NAME}-${SERVICE_NAME}-workshop`); //Need one lambda let LAMBD_ENV_VARS = {} as any; LAMBD_ENV_VARS['envName'] = ENV_NAME; LAMBD_ENV_VARS['serviceName'] = SERVICE_NAME; //step - 1 : create lambda function const cdkLambdaFunction = new lambda.Function(this, `${ENV_NAME}-${SERVICE_NAME}-cdk-fifo-lambda-id`, { runtime: lambda.Runtime.NODEJS_12_X, functionName: `${ENV_NAME}-${SERVICE_NAME}-cdk-fifo-lambda`, description: `cdk workshop lambda for ${ENV_NAME} envrionment and the service name is ${SERVICE_NAME}`, handler: `cdkLambdaFunctionThree.handler`, code: lambda.Code.asset(`deployment/cdkLambdaFunctionThree`), memorySize: 128, environment: LAMBD_ENV_VARS, timeout: Duration.seconds(30) }); cdkLambdaFunction.addEventSource(new SqsEventSource(queue, { batchSize: 10 // default })); } }
/* eslint-disable no-nested-ternary */ /* eslint-disable prettier/prettier */ /* eslint-disable jsx-a11y/click-events-have-key-events */ /* eslint-disable jsx-a11y/no-static-element-interactions */ import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { Box } from '@mui/material'; import { css } from '@emotion/css'; import NavItem from './NavItem'; import translation from '../../utils/translation'; import LoginDialog from '../LoginDialog/LoginDialog'; import SignUpDialog from '../SignUpDialog/SignUpDialog'; import InfoDialog from '../InfoDialog/InfoDialog'; import MapDialog from '../InfoDialog/MapDialog'; function Navbar() { const localeLanguage = useSelector((state) => state.data.localeLanguage); const dispatch = useDispatch(); const user = useSelector((state) => state.data.user); const [openDialog, setOpenDialog] = React.useState(''); const closeDialog = () => { setOpenDialog(''); }; return ( <Box className={css` display: flex; flex-direction: column; color: #000; font-size: 3vh; justify-content: center; align-items: center; overflow: hidden; top: 0; position: fixed; min-width: 50vh; padding-left: 1rem; @media (max-width: 600px){ font-size: 1.5vh; } `} > <Box className={css` display: flex; justify-content: space-between; align-items: center; padding: 1rem; flex-wrap: wrap; flex-direction: row; width: 100%; background-color: #bfc1e0; `} > <div onClick={() => setOpenDialog('about')}> <NavItem>{translation[localeLanguage].aboutUs}</NavItem> </div> <div onClick={() => setOpenDialog('contact')}> <NavItem>{translation[localeLanguage].contactUs}</NavItem> </div> <div onClick={() => setOpenDialog('map')}> <NavItem>{translation[localeLanguage].map}</NavItem> </div> <div onClick={() => setOpenDialog('vip')}> <NavItem> {translation[localeLanguage].vip} </NavItem> </div> {!user.username && ( <> <div onClick={() => setOpenDialog('signup')}> <NavItem>{translation[localeLanguage].signUp}</NavItem> </div> <div onClick={() => setOpenDialog('login')}> <NavItem>{translation[localeLanguage].login}</NavItem> </div> </> )} {user.username && ( <div onClick={() => { dispatch({ type: 'SET_USER', payload: {}, }); }} > <NavItem>{translation[localeLanguage].logout}</NavItem> </div> )} <div> <NavItem>{user?.username}</NavItem> </div> <LoginDialog closeDialog={closeDialog} open={openDialog === 'login'} /> <SignUpDialog closeDialog={closeDialog} open={openDialog === 'signup'} /> <MapDialog open={openDialog === 'map'} closeDialog={closeDialog} /> <InfoDialog closeDialog={closeDialog} open={ openDialog === 'about' || openDialog === 'contact' || openDialog === 'vip' } title={ openDialog === 'about' ? `${translation[localeLanguage].aboutUs}` : openDialog === 'contact' ? `${translation[localeLanguage].contactUs}` : 'VIP' } isContact={openDialog === 'contact'} /> </Box> </Box> ); } export default Navbar;
import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.green), useMaterial3: true, ), home: const MyHomePage(title: 'Diginova'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Center( child: Text( widget.title, style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold), ), ), SizedBox(height: 10), Image.asset( 'assets/image/diginova.jpg', width: 200, height: 200, ), SizedBox(height: 20), Text( 'DigiNova 2014 yılında Sanayi Bakanlığı’nın Tekno-Girişim Sermayesi Destek Programı kapsamında desteklenerek kurulmuştur.', style: TextStyle(fontSize: 18), ), SizedBox(height: 20), ElevatedButton( onPressed: () { _urlAc('https://diginova.com.tr/'); }, child: Text('Web Sayfasına Git'), ), ], ), ), ); } } Future<void> _urlAc(String link) async { if (await canLaunchUrl(Uri.parse(link))) { await launchUrl(Uri.parse(link)); } else { debugPrint('Link açılmıyor.'); } }
<?php declare(strict_types = 1); namespace MyApp\Entity; class Type { // on crée un objet Type // on crée les attributs (variables) de l'objet : private ?int $typeID = null; // on associe pas de valeur car la table incrémentera l'id par elle-même private string $label; public function __construct(?int $typeID, string $label) { // constructeur de l'objet $this->typeID = $typeID; // on atribue la valeur de $id à l'attibut 'id' $this->label = $label; // $this fait référence à l'instance en cours } public function getTypeId():?int { return $this->typeID; } public function getLabel():string { return $this->label; } public function setTypeId(?int $typeID):void { $this->typeID = $typeID; } public function setLabel(?int $label):void { $this->label = $label; } } ?>
/* * Copyright (C) 2022 The Android Open Source Project * * 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. */ #include "Apex.h" #include <android-base/format.h> #include <android-base/logging.h> #include <android-base/strings.h> #include "com_android_apex.h" #include "constants-private.h" using android::base::StartsWith; namespace android { namespace vintf { namespace details { status_t Apex::DeviceVintfDirs(FileSystem* fileSystem, std::vector<std::string>* dirs, std::string* error) { std::vector<std::string> vendor; std::vector<std::string> odm; // Update cached mtime_ int64_t mtime; auto status = fileSystem->modifiedTime(kApexInfoFile, &mtime, error); if (status != OK) { switch (status) { case NAME_NOT_FOUND: status = OK; break; case -EACCES: // Don't error out on access errors, but log it LOG(WARNING) << "APEX Device VINTF Dirs: EACCES: " << (error ? *error : "(unknown error message)"); status = OK; break; default: break; } if ((status == OK) && (error)) { error->clear(); } return status; } mtime_ = mtime; // Load apex-info-list std::string xml; status = fileSystem->fetch(kApexInfoFile, &xml, error); if (status == NAME_NOT_FOUND) { if (error) { error->clear(); } return OK; } if (status != OK) return status; auto apexInfoList = com::android::apex::parseApexInfoList(xml.c_str()); if (!apexInfoList.has_value()) { if (error) { *error = std::string("Not a valid XML ") + kApexInfoFile; } return UNKNOWN_ERROR; } // Get vendor apex vintf dirs for (const auto& apexInfo : apexInfoList->getApexInfo()) { // Skip non-active apexes if (!apexInfo.getIsActive()) continue; // Skip if no preinstalled paths. This shouldn't happen but XML schema says it's optional. if (!apexInfo.hasPreinstalledModulePath()) continue; const std::string& path = apexInfo.getPreinstalledModulePath(); if (StartsWith(path, "/vendor/apex/") || StartsWith(path, "/system/vendor/apex/")) { dirs->push_back(fmt::format("/apex/{}/" VINTF_SUB_DIR, apexInfo.getModuleName())); } } return OK; } // Returns true when /apex/apex-info-list.xml is updated bool Apex::HasUpdate(FileSystem* fileSystem) const { int64_t mtime{}; std::string error; status_t status = fileSystem->modifiedTime(kApexInfoFile, &mtime, &error); if (status == NAME_NOT_FOUND) { return false; } if (status != OK) { LOG(ERROR) << error; return false; } return mtime != mtime_; } } // namespace details } // namespace vintf } // namespace android
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class StringResourcesService { data = [ { "id": "copyright", "val": { "en": "Warning! Place a copyright string for the image at the end of your recipe description. Recepies without theese strings will not be approved by administrators!", "bg": "Внимание! Сложете текст за авторски права в края на начина на приготвяне на вашата рецепта. Рецепти без такъв текст няма да бъадт одобрени от администратор!" } }, { "id": "pending", "val": { "en": "Pending", "bg": "Чакащи" } }, { "id": "approve", "val": { "en": "approve", "bg": "Одобри" } }, { "id": "reject", "val": { "en": "Reject", "bg": "Отхвърли" } }, { "id": "accepted", "val": { "en": "Approved", "bg": "Одобрени" } }, { "id": "accept", "val": { "en": "Approving", "bg": "Одобрение" } }, { "id": "contact", "val": { "en": "Contact us", "bg": "Свържете се" } }, { "id": "irreversable", "val": { "en": "Are you sure you want to delete this recipe? This action is irreversible", "bg": "Сигурни ли стече искате да изтриете тази рецепта? Това действие е необратимо!" } }, { "id": "cancel", "val": { "en": "Cancel", "bg": "Отказ" } }, { "id": "confirm", "val": { "en": "Confirm action", "bg": "Потвърждаване на действие" } }, { "id": "user", "val": { "en": "user", "bg": "потребител" } }, { "id": "admin", "val": { "en": "Admin", "bg": "Администратор" } }, { "id": "superadmin", "val": { "en": "superadmin", "bg": "суперадминистратор" } }, { "id": "edit_your_recipe", "val": { "en": "Edit your recipe", "bg": "Промени своя рецепта" } }, { "id": "servings_1_por", "val": { "en": "Servings have to be at least 1 portion.", "bg": "Минималният брой порции е една. " } }, { "id": "choose_tag", "val": { "en": "Choose tag", "bg": "Изберете таг" } }, { "id": "no_recipes_found", "val": { "en": "No recipes match your search.", "bg": "Няма намерени рецепти." } }, { "id": "loading", "val": { "en": "Loading...", "bg": "Зареждане..." } }, { "id": "guest", "val": { "en": "Guest", "bg": "Гост" } }, { "id": "home", "val": { "en": "Home", "bg": "Начало" } }, { "id": "about", "val": { "en": "About us", "bg": "За нас" } }, { "id": "recipes", "val": { "en": "Recipes", "bg": "Рецепти" } }, { "id": "logout", "val": { "en": "Logout", "bg": "Излезте" } }, { "id": "favorites", "val": { "en": "Favorites", "bg": "Любими" } }, { "id": "admin", "val": { "en": "Admin", "bg": "Администратор" } }, { "id": "create_recipe", "val": { "en": "Create Recipe", "bg": "Създай Рецепта" } }, { "id": "welcome", "val": { "en": "Welcome", "bg": "Здравейте" } }, { "id": "newest_recipes", "val": { "en": "Newest Recipes", "bg": "Последно добавени рецепти" } }, { "id": "servings", "val": { "en": "servings", "bg": "порции" } }, { "id": "cook_time", "val": { "en": "Cook Time", "bg": "време готв." } }, { "id": "min", "val": { "en": "min", "bg": "мин." } }, { "id": "recipes", "val": { "en": "Recipes", "bg": "Рецепти" } }, { "id": "search_for", "val": { "en": "Search For", "bg": "Търси за" } }, { "id": "search", "val": { "en": "Search", "bg": "Търси" } }, { "id": "show_all", "val": { "en": "Show All", "bg": "Покажи всички" } }, { "id": "back_to", "val": { "en": "Back to", "bg": "Обратно към" } }, { "id": "admin", "val": { "en": "Admin", "bg": "Админ" } }, { "id": "edit", "val": { "en": "Edit", "bg": "Промени" } }, { "id": "delete", "val": { "en": "Delete", "bg": "Изтрий" } }, { "id": "ingredients", "val": { "en": "Ingredients", "bg": "Съставки" } }, { "id": "instructions", "val": { "en": "Instructions", "bg": "Начин на приготвяне" } }, { "id": "create_your_recipe", "val": { "en": "Create your recipe", "bg": "Създай своя рецепта" } }, { "id": "title", "val": { "en": "Title", "bg": "Заглавие" } }, { "id": "add_tag", "val": { "en": "Add Tag", "bg": "Добави таг" } }, { "id": "ingredient", "val": { "en": "Ingredient", "bg": "Съставка" } }, { "id": "add_ingredient", "val": { "en": "Add Ingredient", "bg": "Добави съставка" } }, { "id": "image_link", "val": { "en": "Image Link", "bg": "Връзка към изображение" } }, { "id": "minutes", "val": { "en": "minutes", "bg": "минути" } }, { "id": "create", "val": { "en": "Create", "bg": "Създай" } }, { "id": "login_here", "val": { "en": "Login Here", "bg": "Влезте оттук" } }, { "id": "email_address", "val": { "en": "Email address", "bg": "Електронна поща" } }, { "id": "is_required", "val": { "en": "is required", "bg": "е задължително поле" } }, { "id": "password", "val": { "en": "Password", "bg": "Парола" } }, { "id": "login", "val": { "en": "Login", "bg": "Влезте" } }, { "id": "register_here", "val": { "en": "Register Here", "bg": "Регистрирайте се оттук" } }, { "id": "username", "val": { "en": "Username", "bg": "Потребителско име" } }, { "id": "repeat_password", "val": { "en": "Repeat Password", "bg": "Повторете паролата" } }, { "id": "invalid_email", "val": { "en": "Invalid email", "bg": "Невалидна електронна поща" } }, { "id": "passwords_do_not_march", "val": { "en": "Passwords do not match.", "bg": "Паролите не съвпадат." } }, { "id": "register", "val": { "en": "Register", "bg": "Регистрирайте се" } }, { "id": "home_page_text", "val": { "en": "Welcome to CookIt! Here you will find delicious and easy recipes for every occasion. You'll find it here whether you're looking for a quick weeknight dinner, a special holiday feast, or a creative snack for your kids. Our app is designed with busy home cooks in mind, so you can find exactly what you need in no time. Plus, you can save your favorite recipes. So get cooking and enjoy the delicious recipes!", "bg": "Добре дошли в CookIt! Тук ще намерите вкусни и лесни рецепти за всеки повод. Ще го намерите тук, независимо дали търсите бърза делнична вечеря, специален празничен празник или креативна закуска за вашите деца. Нашето приложение е създадено с оглед на заетите домашни готвачи, така че можете да намерите точно това, от което се нуждаете за нула време. Освен това можете да запазите любимите си рецепти. Така че започнете да готвите и се насладете на вкусните рецепти!" } }, { "id": "about_page_text", "val": { "en": "Welcome to CookIt, where cooking and food come together in the tastiest way possible. Our mission is to inspire and help home cooks to create delicious and healthy meals for their families and friends. That's why we publish easy-to-follow recipes all aimed at making cooking accessible to everyone. Our team of experts tests every recipe to ensure it is delicious, healthy, and achievable in the home kitchen. We are always on the lookout for new recipes, cooking techniques, and ingredients, so you can be sure you're getting the latest and greatest in the world of cooking. CookIt is not just a recipe platform, it's a community. We encourage you to share your own recipes, ask questions, and connect with other food lovers. Whether you're an experienced cook or just starting out, CookIt is the place for you. So why not join us on this culinary journey and discover the joys of cooking with CookIt!", "bg": "Добре дошли в CookIt, където готвенето и храната се обединяват по възможно най-вкусния начин. Нашата мисия е да вдъхновяваме и помагаме на домашните готвачи да създават вкусни и здравословни ястия за своите семейства и приятели. Ето защо ние публикуваме лесни за изпълнение рецепти, целящи да направят готвенето достъпно за всеки. Нашият екип от експерти тества всяка рецепта, за да гарантира, че е вкусна, здравословна и постижима в домашната кухня. Винаги сме в търсене на нови рецепти, техники за готвене и съставки, така че можете да сте сигурни, че получавате най-новото и най-доброто в света на готвенето. CookIt не е просто платформа за рецепти, това е общност. Препоръчваме ви да споделяте свои собствени рецепти, да задавате въпроси и да се свързвате с други любители на храната. Независимо дали сте опитен готвач или тепърва започвате, CookIt е мястото за вас. Така че защо не се присъедините към нас в това кулинарно пътешествие и не откриете радостта от готвенето с CookIt!" } }, { "id": "users", "val": { "en": "Users", "bg": "Потребители" } }, { "id": "tags", "val": { "en": "Tags", "bg": "Тагове" } }, { "id": "user_list", "val": { "en": "User List", "bg": "Списък с потребители" } }, { "id": "promote", "val": { "en": "Promote", "bg": "Повиши" } }, { "id": "demote", "val": { "en": "Demote", "bg": "Понижи" } }, { "id": "permanent", "val": { "en": "Permanent", "bg": "Постоянен" } }, { "id": "recipe_list", "val": { "en": "Recipe List", "bg": "Списък с рецепти" } }, { "id": "create_new_tag", "val": { "en": "Create New Tag", "bg": "Създай нов таг" } }, { "id": "edit_tag", "val": { "en": "Edit Tag", "bg": "Редактирай таг" } }, { "id": "name", "val": { "en": "Name", "bg": "Име" } }, { "id": "incompatible", "val": { "en": "Incompatible", "bg": "Несъвместими" } }, { "id": "incorrect_login", "val": { "en": "Incorrect email or password!", "bg": "Грешна електронна поща или парола." } } ] lang = 'bg'; constructor() { } getResource(stringId: string) { const filtered = this.data.filter(el => { if(el.id === stringId){ return true; } return false; }) if(filtered.length > 0){ if(this.lang == "bg") return filtered[0].val.bg; return filtered[0].val.en; } return "N/A"; } getLang() { return this.lang; } }
import React, { useEffect } from "react"; import Head from "next/head"; import './globalStyles.css'; import { CssBaseline } from "@material-ui/core"; import CustomTheme from "../src/theme/CustomTheme"; export default function MyApp(props) { const { Component, pageProps } = props; useEffect(() => { // Remove the server-side injected CSS. const jssStyles = document.querySelector("#jss-server-side"); if (jssStyles) { jssStyles.parentElement.removeChild(jssStyles); } }, []); return ( <> <Head> <title>Pandita</title> <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" /> <link rel="shortcut icon" href="/favicon.ico" /> </Head> <CustomTheme> <CssBaseline /> <Component {...pageProps} /> </CustomTheme> </> ); }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { LoginComponent } from './login/login.component'; const routes: Routes = [ { path: '', component: LoginComponent }, { path: 'app-user-registration', loadChildren: () => import("./user-registration/user-registration.module").then(m => m.UserRegistrationModule), }, { path: 'app-dash-board', loadChildren: () => import("./dash-board/dash-board.module").then(m => m.DashboardModule), // canActivate: [AuthGuard] }, { path: '**', redirectTo: '' } ]; @NgModule({ imports: [RouterModule.forRoot(routes, { useHash: true })], exports: [RouterModule] }) export class AppRoutingModule { }
package com.bazarooma.flatbus.unittests; import org.junit.Before; import org.junit.Test; import com.bazarooma.flatbus.server.ServerEventBus; import com.bazarooma.flatbus.server.ServerEventBusFactory; import com.bazarooma.flatbus.test.OurEventBus; import com.bazarooma.flatbus.test.mathservice.MathService; import static org.mockito.Mockito.*; import static junit.framework.Assert.*; /** * Tests for the {@link ServerEventBus} * @author george georgovassilis * */ public class TestEventBusWithMocking { OurEventBus bus; MathService service; @Before public void setup(){ ServerEventBusFactory factory = new ServerEventBusFactory(); bus = factory.createAndProxy(OurEventBus.class); service = mock(MathService.class); bus.register(service); } @Test public void test(){ when(service.add(1, 2)).thenReturn(3); int result = bus.add(1, 2); assertEquals(3, result); verify(service).add(1, 2); } }
import { SubmitHandler, useForm } from "react-hook-form"; import { StyledButton } from "../../../styles/button"; import { StyledForm } from "../../../styles/form"; import Input from "../Input"; import { useContext } from "react"; import { UserContext } from "../../../providers/UserContext"; import { zodResolver } from "@hookform/resolvers/zod"; import { LoginFormSchema, TLoginFormValues } from "./schemaLogin"; export interface ILoginFormData { email: string; password: string; } const LoginForm = () => { const { userLogin, setLoading, loading } = useContext(UserContext); const { register, handleSubmit, formState: { errors }, } = useForm<TLoginFormValues>({ resolver: zodResolver(LoginFormSchema), }); const submit: SubmitHandler<TLoginFormValues> = (formData) => { userLogin(formData, setLoading); }; return ( <StyledForm onSubmit={handleSubmit(submit)}> <Input type="email" label="Email" {...register("email")} disabled={loading} error={errors.email} /> <Input type="password" label="Senha" {...register("password")} disabled={loading} error={errors.password} /> <StyledButton $buttonSize="default" $buttonStyle="green" type="submit" disabled={loading} > {loading ? "Entrando..." : "Entrar"} </StyledButton> </StyledForm> ); }; export default LoginForm;
<template> <div> <div class="container" :style='{"minHeight":"100vh","width":"100%","alignItems":"flex-start","background":"url(http://codegen.caihongy.cn/20230128/effb535f5a6142daa256f40fb8542933.jpg) no-repeat center bottom / 100% 100%,#fff","justifyContent":"flex-start","display":"flex"}'> <el-form ref="loginForm" :model="loginForm" :style='{"padding":"60px 0 40px","boxShadow":"0 0px 0px rgba(64, 158, 255, .8)","margin":"60px 0 0 12%","borderRadius":"o","background":"rgba(255,255,255,1)","width":"44%","height":"100%"}' :rules="rules"> <div v-if="false" :style='{"margin":"0 0 10px 0","color":"rgba(64, 158, 255, 1)","textAlign":"center","width":"100%","lineHeight":"44px","fontSize":"20px","textShadow":"4px 4px 2px rgba(64, 158, 255, .5)"}'>USER / LOGIN</div> <div v-if="true" :style='{"padding":"0 0 10px ","margin":"20px auto 40px","color":"#888","textAlign":"center","background":"url(http://codegen.caihongy.cn/20230128/4cbad5a2e6f444188a2c08cb74dc8160.png) no-repeat center bottom","width":"80%","lineHeight":"50px","fontSize":"24px","fontWeight":"500"}'>古文物收藏管理系统登录</div> <el-form-item v-if="loginType==1" class="list-item" :style='{"width":"60%","margin":"0 auto 20px","flexWrap":"wrap","display":"flex"}' prop="username"> <div v-if="false" :style='{"width":"64px","lineHeight":"44px","fontSize":"14px","color":"rgba(64, 158, 255, 1)"}'>账号:</div> <input :style='{"border":"2px solid #ddd","padding":"0 10px","color":"#333","borderRadius":"8px","flex":"1","background":"#fff","width":"100%","fontSize":"14px","height":"44px"}' v-model="loginForm.username" placeholder="请输入账户"> </el-form-item> <el-form-item v-if="loginType==1" class="list-item" :style='{"width":"60%","margin":"0 auto 20px","flexWrap":"wrap","display":"flex"}' prop="password"> <div v-if="false" :style='{"width":"64px","lineHeight":"44px","fontSize":"14px","color":"rgba(64, 158, 255, 1)"}'>密码:</div> <input :style='{"border":"2px solid #ddd","padding":"0 10px","color":"#333","borderRadius":"8px","flex":"1","background":"#fff","width":"100%","fontSize":"14px","height":"44px"}' v-model="loginForm.password" placeholder="请输入密码" type="password"> </el-form-item> <el-form-item v-if="roles.length>1" class="list-type" :style='{"width":"50%","margin":"20px auto 10px"}' prop="role"> <el-radio v-model="loginForm.tableName" :label="item.tableName" v-for="(item, index) in roles" :key="index" @change.native="getCurrentRow(item)">{{item.roleName}}</el-radio> </el-form-item> <el-form-item :style='{"padding":"10px 0 20px","margin":"0","alignItems":"center","top":"0","textAlign":"right","left":"0","background":"linear-gradient(180deg, rgba(255,255,255,1) 0%, rgba(178,213,232,1) 100%)","display":"flex","width":"10%","position":"absolute","height":"100%"}'> <el-button v-if="loginType==1" :style='{"border":"0","cursor":"pointer","padding":"0","margin":"0 auto","outline":"none","color":"#288bbf","borderRadius":"0","background":"none","width":"100%","fontSize":"24px","height":"100vh"}' @click="submitForm('loginForm')">登录</el-button> <el-button v-if="loginType==1" :style='{"border":"0","cursor":"pointer","padding":"0 0 ","margin":"0","color":"#666","bottom":"14%","marginLeft":"-50px","outline":"none","borderRadius":"8px","left":"450%","background":"none","width":"100px","fontSize":"16px","lineHeight":"1","position":"absolute","height":"40px"}' @click="resetForm('loginForm')">重置</el-button> <el-upload v-if="loginType==2" :action="baseUrl + 'file/upload'" :show-file-list="false" :on-success="faceLogin"> <el-button :style='{"border":"0","cursor":"pointer","padding":"0","margin":"0 auto","outline":"none","color":"#288bbf","borderRadius":"0","background":"none","width":"100%","fontSize":"24px","height":"100vh"}'>人脸识别登录</el-button> </el-upload> </el-form-item> <div :style='{"width":"100%","margin":"20px 0 0 0","alignItems":"center","flexWrap":"wrap","justifyContent":"center","display":"flex"}'> <router-link :style='{"cursor":"pointer","border":"2px solid #ddd","padding":"0 10px","margin":"0 10px 0 0","color":"#288bbf","borderRadius":"8px","textAlign":"center","background":"#eee","fontSize":"16px","textDecoration":"none","minWidth":"100px","lineHeight":"40px"}' :to="{path: '/register', query: {role: item.tableName,pageFlag:'register'}}" v-if="item.hasFrontRegister=='是'" v-for="(item, index) in roles" :key="index">注册{{item.roleName.replace('注册','')}}</router-link> </div> </el-form> </div> </div> </template> <script> export default { //数据集合 data() { return { baseUrl: this.$config.baseUrl, loginType: 1, roleMenus: [{"backMenu":[{"child":[{"appFrontIcon":"cuIcon-list","buttons":["新增","查看","修改","删除"],"menu":"用户","menuJump":"列表","tableName":"yonghu"}],"menu":"用户管理"},{"child":[{"appFrontIcon":"cuIcon-taxi","buttons":["新增","查看","修改","删除"],"menu":"文物展示","menuJump":"列表","tableName":"wenwuzhanshi"}],"menu":"文物展示管理"},{"child":[{"appFrontIcon":"cuIcon-skin","buttons":["新增","查看","修改","删除"],"menu":"文物类型","menuJump":"列表","tableName":"wenwuleixing"}],"menu":"文物类型管理"},{"child":[{"appFrontIcon":"cuIcon-present","buttons":["新增","查看","修改","删除"],"menu":"文物收藏","menuJump":"列表","tableName":"wenwushouzang"}],"menu":"文物收藏管理"},{"child":[{"appFrontIcon":"cuIcon-cardboard","buttons":["新增","查看","修改","删除"],"menu":"文物维护","menuJump":"列表","tableName":"wenwuweihu"}],"menu":"文物维护管理"},{"child":[{"appFrontIcon":"cuIcon-camera","buttons":["新增","查看","修改","删除"],"menu":"文物封存","menuJump":"列表","tableName":"wenwufengcun"}],"menu":"文物封存管理"},{"child":[{"appFrontIcon":"cuIcon-paint","buttons":["新增","查看","修改","删除"],"menu":"公告栏","menuJump":"列表","tableName":"gonggaolan"}],"menu":"公告栏管理"},{"child":[{"appFrontIcon":"cuIcon-wenzi","buttons":["新增","查看","修改","删除"],"menu":"轮播图管理","tableName":"config"},{"appFrontIcon":"cuIcon-keyboard","buttons":["查看","编辑名称","编辑父级","删除"],"menu":"菜单列表","tableName":"menu"}],"menu":"系统管理"}],"frontMenu":[{"child":[{"appFrontIcon":"cuIcon-list","buttons":["查看"],"menu":"文物展示列表","menuJump":"列表","tableName":"wenwuzhanshi"}],"menu":"文物展示模块"},{"child":[{"appFrontIcon":"cuIcon-album","buttons":["查看"],"menu":"公告栏列表","menuJump":"列表","tableName":"gonggaolan"}],"menu":"公告栏模块"}],"hasBackLogin":"是","hasBackRegister":"否","hasFrontLogin":"否","hasFrontRegister":"否","roleName":"管理员","tableName":"users"},{"backMenu":[{"child":[{"appFrontIcon":"cuIcon-present","buttons":["新增","查看","修改","删除"],"menu":"文物收藏","menuJump":"列表","tableName":"wenwushouzang"}],"menu":"文物收藏管理"},{"child":[{"appFrontIcon":"cuIcon-cardboard","buttons":["新增","查看","修改","删除"],"menu":"文物维护","menuJump":"列表","tableName":"wenwuweihu"}],"menu":"文物维护管理"},{"child":[{"appFrontIcon":"cuIcon-camera","buttons":["新增","查看","修改","删除"],"menu":"文物封存","menuJump":"列表","tableName":"wenwufengcun"}],"menu":"文物封存管理"}],"frontMenu":[{"child":[{"appFrontIcon":"cuIcon-list","buttons":["查看"],"menu":"文物展示列表","menuJump":"列表","tableName":"wenwuzhanshi"}],"menu":"文物展示模块"},{"child":[{"appFrontIcon":"cuIcon-album","buttons":["查看"],"menu":"公告栏列表","menuJump":"列表","tableName":"gonggaolan"}],"menu":"公告栏模块"}],"hasBackLogin":"是","hasBackRegister":"否","hasFrontLogin":"否","hasFrontRegister":"否","roleName":"用户","tableName":"yonghu"}], loginForm: { username: '', password: '', tableName: '', code: '', }, role: '', roles: [], rules: { username: [ { required: true, message: '请输入账户', trigger: 'blur' } ], password: [ { required: true, message: '请输入密码', trigger: 'blur' } ] }, codes: [{ num: 1, color: '#000', rotate: '10deg', size: '16px' }, { num: 2, color: '#000', rotate: '10deg', size: '16px' }, { num: 3, color: '#000', rotate: '10deg', size: '16px' }, { num: 4, color: '#000', rotate: '10deg', size: '16px' }] } }, created() { for(let item in this.roleMenus) { if(this.roleMenus[item].hasFrontLogin=='是') { this.roles.push(this.roleMenus[item]); } } }, mounted() { }, //方法集合 methods: { randomString() { var len = 4; var chars = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ] var colors = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] var sizes = ['14', '15', '16', '17', '18'] var output = [] for (var i = 0; i < len; i++) { // 随机验证码 var key = Math.floor(Math.random() * chars.length) this.codes[i].num = chars[key] // 随机验证码颜色 var code = '#' for (var j = 0; j < 6; j++) { var key = Math.floor(Math.random() * colors.length) code += colors[key] } this.codes[i].color = code // 随机验证码方向 var rotate = Math.floor(Math.random() * 45) var plus = Math.floor(Math.random() * 2) if (plus == 1) rotate = '-' + rotate this.codes[i].rotate = 'rotate(' + rotate + 'deg)' // 随机验证码字体大小 var size = Math.floor(Math.random() * sizes.length) this.codes[i].size = sizes[size] + 'px' } }, getCurrentRow(row) { this.role = row.roleName; }, submitForm(formName) { if (this.roles.length!=1) { if (!this.role) { this.$message.error("请选择登录用户类型"); return false; } } else { this.role = this.roles[0].roleName; this.loginForm.tableName = this.roles[0].tableName; } this.$refs[formName].validate((valid) => { if (valid) { this.$http.get(`${this.loginForm.tableName}/login`, {params: this.loginForm}).then(res => { if (res.data.code === 0) { localStorage.setItem('Token', res.data.token); localStorage.setItem('UserTableName', this.loginForm.tableName); localStorage.setItem('username', this.loginForm.username); localStorage.setItem('adminName', this.loginForm.username); localStorage.setItem('sessionTable', this.loginForm.tableName); localStorage.setItem('role', this.role); localStorage.setItem('keyPath', this.$config.indexNav.length+2); this.$router.push('/index/center'); this.$message({ message: '登录成功', type: 'success', duration: 1500, }); } else { this.$message.error(res.data.msg); } }); } else { return false; } }); }, resetForm(formName) { this.$refs[formName].resetFields(); } } } </script> <style rel="stylesheet/scss" lang="scss" scoped> .container { position: relative; background: url(http://codegen.caihongy.cn/20230128/effb535f5a6142daa256f40fb8542933.jpg) no-repeat center bottom / 100% 100%,#fff; .el-form-item { & /deep/ .el-form-item__content { width: 100%; } } .list-item /deep/ .el-input .el-input__inner { border: 2px solid #ddd; border-radius: 8px; padding: 0 10px; color: #333; flex: 1; background: #fff; width: 100%; font-size: 14px; height: 44px; } .list-code /deep/ .el-input .el-input__inner { border: 2px solid #ddd; border-radius: 8px; padding: 0 10px; outline: none; color: #333; background: #fff; display: inline-block; vertical-align: middle; width: calc(100% - 110px); font-size: 14px; height: 44px; } .list-type /deep/ .el-radio__input .el-radio__inner { background: rgba(53, 53, 53, 0); border-color: #999; } .list-type /deep/ .el-radio__input.is-checked .el-radio__inner { background: #288bbf; border-color: #288bbf; } .list-type /deep/ .el-radio__label { color: #999; font-size: 14px; } .list-type /deep/ .el-radio__input.is-checked+.el-radio__label { color: #288bbf; font-size: 14px; } } </style>
import java.util.Scanner; public class Question { private final String prompt; private final String[] answers; private final int correctAnswer; private static final int ANS_QTY = 4; private static final char[] IDENTIFIERS = {'A', 'B', 'C', 'D'}; public Question(String prompt, int cAnswer, String[] answers){ this.prompt = prompt; this.correctAnswer = cAnswer; this.answers = answers; } public Question(Question q) { this.prompt = q.prompt; this.correctAnswer = q.correctAnswer; this.answers = q.answers; } /* * params: none * returns: question prompt */ public String getPrompt() { return prompt; } /* * params: none * returns: question answers */ public String[] getAnswers() { return answers; } /* * params: none * returns: question correct answer */ public int getCorrectAnswer() { return correctAnswer; } /* * params: none * returns: num of answers in question */ public static int getANSQTY() { return ANS_QTY; } /* * params: none * returns: question identifiers */ public static char[] getIDENTIFIERS() { //limit to ansqty passed through return IDENTIFIERS; } /* * params: user choice * returns: boolean if correct answer matches user choice */ public boolean checkAnswer(int choice) { return (correctAnswer == choice); } @Override public String toString() { String out = ""; out += prompt + "\n"; for (int i = 0; i < ANS_QTY; i++) { out += " " + IDENTIFIERS[i] + ". " + answers[i] + "\n"; } return out; } }
<template> <div> <form class="edit-poll" @submit="editPoll"> <h1>Edit Poll</h1> <input type="text" placeholder="Question" v-model="question" class="question-form" required /> <br /> <VueDatePicker v-model="expiration_date" class="expiration-date-form"></VueDatePicker> <br /> <div v-for="choice in choices" :key="choice.id"> <input type="text" :value="choice.choice_text" class="choice-form" required @change="choice.choice_text = $event.target.value" /> <br /> </div> <br /> <input type="submit" value="Edit Poll" class="submit-poll-button" /> <br /> <input type="button" value="Cancel" @click="cancelPoll" class="cancel-poll-button" /> <br /> </form> </div> </template> <script> import { usePollStore } from '../stores/polls.js' import '../assets/css/edit.css' import closeForm from '../utils.js' import VueDatePicker from '@vuepic/vue-datepicker' import '@vuepic/vue-datepicker/dist/main.css' import { useToast } from 'vue-toast-notification' export default { components: { VueDatePicker }, props: { poll: Object }, data() { return { question: '', expiration_date: '', pollId: '', choices: [] } }, methods: { cancelPoll() { closeForm(this.poll) setTimeout(() => { this.$emit('cancel-poll') }, 500) }, editPoll(event) { this.loader = true event.preventDefault() let poll = { question: this.question, expiration_date: this.expiration_date, choices: this.choices } usePollStore().editPoll(this.pollId, poll) this.cancelPoll() } }, mounted() { this.pollId = this.poll.querySelector('#poll-id').innerHTML usePollStore() .getPoll(this.pollId) .then(() => { this.question = usePollStore().poll.data.question this.expiration_date = usePollStore().poll.data.expiration_date this.choices = usePollStore().poll.data.choices }) .catch(() => { useToast().error('Something went wrong') }) this.expiration_date = this.poll.querySelector('#expiration-date').innerHTML } } </script>
// Copyright(c) 2006 to 2020 ZettaScale Technology and others // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v. 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License // v. 1.0 which is available at // http://www.eclipse.org/org/documents/edl-v10.php. // // SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause #ifndef DDSRT_ENVIRON_H #define DDSRT_ENVIRON_H #include "dds/export.h" #include "dds/ddsrt/attributes.h" #include "dds/ddsrt/expand_vars.h" #include "dds/ddsrt/retcode.h" #if defined(__cplusplus) extern "C" { #endif /** * @brief Get value for environment variable. * * @param[in] name Environment variable name. * @param[out] value Alias to value of environment variable - must not be modified * * @returns A dds_return_t indicating success or failure. * * @retval DDS_RETCODE_OK * Environment variable written to @buf. * @retval DDS_RETCODE_NOT_FOUND * Environment variable not found. * @retval DDS_RETCODE_BAD_PARAMETER * FIXME: document * @retval DDS_RETCODE_OUT_OF_RESOURCES * FIXME: document * @retval DDS_RETCODE_ERROR * Unspecified error. */ DDS_EXPORT dds_return_t ddsrt_getenv( const char *name, const char **value) ddsrt_nonnull_all; /** * @brief Set environment variable value. * * Sets the environment variable to the value specified in value, or * alternatively, unsets the environment variable if value is an empty string. * * @param[in] name Environment variable name. * @param[in] value Value to set environment variable to. * * @returns A dds_return_t indicating success or failure. * * @retval DDS_RETCODE_OK * Environment variable successfully set to @value. * @retval DDS_RETCODE_BAD_PARAMETER * Invalid environment variable name. * @retval DDS_RETCODE_OUT_OF_RESOURCES * Not enough system resources to set environment variable. * @retval DDS_RETCODE_ERROR * Unspecified system error. */ DDS_EXPORT dds_return_t ddsrt_setenv( const char *name, const char *value) ddsrt_nonnull_all; /** * @brief Unset environment variable value. * * @param[in] name Environment variable name. * * @returns A dds_return_t indicating success or failure. * * @retval DDS_RETCODE_OK * Environment variable successfully unset. * @retval DDS_RETCODE_BAD_PARAMETER * Invalid environment variable name. * @retval DDS_RETCODE_OUT_OF_RESOURCES * Not enough system resources to unset environment variable. * @retval DDS_RETCODE_ERROR * Unspecified system error. */ DDS_EXPORT dds_return_t ddsrt_unsetenv( const char *name) ddsrt_nonnull_all; /** * @brief Expand environment variables within string. * * Expands ${X}, ${X:-Y}, ${X:+Y}, ${X:?Y} forms, but not $X. * * The result string should be freed with ddsrt_free(). * * @param[in] string String to expand. * @param[in] domid Domain id that this is relevant to * UINT32_MAX means none (see logging) * also made available as * ${CYCLONEDDS_DOMAIN_ID} * * @returns Allocated char*. * * @retval NULL * Expansion failed. * @retval Pointer * Copy of the string argument with the environment * variables expanded. */ DDS_EXPORT char* ddsrt_expand_envvars( const char *string, uint32_t domid); /** * @brief Expand environment variables within string. * * Expands $X, ${X}, ${X:-Y}, ${X:+Y}, ${X:?Y} forms, $ and \ * can be escaped with \. * * The result string should be freed with ddsrt_free(). * * @param[in] string String to expand. * * @returns Allocated char*. * * @retval NULL * Expansion failed. * @retval Pointer * Copy of the string argument with the environment * variables expanded. */ DDS_EXPORT char* ddsrt_expand_envvars_sh( const char *string, uint32_t domid); #if defined(__cplusplus) } #endif #endif /* DDSRT_ENVIRON_H */
package main import ( "fmt" "time" ) /// Arrays, slices, maps and loops /// https://www.youtube.com/watch?v=8uiZC0l4Ajw func main() { /// Arrays var intArr [3]int32 // varName [Length] datatype fmt.Println(intArr[0]) fmt.Println(intArr[1:3]) /// Changing array values fmt.Println(intArr[1]) intArr[1] = 123 // Changes the value of index 1 to 123 fmt.Println(intArr[1]) var intArr1 [3]int32 = [3]int32{1, 2, 3} // Initialse the values of an Array and declare it fmt.Println(intArr1) intArr2 := [3]int32{1, 2, 3} // Initialse the values of an Array and declare it fmt.Println(intArr2) intArr3 := [...]int32{1, 2, 3} // The compiler works out the max length of the array from the values passed to it (I.e. 3) fmt.Println(intArr3) /// Slices var intSlice []int32 = []int32{4, 5, 6} fmt.Println(intSlice) fmt.Printf("The length is %v with capacity %v", len(intSlice), cap(intSlice)) intSlice = append(intSlice, 7) //Adds a new value to the array (Either creates a new array and moves the data to it (If the length has exceeded it) or if there is capacity left in the array it adds a value to it) fmt.Printf("\nThe length is %v with capacity %v", len(intSlice), cap(intSlice)) fmt.Println(intSlice) var intSlice2 []int32 = []int32{8, 9} // Append new values to an existing array in bulk intSlice = append(intSlice, intSlice2...) fmt.Println(intSlice) var intSlice3 []int32 = make([]int32, 3, 8) // Automatically creates a array with the number of values and the max number (E.g. 3 is the list of values to create and 8 would be the max length before expanding) fmt.Println(intSlice3) /// Maps /// Set of key value pairs var myMap map[string]uint8 = make(map[string]uint8) //This would create a map with a key being string type and value being an unsigned int8 fmt.Println(myMap) var myMap2 = map[string]uint8{"Adam": 23, "Sarah": 45} // Creates a map and assigns key/values fmt.Println(myMap2) fmt.Println(myMap2["Adam"]) // Gets the value of the Key named "Adam" fmt.Println(myMap2["Jason"]) // If you specify a value which doesn't exist you will get the data type default value (In this case it would be the default value of uint8 which would be 0) var age, ok = myMap2["Jason"] // This would allow you to better handle if the name doesn't exist instead of getting the default value and using it... if ok { fmt.Printf("The age is %v", age) } else { fmt.Println("Invalid Name") } delete(myMap2, "Adam") // Delete's a key/value from a Map. age, ok = myMap2["Adam"] // This would allow you to better handle if the name doesn't exist instead of getting the default value and using it... if ok { fmt.Printf("The age is %v", age) } else { fmt.Println("Invalid Name") } // Loops // Can loop through an array, map or slice // loop through a map for name, age := range myMap2 { fmt.Printf("Name: %v, Age: %v\n", name, age) } // loop through an array/slice for i, v := range intArr { fmt.Printf("Index: %v, Value: %v \n", i, v) } // while loop var i int = 0 for i <= 10 { fmt.Println(i) i = i + 1 } for i := 0; i < 10; i++ { // Condensed While loop, 1st item is initialize variable, then the condition and then the post (I.e. what get's executed) fmt.Println(i) } /// Speed comparison for predefined length arrays vs dynamic ones... var n int = 1000000 var testSlice = []int{} // Empty array but no defined length var testSlice2 = make([]int, 0, n) // Empty but with defined length (1,000,000) fmt.Printf("Total time without preallocation: %v\n", timeLoop(testSlice, n)) fmt.Printf("Total time with preallocation: %v\n", timeLoop(testSlice2, n)) // should be around 3x faster... } func timeLoop(slice []int, n int) time.Duration { var t0 = time.Now() for len(slice) < n { slice = append(slice, 1) } return time.Since(t0) }
import React, { useState } from "react"; import { Dialog, DialogTitle, DialogContent, TextField, Button, FormControl, InputLabel, Select, MenuItem, Typography, Box, } from "@mui/material"; export default function ReminderCreation({ open, onClose, onSaveReminder, selectedStartTime, }) { const defaultColor = "#FF0000"; // Default color (e.g., red) const [reminderData, setReminderData] = useState({ title: "", description: "", recurrence: "none", timeZone: "GMT", // Default time zone start: selectedStartTime || null, // Start time from ReactBigCalendar }); const handleSaveReminder = () => { if (reminderData.title) { onSaveReminder(reminderData); setReminderData({ title: "", description: "", recurrence: "none", timeZone: "GMT", start: selectedStartTime || null, }); onClose(); } }; return ( <Dialog open={open} onClose={onClose}> <DialogTitle>Create Reminder</DialogTitle> <DialogContent> <TextField label="Reminder Title" fullWidth margin="normal" value={reminderData.title} onChange={(e) => setReminderData({ ...reminderData, title: e.target.value }) } /> <TextField label="Description" fullWidth multiline rows={4} margin="normal" value={reminderData.description} onChange={(e) => setReminderData({ ...reminderData, description: e.target.value }) } /> <FormControl fullWidth margin="normal"> <InputLabel>Recurrence</InputLabel> <Select value={reminderData.recurrence} onChange={(e) => setReminderData({ ...reminderData, recurrence: e.target.value }) } > <MenuItem value="none">None</MenuItem> <MenuItem value="daily">Daily</MenuItem> <MenuItem value="weekly">Weekly</MenuItem> <MenuItem value="monthly">Monthly</MenuItem> <MenuItem value="yearly">Yearly</MenuItem> </Select> </FormControl> <FormControl fullWidth margin="normal"> <InputLabel>Time Zone</InputLabel> <Select value={reminderData.timeZone} onChange={(e) => setReminderData({ ...reminderData, timeZone: e.target.value }) } > <MenuItem value="auto">Auto (Detect Time Zone)</MenuItem> <MenuItem value="GMT">GMT</MenuItem> <MenuItem value="PST">PST (Pacific Standard Time)</MenuItem> {/* Add more time zones as needed */} </Select> </FormControl> <Typography variant="subtitle1">Start Time:</Typography> <Typography variant="body1"> {reminderData.start ? reminderData.start.toString() : "N/A"} </Typography> </DialogContent> <Button variant="outlined" onClick={handleSaveReminder}> Save Reminder </Button> </Dialog> ); }
<?php namespace App\Http\Middleware; use Closure; use Exception; use Illuminate\Http\Request; use Dcat\Admin\Support\Helper; use Illuminate\Support\Facades\Log; use App\Models\AffiliateSystem\ReferralCode; class StoreReferralCode { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse */ public function handle(Request $request, Closure $next) { $response = $next($request); if ($request->has('ref') && !Helper::isAjaxRequest() && !$request->hasCookie('ref')){ try { /** @var ReferralCode $referral */ $referral = ReferralCode::whereCode($request->get('ref'))->first(); if(is_null($referral)) { return $response; } $visit = visitor()->visit($referral); $response->cookie('ref_code_visit_id', $visit->id); $response->cookie('ref', $referral->id, $referral->lifetime_minutes); } catch(Exception $ex) { Log::critical('StoreReferralCode', ['ex' => $ex->getMessage()]); } } return $response; } }
<?php namespace App\Http\Controllers\API\V1; use App\Repositories\ConclusionContractRepository; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Traits\ResponseTrait; use Illuminate\Http\JsonResponse; class ConclusionContractController extends Controller { use ResponseTrait; protected $conclusionContractRepository; public function __construct(ConclusionContractRepository $conclusionContractRepository) { $this->conclusionContractRepository = $conclusionContractRepository; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request): JsonResponse { return $this->responseSuccess([ 'contracts' => $this->conclusionContractRepository->getAll($request), ], 'List Successfully !'); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $data = $this->conclusionContractRepository->create($request); if (!$data['status']) { return $this->responseError($data, $data['message']); } return $this->responseSuccess($data, 'Create item success!'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(Request $request, $id): JsonResponse { return $this->responseSuccess([ 'conclusionContractSample' => $this->conclusionContractRepository->getById($id), ], 'Tagert Sample Successfully !'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $data = $this->conclusionContractRepository->update($request, $id); if (empty($data['status'])) { return $this->responseError($data, $data['message']); } return $this->responseSuccess($data, 'Update item success!'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function removeItems(Request $request) { $response = $this->conclusionContractRepository->removeItems($request); if (!($response['status'])) { return $this->responseError($response['status'], $response['data'], $response['message']); } return $this->responseSuccess($response, 'Remove item success!'); } }
import React, { useState } from "react"; import "../resources/layout.css"; import { useNavigate } from "react-router-dom"; import { useSelector } from "react-redux"; const DefaultLayout = ({ children }) => { const [collapse, setCollapse] = useState(false); const { user } = useSelector((state) => state.users); const navigate = useNavigate(); const userMenu = [ { name: "Home", path: "/", icon: "ri-home-line", }, { name: "Bookings", path: "/bookings", icon: "ri-file-list-line", }, { name: "Profile", path: "/profile", icon: "ri-user-line", }, { name: "Logout", path: "/logout", icon: "ri-logout-box-line", }, ]; const adminMenu = [ { name: "Home", path: "/", icon: "ri-home-line", }, { name: "Buses", path: "/admin/buses", icon: "ri-bus-line", }, { name: "Users", path: "/admin/users", icon: "ri-user-line", }, { name: "Bookings", path: "/admin/bookings", icon: "ri-file-list-line", }, { name: "Logout", path: "/logout", icon: "ri-logout-box-line", }, ]; const menuToBeRendered = user?.isAdmin ? adminMenu : userMenu; let activeRoute = window.location.pathname; if(window.location.pathname.includes('book-now')){ activeRoute = '/' } return ( <div className="layout-parent"> <div className="sidebar"> <div className="sidebar-header"> <h1 className="logo">PBUS</h1> <h1 className="role"> {" "} {user?.name} <br /> Role: {user?.isAdmin ? "Admin" : "User"} </h1> </div> <div className="d-flex flex-column gap-3 justify-content-start menu"> {menuToBeRendered.map((item, index) => ( <div className={`${ activeRoute === item.path && "active-menu-item" } menu-item`} key={index} > <i className={item.icon} onClick={() => { if (item.path === "/logout") { localStorage.removeItem("token"); navigate("/login"); } else { navigate(item.path); } }} /> {!collapse && ( <span onClick={() => { if (item.path === "/logout") { localStorage.removeItem("token"); navigate("/login"); } else { navigate(item.path); } }} > {item.name} </span> )} </div> ))} </div> </div> <div className="body"> <div className="header"> {collapse ? ( <i className="ri-menu-line" onClick={() => setCollapse(!collapse)} ></i> ) : ( <i className="ri-close-line" onClick={() => setCollapse(!collapse)} ></i> )} </div> <div className="content">{children}</div> </div> </div> ); }; export default DefaultLayout;
<?php /** * @file * Create table for typical_entity_example_2. */ /** * Implements hook_schema(). */ function typical_entity_example_2_schema() { $schema = array(); $schema['typical_entity_example_2'] = array( 'description' => 'The base table for typical_entity_example_2.', 'fields' => array( 'teid' => array( 'description' => 'The primary identifier.', 'type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE, ), 'title' => array( 'description' => 'Entity title.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'description' => array( 'description' => 'Entity description.', 'type' => 'text', ), ), 'primary key' => array('teid'), ); return $schema; }
package org.d3if2074.kontak.network import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.work.Worker import androidx.work.WorkerParameters import org.d3if2074.kontak.MainActivity import org.d3if2074.kontak.R class UpdateWorker ( context: Context, workerParams: WorkerParameters ) : Worker(context, workerParams){ private val notificationId = 44 override fun doWork(): Result { val intent = Intent(applicationContext, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK val pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, 0) val build = NotificationCompat.Builder(applicationContext, MainActivity.CHANNEL_ID) .setSmallIcon(R.mipmap.ic_launcher_round) .setContentTitle(applicationContext.getString( R.string.notif_title )) .setContentText(applicationContext.getString( R.string.notif_text )) .setPriority(NotificationCompat.PRIORITY_HIGH) .setContentIntent(pendingIntent) .setAutoCancel(true) val manager = NotificationManagerCompat.from(applicationContext) manager.notify(notificationId, build.build()) return Result.success() } }
from hashlib import sha256 from loguru import logger import time class Block: """初期化 diff: 難易度の調整\n previous_hash: 前のブロックのハッシュ値\n transaction_data: 登録したい取引データの辞書\n """ def __init__(self, diff: int, previous_hash: str, transaction_data: dict) -> None: self.diff: int = int(diff) self.previous_hash: str = str(previous_hash) self.transaction_data: dict = transaction_data self.timestamp: float = time.time() self.hash: str = self.__calculate_hash() def __calculate_hash(self) -> str: block_hash: str = "" nonce: int = 0 timestamp: float = self.timestamp previous_hash: str = self.previous_hash transaction_data = self.transaction_data logger.debug("start Mining") while True: block_data = { "previous_hash": previous_hash, "transaction_data": transaction_data, "timestamp": timestamp, "nonce": nonce, } # ブロックのハッシュを求める block_hash: str = sha256(str(block_data).encode()).hexdigest() if block_hash[0 : self.diff] == "0" * self.diff: logger.debug( f"finish Mining\nprevious_hash: {self.previous_hash}\nnonce: {nonce}\nhash: {block_hash}\ntimestamp: {self.timestamp}" ) return block_hash else: nonce += 1 if nonce % 100000 == 0: logger.debug(f"Mining: {nonce}...")
= mibl - tools for meta-programming OCaml builds Scheme tools for herding OCaml projects; in particular analyzing and editing link:https://dune.readthedocs.io/en/latest/[Dune], link:https://opam.ocaml.org/doc/Manual.html[OPAM], and link:http://projects.camlcity.org/projects/dl/findlib-1.9.4/doc/ref-html/r759.html[META] files. If you prefer acronyms: **M**eta-**ibl** ("ibl" is Arabic for "camel"). If you prefer recursion: **M**ibl **i**ntegrates **b**uild **l**anguages. IMPORTANT: **STATUS**: Alpha. The code (in C) for the crawling the file system and parsing Dune, Meta, and OPAM and META files is written but the Scheme APIs are still under construction. An earlier version of the Dune API was sufficient for generating Bazel build files, but it is undergoing major revisions. What's there is sufficient for exploration. `mibl` is derived from link:https://ccrma.stanford.edu/software/snd/snd/s7.html[s7]. See link:https://iainctduncan.github.io/scheme-for-max-docs/s7.html[Why S7 Scheme?] for reasons why. == Getting Started [source,starlark, title="WORKSPACE.bazel"] ---- load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") git_repository( name = "mibl", remote = "https://github.com/obazl/mibl", branch = "main" ) ---- NOTE: Once `mibl` is officially released this should be replaced with an `http_archive` rule. There are two ways to run `mibl`: with or without Bazel. == Running mibl in a Bazel environment From within a Bazel project: [source,shell] ---- $ bazel run @mibl//repl ---- Options: `-v` (verbose) and `-d` (debug). Once in the repl, run `dune-load` to crawl your project and produce a hash-table of package specs: [source,scheme] ---- (dune-load "src/lib_stdlib_unix") ---- By default, `dune-load` will interpret a single string arg as a file path relative to the launch directory. You can also give it a list of directories to crawl: [source,scheme] ---- (dune-load '("src/a" "src/b")) ---- You can also pass it two arguments: a path and a list of paths; the first will be interpreted as a path relative to your `$HOME` directory, which will serve as the traversal root; the paths in the second arg will be interpreted relative to that root directory. For example, suppose your current directory is `$HOME/myproj` and you are also working on a related project at `$HOME/mylib`. Then to crawl the `src/foo` and `test/bar` directories of that project (i.e. `$HOME/mylib/src/foo` and `$HOME/mylib/test/bar`), run: [source,scheme] ---- (dune-load "myproj" '("src/foo" "src/bar")) ---- Finally, running without any args - `(dune-load)` - will crawl the tree rooted at the current directory. == Running mibl as a standalone executable You can install `mibl` in your local system by running: [source,shelll] ---- $ bazel run @mibl//deploy ---- Installation follows the link:[XDG] standard: * the `mibl` executable will go in `$HOME/.local/bin`; put this in your `$PATH`. * `mibl` dynamically loads (`dlopen`) file `libc_s7.so`; this will be installed in `$XDG_DATA_HOME/mibl`. By default, `XDG_DATA_HOME` = `$HOME/.local/share`. * Scheme script files used by `mibl` will be installed in `$XDG_DATA_HOME/mibl`. The `*load-path* of `mibl` will be configured to include: * `.` (current directory) * `$PWD/.mibl` * `$HOME/.mibl` * `$XDG_DATA_HOME/.local/share/mibl` * `$XDG_DATA_HOME/.local/share/mibl/s7` Then run `$ mibl` to launch the repl. == Configuring mibl At launch, `mibl` will try to read the first config file if finds by searching: * `$PWD/.config/miblrc` * `$HOME/.config/miblrc` TODO: miblrc docs
const { Sequelize, DataTypes, Model } = require('sequelize'); import sequelize from '../connection/db'; interface UserAttributes { firstName: string; lastName: string; fullName: string; dob: Date, age: number; gender: string; email: string; pno: number; password: string; confirmPassword: string; role: string; } export class User extends Model<UserAttributes> { } User.init( { firstName: { type: DataTypes.STRING, // allowNull: false, // validate: { // notNull: { // msg: 'Please enter your name', // }, // }, }, lastName: { type: DataTypes.STRING, // allowNull defaults to true }, fullName: { type: DataTypes.STRING }, dob: { type: DataTypes.DATEONLY }, age: { type: DataTypes.INTEGER, allowNull: false, validate: { notNull: { msg: 'Please enter your Age', }, }, }, gender: { type: DataTypes.STRING, allowNull: false, validate: { notNull: { msg: 'Please enter your Gender', }, }, }, email: { type: DataTypes.STRING, allowNull: false, unique: true, validate: { isEmail: { args: true, msg: 'email format is not correct' }, notNull: { args: true, msg: "email can't be empty" }, notEmpty: { args: true, msg: "email can't be empty string" }, }, }, pno: { type: DataTypes.BIGINT, allowNull: false, unique: true, validate: { len: [10], isNumeric: true, }, }, password: { type: DataTypes.STRING, allowNull: false, validate: { notNull: { args: true, message: "password can't be empty" }, len: [8, 1000], }, }, confirmPassword: { type: DataTypes.STRING, allowNull: false, validate: { notNull: { args: true, message: "password can't be empty" }, len: [8, 1000], }, }, role: { type: DataTypes.STRING, defaultValue: 'User', }, }, { // Other model options go here tableName: 'users', sequelize: sequelize, // We need to pass the connection instance }, ); // `sequelize.define` also returns the model console.log(User === sequelize.models.User); // true export default User;
import React from "react"; import { Provider } from "react-redux"; import { BrowserRouter } from "react-router-dom"; import { AppShell, ColorScheme, ColorSchemeProvider, MantineProvider, } from "@mantine/core"; import { useLocalStorage } from "@mantine/hooks"; import { NotificationsProvider } from "@mantine/notifications"; import Header from "./components/Header"; import store from "./store/store"; import AppRoutes from "./AppRoutes"; export default function App() { return ( <Provider store={store}> <UiProvider /> </Provider> ); } function UiProvider() { const [colorScheme, setColorScheme] = useLocalStorage<ColorScheme>({ key: "mantine-color-scheme", defaultValue: "light", getInitialValueInEffect: true, }); const toggleColorScheme = (value?: ColorScheme) => setColorScheme(value || (colorScheme === "dark" ? "light" : "dark")); return ( <ColorSchemeProvider colorScheme={colorScheme} toggleColorScheme={toggleColorScheme} > <MantineProvider theme={{ colorScheme }}> <NotificationsProvider> <AppLayout /> </NotificationsProvider> </MantineProvider> </ColorSchemeProvider> ); } function AppLayout() { return ( <BrowserRouter> <AppShell header={<Header />} padding="md" fixed={true} styles={(theme) => ({ main: { backgroundColor: theme.colorScheme === "dark" ? theme.colors.dark[8] : theme.colors.gray[0], }, })} > <AppRoutes /> </AppShell> </BrowserRouter> ); }
//! //! Low-level Block-oriented I/O functions //! use super::ephemeral_file::EphemeralFile; use super::storage_layer::delta_layer::{Adapter, DeltaLayerInner}; use crate::context::RequestContext; use crate::page_cache::{self, PageReadGuard, ReadBufResult, PAGE_SZ}; use crate::virtual_file::VirtualFile; use bytes::Bytes; use std::ops::{Deref, DerefMut}; /// This is implemented by anything that can read 8 kB (PAGE_SZ) /// blocks, using the page cache /// /// There are currently two implementations: EphemeralFile, and FileBlockReader /// below. pub trait BlockReader { /// /// Create a new "cursor" for reading from this reader. /// /// A cursor caches the last accessed page, allowing for faster /// access if the same block is accessed repeatedly. fn block_cursor(&self) -> BlockCursor<'_>; } impl<B> BlockReader for &B where B: BlockReader, { fn block_cursor(&self) -> BlockCursor<'_> { (*self).block_cursor() } } /// Reference to an in-memory copy of an immutable on-disk block. pub enum BlockLease<'a> { PageReadGuard(PageReadGuard<'static>), EphemeralFileMutableTail(&'a [u8; PAGE_SZ]), #[cfg(test)] Arc(std::sync::Arc<[u8; PAGE_SZ]>), } impl From<PageReadGuard<'static>> for BlockLease<'static> { fn from(value: PageReadGuard<'static>) -> BlockLease<'static> { BlockLease::PageReadGuard(value) } } #[cfg(test)] impl<'a> From<std::sync::Arc<[u8; PAGE_SZ]>> for BlockLease<'a> { fn from(value: std::sync::Arc<[u8; PAGE_SZ]>) -> Self { BlockLease::Arc(value) } } impl<'a> Deref for BlockLease<'a> { type Target = [u8; PAGE_SZ]; fn deref(&self) -> &Self::Target { match self { BlockLease::PageReadGuard(v) => v.deref(), BlockLease::EphemeralFileMutableTail(v) => v, #[cfg(test)] BlockLease::Arc(v) => v.deref(), } } } /// Provides the ability to read blocks from different sources, /// similar to using traits for this purpose. /// /// Unlike traits, we also support the read function to be async though. pub(crate) enum BlockReaderRef<'a> { FileBlockReader(&'a FileBlockReader), EphemeralFile(&'a EphemeralFile), Adapter(Adapter<&'a DeltaLayerInner>), #[cfg(test)] TestDisk(&'a super::disk_btree::tests::TestDisk), #[cfg(test)] VirtualFile(&'a VirtualFile), } impl<'a> BlockReaderRef<'a> { #[inline(always)] async fn read_blk( &self, blknum: u32, ctx: &RequestContext, ) -> Result<BlockLease, std::io::Error> { use BlockReaderRef::*; match self { FileBlockReader(r) => r.read_blk(blknum, ctx).await, EphemeralFile(r) => r.read_blk(blknum, ctx).await, Adapter(r) => r.read_blk(blknum, ctx).await, #[cfg(test)] TestDisk(r) => r.read_blk(blknum), #[cfg(test)] VirtualFile(r) => r.read_blk(blknum).await, } } } /// /// A "cursor" for efficiently reading multiple pages from a BlockReader /// /// You can access the last page with `*cursor`. 'read_blk' returns 'self', so /// that in many cases you can use a BlockCursor as a drop-in replacement for /// the underlying BlockReader. For example: /// /// ```no_run /// # use pageserver::tenant::block_io::{BlockReader, FileBlockReader}; /// # use pageserver::context::RequestContext; /// # let reader: FileBlockReader = unimplemented!("stub"); /// # let ctx: RequestContext = unimplemented!("stub"); /// let cursor = reader.block_cursor(); /// let buf = cursor.read_blk(1, &ctx); /// // do stuff with 'buf' /// let buf = cursor.read_blk(2, &ctx); /// // do stuff with 'buf' /// ``` /// pub struct BlockCursor<'a> { reader: BlockReaderRef<'a>, } impl<'a> BlockCursor<'a> { pub(crate) fn new(reader: BlockReaderRef<'a>) -> Self { BlockCursor { reader } } // Needed by cli pub fn new_fileblockreader(reader: &'a FileBlockReader) -> Self { BlockCursor { reader: BlockReaderRef::FileBlockReader(reader), } } /// Read a block. /// /// Returns a "lease" object that can be used to /// access to the contents of the page. (For the page cache, the /// lease object represents a lock on the buffer.) #[inline(always)] pub async fn read_blk( &self, blknum: u32, ctx: &RequestContext, ) -> Result<BlockLease, std::io::Error> { self.reader.read_blk(blknum, ctx).await } } /// An adapter for reading a (virtual) file using the page cache. /// /// The file is assumed to be immutable. This doesn't provide any functions /// for modifying the file, nor for invalidating the cache if it is modified. pub struct FileBlockReader { pub file: VirtualFile, /// Unique ID of this file, used as key in the page cache. file_id: page_cache::FileId, } impl FileBlockReader { pub fn new(file: VirtualFile) -> Self { let file_id = page_cache::next_file_id(); FileBlockReader { file_id, file } } /// Read a page from the underlying file into given buffer. async fn fill_buffer(&self, buf: &mut [u8], blkno: u32) -> Result<(), std::io::Error> { assert!(buf.len() == PAGE_SZ); self.file .read_exact_at(buf, blkno as u64 * PAGE_SZ as u64) .await } /// Read a block. /// /// Returns a "lease" object that can be used to /// access to the contents of the page. (For the page cache, the /// lease object represents a lock on the buffer.) pub async fn read_blk( &self, blknum: u32, ctx: &RequestContext, ) -> Result<BlockLease, std::io::Error> { let cache = page_cache::get(); match cache .read_immutable_buf(self.file_id, blknum, ctx) .await .map_err(|e| { std::io::Error::new( std::io::ErrorKind::Other, format!("Failed to read immutable buf: {e:#}"), ) })? { ReadBufResult::Found(guard) => Ok(guard.into()), ReadBufResult::NotFound(mut write_guard) => { // Read the page from disk into the buffer self.fill_buffer(write_guard.deref_mut(), blknum).await?; Ok(write_guard.mark_valid().into()) } } } } impl BlockReader for FileBlockReader { fn block_cursor(&self) -> BlockCursor<'_> { BlockCursor::new(BlockReaderRef::FileBlockReader(self)) } } /// /// Trait for block-oriented output /// pub trait BlockWriter { /// /// Write a page to the underlying storage. /// /// 'buf' must be of size PAGE_SZ. Returns the block number the page was /// written to. /// fn write_blk(&mut self, buf: Bytes) -> Result<u32, std::io::Error>; } /// /// A simple in-memory buffer of blocks. /// pub struct BlockBuf { pub blocks: Vec<Bytes>, } impl BlockWriter for BlockBuf { fn write_blk(&mut self, buf: Bytes) -> Result<u32, std::io::Error> { assert!(buf.len() == PAGE_SZ); let blknum = self.blocks.len(); self.blocks.push(buf); Ok(blknum as u32) } } impl BlockBuf { pub fn new() -> Self { BlockBuf { blocks: Vec::new() } } pub fn size(&self) -> u64 { (self.blocks.len() * PAGE_SZ) as u64 } } impl Default for BlockBuf { fn default() -> Self { Self::new() } }
--- layout: post title: Aggregates in Vue Grid component | Syncfusion description: Learn here all about Aggregates in Syncfusion Vue Grid component of Syncfusion Essential JS 2 and more. control: Aggregates platform: ej2-vue documentation: ug domainurl: ##DomainURL## --- # Aggregates in Vue Grid component Aggregate values are displayed in the footer, group footer and group caption of Grid. It can be configured through `e-aggregates` directive. The [`field`](https://ej2.syncfusion.com/vue/documentation/api/grid/aggregateColumn/#field) and [`type`](https://ej2.syncfusion.com/vue/documentation/api/grid/aggregateColumn/#type) are the minimum properties required to represent an aggregate column. To use aggregate feature, you need to inject the `Aggregate` module into the `provide` section. By default, the aggregate value can be displayed in footer, group and caption cells, to show the aggregate value in any of these cells, use the [`footerTemplate`](https://ej2.syncfusion.com/vue/documentation/api/grid/aggregateColumn/#footertemplate),[`groupFooterTemplate`](https://ej2.syncfusion.com/vue/documentation/api/grid/aggregateColumn/#groupfootertemplate) and [`groupCaptionTemplate`](https://ej2.syncfusion.com/vue/documentation/api/grid/aggregateColumn/#groupcaptiontemplate) properties. To get start quickly with Aggregate Options, you can check on this video: {% youtube "https://www.youtube.com/watch?v=SGpR92dMHnw" %} ## Built-in aggregate types Aggregate type must be specified in [`type`](https://ej2.syncfusion.com/vue/documentation/api/grid/aggregateColumn/#type) property to configure an aggregate column. The built-in aggregates are, * Sum * Average * Min * Max * Count * TrueCount * FalseCount > * Multiple aggregates can be used for an aggregate column by setting the [`type`](https://ej2.syncfusion.com/vue/documentation/api/grid/aggregateColumn/#type) property with an array of aggregate type. > * Multiple types for a column is supported only when one of the aggregate templates is used.
class External::LessonsController < ExternalController before_action :set_event, only: %i[ index show ] before_action :get_ticket, only: %i[ form ] before_action :get_lesson, only: [ :show ] before_action :get_video_embedder, only: %i[ index show ] def index @lessons = @event.lessons @lessons_checker = [] @lessons.each_with_index do |lesson, index| @lessons_checker[index] = Access::Checker.call(lesson) end @video_embedder = Lessons::Embedder end def show @purchase = Access::Checker.call(@event, :purchase_date) @lesson_checker = Access::Checker.call(@lesson) end def search; end def form if @ticket.save @lesson = Lesson.find(params[:lesson_id]) redirect_to quiz_path(@lesson.event.slug, @lesson) else redirect_to lesson_validate_path(params["slug_event"]), notice: I18n.t('lesson.form.unable_record') end end private def set_event @event = Event.find_by(slug: params[:slug_event]) end def get_ticket if session[:student_phone].present? @ticket = Ticket.joins(:event, :student) .where(events: { slug: params["slug_event"] }, students: { phone: session[:student_phone] }).take else store_student_phone get_ticket end end def store_student_phone session[:student_phone] = params["phone"] end def get_lesson @lesson = Lesson.find(params[:lesson_id]) end def get_video_embedder @video_embedder = Lessons::Embedder end end
import { PIECES } from "../constants"; import { Piece, PieceKeys } from "../types/piece"; export const setRandomPiece = (excludeKey: PieceKeys = "o") => { // Step 1: Get keys as an array const keysArray: PieceKeys[] = Object.keys(PIECES).filter( (key) => key !== excludeKey ) as PieceKeys[]; // Step 2: Generate a random index const randomIndex = Math.floor(Math.random() * keysArray.length); // Step 3: Use the random index to get a random key const newKey = keysArray[randomIndex]; const newPiece = PIECES[newKey]; // Step 4: Generate a random index from array const randomArrayIndex = Math.floor(Math.random() * newPiece.shape.length); // Step 2: Use the random index to get a random element const randomShape = newPiece.shape[randomArrayIndex]; const piece: Piece = { key: newKey, shape: randomShape, rotation: randomArrayIndex, position: { y: 0, x: 6 }, color: newPiece.color, }; return piece; };
interface DBUserProps { image?: string, githubUsername: string, name: string, summary?: string, githubLink?: string, linkeldn?: string } interface ThemeProps { handleTheme: () => void, theme: SetThemeProps setTheme: React.Dispatch<React.SetStateAction<SetThemeProps>> } interface SetThemeProps { checked: boolean, themeSelected: string } interface PaginationProps { users: DBUserProps[], setUsers: React.Dispatch<React.SetStateAction<DBUserProps[]>>, totalPages: number, currentPage: number, setCurrentPage: React.Dispatch<React.SetStateAction<number>>, handleChange: (event: React.ChangeEvent<unknown>, value: number) => void } export type { DBUserProps, ThemeProps, SetThemeProps, PaginationProps }
import { Body, ConsoleLogger, Controller, Delete, Get, HttpStatus, Param, Post, Put, Res, UploadedFile, UseInterceptors } from '@nestjs/common'; import { ApplicationService } from './application.service'; import { Application } from '../schemas/application.schema'; import { FileInterceptor } from '@nestjs/platform-express'; import { UpdateApplicationDto } from './dto/UpdateApplication.dto'; import { Response } from 'express'; import * as pdf from 'html-pdf'; import { CvData } from '../schemas/cvdata.schema'; @Controller('application') export class ApplicationController { constructor(private readonly applicationservice:ApplicationService){} private readonly logger = new ConsoleLogger(ApplicationController.name); // @Post() // async applyForJob(@Body() applicationData: Application): Promise<Application> { // return this.applicationservice.applyForJob(applicationData); // } @Get() async findAll(): Promise<Application[]> { return this.applicationservice.findAll(); } @Post() @UseInterceptors(FileInterceptor('cv')) async applyForJob(@UploadedFile() file: Express.Multer.File, @Body() applicationData: Application): Promise<Application> { return this.applicationservice.applyForJob(applicationData, file); } @Post('upload') // Le chemin de l'endpoint @UseInterceptors(FileInterceptor('file')) // 'file' est le nom du champ dans FormData async uploadFile(@UploadedFile() file) { console.log(file); // Traitez le fichier téléchargé ici } @Post('/delete-all') async deleteAllCandidates(): Promise<string> { await this.applicationservice.deleteAllCandidates(); return 'All candidates deleted successfully'; } @Delete(':id') async deleteCandidate(@Param('id') id: string): Promise<void> { await this.applicationservice.deleteCandidate(id); } // @Put(':id') // async updateCandidate(@Param('id') id: string, @Body() updateCandidateDto: UpdateApplicationDto) { // return this.applicationservice.updateCandidate(id, updateCandidateDto); // } @Put(':id') updateApplication(@Param('id') id: string, @Body() UpdateApplicationDto: UpdateApplicationDto): Promise<Application> { return this.applicationservice.updateCandidate(id, UpdateApplicationDto); } // @Get('download') // async downloadSheet(): Promise<string> { // try { // const csvContent = await this.applicationservice.downloadSheet(); // return csvContent; // } catch (error) { // // Gérer les erreurs ici // console.error('Error downloading sheet:', error); // throw error; // } // } @Get('download') async downloadExcel(@Res() res: Response): Promise<void> { try { const filePath = await this.applicationservice.exportResponsesToExcel(); res.download(filePath, 'optiflow.xlsx', (err) => { if (err) { console.error('Error downloading file:', err); res.status(500).send('Internal Server Error'); } else { console.log('File downloaded successfully'); } }); } catch (error) { console.error('Error:', error); res.status(500).send('Internal Server Error'); } } @Post('generate') async generateCv(@Body() cvData: CvData, @Res() res): Promise<void> { try { const htmlContent = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CV</title> <style> body { font-family: Arial, sans-serif; background-color: #f4f4f4; color: #333; margin: 0; padding: 20px; } .container { max-width: 800px; margin: auto; background: #fff; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); display: flex; /* Utilisation de flexbox pour aligner les sections */ } .contact-info { width: 30%; /* Les coordonnées occupent 30% */ border-right: 1px solid #ccc; /* Ajout d'une bordure pour séparer */ padding-right: 20px; /* Espacement pour les coordonnées */ margin-right: 20px; /* Espacement entre les sections */ } } .contact-info h3 { margin-top: 0; /* Suppression de la marge pour le titre */ } .content { flex: 1; /* L'expérience et les compétences occupent le reste */ } .education, .skills, .profile { margin-top: 20px; /* Espacement entre les sections */ } h1 { text-align: center; color: #333; margin-top: 0; /* Suppression de la marge supérieure par défaut */ } p { margin-bottom: 10px; } .education h3, .skills h3 { margin-bottom: 10px; } .skills ul { list-style-type: none; padding-left: 0; } .skills li { margin-bottom: 5px; } </style> </head> <body> <h1>CV</h1> <div style="margin-bottom: 20px;"></div> <!-- Espace --> <div class="container"> <div class="contact-info"> <h3>Coordonnées</h3> <p>Téléphone: ${cvData.phone1}</p> <p>Adresse: ${cvData.Adresse}</p> <p>Email: ${cvData.email}</p> </div> <div class="content"> <div class="profile"> <h3>Profile</h3> <ul> ${cvData.profile} </ul> </div> <hr> <div class="education"> <h3>Éducation</h3> <ul> ${cvData.educations.split(',').map(education=> `<li>${education.trim()}</li>`).join('')} </ul> </div> <hr> <div class="skills"> <h3>Compétences</h3> <ul> ${cvData.competences.split(',').map(competence => `<li>${competence.trim()}</li>`).join('')} </ul> </div> </div> </div> </body> </html> `; pdf.create(htmlContent).toStream((err, stream) => { if (err) { console.error('Error generating PDF:', err); return res.status(HttpStatus.INTERNAL_SERVER_ERROR).send('Error generatingPDF');} res.setHeader('Content-Type', 'application/pdf'); res.setHeader('Content-Disposition', 'attachment;filename="cv.pdf"'); stream.pipe(res); }); } catch (error) { console.error('Error generating PDF:', error); res.status(HttpStatus.INTERNAL_SERVER_ERROR).send('Errorgenerating PDF'); } } }
package com.a6raywa1cher.rescheduletsuspring.components.importers.tsutimetable; import com.a6raywa1cher.rescheduletsuspring.components.importers.AbstractExternalModelsImporter; import com.a6raywa1cher.rescheduletsuspring.components.importers.ImportException; import com.a6raywa1cher.rescheduletsuspring.components.importers.LessonCellSynchronizationService; import com.a6raywa1cher.rescheduletsuspring.components.importers.enhancer.LessonCellEnhancerService; import com.a6raywa1cher.rescheduletsuspring.components.importers.loader.DataLoader; import com.a6raywa1cher.rescheduletsuspring.components.importers.tsutimetable.models.group.GroupScheduleDto; import com.a6raywa1cher.rescheduletsuspring.components.importers.tsutimetable.models.group.LessonDto; import com.a6raywa1cher.rescheduletsuspring.components.importers.tsutimetable.models.group.LessonTimeDto; import com.a6raywa1cher.rescheduletsuspring.components.importers.tsutimetable.models.selectors.SelectorGroupDto; import com.a6raywa1cher.rescheduletsuspring.components.importers.tsutimetable.models.selectors.SelectorGroupLevel; import com.a6raywa1cher.rescheduletsuspring.components.importers.tsutimetable.models.selectors.SelectorHolderDto; import com.a6raywa1cher.rescheduletsuspring.models.LessonCell; import com.a6raywa1cher.rescheduletsuspring.models.submodels.LessonCellCoordinates; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import one.util.streamex.EntryStream; import one.util.streamex.StreamEx; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.stereotype.Service; import java.io.IOException; import java.time.Clock; import java.time.LocalDate; import java.util.*; import java.util.stream.Collectors; @Service @ConditionalOnExpression("${app.tsudb.enabled:true} && '${app.tsudb.remote-type:timetable}' == 'timetable'") @AllArgsConstructor @Slf4j public class TsuTimetableExternalModelsImporter extends AbstractExternalModelsImporter { private final ObjectMapper objectMapper = new ObjectMapper() .registerModule(new Jdk8Module()) .registerModule(new JavaTimeModule()) .enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE); private final LessonCellSynchronizationService lessonCellSynchronizationService; private final LessonCellEnhancerService lessonCellEnhancerService; private final DataLoader dataLoader; private final List<LessonCellTimetableMapper> lessonCellTimetableMappers; private final Clock clock; @Override public void internalImportExternalModels(boolean overrideCache) throws ImportException { log.info("Starting import"); prepareDataLoader(overrideCache); log.info("Importer have finished preparing data loader"); List<SelectorGroupDto> groups = queryAllGroups(overrideCache); log.info("Found {} groups", groups.size()); List<SelectorGroupDto> filterGroups = filterGroups(groups); log.info("Filtered {} groups", filterGroups.size()); Map<SelectorGroupDto, List<GroupScheduleDto>> schedules = queryGroupSchedules(filterGroups, overrideCache); log.info("Found {} schedules", schedules.size()); Map<SelectorGroupDto, List<GroupScheduleDto>> filteredSchedules = filterSchedules(schedules); log.info("Filtered {} schedules", filteredSchedules.size()); List<LessonCell> lessonCells = mapSchedules(filteredSchedules); log.info("Extracted {} lesson cells", lessonCells.size()); List<LessonCell> enhancedLessonCells = lessonCellEnhancerService.enhance(lessonCells); log.info("Enhanced {} lesson cells", enhancedLessonCells.size()); rebuildDatabase(enhancedLessonCells); log.info("Import finished"); } private void prepareDataLoader(boolean overrideCache) throws ImportException { if (overrideCache) { try { dataLoader.dropCache(); } catch (IOException e) { throw new ImportException("Drop cache error", e); } } } private List<SelectorGroupDto> queryAllGroups(boolean overrideCache) throws ImportException { try { SelectorHolderDto selectorHolderDto = objectMapper.readValue(dataLoader.load("selectors", overrideCache), SelectorHolderDto.class); return selectorHolderDto.getGroups(); } catch (IOException e) { throw new ImportException("Group load error", e); } } private List<SelectorGroupDto> filterGroups(List<SelectorGroupDto> selectorGroups) { return selectorGroups.stream() .filter(group -> group.getLevelId() != null && !SelectorGroupLevel.UNKNOWN.equals(group.getLevelId())) .filter(group -> group.getStudyYearName().matches("\\d+")) .filter(group -> Boolean.FALSE.equals(group.getShortStudy())) .filter(group -> Boolean.FALSE.equals(group.getIndividualPlan())) .collect(Collectors.toList()); } private Map<SelectorGroupDto, List<GroupScheduleDto>> queryGroupSchedules( List<SelectorGroupDto> selectorGroupDtos, boolean overrideCache ) throws ImportException { Map<SelectorGroupDto, List<GroupScheduleDto>> output = new HashMap<>(); for (SelectorGroupDto selectorGroupDto : selectorGroupDtos) { try { String path = "group?type=classes&group=" + selectorGroupDto.getGroupId(); String rawData = dataLoader.load(path, overrideCache); if (rawData.contains("Расписание на найдено")) { log.info("Group {} ({}) schedule is absent", selectorGroupDto.getGroupId(), selectorGroupDto.getGroupName()); continue; } List<GroupScheduleDto> groupScheduleDtos = objectMapper.readValue( rawData, objectMapper.getTypeFactory().constructCollectionType(List.class, GroupScheduleDto.class) ); output.put(selectorGroupDto, groupScheduleDtos); } catch (IOException e) { throw new ImportException( String.format( "Group %d (%s) schedule load error", selectorGroupDto.getGroupId(), selectorGroupDto.getGroupName() ), e ); } } return output; } private Map<SelectorGroupDto, List<GroupScheduleDto>> filterSchedules( Map<SelectorGroupDto, List<GroupScheduleDto>> schedules ) { LocalDate now = LocalDate.now(clock); return EntryStream.of(schedules) .mapValues(dtos -> StreamEx.of(dtos) .filter(dto -> dto.getStart().isBefore(now) && now.isBefore(dto.getFinish())) .toList() ) .toImmutableMap(); } private List<LessonCell> mapSchedules( Map<SelectorGroupDto, List<GroupScheduleDto>> schedules ) throws ImportException { List<LessonCell> output = new ArrayList<>(); for (var entry : schedules.entrySet()) { SelectorGroupDto selectorGroupDto = entry.getKey(); List<GroupScheduleDto> groupScheduleDtos = entry.getValue(); for (GroupScheduleDto groupScheduleDto : groupScheduleDtos) { for (LessonDto lessonDto : groupScheduleDto.getLessons()) { for (String professor : lessonDto.getProfessors()) { LessonTimeDto lessonTimeDto = groupScheduleDto.getLessonTimeData().get(lessonDto.getLessonNumber()); LessonCell lessonCell = LessonCell.builder() .ignoreExternalDb(false) .build(); LessonCellTimetableMapperContext ctx = new LessonCellTimetableMapperContext( groupScheduleDto, lessonDto, lessonTimeDto, selectorGroupDto, professor ); for (LessonCellTimetableMapper mapper : lessonCellTimetableMappers) { mapper.map(ctx, lessonCell); } lessonCell.setExternalId(LessonCellCoordinates.convert(lessonCell).toIdentifier()); output.add(lessonCell); } } } } return output; } protected void rebuildDatabase(List<LessonCell> preparedCells) throws ImportException { try { lessonCellSynchronizationService.rebuildDatabase(Set.copyOf(preparedCells)); } catch (Exception e) { throw new ImportException(e.getMessage(), e); } } @Override public boolean isBusy() { return super.isBusy() || lessonCellSynchronizationService.isUpdatingLocalDatabase(); } }
/* Copyright (©) 2003-2023 Teus Benschop. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <config/libraries.h> #ifdef HAVE_GTEST #include "gtest/gtest.h" #include <unittests/utilities.h> #include <database/state.h> #include <database/bibles.h> #include <search/logic.h> using namespace std; void test_search_setup () { string standardUSFM1 = "\\c 1\n" "\\p\n" "\\v 1 Text of the first verse.\n" "\\v 2 \\add Text of the second \\add*verse.\n" "\\s Heading\n" "\\p\n" "\\v 3 Text of the 3rd third verse.\n" "\\v 4 Text of the 4th \\add fourth\\add* verse.\n" "\\v 5 Text of the 5th fifth verse is this: Verse five ✆.\n" "\\v 6 Text of the 6th sixth verse ✆.\n" "\\v 7 Text of the seventh verse with some UTF-8 characters: ✆ ❼ ሯ.\n" "\\v 8 Verse eight ✆ ❼ ሯ.\n" "\\v 9 Verse nine nine.\n" "\\v 10 خدا بود و کلمه کلمه خدا بود. در ابتدا کلمه بود و کلمه نزد.\n"; string standardUSFM2 = "\\c 1\n" "\\p\n" "\\v 3 And he said.\n"; string standardUSFM3 = "\\c 3 \n" "\\s1 Manusia pertama berdosa karena tidak mentaati Allah.\n" "\\p\n" "\\v 1 Ular adalah binatang yang paling licik diantara semua binatang buas yang ALLAH ciptajkan. Ular bertanya kepada perempuan itu, “Apakah benar Allah berkata kepada kalian, ‘Jangan memakan satu buah pun dari semua pohon yang ada di taman ini?’ ’’\n" "\\v 2-3 Perempuan itu menjawab, “ALLAH melarang kami menyentuh apa lagi memakan buah yang berada di tengah-tengah taman. Bila kami melanggar larangannya, maka kami akan mati! Tetapi untuk semua buah yang lain kami boleh memakannya.”\n" "\\v 4,5 Ular berkata kepada perempuan itu,”Tentu saja kamu tidak akan mati. ALLAH mengatakan hal itu karena tahu kalau kamu makan buah dari pohon yang berada di tengah taman itu, kamu akan memahami sesuatu yang baru yaitu mata dan pikiranmu akan terbuka dan kamu akan menjadi sama seperti Allah. Kamu akan mengetahui apa yang baik yang boleh dilakukan dan yang jahat, yang tidak boleh dilakukan.\n" "\\v 6 Perempuan itu melihat bahwa pohon itu menghasilkan buah yang sangat indah dan enak untuk dimakan. Maka dia menginginkannya karena mengira, akan menjadi perempuan yang bijaksana. Lalu, dipetiklah beberapa buah dan dimakannya. Kemudian, dia memberikan beberapa buah juga kepada suaminya dan suaminya juga memakannya.\n"; Database_State::create (); Database_Bibles database_bibles; database_bibles.create_bible ("phpunit"); database_bibles.store_chapter ("phpunit", 2, 3, standardUSFM1); database_bibles.create_bible ("phpunit2"); database_bibles.store_chapter ("phpunit2", 4, 5, standardUSFM2); database_bibles.create_bible ("phpunit3"); database_bibles.store_chapter ("phpunit3", 6, 7, standardUSFM3); } TEST (search, logic) { // Test updating search fields. { refresh_sandbox (false); test_search_setup (); search_logic_index_chapter ("phpunit", 2, 3); } // Test searching and getting Bible passage { refresh_sandbox (true); test_search_setup (); vector <Passage> passages = search_logic_search_text ("sixth", {"phpunit"}); EXPECT_EQ (1, static_cast <int> (passages.size())); if (!passages.empty ()) { EXPECT_EQ ("phpunit", passages[0].m_bible); EXPECT_EQ (2, passages[0].m_book); EXPECT_EQ (3, passages[0].m_chapter); EXPECT_EQ ("6", passages[0].m_verse); } } // Search in combined verses. { refresh_sandbox (true); test_search_setup (); vector <Passage> passages = search_logic_search_text ("ALLAH", {"phpunit3"}); EXPECT_EQ (4, static_cast <int> (passages.size())); if (passages.size () == 4) { EXPECT_EQ ("phpunit3", passages[0].m_bible); EXPECT_EQ (6, passages[1].m_book); EXPECT_EQ (7, passages[2].m_chapter); EXPECT_EQ ("0", passages[0].m_verse); EXPECT_EQ ("1", passages[1].m_verse); EXPECT_EQ ("2", passages[2].m_verse); EXPECT_EQ ("4", passages[3].m_verse); } } // Test search Bible { refresh_sandbox (true); test_search_setup (); vector <Passage> passages = search_logic_search_bible_text ("phpunit", "sixth"); EXPECT_EQ (1, static_cast<int>(passages.size ())); passages = search_logic_search_bible_text ("phpunit2", "sixth"); EXPECT_EQ (0, static_cast<int>(passages.size ())); passages = search_logic_search_bible_text ("phpunit2", "said"); EXPECT_EQ (1, static_cast<int>(passages.size ())); } // Test search Bible case sensitive. { refresh_sandbox (true); test_search_setup (); vector <Passage> passages = search_logic_search_bible_text_case_sensitive ("phpunit", "Verse"); EXPECT_EQ (3, static_cast<int>(passages.size ())); passages = search_logic_search_bible_text_case_sensitive ("phpunit", "sixth"); EXPECT_EQ (1, static_cast<int>(passages.size ())); passages = search_logic_search_bible_text_case_sensitive ("phpunit2", "said"); EXPECT_EQ (1, static_cast<int>(passages.size ())); } // Searching in USFM. { refresh_sandbox (true); test_search_setup (); vector <Passage> passages = search_logic_search_bible_usfm ("phpunit", "\\Add"); EXPECT_EQ (2, static_cast<int>(passages.size ())); } // Searching in USFM case-sensitive. { refresh_sandbox (true); test_search_setup (); vector <Passage> passages = search_logic_search_bible_usfm_case_sensitive ("phpunit", "\\Add"); EXPECT_EQ (0, static_cast<int>(passages.size ())); passages = search_logic_search_bible_usfm_case_sensitive ("phpunit", "\\add"); EXPECT_EQ (2, static_cast<int>(passages.size ())); } // Test getting Bible verse text. { refresh_sandbox (true); test_search_setup (); // Plain. string text = search_logic_get_bible_verse_text ("phpunit", 2, 3, 5); EXPECT_EQ ("Text of the 5th fifth verse is this: Verse five ✆.", text); // USFM. text = search_logic_get_bible_verse_usfm ("phpunit", 2, 3, 5); EXPECT_EQ ("\\v 5 Text of the 5th fifth verse is this: Verse five ✆.", text); } // Test deleting a bible or book or chapter. { refresh_sandbox (true); test_search_setup (); vector <Passage> passages = search_logic_search_bible_text ("phpunit", "e"); EXPECT_EQ (10, static_cast <int> (passages.size())); search_logic_delete_bible ("phpunit"); passages = search_logic_search_bible_text ("phpunit", "e"); EXPECT_EQ (0, static_cast <int> (passages.size())); test_search_setup (); search_logic_delete_book ("phpunit", 3); passages = search_logic_search_bible_text ("phpunit", "e"); EXPECT_EQ (10, static_cast <int> (passages.size())); search_logic_delete_book ("phpunit", 2); passages = search_logic_search_bible_text ("phpunit", "e"); EXPECT_EQ (0, static_cast <int> (passages.size())); test_search_setup (); search_logic_delete_chapter ("phpunit", 3, 3); passages = search_logic_search_bible_text ("phpunit", "e"); EXPECT_EQ (10, static_cast <int> (passages.size())); search_logic_delete_chapter ("phpunit", 2, 3); passages = search_logic_search_bible_text ("phpunit", "e"); EXPECT_EQ (0, static_cast <int> (passages.size())); } // Test total verse count in Bible. { refresh_sandbox (true); test_search_setup (); int count = search_logic_get_verse_count ("phpunit"); EXPECT_EQ (11, count); } } #endif
import React from 'react' import { Container } from './styles' import { motion } from 'framer-motion' const Results = ({ query, results }: Result) => { return ( <motion.div initial="collapsed" animate="open" exit="collapsed" variants={{ open: { opacity: 1, height: "auto" }, collapsed: { opacity: 0, height: 0 } }} transition={{ duration: 0.8, ease: [0.04, 0.62, 0.23, 0.98] }} > <Container> <span>Resultados para <b>{query}</b></span> <div className="results"> {results?.map(country => ( <div className="result"> <div className="name">{country.name}</div> <div className="tag"> População <b>{country.population.toLocaleString('pt-BR')}</b> </div> </div> ))} </div> </Container> </motion.div> ) } interface Result { query: string, results: [ { name: string, population: number } ] | undefined } export default Results
use websocket::ClientBuilder; use websocket::OwnedMessage; use clap::{ArgAction, Parser}; // •✖ #[derive(Parser)] struct Cli { #[arg( short = 'p', long = "port", default_value = "8080", help = "Server port" )] port: u16, #[arg(short = 'D', long = "debug", help = "Enable debug mode", action = ArgAction::SetTrue)] debug: bool, } fn main() { let args = Cli::parse(); let client = ClientBuilder::new(&(String::from("ws://127.0.0.1:") + &args.port.to_string())) .unwrap() .add_protocol("rust-websocket") .connect_insecure() .unwrap(); println!("Connected to server"); let (mut receiver, _sender) = client.split().unwrap(); for message in receiver.incoming_messages() { if let OwnedMessage::Binary(mut data) = message.unwrap() { // Clear the screen print!("\x1B[2J\x1B[1;1H"); if args.debug { println!("{:?}", data); } let width = data.remove(0); let height = data.remove(0); let size = width as usize * height as usize; let bytes = data .iter() .flat_map(|byte| { (0..8) .map(|i| (byte & (1 << i) != 0) as u8) .collect::<Vec<u8>>() }) .collect::<Vec<u8>>(); for row in bytes[0..size].chunks(width as usize) { for &cell in row { print!("{}", if cell == 1 { "✖ " } else { "• " }); } println!(); } } } }
--- title: no_registry 匯入屬性 ms.date: 08/29/2019 f1_keywords: - no_registry helpviewer_keywords: - no_registry attribute ms.assetid: d30de4e2-551c-428c-98fd-951330d578d3 ms.openlocfilehash: 7c81cc2f570cb9ac4e977dac6d55cb69e491d3b2 ms.sourcegitcommit: 6e1c1822e7bcf3d2ef23eb8fac6465f88743facf ms.translationtype: MT ms.contentlocale: zh-TW ms.lasthandoff: 09/03/2019 ms.locfileid: "70220718" --- # <a name="no_registry-import-attribute"></a>no_registry 匯入屬性 **no_registry**會告知編譯器不要搜尋使用`#import`匯入之類型程式庫的登錄。 ## <a name="syntax"></a>語法 > **#import***類型-程式庫***no_registry** ### <a name="parameters"></a>參數 *類型-程式庫*\ 類型程式庫。 ## <a name="remarks"></a>備註 如果在 include 目錄中找不到參考的類型程式庫, 即使類型程式庫位於登錄中, 編譯也會失敗。 **no_registry**會傳播至以隱含方式匯入`auto_search`的其他類型程式庫。 編譯器永遠不會在登錄中搜尋檔案名所指定的類型程式庫, 而且會直接`#import`傳遞到。 當`auto_search`指定時, 會使用`#import`初始`#import`的**no_registry**設定來產生額外的指示詞。 如果`#import` **no_registry 初始**指示詞, `#import`則產生的也會是 no_registry `auto_search`。 如果您想要匯入交叉參考的類型程式庫, **no_registry**會很有用。 它會讓編譯器不會在登錄中尋找較舊版本的檔案。 如果類型程式庫未註冊, **no_registry**也很有用。 ## <a name="see-also"></a>另請參閱 [#import 屬性](../preprocessor/hash-import-attributes-cpp.md)\ [#import 指示詞](../preprocessor/hash-import-directive-cpp.md)
import { jwtDecode } from "jwt-decode"; class AuthService { async login(email, password) { try { const response = await fetch("http://localhost:5267/api/user/login", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ email, password }), }); if (!response.ok) { const errorText = await response.text(); throw new Error(errorText); } const data = await response.json(); if (!data.token) { throw new Error("No token found in response"); } localStorage.setItem("token", data.token); return data; } catch (error) { throw new Error(error.message || "An error occurred during login."); } } async register(username, email, password) { try { const response = await fetch("http://localhost:5267/api/user/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ username, email, password }), }); const data = await response.json(); if (response.ok) { return await this.login(email, password); } else { throw new Error(data.message || "Registration failed"); } } catch (error) { throw new Error( error.message || "An error occurred during registration." ); } } logout() { localStorage.removeItem("token"); } getToken() { return localStorage.getItem("token"); } isLoggedIn() { return !!localStorage.getItem("token"); } getUserId() { const token = localStorage.getItem("token"); if (!token) { throw new Error("JWT token is missing."); } try { const decodedToken = jwtDecode(token); const userId = decodedToken.nameid; return userId; } catch (error) { throw new Error("Failed to decode JWT token."); } } } const authService = new AuthService(); export default authService;
class ThresholdsController < ApplicationController before_action :set_threshold, only: [:show, :edit, :update, :destroy] # GET /thresholds # GET /thresholds.json def index @thresholds = Threshold.all end # GET /thresholds/1 # GET /thresholds/1.json def show end # GET /thresholds/new def new @threshold = Threshold.new end # GET /thresholds/1/edit def edit end # POST /thresholds # POST /thresholds.json def create @threshold = Threshold.new(threshold_params) respond_to do |format| if @threshold.save format.html { redirect_to thresholds_path, notice: 'Threshold was successfully created.' } format.json { render :show, status: :created, location: @threshold } else format.html { render :new } format.json { render json: @threshold.errors, status: :unprocessable_entity } end end end # PATCH/PUT /thresholds/1 # PATCH/PUT /thresholds/1.json def update respond_to do |format| if @threshold.update(threshold_params) format.html { redirect_to thresholds_path, notice: 'Threshold was successfully updated.' } format.json { render :show, status: :ok, location: @threshold } else format.html { render :edit } format.json { render json: @threshold.errors, status: :unprocessable_entity } end end end # DELETE /thresholds/1 # DELETE /thresholds/1.json def destroy @threshold.destroy respond_to do |format| format.html { redirect_to thresholds_url, notice: 'Threshold was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_threshold @threshold = Threshold.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def threshold_params params.require(:threshold).permit(:sensor_id, :comparing_string, :comparing_value, :status, :action) end end
// 实现 add(1)(2)(3) => 6 function add(x) { return function (y) { if (typeof y === "undefined") { return x; } else { return add(x + y); } }; } function add(x) { // let args = [].slice.call(arguments) // console.log(args) return function (y) { if (typeof y === "undefined") { return x; } else { return add(x + y); } }; } console.log(add(1)(2)); // 柯理化封装 function curry(fn) { console.log(fn.length, "fn"); return function curried() { let args = Array.prototype.slice.call(arguments), context = this; return args.length >= fn.length ? fn.apply(context, args) : function () { let rest = [].slice.call(arguments); return curried.apply(context, args.concat(rest)); }; }; } function add(a, b, c) { return a + b + c; } const curryAdd = curry(add); console.log(curryAdd(1)(2, 3)); // newAdd(1,2,3)(10) //16 // newAdd(1)(2)(3,4)(5) //15 function newAdd() { console.log(newAdd.length, "length"); var args = Array.prototype.slice.call(arguments); console.log(args, "arg"); return function () { var sub_arg = Array.prototype.slice.call(arguments); console.log(sub_arg, "sub_arg"); if (sub_arg.length) { return newAdd.call(null, args.concat(sub_arg)); } else { const sum = args.reduce((a, b) => { return a + b; }); console.log(sum, "sum"); return sum; } }; // fn.valueOf = function () { // return args.reduce((a, b) => { // return a + b; // }); // }; // return fn; } console.log(newAdd(1, 2, 3)(10)); function add() { var args = Array.prototype.slice.call(arguments); var fn = function () { var sub_arg = Array.prototype.slice.call(arguments); // 把全部的参数聚集到参数的入口为一个参数: args.concat(sub_arg) return add.apply(null, args.concat(sub_arg)); }; fn.valueOf = function () { return args.reduce(function (a, b) { return a + b; }); }; return fn; } console.log(add(1, 2, 3)(10));
import type { Metadata } from "next"; import { Poppins } from "next/font/google"; import "./globals.css"; import Navbar from "./components/nav/Navbar"; import Footer from "./components/footer/Footer"; import CartProvider from "@/providers/CartProvider"; import { Toaster } from "react-hot-toast"; import { getCurrentUser } from "@/actions/getCurrentUser"; const poppins = Poppins({ subsets: ["latin"], weight: ["400", "700"] }); export const metadata: Metadata = { title: "EtronKart", description: "Generated by create next app", }; export default async function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body className={`${poppins.className} text-slate-700`}> <Toaster toastOptions={{ style: { background: "rgb(51 65 85)", color: "#fff", }, }} /> <CartProvider> <div className="flex flex-col min-h-screen"> <Navbar /> <main className="flex-grow">{children}</main> <Footer /> </div> </CartProvider> </body> </html> ); }
# 1.1.1 Disable unused filesystems A number of uncommon filesystem types are supported under Linux. Removing support for unneeded filesystem types reduces the local attack surface of the system. If a filesystem type is not needed it should be disabled. Native Linux file systems are designed to ensure that built-in security controls function as expected. Non-native filesystems can lead to unexpected consequences to both the security and functionality of the system and should be used with caution. Many filesystems are created for niche use cases and are not maintained and supported as the operating systems are updated and patched. Users of non-native filesystems should ensure that there is attention and ongoing support for them, especially in light of frequent operating system changes ### 1.1.1.1 Ensure mounting of cramfs filesystems is disabled #### Description: The cramfs filesystem type is a compressed read-only Linux filesystem embedded in small footprint systems. A cramfs image can be used without having to first decompressthe image. #### Rationale: Removing support for unneeded filesystem types reduces the local attack surface of the system. If this filesystem type is not needed, disable it. ### 1.1.1.2 Ensure mounting of freevxfs filesystems is disabled #### Description: The freevxfs filesystem type is a free version of the Veritas type filesystem. This is the primary filesystem type for HP-UX operating systems. #### Rationale: Removing support for unneeded filesystem types reduces the local attack surface of the system. If this filesystem type is not needed, disable it. ### 1.1.1.3 Ensure mounting of jffs2 filesystems is disabled #### Description: The jffs2 (journaling flash filesystem 2) filesystem type is a log-structured filesystem used in flash memory devices. #### Rationale: Removing support for unneeded filesystem types reduces the local attack surface of the system. If this filesystem type is not needed, disable it. ### 1.1.1.4 Ensure mounting of hfs filesystems is disabled #### Description: The hfs filesystem type is a hierarchical filesystem that allows you to mount Mac OS filesystems. #### Rationale: Removing support for unneeded filesystem types reduces the local attack surface of the system. If this filesystem type is not needed, disable it. ### 1.1.1.5 Ensure mounting of hfsplus filesystems is disabled #### Description: The hfsplus filesystem type is a hierarchical filesystem designed to replace hfs that allows you to mount Mac OS filesystems. #### Rationale: Removing support for unneeded filesystem types reduces the local attack surface of the system. If this filesystem type is not needed, disable it. ### 1.1.1.6 Ensure mounting of squashfs filesystems is disabled #### Description: The squashfs filesystem type is a compressed read-only Linux filesystem embedded in small footprint systems. A squashfs image can be used without having to first decompress the image. #### Rationale: Removing support for unneeded filesystem types reduces the local attack surface of the system. If this filesystem type is not needed, disable it. #### Impact: As Snap packages utilizes squashfs as a compressed filesystem, disabling squashfs will cause Snap packages to fail. Snap application packages of software are self-contained and work across a range of Linux distributions. This is unlike traditional Linux package management approaches, like APT or RPM, which require specifically adapted packages per Linux distribution on an application update and delay therefore application deployment from developers to their software's end-user. Snaps themselves have no dependency on any external store ("App store"), can be obtained from any source and can be therefore used for upstream software deployment. ### 1.1.1.7 Ensure mounting of udf filesystems is disabled #### Description: The udf filesystem type is the universal disk format used to implement ISO/IEC 13346 and ECMA-167 specifications. This is an open vendor filesystem type for data storage on a broad range of media. This filesystem type is necessary to support writing DVDs and newer optical disc formats. #### Rationale: Removing support for unneeded filesystem types reduces the local attack surface of the system. If this filesystem type is not needed, disable it.
--- title: '项目总体' --- ### 开发平台首页 - 开发平台首页,显示前十个帖子 - 生成实体类对应discuss_post表,并将其对应dao层完成 - 分页查询,若需查某一个id的评论,则userId动态加入sql - 查询所有评论数,若需查某一个id的所有评论数,则加入动态sql - 开发分页组件,分页显示所有帖子 ### 开发平台登录模块 #### 发送邮件 - 邮箱设置 - 启用客户端SMTP服务 - 功能开发 - 导入jar包 - 邮箱参数配置 - 使用JavaMailSender发送邮件 - 模板引擎 - 使用 Thymeleaf 发送HTML邮件 #### 开发注册功能 - 访问注册页面,Controller 层定义 `getRegisterPage` 方法,返回登录页面 register.html - 导入 commons lang 包 - 在 application.properties 文件中配置网站域名,便于后面激活邮件中的激活地址能访问服务器 - 在util包中定义一个工具类 CommunityUtil,提供静态方法: - 生成随机字符串:利用Java自带的UUID工具包,其中生成的随机字符串中包含 `"-"`,要将其替换为空字符串 - MD5加密:给密码进行MD5加密,此外,为了更安全,在加密前明文密码中加入盐 `salt`,即 `hello -> hello + 3e4a8`,再进行MD5加密,这一步不在该方法中实现。 - 在 UserService 中定义注册方法,返回的是一个map对象 - 空值处理,包括对象本身,账号,密码等 - 验证账号是否已被注册,邮箱是否被注册 - 生成5位随机字符串作为 `salt` ,加到明文密码中,再进行 md5 加密 - 对用户类型,状态,激活码进行设置,同时随机赋给一个头像 `http://images.nowcoder.com/head/%dt.png`,`%d`属于 1~1000,创建的时间也进行设置 - 在 activation.html 中修改激活邮件模板 - 发送激活邮件:利用 `context` 容器存储注册用户的账号以及存储用户要通过邮箱获取的激活路径,用模板引擎生成格式化的模板,并通过 `mailClient` 发送邮件 - 在 loginController 中定义Post请求的处理方法,传入的是 Model 和 账号,密码,邮箱(可以封装为 User 对象) - 通过 UserService 调用 register 方法,根据返回的 Map 确定要怎么处理请求,若为 `null` 说明注册成功,返回到处理结果页面 operate-result.html。若注册不成功,则返回注册页面,同时要将注册失败的信息存储到model中,以在注册页面中显示。 - 在 register.html 中提交表单需要定义 name 属性,要跟接收类 User 的属性对应。同时,由于该页面也要复用,因此要对注册失败信息判断是否显示。若判断需要显示,则原来输入的账号密码等还要显示。 - 账号激活处理 - 在 util 中定义常量接口,定义一些状态,在这里要定义的是激活的三个结果状态:成功、重复激活、失败。 - 在 UserService 中定义激活方法,如果 userId 对应的激活码对应上的话,就激活。 - 在 loginController 中定义激活请求处理 - 调用激活方法并返回结果,根据结果处理请求。无论激活是否成功,都返回到处理结果页面 operate-result.html,不同的是携带的信息不一样。 - 定义登录页面 #### 生成验证码 - 导入 Kaptcha 的 jar 包 - 编写 Kaptcha 配置类 - Kaptcha 核心是一个实现类 Kaptcha,有一个默认实现类 DefaultKaptcha,其主要利用方法 `setConfig()` 进行配置,而 `setConfig()` 需要一个 `Config` 对象,而 `Config` 对象需要传入 `Properties` 对象 - 进行配置,设置图片长宽高、文字的字体颜色、文字候选、文字长度、采用的噪声类。 - 生成随机字符、生成图片,通过 response 输出流将图片输出出去。 - 在 login.html 中通过 js 动态地改变验证码,即每次刷新都能访问图片。 #### 开发登录、退出功能 - 访问登录页面 - 点击顶部区域内的链接,打开登录页面 - 定义实体类,与 login_ticket 表对应,以及定义它的 mapper , - 登录 - 验证账号、密码、验证码。成功时,生成登录凭证,发放给客户端;失败时,跳转回登录页。 - 在 UserService 中定义登录方法,返回 map 集合,因为处理的结果有多种 - 对空值进行处理 - 验证账号及其状态,确认库中是否有该账号,以及判断该账号的状态是否激活了 - 验证密码,要将传入的明文密码先加密了再与库中的进行比较 - 登录成功,则生成登录凭证 - 在 loginController 中定义登录请求方法 - 检查验证码 - 检查账号密码 - 退出 - 将登录凭证修改为失效状态。 - 跳转至网站首页。 #### 显示登录信息 - 通过设置拦截器来实现 - 从cookie中获取凭证 - 如果凭证不为空则查询凭证,检查凭证是否有效,若有效根据凭证查询用户 - 在请求开始时查询登录用户 - 在本次请求中持有用户数据 - 在模板视图上显示用户数据 - 在请求结束时清理用户数据 #### 账号设置 - 上传文件 - 请求:必须是POST请求 - 表单:enctype="multipart/form-data" - spring MVC:通过 MultipartFile 处理上传文件 - 开发步骤: - 访问账号设置页面 - 上传头像 - 获取头像 #### 检查登录状态 - 使用拦截器 - 在方法前标注自定义注解 - 拦截所有请求,只处理带有该注解的方法 - 自定义注解(通过元注解定义) - 常用的元注解: `@Target`、`@Retention`、`@Document`、`@Inherited` - 如何读取注解:`Method.getDeclaredAnnotations()`、`Method.getAnnotation(Class<T> annotationClass)` ### 平台核心模块 #### 过滤敏感词 - 前缀树 - 名称:Trie、字典树、查找树 - 特点:查找效率高,消耗内存大 - 应用:字符串检索、词频统计、字符串排序等 - 敏感词过滤器 - 定义前缀树 - 根据敏感词,初始化前缀树 - 编写过滤敏感词的方法 #### 发布帖子 - AJAX - Asynchronous JavaScript and XML - 异步的JavaScript与XML,不是一门新技术,只是一个新的术语 - 使用AJAX,网页能够将增量更新呈现在页面上,而不需要刷新整个页面 - 虽然X代表XML,但目前JSON的使用比XML更加普遍 - 采用AJAX请求,实现发布帖子的功能 #### 帖子详情 - DiscussPostMapper - DiscussPostService - DiscussPostController - index.html - 在帖子标题上增加访问详情页面的链接 - discuss-detail.html - 处理静态资源的访问路径 - 复用index.html的header区域 - 显示标题、作者、发布时间、帖子正文等内容 #### 显示评论 - 数据层 - 根据实体查询一页评论数据 - 根据实体查询评论的数量 - 业务层 - 处理查询评论的业务 - 处理查询评论数量的业务 - 表现层 - 显示帖子详情数据时,同时显示该帖子所有的评论数据 #### 添加评论 - 数据层 - 增加评论数据 - 修改帖子的评论数量 - 业务层 - 处理添加评论的业务 - 先增加评论,再更新帖子的评论数量 - 表现层 - 处理添加评论数据的请求 - 设置添加评论的表单 #### 私信列表 - 私信列表 - 查询当前用户的会话列表 - 每个会话只显示一条最新的私信 - 支持分页显示 - 私信详情 - 查询某个会话所包含的私信 - 支持分页显示 #### 发送私信 - 发送私信 - 采用异步的方式发送私信 - 发送成功后输信私信列表 - 设置已读 - 访问私信详情时,将显示的私信设置为已读状态 #### 统一处理异常 - @ControllerAdvice - 用于修饰类,表示该类是Controller的全局配置类。 - 在此类中,可以对Controller进行如下三种全局配置:异常处理方案、绑定数据方案、绑定参数方案。 - @ExceptionHandler - 用于修饰方法,该方法会在Controller出现异常后被调用,用于处理捕获到的异常。 - @ModelAttribute - 用于修饰方法,该方法会在Controller方法执行前被调用,用于为Model对象绑定参数。 - @DataBinder - 用于修饰方法,该方法会在Controller方法执行前被调用,用于绑定参数的转换器。 #### 统一记录日志 - AOP的概念 - Aspect Oriented Programing,即面向方面(切面)编程 - AOP是一种编程思想,是对OOP的补充,可以进一步提高编程的效率。 - AOP的实现 - AspectJ - AspectJ是语言级的实现,它扩展了Java语言,定义了AOP语法。 - AspectJ在编译期织入代码,它有一个专门的编译器,用来生成遵守Java字节码规范的class文件。 - Spring AOP - Spring AOP使用纯Java实现,它不需要专门的编译过程,也不需要特殊的类装载器。 - Spring AOP在运行时通过代理的方式织入代码,只支持方法类型的连接点 - Spring支持对AspectJ的集成。 - Spring AOP - JDK动态代理 - Java提供的动态代理技术,可以在运行时创建接口的代理实例。 - Spring AOP默认采用此种方式,在接口的代理实例中织入代码。 - CGLib动态代理 - 采用底层的字节码技术,在运行时创建子类代理实例。 - 当目标对象不存在接口时,Spring AOP会采用此种方式,在子类实例中织入代码 ### Redis,一站式高性能存储方案 #### 点赞 - 点赞 - 支持对帖子、评论点赞,赞帖子同时会给帖子的主人点赞 - 第1次点赞,第2次取消点赞 - 首页点赞数量 - 统计帖子的点赞数量 - 详情页点赞数量 - 统计点赞数量 - 显示点赞状态 #### 我收到的赞 - 重构点赞功能 - 以用户为key,记录点赞数量 - increment(key),decrement(key) - 开发个人主页 - 以用户为key,查询点赞数量 #### 关注、取消关注 - 需求 - 开发关注、取消关注功能 - 统计用户的关注数、粉丝数 - 关键 - 若A关注了B,则A是B的Follower(粉丝),B是A的Followee(关注目标) - 关注的目标可以是用户、帖子、题目等,在实现时将这些目标抽象为实体 #### 关注列表、粉丝列表 - 业务层 - 查询某个用户关注的人,支持分页 - 查询某个用户的粉丝,支持分页 - 表现层 - 处理“查询关注的人”、“查询粉丝”请求 - 编写“查询关注的人”、“查询粉丝”模板 #### 优化登录模块 - 使用Redis存储验证码 - 验证码需要频繁的访问与刷新,对性能要求较高 - 验证码不需永久保存,通常在很短的时间后就会失效 - 分布式部署时,存在Session共享的问题 - 使用Redis存储登录凭证 - 处理每次请求时,都要查询用户的登录凭证,访问的频率非常高 - 使用Redis缓存用户信息 - 处理每次请求时,都要根据凭证查询用户信息,访问的频率非常高 ### Kafka,构建TB级异步消息系统 #### 发送系统通知 - 触发事件 - 评论后,发布通知 - 点赞后,发布通知 - 关注后,发布通知 - 处理事件 - 封装事件对象 - 开发事件的生产者 - 开发事件的消费者 - 业务逻辑 - 当点赞评论关注后,后台封装成一个事件向某一个用户发送消息(Producer),在点赞评论关注时调用该功能,还得传入对应的帖子id, - 当消费者(Consumer)接收到消息后,将事件存储到Message表中,而被点赞用户登录后则能接收到系统通知,即查询到Message表中的数据 #### 显示系统通知 - 通知列表 - 显示评论、点赞、关注三种类型的通知 - 通知详情 - 分页显示某一类主题所包含的通知 - 未读消息 - 在页面头部显示所有的未读消息数量 ### 开发平台搜索功能 - 将Elasticsearch和实体类之间建立联系,在实体类中加入注解 - 搜索服务 - 将帖子保存至 Elasticsearch 服务器 - 从 Elasticsearch 服务器删除帖子 - 从 Elasticsearch 服务器搜索帖子 - 发布事件 - 发布帖子时,将帖子异步的提交到 Elasticsearch 服务器 - 增加评论时,将帖子异步的提交到 Elasticsearch 服务器 - 在消费组件中增加一个方法,消费帖子发布事件 - 显示结果 - 在控制器中处理搜索请求,在HTML上显示搜索结果 ### 项目优化 #### 权限控制 - 登录检查 - 之前采用拦截器实现了登录检查,这是简单的权限管理方案,现在将其废弃 - 授权配置 - 对当前系统内包含的所有的请求,分配访问权限(普通用户、版主、管理员) - 认证方案 - 绕过Security认证流程,采用系统原来的认证方案 - CSRF配置 - 防止CSRF攻击的基本原理,以及表单、AJAX相关的配置 #### 置顶、加精、删除 - 功能实现 - 点击置顶,修改帖子的类型 - 点击 “加精”、“删除”, 修改帖子的状态。 - 权限管理 - 版主可以执行“置顶”、“加精”操作 - 管理员可以执行“删除”操作 - 按钮显示 - 版主可以看到“置顶”、“加精”按钮 - 管理员可以看到“删除”按钮 #### 网站数据统计 - UV (Unique Visitor) - 独立访客,需通过用户IP排重统计数据 - 每次访问都要进行统计 - HyperLogLog,性能好,且存储空间小 - DAU (Daily Active User) - 日活跃用户,需通过用户ID排重统计数据 - 访问过一次,则认为其活跃 - Bitmap,性能好、且可以统计精确的结果 ### 任务执行和调度 在浏览器发给服务器的请求中间会经过 Nginx ,来实现负载均衡 - JDK 线程池(**面试重点**) - 普通线程池:ExecutorService - 可执行定时任务的线程池:ScheduledExecutorService - Spring 线程池(**面试重点**)(不在分布式环境下的话推荐使用spring提供的) - Spring普通线程池:ThreadPoolTaskExecutor,有简化使用方式:注解方式:@Async - Spring可执行定时任务的线程池:ThreadPoolTaskScheduler(没有解决分布式情况下冲突的问题),也有简化使用方式:注解:@Scheduled - 分布式定时任务 - Spring Quartz:需要在数据库里存入一些信息(一些表) - 核心组件:Scheduler接口(需要定义任务)、Job接口(定义一个任务)、JobDetail接口(用来配置Job)、Trigger接口(用来配置Job什么时候运行,以什么样频率执行任务) - 配置完后程序启动时Quartz会读取配置信息,存到数据库里(需配置properties文件,数据库里的表:`qrtz_job_details、qrtz_simple_trigger、qrtz_triggers、qrtz_scheduler_state、qrtz_locks`),后面Quartz就直接读取数据库来执行任务,不需要重新配置 ### 热帖排行 - 计算公式:log(精华分 + 评论数\*10 + 点赞数\*2 + 收藏数\*2) + (发布时间 - 牛客纪元) - 因为没有收藏功能,所以可以忽略收藏数这个因素 - 采用定时任务来实现,只处理分数变化的帖子,将分数变化的帖子存储到集合里,不用处理所有帖子 - 用Redis作为缓存存储分数变化的帖子,将帖子存储到set里 ### 生成长图 - wkhtmltopdf:命令行的方式 - wkhtmltopdf url file:模板内容生成pdf - wkhtmltoimage url file:网页生成本地图片 - java - Runtime.getRuntime().exec() ### 将文件上传至云服务器 - 客户端上传 - 客户端将数据提交给云服务器,并等待其响应 - 用户上传头像时,将表单数据提交给云服务器 - 服务器直传 - 应用服务器将数据直接提交给云服务器,并等待其响应 - 分享时,服务端将自动生成的图片,直接提交给云服务器 ### 优化网站的性能 - 本地缓存 - 将数据缓存在应用服务器上,性能最好 - 常用缓存工具:Ehcache、Guava、Caffeine等 - 分布式缓存 - 将数据缓存在 NoSQL 数据库上,跨服务器 - 常用缓存工具:MemCache、Redis等 - 多级缓存 - \> 一级缓存(本地缓存) \> 二级缓存(分布式缓存) \> DB - 避免缓存雪崩(缓存失效,大量请求直达DB),提高系统的可用性 - Caffeine - 核心接口:Cache, LoadingCache, AsyncLoadingCache
import { Component, Host, Prop, h, Element , State } from '@stencil/core'; import { Breakpoints } from '../../utils/breakpoints'; import { mediaQueryListenerManager } from '../../utils/media-query-listener-manager' import { StyleManager } from '../../utils/style-manager'; import { StyleDefinition } from '../../utils/style-util'; // Define a type for responsive props export type ResponsiveProp<T> = T | { [key in keyof typeof Breakpoints]?: T }; export type FlexDirection = 'row' | 'row-reverse' | 'column' | 'column-reverse' | ''; export type FlexWrap = 'nowrap' | 'wrap' | 'wrap-reverse' | ''; const RESPONSIVE_PROPS: string[] = ['fxyDirection', 'fxyWrap', 'fxyGap', 'fxyAlign', 'fxyFill']; @Component({ tag: 'fxy-container', shadow: true, }) export class FlexyContainer { private mediaQueryManager = mediaQueryListenerManager; //new MediaQueryListenerManager(Breakpoints); private styleManager = StyleManager; @State() isMobile: boolean = false; @Element() private el: HTMLElement; /** * If `true`, the container will fill its parent's height and width. */ @Prop() fxyFill: boolean; /** * If `true`, the container will fill its parent's height and width on extra small devices. */ @Prop() fxyFillXs: boolean; /** * If `true`, the container will fill its parent's height and width on small devices. */ @Prop() fxyFillSm: boolean; /** * If `true`, the container will fill its parent's height and width on medium devices. */ @Prop() fxyFillMd: boolean; /** * If `true`, the container will fill its parent's height and width on large devices. */ @Prop() fxyFillLg: boolean; /** * If `true`, the container will fill its parent's height and width on extra large devices. */ @Prop() fxyFillXl: boolean; /** * Sets the `place-content` value for aligning content within the container. * Accepts a combination of `justify-content` and `align-content` values. * Example: "center space-around". */ @Prop() fxyAlign: string = "flex-start stretch"; /** * Sets the `place-content` value for aligning content within the containerfor extra-small devices */ @Prop() fxyAlignXs: string = ""; /** * Sets the `place-content` value for aligning content within the containerfor small devices */ @Prop() fxyAlignSm: string = ""; /** * Sets the `place-content` value for aligning content within the containerfor medium devices */ @Prop() fxyAlignMd: string = ""; /** * Sets the `place-content` value for aligning content within the containerfor large devices */ @Prop() fxyAlignLg: string = ""; /** * Sets the `place-content` value for aligning content within the containerfor extra large devices */ @Prop() fxyAlignXl: string = ""; /** * Sets the flex-direction of the container. * Can be "row", "row-reverse", "column", or "column-reverse". */ @Prop() fxyDirection: ResponsiveProp<FlexDirection> = 'row'; /** * Flex direction for extra-small devices. * Accepts 'row', 'row-reverse', 'column', 'column-reverse'. */ @Prop() fxyDirectionXs: FlexDirection = ''; /** * Flex direction for small devices. * Accepts 'row', 'row-reverse', 'column', 'column-reverse'. */ @Prop() fxyDirectionSm: FlexDirection = ''; /** * Flex direction for medium devices. * Accepts 'row', 'row-reverse', 'column', 'column-reverse'. */ @Prop() fxyDirectionMd: FlexDirection = ''; /** * Flex direction for large devices. * Accepts 'row', 'row-reverse', 'column', 'column-reverse'. */ @Prop() fxyDirectionLg: FlexDirection = ''; /** * Flex direction for extra-large devices. * Accepts 'row', 'row-reverse', 'column', 'column-reverse'. */ @Prop() fxyDirectionXl: FlexDirection = ''; /** * Sets spacing between immediate child elements (`fxy-item`). * The value is applied as a right margin to all children except the last one. */ @Prop({mutable: true}) fxyGap: string = '0px'; /** * Sets spacing between immediate child elements (`fxy-item`) for extra small devices.. */ @Prop() fxyGapXs: string = ''; /** * Sets spacing between immediate child elements (`fxy-item`) for small devices.. */ @Prop() fxyGapSm: string = ''; /** * Sets spacing between immediate child elements (`fxy-item`) for medium devices.. */ @Prop() fxyGapMd: string = ''; /** * Sets spacing between immediate child elements (`fxy-item`) for large devices.. */ @Prop() fxyGapLg: string = ''; /** * Sets spacing between immediate child elements (`fxy-item`) for extra large devices.. */ @Prop() fxyGapXl: string = ''; /** * Sets the flex-wrap property of the container. */ @Prop() fxyWrap: FlexWrap = 'nowrap'; /** * Sets the flex-wrap property of the container for extra small devices.. * Can be "nowrap", "wrap", or "wrap-reverse". */ @Prop() fxyWrapXs: FlexWrap = ''; /** * Sets the flex-wrap property of the container for small devices.. * Can be "nowrap", "wrap", or "wrap-reverse". */ @Prop() fxyWrapSm: FlexWrap = ''; /** * Sets the flex-wrap property of the container for medium devices.. * Can be "nowrap", "wrap", or "wrap-reverse". */ @Prop() fxyWrapMd: FlexWrap = ''; /** * Sets the flex-wrap property of the container for large devices.. * Can be "nowrap", "wrap", or "wrap-reverse". */ @Prop() fxyWrapLg: FlexWrap = ''; /** * Sets the flex-wrap property of the container for extra large devices.. * Can be "nowrap", "wrap", or "wrap-reverse". */ @Prop() fxyWrapXl: FlexWrap = ''; /** * Applies the `fxyGap` value as a margin-right to all child `fxy-item` elements except the last one. */ private applyGapToItems() { if (this.fxyGap) { const items = Array.from(this.el.children).filter(child => child.tagName.toLowerCase() === 'fxy-item'); items.forEach((item: HTMLElement, index) => { if (index < items.length - 1) { // Apply to all except the last if(this.fxyDirection === 'row') { item.style.marginRight = this.fxyGap; item.style.marginBottom = ''; } else { item.style.marginRight = ''; item.style.marginBottom = this.fxyGap ? this.fxyGap : ' '; } } }); } } componentWillLoad() { let results = this.styleManager.identifyBreakpointValues(RESPONSIVE_PROPS, this.el); if(Object.keys(results).length) { this.mediaQueryManager.mediaQueryChanges.subscribe((event: MediaQueryListEvent) => { this.styleManager.applyStyles(this.el, event); }); } } /** * Parses the `fxyAlign` property value to set the `place-content` CSS property. * Replaces "none" with default values for `justify-content` and `align-content`. */ private parseFxyAlign(): StyleDefinition { const css = {}; const [mainAxis, crossAxis] = this.fxyAlign.split(' '); // Main axis switch (mainAxis) { case 'center': css['justify-content'] = 'center'; break; case 'space-around': css['justify-content'] = 'space-around'; break; case 'space-between': css['justify-content'] = 'space-between'; break; case 'space-evenly': css['justify-content'] = 'space-evenly'; break; case 'end': case 'flex-end': css['justify-content'] = 'flex-end'; break; case 'start': case 'flex-start': default : css['justify-content'] = 'flex-start'; // default main axis break; } // Cross-axis switch (crossAxis) { case 'start': case 'flex-start': css['align-items'] = css['align-content'] = 'flex-start'; break; case 'center': css['align-items'] = css['align-content'] = 'center'; break; case 'end': case 'flex-end': css['align-items'] = css['align-content'] = 'flex-end'; break; case 'space-between': css['align-content'] = 'space-between'; css['align-items'] = 'stretch'; break; case 'space-around': css['align-content'] = 'space-around'; css['align-items'] = 'stretch'; break; case 'baseline': css['align-content'] = 'stretch'; css['align-items'] = 'baseline'; break; case 'stretch': default : // 'stretch' css['align-items'] = css['align-content'] = 'stretch'; // default cross axis break; } return css; } buildFxyFillStyles(): StyleDefinition { if (this.fxyFill) { return { height: '100%', minHeight: '100%', width: '100%', minWidth: '100%', }; } return { height: '', minHeight: '', width: '', minWidth: '' }; } buildStyles() { const placeContent = this.parseFxyAlign(); const fillStyles = this.buildFxyFillStyles() as any; return { 'display': 'flex', 'flex-direction': this.fxyDirection, 'flex-wrap': this.fxyWrap, 'box-sizing': 'border-box', ...fillStyles, ...placeContent, }; } componentWillRender() { this.applyGapToItems(); } disconnectedCallback() { this.mediaQueryManager.removeListeners(); } render() { const style = this.buildStyles() return ( <Host style={style}> <slot></slot> </Host> ); } }
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://thymeleaf.or"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Listagem de sócios</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css"> </head> <body class="bg-light" > <div class="container"> <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Quem somos</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-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 me-auto mb-2 mb-lg-0"> <li class="nav-item"><a class="nav-link active" aria-current="page" th:href="@{/}">Home</a></li> <li class="nav-item"><a class="nav-link" th:href="@{/socios}">Sócios</a> </li> <li class="nav-item"><a class="nav-link" th:href="@{/dependentes}">Dependentes</a> </li> </ul> <span class="navbar-text">SisGen</span> </div> </div> </nav> <h2 class="mb-4 mt-4 ms-4"> Lista de sócios </h2> <table class="table table-striped table-hover ms-4"> <tr> <th>Id</th> <th>Nome</th> <th>Ativo</th> <th>Renda</th> <th> </th> </tr> <tr th:each="socios : ${socios}"> <td th:text="${socios.id}"></td> <td th:text="${socios.nome}"></td> <td th:text="${socios.ativo}"></td> <td th:text="${socios.renda}"></td> <td> <a th:href="@{/socios/{id}/edit(id=${socios.id})}"> <i class="bi bi-pencil"></i> </a> <a th:href="@{/socios/{id}/delete(id=${socios.id})}"> <i class="bi bi-trash3-fill"></i> </a> </td> </tr> </table> </div> </body> </html>
package com.example.calcease; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private TextView display; private String currentInput = ""; private double firstOperand = 0; private String operator = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); display = findViewById(R.id.display); // Set click listeners for number buttons (1-9) for (int i = 1; i <= 9; i++) { int resID = getResources().getIdentifier("button" + i, "id", getPackageName()); Button button = findViewById(resID); setNumberButtonClickListener(button, String.valueOf(i)); } // Set click listeners for operator buttons (+, -, *, /) Button plusButton = findViewById(R.id.buttonPlus); setOperatorButtonClickListener(plusButton, "+"); Button minusButton = findViewById(R.id.buttonMinus); setOperatorButtonClickListener(minusButton, "-"); Button multiplyButton = findViewById(R.id.buttonMultiply); setOperatorButtonClickListener(multiplyButton, "*"); Button divideButton = findViewById(R.id.buttonDivide); setOperatorButtonClickListener(divideButton, "/"); // Set click listener for the equals button Button equalsButton = findViewById(R.id.buttonEquals); equalsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!currentInput.isEmpty()) { double secondOperand = Double.parseDouble(currentInput); double result = performOperation(firstOperand, secondOperand, operator); currentInput = String.valueOf(result); updateDisplay(); } } }); // Set click listener for the clear button Button clearButton = findViewById(R.id.buttonClear); clearButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currentInput = ""; firstOperand = 0; operator = ""; updateDisplay(); } }); } private void setNumberButtonClickListener(Button button, final String number) { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currentInput += number; updateDisplay(); } }); } private void setOperatorButtonClickListener(Button button, final String op) { button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!currentInput.isEmpty()) { firstOperand = Double.parseDouble(currentInput); operator = op; currentInput = ""; } } }); } private void updateDisplay() { display.setText(currentInput); } private double performOperation(double firstOperand, double secondOperand, String operator) { double result = 0; switch (operator) { case "+": result = firstOperand + secondOperand; break; case "-": result = firstOperand - secondOperand; break; case "*": result = firstOperand * secondOperand; break; case "/": if (secondOperand != 0) { result = firstOperand / secondOperand; } else { currentInput = "Error"; updateDisplay(); } break; } return result; } }
#!/usr/bin/env Rscript library("ggplot2") solicitudes <- c(30,30,30,50,50,50,100,100,100) concurrencia <- c("25%","50%","75%","25%","50%","75%","25%","50%","75%") tiempo <- c(8.823,7.552,6.827,10.215,12.506,13.959,26.966,22.850,24.473) solicitudes.factor <- factor(solicitudes) concurrencia.factor <- factor(concurrencia) as.numeric(solicitudes.factor) as.character(concurrencia.factor) datos <- data.frame(solicitudes.factor, concurrencia.factor, tiempo) ggplot(data = datos, aes(x = concurrencia.factor, y = tiempo, fill = solicitudes.factor)) + geom_bar(stat = "identity", position = position_dodge(), colour = "black") + coord_cartesian(ylim=c(0, 30)) + scale_y_continuous(breaks=seq(0, 30, 2.5)) + scale_fill_discrete(name="Número de\nsolicitudes") + xlab("Nivel de concurrencia") + ylab("Segundos") + ggtitle("Tiempo de ejecución") + theme(plot.title=element_text(face="bold", size=20), axis.title=element_text(size=14)) ggsave("gra_te.png")
@extends('layouts.app') @section('content') <div class="container py-5"> <div class="row justify-content-center"> <div class="col-md-8 col-lg-6"> <div class="py-2 border-bottom border-secondary mb-4"> <h2 class="fw-bold text-center fs-1">Iniciar sesión</h2> </div> </div> </div> <div class="row justify-content-center"> <div class="col-md-8 col-lg-6"> <form action="{{ route('login') }}" method="POST"> @csrf @if(session('mensaje')) <div class="text-danger d-flex align-items-center gap-2 py-2" role="alert"> <i class="bi bi-exclamation-circle"></i> <div>{{session('mensaje')}}</div> </div> @endif <div class="mb-3"> <label for="email" class="form-label fw-bold">Email</label> <input id="email" name="email" type="text" placeholder="Tu email" class="form-control @error('email') border-danger @enderror" value="{{old('email')}}"> @error('email') <div class="text-danger d-flex align-items-center gap-2 py-2" role="alert"> <i class="bi bi-exclamation-circle"></i> <div>{{$message}}</div> </div> @enderror </div> <div class="mb-3"> <label for="password" class="form-label fw-bold">Contraseña</label> <input id="password" name="password" type="password" placeholder="Tu contraseña" class="form-control @error('password') border-danger @enderror"> @error('password') <div class="text-danger d-flex align-items-center gap-2 py-2" role="alert"> <i class="bi bi-exclamation-circle"></i> <div>{{$message}}</div> </div> @enderror </div> <div> <input type="checkbox" name="remember"><label class="ms-2">Mantener mi sesión abierta</label> </div> <div class="text-center"> <input type="submit" value="Iniciar sesión" class="btn btn-dark btn-outline-light my-3"> </div> </form> </div> </div> </div> @endsection
// Copyright 2022 ByteDance and/or its affiliates. // // 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. #include <atomic> #include <cstring> #include <string> #include <utility> #include "absl/strings/str_cat.h" #include "monolith/native_training/runtime/ops/embedding_hash_table_tf_bridge.h" #include "monolith/native_training/runtime/ops/file_utils.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/kernels/ops_util.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/io/record_reader.h" #include "tensorflow/core/platform/threadpool.h" namespace tensorflow { namespace monolith_tf { namespace { // Carries the data through async process. // It will ref and unref |p_hash_table|. struct AsyncPack { AsyncPack(OpKernelContext* p_ctx, EmbeddingHashTableTfBridge* p_hash_table, std::string p_basename, std::function<void()> p_done, int p_thread_num) : ctx(p_ctx), basename(std::move(p_basename)), record_count(0), hash_table(p_hash_table), done(std::move(p_done)), thread_num(p_thread_num), finish_num(0), status(thread_num) { hash_table->Ref(); } ~AsyncPack() { hash_table->Unref(); } OpKernelContext* ctx; std::string basename; std::atomic_long record_count; EmbeddingHashTableTfBridge* hash_table; std::function<void()> done; const int thread_num; std::atomic_int finish_num; std::vector<Status> status; }; } // namespace class HashTableRestoreOp : public AsyncOpKernel { public: explicit HashTableRestoreOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {} void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override { EmbeddingHashTableTfBridge* hash_table = nullptr; OP_REQUIRES_OK_ASYNC( ctx, LookupResource(ctx, HandleFromInput(ctx, 0), &hash_table), done); core::ScopedUnref unref(hash_table); const Tensor& basename_tensor = ctx->input(1); const std::string basename = basename_tensor.scalar<tstring>()(); std::vector<std::string> files; OP_REQUIRES_OK_ASYNC( ctx, ctx->env()->GetMatchingPaths(absl::StrCat(basename, "-*"), &files), done); FileSpec file_spec; OP_REQUIRES_OK_ASYNC(ctx, ValidateShardedFiles(basename, files, &file_spec), done); OP_REQUIRES_ASYNC(ctx, file_spec.nshards() > 0, errors::NotFound("Unable to find the dump files for: ", name(), " in ", basename), done); ctx->set_output(0, ctx->input(0)); hash_table->Clear(); int nshards = files.size(); auto pack = new AsyncPack(ctx, hash_table, basename, std::move(done), nshards); for (int i = 0; i < nshards; ++i) { ctx->device()->tensorflow_cpu_worker_threads()->workers->Schedule( [this, pack, i, nshards] { WorkerThread({i, nshards}, pack); }); } } private: void WorkerThread(EmbeddingHashTableTfBridge::DumpShard shard, AsyncPack* p) { p->status[shard.idx] = RestoreOneShard(shard, p); if (p->finish_num.fetch_add(1) == p->thread_num - 1) { auto summary = p->hash_table->Summary(); auto basename = tensorflow::io::Basename(p->basename); LOG(INFO) << absl::StrFormat( "Hash table: %s, summary: %s, restore read %ld records, skip %ld " "zero embeddings", basename, summary, p->record_count, p->record_count - p->hash_table->Size()); Cleanup(p); } } Status RestoreOneShard(EmbeddingHashTableTfBridge::DumpShard shard, AsyncPack* p) { std::string filename = GetShardedFileName(p->basename, shard.idx, shard.total); std::unique_ptr<RandomAccessFile> f; TF_RETURN_IF_ERROR(p->ctx->env()->NewRandomAccessFile(filename, &f)); io::RecordReaderOptions opts; opts.buffer_size = 10 * 1024 * 1024; io::SequentialRecordReader reader(f.get(), opts); Status restore_status; auto get_fn = [&reader, &restore_status, &p]( EmbeddingHashTableTfBridge::EntryDump* dump, int64_t* max_update_ts) { Status s = GetRecord(&reader, dump); if (TF_PREDICT_FALSE(!s.ok())) { if (!errors::IsOutOfRange(s)) { restore_status = s; } return false; } p->record_count.fetch_add(1); if (!dump->has_last_update_ts_sec()) { dump->set_last_update_ts_sec(0); } *max_update_ts = std::max(dump->last_update_ts_sec(), *max_update_ts); return true; }; TF_RETURN_IF_ERROR(p->hash_table->Restore(p->ctx, shard, get_fn)); TF_RETURN_IF_ERROR(restore_status); return Status::OK(); } static Status GetRecord(io::SequentialRecordReader* reader, EmbeddingHashTableTfBridge::EntryDump* dump) { tstring s; TF_RETURN_IF_ERROR(reader->ReadRecord(&s)); if (!dump->ParseFromArray(s.data(), s.size())) { return errors::FailedPrecondition( "Unable to parse data. Data might be corrupted"); } return Status::OK(); } // Clean up when all shards are done. void Cleanup(AsyncPack* p) { auto done = [p]() { // We want to delete p first and then call done. auto done = std::move(p->done); delete p; done(); }; for (int i = 0; i < p->thread_num; ++i) { OP_REQUIRES_OK_ASYNC(p->ctx, p->status[i], done); } done(); } }; REGISTER_OP("MonolithHashTableRestore") .Input("handle: resource") .Input("basename: string") .Output("output_handle: resource") .SetShapeFn(shape_inference::ScalarShape); REGISTER_KERNEL_BUILDER(Name("MonolithHashTableRestore").Device(DEVICE_CPU), HashTableRestoreOp); } // namespace monolith_tf } // namespace tensorflow
/**************************************************************************** ** ** SPDX-License-Identifier: BSD-2-Clause-Patent ** ** SPDX-FileCopyrightText: Copyright (c) 2023 SoftAtHome ** ** Redistribution and use in source and binary forms, with or without modification, ** are permitted provided that the following conditions are met: ** ** 1. Redistributions of source code must retain the above copyright notice, ** this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright notice, ** this list of conditions and the following disclaimer in the documentation ** and/or other materials provided with the distribution. ** ** Subject to the terms and conditions of this license, each copyright holder ** and contributor hereby grants to those receiving rights under this license ** a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable ** (except for failure to satisfy the conditions of this license) patent license ** to make, have made, use, offer to sell, sell, import, and otherwise transfer ** this software, where such license applies only to those patent claims, already ** acquired or hereafter acquired, licensable by such copyright holder or contributor ** that are necessarily infringed by: ** ** (a) their Contribution(s) (the licensed copyrights of copyright holders and ** non-copyrightable additions of contributors, in source or binary form) alone; ** or ** ** (b) combination of their Contribution(s) with the work of authorship to which ** such Contribution(s) was added by such copyright holder or contributor, if, ** at the time the Contribution is added, such addition causes such combination ** to be necessarily infringed. The patent license shall not apply to any other ** combinations which include the Contribution. ** ** Except as expressly stated above, no rights or licenses from any copyright ** holder or contributor is granted under this license, whether expressly, by ** implication, estoppel or otherwise. ** ** DISCLAIMER ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ** ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE ** LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE ** USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ****************************************************************************/ #if !defined(__AMXS_SYNC_OBJECT_H__) #define __AMXS_SYNC_OBJECT_H__ #ifdef __cplusplus extern "C" { #endif #include <amxs/amxs_types.h> /** @file @brief Ambiorix Object Synchronization API header file */ /** @ingroup amxs_sync @defgroup amxs_sync_object Object synchronization API */ /** @ingroup amxs_sync_object @brief Synchronization object constructor function Allocates memory for a new synchronization object and initializes this object. Use @ref amxs_sync_object_delete to remove the synchronization object and free all allocated memory. @param object Pointer to a synchronization object pointer. The address of the new allocated synchronization object is stored in this pointer. @param object_a Name of the object in object A @param object_b Name of the object in object B @param attributes Bitwise OR of zero or more of the following attributes: - @ref AMXS_SYNC_DEFAULT - @ref AMXS_SYNC_ONLY_B_TO_A - @ref AMXS_SYNC_ONLY_A_TO_B - @ref AMXS_SYNC_INIT_B @param translation_cb Callback function to translate data coming from an object event. The output data of this function will be passed to the action callback function if this function executes succesfully. If this argument is NULL, the data from the event will be passed directly to the action callback function. @param action_cb Callback function to act on an object event. @param priv Pointer to user data which will be passed to the translation and action callbacks. @return amxs_status_ok when the synchronization object is created, or another status code when failed to create the synchronization object. */ amxs_status_t amxs_sync_object_new(amxs_sync_object_t** object, const char* object_a, const char* object_b, int attributes, amxs_translation_cb_t translation_cb, amxs_action_cb_t action_cb, void* priv); /** @ingroup amxs_sync_object @brief Synchronization object constructor function Allocates memory for a new synchronization object and initializes this object. Use @ref amxs_sync_object_delete to remove the synchronization object and free all allocated memory. Uses default translation @ref amxs_sync_object_copy_trans_cb and action @ref amxs_sync_object_copy_action_cb callbacks. @param object Pointer to a synchronization object pointer. The address of the new allocated synchronization object is stored in this pointer. @param object_a Name of the object in object A @param object_b Name of the object in object B @param attributes Bitwise OR of zero or more of the following attributes: - @ref AMXS_SYNC_DEFAULT - @ref AMXS_SYNC_ONLY_B_TO_A - @ref AMXS_SYNC_ONLY_A_TO_B - @ref AMXS_SYNC_INIT_B @return amxs_status_ok when the synchronization object is created, or another status code when failed to create the synchronization object. */ amxs_status_t amxs_sync_object_new_copy(amxs_sync_object_t** object, const char* object_a, const char* object_b, int attributes); /** @ingroup amxs_sync_object @brief Synchronization object destructor function Frees all memory allocated for a synchronization object. Also removes the synchronization object from any synchronization object or context it was attached to. All attached synchronization objects and parameters will be freed as well. @param object Pointer to a synchronization object pointer. */ void amxs_sync_object_delete(amxs_sync_object_t** object); /** @ingroup amxs_sync_object @brief Adds a synchronization parameter to a synchronization object. The synchronization parameter can be be created using @ref amxs_sync_param_new. Adding the synchronization parameter fails when: - The parameter was already added to the object. - The parameter attributes are conflicting with those of the object. E.g. The object has the @ref AMXS_SYNC_ONLY_B_TO_A attribute set, and the parameter has @ref AMXS_SYNC_ONLY_A_TO_B set. If the object attributes are more strict than those of the parameter, the parameter attributes will be updated to match those of the object. @param object Pointer to a synchronization object. @param param Pointer to a synchronization parameter. @return - amxs_status_ok: the synchronization parameter is added to the synchronization object - amxs_status_duplicate: another synchronization parameter with the same direction and parameter names already exists for this synchronization object - amxs_status_invalid_attr: the attributes of the synchronization parameter are conflicting with those of the synchronization object - amxs_status_unknown_error: any other error */ amxs_status_t amxs_sync_object_add_param(amxs_sync_object_t* object, amxs_sync_param_t* param); /** @ingroup amxs_sync_object @brief Creates and adds a synchronization parameter to a synchronization object. Allocates memory for a new synchronization parameter and initializes this parameter. Then adds it to the synchronization object. Adding the synchronization parameter fails when: - The parameter was already added to the object. - The parameter attributes are conflicting with those of the object. E.g. The object has the @ref AMXS_SYNC_ONLY_B_TO_A attribute set, and the parameter has @ref AMXS_SYNC_ONLY_A_TO_B set. If the object attributes are more strict than those of the parameter, the parameter attributes will be updated to match those of the object. @param object Pointer to a synchronization object. @param param_a Name of the parameter in object A @param param_b Name of the parameter in object B @param attributes Bitwise OR of zero or more of the following attributes: - @ref AMXS_SYNC_DEFAULT - @ref AMXS_SYNC_ONLY_B_TO_A - @ref AMXS_SYNC_ONLY_A_TO_B - @ref AMXS_SYNC_INIT_B @param translation_cb Callback function to translate data coming from a parameter changed event. The output data of this function will be passed to the action callback function if this function executes succesfully. If this argument is NULL, the data from the event will be passed directly to the action callback function. @param action_cb Callback function to act on a parameter changed event. @param priv Pointer to user data which will be passed to the translation and action callbacks. @return - amxs_status_ok: the synchronization parameter is added to the synchronization object - amxs_status_duplicate: another synchronization parameter with the same direction and parameter names already exists for this synchronization object - amxs_status_invalid_attr: the attributes of the synchronization parameter are conflicting with those of the synchronization object - amxs_status_unknown_error: any other error */ amxs_status_t amxs_sync_object_add_new_param(amxs_sync_object_t* object, const char* param_a, const char* param_b, int attributes, amxs_translation_cb_t translation_cb, amxs_action_cb_t action_cb, void* priv); /** @ingroup amxs_sync_object @brief Creates and adds a synchronization parameter to a synchronization object. Allocates memory for a new synchronization parameter and initializes this parameter. Then adds it to the synchronization object. Adding the synchronization parameter fails when: - The parameter was already added to the object. - The parameter attributes are conflicting with those of the object. E.g. The object has the @ref AMXS_SYNC_ONLY_B_TO_A attribute set, and the parameter has @ref AMXS_SYNC_ONLY_A_TO_B set. If the object attributes are more strict than those of the parameter, the parameter attributes will be updated to match those of the object. Uses default translation @ref amxs_sync_batch_param_copy_trans_cb and action @ref amxs_sync_param_copy_action_cb callbacks. @param object Pointer to a synchronization object. @param param_a Name of the parameter in object A @param param_b Name of the parameter in object B @param attributes Bitwise OR of zero or more of the following attributes: - @ref AMXS_SYNC_DEFAULT - @ref AMXS_SYNC_ONLY_B_TO_A - @ref AMXS_SYNC_ONLY_A_TO_B - @ref AMXS_SYNC_INIT_B @return - amxs_status_ok: the synchronization parameter is added to the synchronization object - amxs_status_duplicate: another synchronization parameter with the same direction and parameter names already exists for this synchronization object - amxs_status_invalid_attr: the attributes of the synchronization parameter are conflicting with those of the synchronization object - amxs_status_unknown_error: any other error */ amxs_status_t amxs_sync_object_add_new_copy_param(amxs_sync_object_t* object, const char* param_a, const char* param_b, int attributes); /** @ingroup amxs_sync_object @brief Adds a synchronization object to a synchronization object. The synchronization object can be be created using @ref amxs_sync_object_new. Adding the synchronization object fails when: - The child object was already added to the parent object. - The child object attributes are conflicting with those of the parent object. E.g. The child object has the @ref AMXS_SYNC_ONLY_B_TO_A attribute set, and the parent object has @ref AMXS_SYNC_ONLY_A_TO_B set. If the parent attributes are more strict than those of the child, the child attributes will be updated to match those of the parent. @param parent Pointer to the parent synchronization object. @param child Pointer to the child synchronization object. @return - amxs_status_ok: the child object is added to the parent object - amxs_status_duplicate: another child object with the same direction and object names already exists for the parent object - amxs_status_invalid_attr: the attributes of the child object are conflicting with those of the parent object - amxs_status_unknown_error: any other error */ amxs_status_t amxs_sync_object_add_object(amxs_sync_object_t* parent, amxs_sync_object_t* child); /** @ingroup amxs_sync_object @brief Creates and adds a synchronization object to a synchronization object. Allocates memory for a new synchronization object and initializes this object. Then adds it to the parent synchronization object. Adding the synchronization object fails when: - The child object was already added to the parent object. - The child object attributes are conflicting with those of the parent object. E.g. The child object has the @ref AMXS_SYNC_ONLY_B_TO_A attribute set, and the parent object has @ref AMXS_SYNC_ONLY_A_TO_B set. If the parent attributes are more strict than those of the child, the child attributes will be updated to match those of the parent. @param parent Pointer to the parent synchronization object. @param object_a Name of the object in object A @param object_b Name of the object in object B @param attributes Bitwise OR of zero or more of the following attributes: - @ref AMXS_SYNC_DEFAULT - @ref AMXS_SYNC_ONLY_B_TO_A - @ref AMXS_SYNC_ONLY_A_TO_B - @ref AMXS_SYNC_INIT_B @param translation_cb Callback function to translate data coming from an object event. The output data of this function will be passed to the action callback function if this function executes succesfully. If this argument is NULL, the data from the event will be passed directly to the action callback function. @param action_cb Callback function to act on an object event. @param priv Pointer to user data which will be passed to the translation and action callbacks. @return - amxs_status_ok: the new child object is added to the parent object - amxs_status_duplicate: another child object with the same direction and object names already exists for the parent object - amxs_status_invalid_attr: the attributes of the child object are conflicting with those of the parent object - amxs_status_unknown_error: any other error */ amxs_status_t amxs_sync_object_add_new_object(amxs_sync_object_t* parent, const char* object_a, const char* object_b, int attributes, amxs_translation_cb_t translation_cb, amxs_action_cb_t action_cb, void* priv); /** @ingroup amxs_sync_object @brief Creates and adds a synchronization object to a synchronization object. Allocates memory for a new synchronization object and initializes this object. Then adds it to the parent synchronization object. Adding the synchronization object fails when: - The child object was already added to the parent object. - The child object attributes are conflicting with those of the parent object. E.g. The child object has the @ref AMXS_SYNC_ONLY_B_TO_A attribute set, and the parent object has @ref AMXS_SYNC_ONLY_A_TO_B set. If the parent attributes are more strict than those of the child, the child attributes will be updated to match those of the parent. Uses default translation @ref amxs_sync_object_copy_trans_cb and action @ref amxs_sync_object_copy_action_cb callbacks. @param parent Pointer to the parent synchronization object. @param object_a Name of the object in object A @param object_b Name of the object in object B @param attributes Bitwise OR of zero or more of the following attributes: - @ref AMXS_SYNC_DEFAULT - @ref AMXS_SYNC_ONLY_B_TO_A - @ref AMXS_SYNC_ONLY_A_TO_B - @ref AMXS_SYNC_INIT_B @return - amxs_status_ok: the new child object is added to the parent object - amxs_status_duplicate: another child object with the same direction and object names already exists for the parent object - amxs_status_invalid_attr: the attributes of the child object are conflicting with those of the parent object - amxs_status_unknown_error: any other error */ amxs_status_t amxs_sync_object_add_new_copy_object(amxs_sync_object_t* parent, const char* object_a, const char* object_b, int attributes); #ifdef __cplusplus } #endif #endif // __AMXS_SYNC_OBJECT_H__
/// <reference path="../../../global.d.ts" /> /** * The window in the game. * * @class * @extends PIXI.Container */ export default class Window extends PIXI.Container { _isWindow: boolean; _windowskin: unknown; _width: number; _height: number; _cursorRect: typeof Rectangle; _openness: unknown; _animationCount: number; _padding: unknown; _margin: unknown; _colorTone: (unknown | number)[]; _innerChildren: []; _container: typeof PIXI.Container; _backSprite: typeof Sprite; _frameSprite: typeof Sprite; _contentsBackSprite: typeof Sprite; _cursorSprite: typeof Sprite; _contentsSprite: typeof Sprite; _downArrowSprite: typeof Sprite; _upArrowSprite: typeof Sprite; _pauseSignSprite: typeof Sprite; _clientArea: typeof Sprite; constructor(...args: any[]); initialize(): void; /** * The image used as a window skin. * * @type Bitmap * @name Window#windowskin */ get windowskin(): any; set windowskin(value: any); /** * The bitmap used for the window contents. * * @type Bitmap * @name Window#contents */ get contents(): any; set contents(value: any); /** * The bitmap used for the window contents background. * * @type Bitmap * @name Window#contentsBack */ get contentsBack(): any; set contentsBack(value: any); /** * The width of the window in pixels. * * @type number * @name Window#width */ get width(): any; set width(value: any); /** * The height of the window in pixels. * * @type number * @name Window#height */ get height(): any; set height(value: any); /** * The size of the padding between the frame and contents. * * @type number * @name Window#padding */ get padding(): any; set padding(value: any); /** * The size of the margin for the window background. * * @type number * @name Window#margin */ get margin(): any; set margin(value: any); /** * The opacity of the window without contents (0 to 255). * * @type number * @name Window#opacity */ get opacity(): any; set opacity(value: any); /** * The opacity of the window background (0 to 255). * * @type number * @name Window#backOpacity */ get backOpacity(): any; set backOpacity(value: any); /** * The opacity of the window contents (0 to 255). * * @type number * @name Window#contentsOpacity */ get contentsOpacity(): any; set contentsOpacity(value: any); /** * The openness of the window (0 to 255). * * @type number * @name Window#openness */ get openness(): any; set openness(value: any); /** * The width of the content area in pixels. * * @readonly * @type number * @name Window#innerWidth */ get innerWidth(): number; /** * The height of the content area in pixels. * * @readonly * @type number * @name Window#innerHeight */ get innerHeight(): number; /** * The rectangle of the content area. * * @readonly * @type Rectangle * @name Window#innerRect */ get innerRect(): import("./Rectangle").default; /** * Destroys the window. */ destroy(): void; /** * Updates the window for each frame. */ update(): void; /** * Sets the x, y, width, and height all at once. * * @param {number} x - The x coordinate of the window. * @param {number} y - The y coordinate of the window. * @param {number} width - The width of the window. * @param {number} height - The height of the window. */ move(x: number, y: number, width: number, height: number): void; /** * Checks whether the window is completely open (openness == 255). * * @returns {boolean} True if the window is open. */ isOpen(): boolean; /** * Checks whether the window is completely closed (openness == 0). * * @returns {boolean} True if the window is closed. */ isClosed(): boolean; /** * Sets the position of the command cursor. * * @param {number} x - The x coordinate of the cursor. * @param {number} y - The y coordinate of the cursor. * @param {number} width - The width of the cursor. * @param {number} height - The height of the cursor. */ setCursorRect(x: number, y: number, width: number, height: number): void; /** * Moves the cursor position by the given amount. * * @param {number} x - The amount of horizontal movement. * @param {number} y - The amount of vertical movement. */ moveCursorBy(x: number, y: number): void; /** * Moves the inner children by the given amount. * * @param {number} x - The amount of horizontal movement. * @param {number} y - The amount of vertical movement. */ moveInnerChildrenBy(x: number, y: number): void; /** * Changes the color of the background. * * @param {number} r - The red value in the range (-255, 255). * @param {number} g - The green value in the range (-255, 255). * @param {number} b - The blue value in the range (-255, 255). */ setTone(r: number, g: number, b: number): void; /** * Adds a child between the background and contents. * * @param {object} child - The child to add. * @returns {object} The child that was added. */ addChildToBack(child: object): PIXI.DisplayObject; /** * Adds a child to the client area. * * @param {object} child - The child to add. * @returns {object} The child that was added. */ addInnerChild(child: object): any; /** * Updates the transform on all children of this container for rendering. */ updateTransform(): void; /** * Draws the window shape into PIXI.Graphics object. Used by WindowLayer. */ drawShape(graphics: any): void; _createAllParts(): void; _createContainer(): void; _createBackSprite(): void; _createFrameSprite(): void; _createClientArea(): void; _createContentsBackSprite(): void; _createCursorSprite(): void; _createContentsSprite(): void; _createArrowSprites(): void; _createPauseSignSprites(): void; _onWindowskinLoad(): void; _refreshAllParts(): void; _refreshBack(): void; _refreshFrame(): void; _refreshCursor(): void; _setRectPartsGeometry(sprite: any, srect: any, drect: any, m: any): void; _refreshArrows(): void; _refreshPauseSign(): void; _updateClientArea(): void; _updateFrame(): void; _updateContentsBack(): void; _updateCursor(): void; _makeCursorAlpha(): number; _updateContents(): void; _updateArrows(): void; _updatePauseSign(): void; _updateFilterArea(): void; }
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # from datetime import datetime import pytest from source_marketo.utils import clean_string, format_value, to_datetime_str test_data = [ (1, {"type": "integer"}, int), ("string", {"type": "string"}, str), (True, {"type": ["boolean", "null"]}, bool), (1, {"type": ["number", "null"]}, float), ("", {"type": ["number", "null"]}, type(None)), ("1.5", {"type": "integer"}, int), ("15", {"type": "integer"}, int), ("true", {"type": "boolean"}, bool), ("test_custom", {"type": "custom_type"}, str), ] @pytest.mark.parametrize("value,schema,expected_output_type", test_data) def test_format_value(value, schema, expected_output_type): test = format_value(value, schema) assert isinstance(test, expected_output_type) test_data = [ ("api method name", "api_method_name"), ("API Method Name", "api_method_name"), ("modifying user", "modifying_user"), ("Modifying User", "modifying_user"), ("request id", "request_id"), ("Request Id", "request_id"), ("Page URL", "page_url"), ("Client IP Address", "client_ip_address"), ("Marketo Sales Person ID", "marketo_sales_person_id"), ("Merge IDs", "merge_ids"), ("SFDC Type", "sfdc_type"), ("Remove from CRM", "remove_from_crm"), ("SLA Expiration", "sla_expiration"), ("updatedAt", "updated_at"), ("UpdatedAt", "updated_at"), ("base URL", "base_url"), ("UPdatedAt", "u_pdated_at"), ("updated_at", "updated_at"), (" updated_at ", "updated_at"), ("updatedat", "updatedat"), ("", ""), ] @pytest.mark.parametrize("value,expected", test_data) def test_clean_string(value, expected): test = clean_string(value) assert test == expected def test_to_datetime_str(): input_ = datetime(2023, 1, 1) expected = "2023-01-01T00:00:00Z" assert to_datetime_str(input_) == expected
# Frequently Asked Questions This document will focus on the technology behind the Nebulas platform. For broader questions, please view the [Reddit FAQ](https://www.reddit.com/r/nebulas/comments/7nt5y0/frequently_asked_questionsfaq/). For a better understanding of the Nebulas platform it's highly recommended to read the [Nebulas Technical Whitepaper](https://nebulas.io/docs/NebulasTechnicalWhitepaper.pdf). **Table of Contents** 1. [Nebulas Rank \(NR\)](faq.md#nebulas-rank-nr) 2. [Nebulas Force \(NF\)](faq.md#nebulas-force-nf) 3. [Developer Incentive Protocol \(DIP\)](faq.md#developer-incentive-protocol-dip) 4. [Proof of Devotion \(PoD\) Consensus Algorithm](faq.md#proof-of-devotion-pod-consensus-algorithm) 5. [Nebulas Search Engine](faq.md#nebulas-search-engine) 6. [Fundamentals](faq.md#fundamentals) 1. [Nebulas Name Service \(NNS\)](faq.md#nebulas-name-service-nns) 2. [Lightning Network](faq.md#lightning-network) 3. [Nebulas Token \(NAS\)](faq.md#nebulas-token-nas) 4. [Smart Contracts](faq.md#smart-contracts) 1. [Language Support](faq.md#what-languages-will-be-supported-when-main-net-launches) 2. [Ethereum Compatibility](faq.md#will-ethereum-smart-contracts-solidity-be-fully-supported) ## Nebulas Rank \(NR\) Measures value by considering liquidity and propagation of the address. Nebulas Ranking tries to establish a trustful, computable and deterministic measurement approach. With the value ranking system, we will see more and more outstanding applications surfacing on the Nebulas platform. #### When will Nebulas Rank \(NR\) be ready? > The Nebulas Rank was released in December of 2018. At the time of writing this, June 28th of 2019, the NR Query Server is not online since the NR algorithm was updated, as it needs to be refactored. You are welcome to claim this project [here](https://go.nebulas.io/project/130). #### Will dApps with more transactions naturally be ranked higher? > Not necessarily, as transaction count would only increase the in-and-out degree over a period of time, up to a certain point. The way the Nebulas Rank is calculated uses, among many other variables, one's median account stake. The median account stake is the median of the account balance over a period of time. #### How does the Nebulas Rank \(NR\) separate quality dApps from highly transacted dApps? > By utilizing the Median Account Stake in its calculations, the NR ensures fairness and resists manipulation to a reasonable degree, ensuring the likelihood of high quality dApps floating to the top of the hierarchy. #### Is the Nebulas Ranking algorithm open-source? > Yes. #### Who can contribute to the algorithm? > At this time the Nebulas core team is responsible for the development of the algorithm. However, anyone is free to make suggestions, bug reports, and contribute with code. The SDK's repository can be accessed [here](https://github.com/nebulasio/nebnr), and the Nebulas Rank Offline Service can be accessed [here](https://github.com/nebulasio/nr-service). #### Can the Nebulas Rank \(NR\) algorithm be cheated? > Nothing is impervious to manipulation, but our goal is to make manipulation of the algorithm as expensive and difficult as possible. ## Nebulas Force \(NF\) Supports upgrading core protocols and smart contracts on the chains. It provides self-evolving capabilities to Nebulas system and its applications. With Nebulas Force, developers can build rich applications in fast iterations, and the applications can dynamically adapt to community or market changes. #### When will Nebulas Force \(NF\) be ready? > As per the [roadmap](https://wiki.nebulas.io/en/latest/roadmap.html), Nebulas Force is poised to be released at the end of 2019. #### Can smart contracts be upgraded? > Yes, \[short summary explaining how it works\] #### How is Nebulas Force \(NF\) smart contract upgrading better than other solutions that are currently or soon-to-be available? > answer here #### Can the Nebulas blockchain protocol code be upgraded without forking? > Yes, \[short summary explaining how it works\] #### Can the Nebulas Virtual Machine \(NVM\) be upgraded? > Yes, \[short summary explaining how it works\] ## Developer Incentive Protocol \(DIP\) Designed to build the blockchain ecosystem in a better way. The Nebulas token incentives will help top developers to add more value to the Nebulas blockchain. #### When will the Developer Incentive Protocol \(DIP\) be ready? > The Developer Incentive Protocol was deployed on the Nebulas Testnet in January of 2019. It was formally deployed on the Mainnet in May of 2019. #### Will there be a limit as to how many rewards one dApp can receive? > answer here #### Will developers still be able to do their own ICOs? > answer here #### Will only the top Nebulas Rank \(NR\) dApps receive rewards? > answer here #### How often will rewards be given? > answer here #### How will you stop cheaters? > The way the DIP is is designed makes it very hard for cheaters to be successful. Since smart contracts can only be called passively, it would be highly cost ineffective for a user to try to cheat the system. More about this topic can be read in the Technical Whitepaper. ## Proof of Devotion \(PoD\) Consensus Algorithm To build a healthy ecosystem, Nebulas proposes three key points for consensus algorithm: speediness, irreversibility and fairness. By adopting the advantages of PoS and PoI, and leveraging NR, PoD will take the lead in consensus algorithms. #### When will the Proof of Devotion \(PoD\) Consensus Algorithm be ready? > answer here #### What consensus algorithm will be used until PoD is ready? > answer here #### How are bookkeepers chosen? > The PoD consensus algorithm uses the Nebulas Rank \(NR\) to qualify nodes to be eligible. One node from the set is randomly chosen to propose the new block and the rest will become the validators. #### Do bookkeepers still have to stake? > Yes, once chosen to be a validator for a new block, the validator will need to place a deposit to continue. #### How many validators will there be in each set? > answer here #### What anti-cheating mechanisms are there? > answer here ## Nebulas Search Engine Nebulas constructs a search engine for decentralized applications based on Nebulas value ranking. Using this engine, users can easily find desired decentralized applications from the massive market. #### When will the Nebulas Search Engine be ready? > answer here #### Will you be able to search dApps not on the Nebulas platform? > answer here #### Will the Nebulas Search Engine also be decentralized? > answer here #### Will the Nebulas Rank \(NR\) control the search results ranking? > answer here #### What data will you be able to search? > We plan on developing many different ways to be able to search the blockchain: > > * crawl relevant webpages and establish a map between them and the smart contracts > * analyze the code of open-source smart contracts > * establish contract standards that enable easier searching ## Fundamentals ### Nebulas Name Service \(NNS\) By using smart contracts, the Nebulas development team will implement a DNS-like domain system named Nebulas Name Service \(NNS\) on the chain while ensuring that it is unrestricted, free and open. Any third-party developers can implement their own domain name resolution services independently or based on NNS. #### When will the Nebulas Name Service be ready? > answer here #### When a name is bid on, how long do others have to place their bid? > answer here #### How do others get notified that a name is being bid on? > answer here #### When a name is reserved who gets the bid amount? > answer here #### If I want to renew my name after one year will I need to deposit more NAS? > answer here #### Will we be able to reserve names prior to the launch of NNS? > answer here ### Lightning Network Nebulas implements the lightning network as the infrastructure of blockchains and offers flexible design. Any third-party developers can use the basic service of lightning network to develop applications for frequent transaction scenarios on Nebulas. In addition, Nebulas will launch the world’s first wallet app that supports the lightning network. #### When will lightning network be supported? > answer here ### The Nebulas Token \(NAS\) The Nebulas network has its own built-in token, NAS. NAS plays two roles in the network. First, as the original money in the network, NAS provides asset liquidity among users, and functions as the incentive token for PoD bookkeepers and DIP. Second, NAS will be charged as the calculation fee for running smart contracts. The minimum unit of NAS is 10−18 NAS. #### What will happen to the Nebulas ERC20 tokens when NAS is launched? > The ERC20 tokens were swapped by its owners and exchanges that held them at a 1 to 1 rate. #### Will dApps on the Nebulas platform be able to issue their owns ICOs and tokens? > answer here ### Smart Contracts #### What languages will be supported when Main-net launches? > answer here #### Will Ethereum Smart Contracts \(Solidity\) be fully supported? > answer here #### What other language support will follow \(and when\)? > answer here #### binary storage What is recommended way to store binary data in Nebulas blockchain? Is it possible at all? Do you encourage such use of blockchain? Also, i couldn't find information regarding GlobalContractStorage mentioned in docs, what is it? > Currently binary data can be stored on chain by binary transaction. The limit size of binary is 128k. But we don’t encourage storing data on the chain because the user might store some illegal data. > > `GlobalContractStorage`not currently implemented. It provides support for multiple contract sharing data for the same developer. #### ChainID & connect Can you tell us what the chainID of Mainnet and Testnet is? I have compiled the source code of our nebulas, but not even our test network? > chainID of Nebulas: * Mainnet: 1 * Testnet: 1001 * private: default 100, users can customize the values. > The network connection: * Mainnet: * source code:[master](https://github.com/nebulasio/go-nebulas/tree/master) * wiki:[Mainnet](https://github.com/nebulasio/nebdocs/blob/master/docs/go-nebulas/mainnet.md) * Testnet: * source code:[testnet](https://github.com/nebulasio/go-nebulas/tree/testnet) * wiki:[Testnet](https://github.com/nebulasio/nebdocs/blob/master/docs/go-nebulas/testnet.md) #### Smart Contract Deployment Our smart contract deployment, I think is to submit all contract code directly, is the deployment method like this? > Yeah, We can deploy the contract code directly, just as it is to release code to the NPM repository, which is very simple and convenient. #### smart contract IDE We don't have any other smart contract ides, like solidity's "Remix"? Or is there documentation detailing which contract parameters can be obtained? \(because I need to implement the random number and realize the logic, I calculate the final random number according to the parameters of the network, so I may need some additional network parameters that will not be manipulated.\) > You can use [web-wallet](https://github.com/nebulasio/web-wallet) to deploy the contract, it has test function to check the parameters and contract execution result.
<template> <Page> <ActionBar title="Detail" class="action-bar" /> <ScrollView orientation="vertical"> <StackLayout orientation="vertical" margin="10"> <Image :src="selectedApartment.Image_URL" height="300" stretch="aspectFill" /> <Label class="h1" :text="selectedApartment.Property_Title" /> <GridLayout columns="auto, auto, auto" rows="auto, auto"> <Label col="0" row="0" :text="'Estate: '+selectedApartment.Estate+', '" /> <Label col="1" row="0" :text="'Bredroom: '+selectedApartment.Bedrooms" /> <Label col="0" row="1" :text="'Rent Price: $' + selectedApartment.Rent+', '" /> <Label col="1" row="1" :text="'Tenants: '+selectedApartment.Expected_Tenants+', '" /> <Label col="2" row="1" :text="'Area: '+selectedApartment.Gross_Area" /> </GridLayout> <GridLayout columns="*, *" rows="50, 50"> <Button col="0" row="0" text="Move-in" @tap="addtoMine()" class="btn btn-primary btn rounded-lg" /> <Button col="1" row="0" text="Address" @tap="showmap()" class="btn btn-primary btn rounded-lg" /> </GridLayout> </StackLayout> </ScrollView> </Page> </template> <script> import maps from "./maps"; export default { props: ["selectedApartment", "$delegate"], methods: { showmap: function() { this.$navigateTo(maps, { transition: {}, transitionIOS: {}, transitionAndroid: {}, props: { onmap: this.selectedApartment.Estate, qLatitude: this.selectedApartment.Latitude, qLongitude: this.selectedApartment.Longitude, $delegate: this } }); }, async addtoMine() { var result = await confirm({ title: "Confirm?", message: "This apartment will added to your rentals.", okButtonText: "Yes", cancelButtonText: "Cancel" }); if (result) { global.rootURL = "http://192.168.3.34:1337"; var response = await fetch( global.rootURL + "/user/" + 2 + "/rents/add/" + this.selectedApartment.id, { method: "GET", credentials: "same-origin" } ); if (response.ok) { var data = await response.json(); alert(data.message); } else { alert(response.status + ": " + response.statusText); } } } }, data() { return {}; } }; </script> <style> </style>
/**Decorators wrap another function in another function */ /**Support the principle of DRY code */ let sum = (...args) => { return [...args].reduce((acc, num) => acc + num) } /**Let is recommended for use with decorator functions */ const callCounter = (fn) => { let count = 0; return (...args) => { console.log(`Sum has has been called ${count += 1} times`); return fn(...args) } } sum = callCounter(sum) console.log(sum(2,4,6)); console.log(sum(2,4,6)); console.log(sum(2,4,6,10,123));
<template> <view class="page-content"> <uv-navbar leftText="" :placeholder="true" title="监控项目详情" autoBack> <template v-slot:right> <uv-icon name="edit-pen" size="20" @click="edit"></uv-icon> </template> </uv-navbar> <uv-form labelPosition="left" labelWidth="80" :model="form"> <uv-form-item label="项目uuid" prop="projectKey" borderBottom> {{form.projectKey}} </uv-form-item> <uv-form-item label="项目名称" prop="projectName" borderBottom> {{form.projectName}} </uv-form-item> <uv-form-item label="项目类型" prop="projectType" borderBottom> {{form.projectType}} </uv-form-item> <uv-form-item label="创建时间" prop="createTime" borderBottom> {{form.createTime}} </uv-form-item> <uv-form-item label="更新时间" prop="updateTime" borderBottom> {{form.updateTime}} </uv-form-item> </uv-form> <uv-button v-if="$perms('admin:monitor_project:edit')" type="primary" text="编辑" customStyle="margin-top: 20rpx" @click="edit" ></uv-button> </view> </template> <script setup lang="ts"> import { reactive, ref, computed } from "vue"; import { onLoad, onShow, onPullDownRefresh } from "@dcloudio/uni-app"; import { useDictData } from "@/hooks/useDictOptions"; import { monitor_project_detail } from "@/api/monitor_project"; import type {type_monitor_project} from "@/api/monitor_project"; import { toast, alert, toPath } from "@/utils/utils"; let form = ref<type_monitor_project>({ id: 0, projectKey: "", projectName: "", projectType: "", createTime: "", updateTime: "", }); onLoad((e) => { console.log("onLoad", e); getDetails(e.id); }); onShow((e) => { if (form.value?.id) { getDetails(form.value.id); } }); onPullDownRefresh(() => { getDetails(form.value.id); }); function getDetails(id) { monitor_project_detail(id).then((res) => { uni.stopPullDownRefresh(); if (res.code == 200) { if (res.data) { form.value = res?.data } } else { toast(res.message); } }) .catch((err) => { uni.stopPullDownRefresh(); toast(err.message||"网络错误"); }); } function edit() { toPath("/pages/monitor_project/edit", { id: form.value.id }); } </script> <style lang="scss" scoped> .page-content { padding: 10rpx 20rpx 300rpx; } </style>
import React, { useState } from "react"; import { Input } from "./Input"; import { ObjectiveInput } from "./ObjectiveInput"; import { Select } from "./Select"; export const Form = ({ formData, onChangeInput, onSubmittttttt, reset }) => { return ( <form onSubmit={onSubmittttttt}> <Input label="Name" name="name" type="text" value={formData.name} onChangeInput={onChangeInput} /> <ObjectiveInput label="Gender" name="gender" type="radio" value={formData.gender} onChangeInput={onChangeInput} options={[ { label: "Male", value: "Male" }, { label: "Female", value: "Female" }, ]} /> <Select label="Nationality" name="nationality" value={formData.nationality} onChangeInput={onChangeInput} options={[ { label: "Bangladeshi", value: "Bangladesh" }, { label: "Indian", value: "India" }, { label: "USA", value: "Russia" }, { label: "UK", value: "UK" }, ]} /> <ObjectiveInput label="Degree" name="degree" type="checkbox" value={formData.degree} onChangeInput={onChangeInput} options={[ { label: "SSC", value: "SSC" }, { label: "HSC", value: "HSC" }, { label: "BSc", value: "BSc" }, { label: "MS", value: "MS" }, ]} /> <div> <label htmlFor="name">Address</label> <textarea name="address" id="address" value={formData.address} onChange={onChangeInput} /> </div> <div> <button type="submit">Submit</button> <button type="reset" onClick={reset}> Reset </button> </div> </form> ); };
//non binary solution var missingNumber = function(nums) { let length = nums.length; nums = new Set(nums) while (length > - 1) { if (nums.has(length)) length--; else break; } return length; }; //algorithmic way n * (n + 1) / 2 where //o(n)time -- o(1) space var missingNumber = function(nums) { let length = nums.length; //n * (n + 1) / 2 --- algorithm let gsum = length * (length + 1)/2 //gets sum of 1 to n numbers let reduce = nums.reduce((a, b) => a + b, 0) return gsum - reduce; }; //binary solution // ^ is XOR, aka bits must be different to get 1 (but 1 and 1 is 0) //XOR 2 same numbers it will return 0 //XOR any number other than 0 and 0, it will return that number var missingNumber = function(nums) { let missing = 0; for (let i = 0; i < nums.length + 1; i++) { missing = missing ^ i; if (i < nums.length) { missing = missing ^ nums[i]; } } return missing; };
Фундаментальная теория тестирования В тестировании нет четких определений, как в физике, математике, которые при перефразировании становятся абсолютно неверными. Поэтому важно понимать процессы и подходы. В данной статье разберем основные определения теории тестирования. Перейдем к основным понятиям Тестирование программного обеспечения (Software Testing) — проверка соответствия реальных и ожидаемых результатов поведения программы, проводимая на конечном наборе тестов, выбранном определённым образом. Цель тестирования — проверка соответствия ПО предъявляемым требованиям, обеспечение уверенности в качестве ПО, поиск очевидных ошибок в программном обеспечении, которые должны быть выявлены до того, как их обнаружат пользователи программы. Для чего проводится тестирование ПО? Для проверки соответствия требованиям. Для обнаружение проблем на более ранних этапах разработки и предотвращение повышения стоимости продукта. Обнаружение вариантов использования, которые не были предусмотрены при разработке. А также взгляд на продукт со стороны пользователя. Повышение лояльности к компании и продукту, т.к. любой обнаруженный дефект негативно влияет на доверие пользователей. Принципы тестирования Принцип 1 — Тестирование демонстрирует наличие дефектов (Testing shows presence of defects). Тестирование только снижает вероятность наличия дефектов, которые находятся в программном обеспечении, но не гарантирует их отсутствия. Принцип 2 — Исчерпывающее тестирование невозможно (Exhaustive testing is impossible). Полное тестирование с использованием всех входных комбинаций данных, результатов и предусловий физически невыполнимо (исключение — тривиальные случаи). Принцип 3 — Раннее тестирование (Early testing). Следует начинать тестирование на ранних стадиях жизненного цикла разработки ПО, чтобы найти дефекты как можно раньше. Принцип 4 — Скопление дефектов (Defects clustering). Большая часть дефектов находится в ограниченном количестве модулей. Принцип 5 — Парадокс пестицида (Pesticide paradox). Если повторять те же тестовые сценарии снова и снова, в какой-то момент этот набор тестов перестанет выявлять новые дефекты. Принцип 6 — Тестирование зависит от контекста (Testing is context depending). Тестирование проводится по-разному в зависимости от контекста. Например, программное обеспечение, в котором критически важна безопасность, тестируется иначе, чем новостной портал. Принцип 7 — Заблуждение об отсутствии ошибок (Absence-of-errors fallacy). Отсутствие найденных дефектов при тестировании не всегда означает готовность продукта к релизу. Система должна быть удобна пользователю в использовании и удовлетворять его ожиданиям и потребностям. Обеспечение качества (QA — Quality Assurance) и контроль качества (QC — Quality Control) — эти термины похожи на взаимозаменяемые, но разница между обеспечением качества и контролем качества все-таки есть, хоть на практике процессы и имеют некоторую схожесть. QC (Quality Control) — Контроль качества продукта — анализ результатов тестирования и качества новых версий выпускаемого продукта. К задачам контроля качества относятся: проверка готовности ПО к релизу; проверка соответствия требований и качества данного проекта. QA (Quality Assurance) — Обеспечение качества продукта — изучение возможностей по изменению и улучшению процесса разработки, улучшению коммуникаций в команде, где тестирование является только одним из аспектов обеспечения качества. К задачам обеспечения качества относятся: проверка технических характеристик и требований к ПО; оценка рисков; планирование задач для улучшения качества продукции; подготовка документации, тестового окружения и данных; тестирование; анализ результатов тестирования, а также составление отчетов и других документов. Скриншот Верификация и валидация — два понятия тесно связаны с процессами тестирования и обеспечения качества. К сожалению, их часто путают, хотя отличия между ними достаточно существенны. Верификация (verification) — это процесс оценки системы, чтобы понять, удовлетворяют ли результаты текущего этапа разработки условиям, которые были сформулированы в его начале. Валидация (validation) — это определение соответствия разрабатываемого ПО ожиданиям и потребностям пользователя, его требованиям к системе. Пример: когда разрабатывали аэробус А310, то надо было сделать так, чтобы закрылки вставали в положение «торможение», когда шасси коснулись земли. Запрограммировали так, что когда шасси начинают крутиться, то закрылки ставим в положение «торможение». Но вот во время испытаний в Варшаве самолет выкатился за пределы полосы, так как была мокрая поверхность. Он проскользил, только потом был крутящий момент и они, закрылки, открылись. С точки зрения «верификации» — программа сработала, с точки зрения «валидации» — нет. Поэтому код изменили так, чтобы в момент изменения давления в шинах открывались закрылки. Документацию, которая используется на проектах по разработке ПО, можно условно разделить на две группы: Проектная документация — включает в себя всё, что относится к проекту в целом. Продуктовая документация — часть проектной документации, выделяемая отдельно, которая относится непосредственно к разрабатываемому приложению или системе. Этапы тестирования: Анализ продукта Работа с требованиями Разработка стратегии тестирования и планирование процедур контроля качества Создание тестовой документации Тестирование прототипа Основное тестирование Стабилизация Эксплуатация Стадии разработки ПО — этапы, которые проходят команды разработчиков ПО, прежде чем программа станет доступной для широкого круга пользователей. Программный продукт проходит следующие стадии: анализ требований к проекту; проектирование; реализация; тестирование продукта; внедрение и поддержка. Требования Требования — это спецификация (описание) того, что должно быть реализовано. Требования описывают то, что необходимо реализовать, без детализации технической стороны решения. Атрибуты требований: Корректность — точное описание разрабатываемого функционала. Проверяемость — формулировка требований таким образом, чтобы можно было выставить однозначный вердикт, выполнено все в соответствии с требованиями или нет. Полнота — в требовании должна содержаться вся необходимая для реализации функциональности информация. Недвусмысленность — требование должно содержать однозначные формулировки. Непротиворечивость — требование не должно содержать внутренних противоречий и противоречий другим требованиям и документам. Приоритетность — у каждого требования должен быть приоритет(количественная оценка степени значимости требования). Этот атрибут позволит грамотно управлять ресурсами на проекте. Атомарность — требование нельзя разбить на отдельные части без потери деталей. Модифицируемость — в каждое требование можно внести изменение. Прослеживаемость — каждое требование должно иметь уникальный идентификатор, по которому на него можно сослаться. Дефект (bug) — отклонение фактического результата от ожидаемого. Отчёт о дефекте (bug report) — документ, который содержит отчет о любом недостатке в компоненте или системе, который потенциально может привести компонент или систему к невозможности выполнить требуемую функцию. Атрибуты отчета о дефекте: Уникальный идентификатор (ID) — присваивается автоматически системой при создании баг-репорта. Тема (краткое описание, Summary) — кратко сформулированный смысл дефекта, отвечающий на вопросы: Что? Где? Когда(при каких условиях)? Подробное описание (Description) — более широкое описание дефекта (указывается опционально). Шаги для воспроизведения (Steps To Reproduce) — описание четкой последовательности действий, которая привела к выявлению дефекта. В шагах воспроизведения должен быть описан каждый шаг, вплоть до конкретных вводимых значений, если они играют роль в воспроизведении дефекта. Фактический результат (Actual result) — описывается поведение системы на момент обнаружения дефекта в ней. чаще всего, содержит краткое описание некорректного поведения(может совпадать с темой отчета о дефекте). Ожидаемый результат (Expected result) — описание того, как именно должна работать система в соответствии с документацией. Вложения (Attachments) — скриншоты, видео или лог-файлы. Серьёзность дефекта (важность, Severity) — характеризует влияние дефекта на работоспособность приложения. Приоритет дефекта (срочность, Priority) — указывает на очерёдность выполнения задачи или устранения дефекта. Статус (Status) — определяет текущее состояние дефекта. Статусы дефектов могут быть разными в разных баг-трекинговых системах. Окружение (Environment) – окружение, на котором воспроизвелся баг. Жизненный цикл бага Скриншот Severity vs Priority Серьёзность (severity) показывает степень ущерба, который наносится проекту существованием дефекта. Severity выставляется тестировщиком. Градация Серьезности дефекта (Severity): Блокирующий (S1 – Blocker) тестирование значительной части функциональности вообще недоступно. Блокирующая ошибка, приводящая приложение в нерабочее состояние, в результате которого дальнейшая работа с тестируемой системой или ее ключевыми функциями становится невозможна. Критический (S2 – Critical) критическая ошибка, неправильно работающая ключевая бизнес-логика, дыра в системе безопасности, проблема, приведшая к временному падению сервера или приводящая в нерабочее состояние некоторую часть системы, то есть не работает важная часть одной какой-либо функции либо не работает значительная часть, но имеется workaround (обходной путь/другие входные точки), позволяющий продолжить тестирование. Значительный (S3 – Major) не работает важная часть одной какой-либо функции/бизнес-логики, но при выполнении специфических условий, либо есть workaround, позволяющий продолжить ее тестирование либо не работает не очень значительная часть какой-либо функции. Также относится к дефектам с высокими visibility – обычно не сильно влияющие на функциональность дефекты дизайна, которые, однако, сразу бросаются в глаза. Незначительный (S4 – Minor) часто ошибки GUI, которые не влияют на функциональность, но портят юзабилити или внешний вид. Также незначительные функциональные дефекты, либо которые воспроизводятся на определенном устройстве. Тривиальный (S5 – Trivial) почти всегда дефекты на GUI — опечатки в тексте, несоответствие шрифта и оттенка и т.п., либо плохо воспроизводимая ошибка, не касающаяся бизнес-логики, проблема сторонних библиотек или сервисов, проблема, не оказывающая никакого влияния на общее качество продукта. Срочность (priority) показывает, как быстро дефект должен быть устранён. Priority выставляется менеджером, тимлидом или заказчиком Градация Приоритета дефекта (Priority): P1 Высокий (High) Критическая для проекта ошибка. Должна быть исправлена как можно быстрее. P2 Средний (Medium) Не критичная для проекта ошибка, однако требует обязательного решения. P3 Низкий (Low) Наличие данной ошибки не является критичным и не требует срочного решения. Может быть исправлена, когда у команды появится время на ее устранение. Существует шесть базовых типов задач: Эпик (epic) — большая задача, на решение которой команде нужно несколько спринтов. Требование (requirement ) — задача, содержащая в себе описание реализации той или иной фичи. История (story) — часть большой задачи (эпика), которую команда может решить за 1 спринт. Задача (task) — техническая задача, которую делает один из членов команды. Под-задача (sub-task) — часть истории / задачи, которая описывает минимальный объем работы члена команды. Баг (bug) — задача, которая описывает ошибку в системе. Тестовые среды Среда разработки (Development Env) – за данную среду отвечают разработчики, в ней они пишут код, проводят отладку, исправляют ошибки Среда тестирования (Test Env) – среда, в которой работают тестировщики (проверяют функционал, проводят smoke и регрессионные тесты, воспроизводят. Интеграционная среда (Integration Env) – среда, в которой проводят тестирование взаимодействующих друг с другом модулей, систем, продуктов. Предпрод (Preprod Env) – среда, которая максимально приближена к продакшену. Здесь проводится заключительное тестирование функционала. Продакшн среда (Production Env) – среда, в которой работают пользователи. Основные фазы тестирования Pre-Alpha: прототип, в котором всё ещё присутствует много ошибок и наверняка неполный функционал. Необходим для ознакомления с будущими возможностями программ. Alpha: является ранней версией программного продукта, тестирование которой проводится внутри фирмы-разработчика. Beta: практически готовый продукт, который разработан в первую очередь для тестирования конечными пользователями. Release Candidate (RC): возможные ошибки в каждой из фичей уже устранены и разработчики выпускают версию на которой проводится регрессионное тестирование. Release: финальная версия программы, которая готова к использованию. Основные виды тестирования ПО Вид тестирования — это совокупность активностей, направленных на тестирование заданных характеристик системы или её части, основанная на конкретных целях. Скриншот Классификация по запуску кода на исполнение: Статическое тестирование — процесс тестирования, который проводится для верификации практически любого артефакта разработки: программного кода компонент, требований, системных спецификаций, функциональных спецификаций, документов проектирования и архитектуры программных систем и их компонентов. Динамическое тестирование — тестирование проводится на работающей системе, не может быть осуществлено без запуска программного кода приложения. Классификация по доступу к коду и архитектуре: Тестирование белого ящика — метод тестирования ПО, который предполагает полный доступ к коду проекта. Тестирование серого ящика — метод тестирования ПО, который предполагает частичный доступ к коду проекта (комбинация White Box и Black Box методов). Тестирование чёрного ящика — метод тестирования ПО, который не предполагает доступа (полного или частичного) к системе. Основывается на работе исключительно с внешним интерфейсом тестируемой системы. Классификация по уровню детализации приложения: Модульное тестирование — проводится для тестирования какого-либо одного логически выделенного и изолированного элемента (модуля) системы в коде. Проводится самими разработчиками, так как предполагает полный доступ к коду. Интеграционное тестирование — тестирование, направленное на проверку корректности взаимодействия нескольких модулей, объединенных в единое целое. Системное тестирование — процесс тестирования системы, на котором проводится не только функциональное тестирование, но и оценка характеристик качества системы — ее устойчивости, надежности, безопасности и производительности. Приёмочное тестирование — проверяет соответствие системы потребностям, требованиям и бизнес-процессам пользователя. Классификация по степени автоматизации: Ручное тестирование. Автоматизированное тестирование. Классификация по принципам работы с приложением Позитивное тестирование — тестирование, при котором используются только корректные данные. Негативное тестирование — тестирование приложения, при котором используются некорректные данные и выполняются некорректные операции. Классификация по уровню функционального тестирования: Дымовое тестирование (smoke test) — тестирование, выполняемое на новой сборке, с целью подтверждения того, что программное обеспечение стартует и выполняет основные для бизнеса функции. Тестирование критического пути (critical path) — направлено для проверки функциональности, используемой обычными пользователями во время их повседневной деятельности. Расширенное тестирование (extended) — направлено на исследование всей заявленной в требованиях функциональности. Классификация в зависимости от исполнителей: Альфа-тестирование — является ранней версией программного продукта. Может выполняться внутри организации-разработчика с возможным частичным привлечением конечных пользователей. Бета-тестирование — программное обеспечение, выпускаемое для ограниченного количества пользователей. Главная цель — получить отзывы клиентов о продукте и внести соответствующие изменения. Классификация в зависимости от целей тестирования: Функциональное тестирование (functional testing) — направлено на проверку корректности работы функциональности приложения. Нефункциональное тестирование (non-functional testing) — тестирование атрибутов компонента или системы, не относящихся к функциональности. Тестирование производительности (performance testing) — определение стабильности и потребления ресурсов в условиях различных сценариев использования и нагрузок. Нагрузочное тестирование (load testing) — определение или сбор показателей производительности и времени отклика программно-технической системы или устройства в ответ на внешний запрос с целью установления соответствия требованиям, предъявляемым к данной системе (устройству). Тестирование масштабируемости (scalability testing) — тестирование, которое измеряет производительность сети или системы, когда количество пользовательских запросов увеличивается или уменьшается. Объёмное тестирование (volume testing) — это тип тестирования программного обеспечения, которое проводится для тестирования программного приложения с определенным объемом данных. Стрессовое тестирование (stress testing) — тип тестирования направленный для проверки, как система обращается с нарастающей нагрузкой (количеством одновременных пользователей). Инсталляционное тестирование (installation testing) — тестирование, направленное на проверку успешной установки и настройки, обновления или удаления приложения. Тестирование интерфейса (GUI/UI testing) — проверка требований к пользовательскому интерфейсу. Тестирование удобства использования (usability testing) — это метод тестирования, направленный на установление степени удобства использования, понятности и привлекательности для пользователей разрабатываемого продукта в контексте заданных условий. Тестирование локализации (localization testing) — проверка адаптации программного обеспечения для определенной аудитории в соответствии с ее культурными особенностями. Тестирование безопасности (security testing) — это стратегия тестирования, используемая для проверки безопасности системы, а также для анализа рисков, связанных с обеспечением целостного подхода к защите приложения, атак хакеров, вирусов, несанкционированного доступа к конфиденциальным данным. Тестирование надёжности (reliability testing) — один из видов нефункционального тестирования ПО, целью которого является проверка работоспособности приложения при длительном тестировании с ожидаемым уровнем нагрузки. Регрессионное тестирование (regression testing) — тестирование уже проверенной ранее функциональности после внесения изменений в код приложения, для уверенности в том, что эти изменения не внесли ошибки в областях, которые не подверглись изменениям. Повторное/подтверждающее тестирование (re-testing/confirmation testing) — тестирование, во время которого исполняются тестовые сценарии, выявившие ошибки во время последнего запуска, для подтверждения успешности исправления этих ошибок. Тест-дизайн — это этап тестирования ПО, на котором проектируются и создаются тестовые случаи (тест-кейсы). Техники тест-дизайна Автор книги "A Practitioner’s Guide to Software Test Design", Lee Copeland, выделяет следующие техники тест-дизайна: Тестирование на основе классов эквивалентности (equivalence partitioning) — это техника, основанная на методе чёрного ящика, при которой мы разделяем функционал (часто диапазон возможных вводимых значений) на группы эквивалентных по своему влиянию на систему значений. Техника анализа граничных значений (boundary value testing) — это техника проверки поведения продукта на крайних (граничных) значениях входных данных. Попарное тестирование (pairwise testing) — это техника формирования наборов тестовых данных из полного набора входных данных в системе, которая позволяет существенно сократить количество тест-кейсов. Тестирование на основе состояний и переходов (State-Transition Testing) — применяется для фиксирования требований и описания дизайна приложения. Таблицы принятия решений (Decision Table Testing) — техника тестирования, основанная на методе чёрного ящика, которая применяется для систем со сложной логикой. Доменный анализ (Domain Analysis Testing) — это техника основана на разбиении диапазона возможных значений переменной на поддиапазоны, с последующим выбором одного или нескольких значений из каждого домена для тестирования. Сценарий использования (Use Case Testing) — Use Case описывает сценарий взаимодействия двух и более участников (как правило — пользователя и системы). Методы тестирования Скриншот Тестирование белого ящика — метод тестирования ПО, который предполагает, что внутренняя структура/устройство/реализация системы известны тестировщику. Согласно ISTQB, тестирование белого ящика — это: тестирование, основанное на анализе внутренней структуры компонента или системы; тест-дизайн, основанный на технике белого ящика — процедура написания или выбора тест-кейсов на основе анализа внутреннего устройства системы или компонента. Почему «белый ящик»? Тестируемая программа для тестировщика — прозрачный ящик, содержимое которого он прекрасно видит. Тестирование серого ящика — метод тестирования ПО, который предполагает комбинацию White Box и Black Box подходов. То есть, внутреннее устройство программы нам известно лишь частично. Тестирование чёрного ящика — также известное как тестирование, основанное на спецификации или тестирование поведения — техника тестирования, основанная на работе исключительно с внешними интерфейсами тестируемой системы. Согласно ISTQB, тестирование черного ящика — это: тестирование, как функциональное, так и нефункциональное, не предполагающее знания внутреннего устройства компонента или системы; тест-дизайн, основанный на технике черного ящика — процедура написания или выбора тест-кейсов на основе анализа функциональной или нефункциональной спецификации компонента или системы без знания ее внутреннего устройства. Тестовая документация Тест план (Test Plan) — это документ, который описывает весь объем работ по тестированию, начиная с описания объекта, стратегии, расписания, критериев начала и окончания тестирования, до необходимого в процессе работы оборудования, специальных знаний, а также оценки рисков. Тест план должен отвечать на следующие вопросы: Что необходимо протестировать? Как будет проводиться тестирование? Когда будет проводиться тестирование? Критерии начала тестирования. Критерии окончания тестирования. Основные пункты тест плана: Идентификатор тест плана (Test plan identifier); Введение (Introduction); Объект тестирования (Test items); Функции, которые будут протестированы (Features to be tested;) Функции, которые не будут протестированы (Features not to be tested); Тестовые подходы (Approach); Критерии прохождения тестирования (Item pass/fail criteria); Критерии приостановления и возобновления тестирования (Suspension criteria and resumption requirements); Результаты тестирования (Test deliverables); Задачи тестирования (Testing tasks); Ресурсы системы (Environmental needs); Обязанности (Responsibilities); Роли и ответственность (Staffing and training needs); Расписание (Schedule); Оценка рисков (Risks and contingencies); Согласования (Approvals). Чек-лист (check list) — это документ, который описывает что должно быть протестировано. Чек-лист может быть абсолютно разного уровня детализации. Чаще всего чек-лист содержит только действия, без ожидаемого результата. Чек-лист менее формализован. Тестовый сценарий (test case) — это артефакт, описывающий совокупность шагов, конкретных условий и параметров, необходимых для проверки реализации тестируемой функции или её части. Атрибуты тест кейса: Предусловия (PreConditions) — список действий, которые приводят систему к состоянию пригодному для проведения основной проверки. Либо список условий, выполнение которых говорит о том, что система находится в пригодном для проведения основного теста состояния. Шаги (Steps) — список действий, переводящих систему из одного состояния в другое, для получения результата, на основании которого можно сделать вывод о удовлетворении реализации, поставленным требованиям. Ожидаемый результат (Expected result) — что по факту должны получить.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>David Ramalho Portfolio</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" integrity="sha256-46qynGAkLSFpVbEBog43gvNhfrOj+BmwXdxFgVK/Kvc=" crossorigin="anonymous" /> <!-- Update these with your own fonts --> <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:400,900|Source+Sans+Pro:300,900&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="css/style.css" /> </head> <body> <header> <button class="nav-toggle" aria-label="toggle navigation"> <span class="hamburger"></span> </button> <nav class="nav"> <ul class="nav__list"> <li class="nav__item"><a href="#home" class="nav__link">Home</a></li> <li class="nav__item"> <a href="#services" class="nav__link">Skills</a> </li> <li class="nav__item"> <a href="#about" class="nav__link">About me</a> </li> <li class="nav__item"> <a href="#work" class="nav__link">Projects</a> </li> </ul> </nav> </header> <!-- Introduction --> <section class="intro" id="home"> <h1 class="section__title section__title--intro"> Hi, I am <strong>David Ramalho</strong> </h1> <p class="section__subtitle section__subtitle--intro"> full stack dev <a class="intro__link" href="https://www.linkedin.com/in/david-moguidante-ramalho-61061052/" target="blank" > <i class="fab fa-linkedin"></i ></a> <a class="intro__link" href="https://github.com/davidRamalho" target="blank" > <i class="fab fa-github"></i ></a> <a class="intro__link" href="img/David Ramalho - Resume.pdf" target="blank"> <i class="far fa-file-alt"></i ></a> <a class="intro__link" href="mailto:david.m.ramalho@gmail.com" target="blank" > <i class="far fa-envelope"></i ></a> </p> <img src="img/profile.jpg" alt="a picture of David Ramalho smiling" class="intro__img" /> </section> <!-- Skills --> <section class="my-services" id="services"> <h2 class="section__title section__title--services">Skills</h2> <div class="services"> <div class="service"> <h3>Languages</h3> <li>JavaScript</li> <li>PHP</li> <li>Ruby</li> <br /><br /> </div> <!-- / service --> <div class="service"> <h3>Libraries & Frameworks</h3> <li>Laravel</li> <li>jQuery</li> <li>React</li> <li>Express</li> <li>Ruby on Rails</li> <br /><br /> </div> <!-- / service --> <div class="service"> <h3>Databases</h3> <li>MySQL</li> <li>PostgreSQL</li> <br /><br /> </div> <!-- / service --> <div class="service"> <h3>Spoken Languages</h3> <li>English</li> <li>Brazilian Portuguese</li> <li>Spanish</li> <br /><br /> </div> <!-- / service --> </div> <!-- / services --> <a href="#work" class="btn">My Work</a> </section> <!-- About me --> <section class="about-me" id="about"> <h2 class="section__title section__title--about">Who I am</h2> <p class="section__subtitle section__subtitle--about"> Full Stack Developer based out of Calgary </p> <div class="about-me__body"> <p> I am a developer with a passion for code, full-stack development, continuous learning and new technologies. I am most interested in finding solutions to real-world problems. My educational and employment history revolves around web development, science and logistics. Most recently, while working at Exempt Edge, I was the main developer in a large project to completely revamp the application's notifications feature. </p> </div> <img src="img/onComputer.jpg" alt="David on onComputer" class="about-me__img" /> </section> <!-- My Work --> <section class="my-work" id="work"> <h2 class="section__title section__title--work">Projects</h2> <p class="section__subtitle section__subtitle--work"> Click through some of my personal projects! </p> <div class="portfolio"> <!-- Portfolio item 01 --> <a href="ADTimeScheduling.html" class="portfolio__item"> <img src="img/ADTimeScheduling.png" alt="" class="portfolio__img" /> </a> <!-- Portfolio item 02 --> <a href="LysArtPets.html" class="portfolio__item"> <img src="img/LysArtPets.png" alt="" class="portfolio__img" /> </a> <!-- Portfolio item 03 --> <a href="downtownMarina.html" class="portfolio__item"> <img src="img/downtownMarina.png" alt="" class="portfolio__img" /> </a> <!-- Portfolio item 04 --> <a href="storyCreator.html" class="portfolio__item"> <img src="img/UserPage.png" alt="" class="portfolio__img" /> </a> <!-- Portfolio item 05 --> <a href="Tweeter.html" class="portfolio__item"> <img src="img/tablet-size.png" alt="" class="portfolio__img" /> </a> <!-- Portfolio item 06 --> <a href="interviewScheduler.html" class="portfolio__item"> <img src="img/adding-deleting-appointments.png" alt="" class="portfolio__img" /> </a> </div> </section> <!-- Footer --> <footer class="footer"> <a href="img/David Ramalho - Resume.pdf" class="footer__link" target="blank">Resume</a> <a href="mailto:david.m.ramalho@gmail.com" class="footer__link" >david.m.ramalho@gmail.com</a > <ul class="social-list"> <li class="social-list__item"> <a class="social-list__link" href="https://www.linkedin.com/in/david-moguidante-ramalho-61061052/" target="blank" > <i class="fab fa-linkedin"></i> </a> </li> <li class="social-list__item"> <a class="social-list__link" href="https://github.com/davidRamalho" target="blank" > <i class="fab fa-github"></i> </a> </li> </ul> </footer> <script src="js/index.js"></script> </body> </html>
"use client"; import React, { useState } from "react"; import FilterDropDown from "../FilterDropDown"; import Title from "../Title"; import AssetCard from "./AssetCard"; import { GetNftsForOwnerOptions } from "alchemy-sdk"; import { useAccount } from "wagmi"; import { useQuery } from "@tanstack/react-query"; import { useAuthContext } from "@/contexts/AuthContext"; import { getAssetTypes } from "@/api-modules/assets"; import { getNftsByrOnwerAlchemy } from "@/lib/getNftsByrOnwerAlchemy"; import { useRouter } from "next/navigation"; import useUpdateSearchParams from "@/hooks/useUpdateSearchParams"; import EmptyPage from "../EmptyPage"; import BackArrow from "../icon/BackArrow"; import { useTranslation } from "@/app/i18n/client"; function AssetManagement({ lng }: { lng: string }) { const { t } = useTranslation(lng, "assets"); const [allAssetTypes, setAllAssetTypes] = useState<any>([]); const [typeSelected, setTypeSelected] = useState<any>(); const router = useRouter(); const { updateSearchParams, searchParams } = useUpdateSearchParams(); const pageKey = searchParams.get("pageKey"); const { address } = useAccount(); const { isLogin } = useAuthContext(); useQuery( ["getAssetTypes"], async () => { const response = await getAssetTypes(); setAllAssetTypes([{ typeKey: "all", typeName: "All" }, ...response.data.data]); setTypeSelected({ typeKey: "all", typeName: "All" }); return response.data; }, { enabled: isLogin, } ); const { data: userNfts } = useQuery( ["getUserNfts", address, isLogin, typeSelected, allAssetTypes, pageKey], async () => { let contractAddresses: string[] = []; if (typeSelected.typeKey == "all") { contractAddresses = allAssetTypes.filter((type) => type.typeKey !== "all").map((type) => type.contractAddress); } else { contractAddresses = [typeSelected.contractAddress]; } const alchemyOptions: GetNftsForOwnerOptions = { pageSize: 10, contractAddresses, }; if (pageKey) { alchemyOptions.pageKey = pageKey; } const response = await getNftsByrOnwerAlchemy(address, alchemyOptions); return response; }, { enabled: isLogin && !!address && !!typeSelected && !!allAssetTypes, } ); const handleClickNextBtn = () => { if (userNfts.pageKey) { updateSearchParams("pageKey", userNfts.pageKey); } }; const handleClickBackBtn = () => { if (pageKey) { router.back(); } }; return ( <div className="max-w-maxContent mx-auto"> <Title>{t("title")}</Title> <div className="flex w-full items-center pb-5 gap-2 justify-between"> <div> <FilterDropDown listDropdown={allAssetTypes} showing={typeSelected} setShowing={setTypeSelected} title={t("type-filter")} textDefault={"All"} className="w-full pt-2" /> <p className="my-3 font-semibold dark:text-textDark text-base"> {t("total")}: {userNfts?.totalCount} </p> <div className="flex items-center gap-4"> <button onClick={handleClickBackBtn} className="flex border rounded-md disabled:opacity-50 disabled:cursor-not-allowed gap-2 px-2 bg-gray-300 whitespace-nowrap items-center" disabled={!pageKey} > {t("back-button")} <BackArrow /> </button> <button onClick={handleClickNextBtn} className="flex gap-2 border rounded-md px-2 bg-gray-300 disabled:opacity-50 disabled:cursor-not-allowed items-center" disabled={!userNfts?.pageKey} > <BackArrow className="rotate-180" /> {t("next-button")} </button> </div> </div> </div> {userNfts?.totalCount === 0 && ( <EmptyPage title={t("empty-notification")} classNameContainer="min-h-[calc(100vh-80px-16px-52px-94px-130px-60px)]" className="w-[300px] md:w-[450px] h-[360px] justify-around" description={t("description-empty")} firstBtn={t("depository")} hrefFirstBtn="/depositories" secondBtn="Marketplace" /> )} {userNfts && userNfts?.totalCount !== 0 && ( <div> <div className="md:grid justify-between md:grid-cols-5 flex flex-col gap-5 pb-6"> {userNfts?.ownedNfts.map((nft, index) => ( <AssetCard data={nft} key={`${nft.tokenId}-${index}`} /> ))} </div> </div> )} {!userNfts && ( <div> <div className="md:grid justify-between md:grid-cols-5 flex flex-col gap-5 pb-6"> {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((i) => ( <LoadingNftCard key={i} /> ))} </div> </div> )} </div> ); } export default AssetManagement; function LoadingNftCard() { return ( <div className="smooth-transform"> <div className="min-w-[98px] aspect-square w-full skeleton-loading rounded-t-md relative cursor-pointer"></div> <div className="w-full h-[60px] min-w-[98px] p-[10px] bg-white dark:bg-bgDark shadow-2xl rounded-b-md"> <div className="w-full skeleton-loading h-4 rounded-sm"></div> <div className="w-1/2 skeleton-loading h-4 mt-2 rounded-sm"></div> </div> </div> ); }
import { Box, Container, Paper, Tab, Tabs, styled } from "@mui/material"; import { useState } from "react"; import Stake from "../components/stake"; import UnStake from "../components/unstake"; interface TabPanelProps { children?: React.ReactNode; index: number; value: number; } function a11yProps(index: number) { return { id: `simple-tab-${index}`, "aria-controls": `simple-tabpanel-${index}`, }; } function TabPanel(props: TabPanelProps) { const { children, value, index, ...other } = props; return ( <div role="tabpanel" hidden={value !== index} id={`simple-tabpanel-${index}`} aria-labelledby={`simple-tab-${index}`} {...other} > {value === index && <Box sx={{ p: 3 }}>{children}</Box>} </div> ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * This is a starter component and can be deleted. * * * * * * * * * * * * * * * * * * * * * * * * * * * * Delete this file and get started with your project! * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ const style = ( <style dangerouslySetInnerHTML={{ __html: ` html { -webkit-text-size-adjust: 100%; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; line-height: 1.5; tab-size: 4; scroll-behavior: smooth; } body { font-family: inherit; line-height: inherit; margin: 0; } h1, h2, p, pre { margin: 0; } *, ::before, ::after { box-sizing: border-box; border-width: 0; border-style: solid; border-color: currentColor; } h1, h2 { font-size: inherit; font-weight: inherit; } a { color: inherit; text-decoration: inherit; } pre { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace; } svg { display: block; vertical-align: middle; shape-rendering: auto; text-rendering: optimizeLegibility; } pre { background-color: rgba(55, 65, 81, 1); border-radius: 0.25rem; color: rgba(229, 231, 235, 1); font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace; overflow: scroll; padding: 0.5rem 0.75rem; } .shadow { box-shadow: 0 0 #0000, 0 0 #0000, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); } .rounded { border-radius: 1.5rem; } .wrapper { width: 100%; } .container { margin-left: auto; margin-right: auto; max-width: 768px; padding-bottom: 3rem; padding-left: 1rem; padding-right: 1rem; color: rgba(55, 65, 81, 1); width: 100%; } #welcome { margin-top: 2.5rem; } #welcome h1 { font-size: 3rem; font-weight: 500; letter-spacing: -0.025em; line-height: 1; } #welcome span { display: block; font-size: 1.875rem; font-weight: 300; line-height: 2.25rem; margin-bottom: 0.5rem; } #hero { align-items: center; background-color: hsla(214, 62%, 21%, 1); border: none; box-sizing: border-box; color: rgba(55, 65, 81, 1); display: grid; grid-template-columns: 1fr; margin-top: 3.5rem; } #hero .text-container { color: rgba(255, 255, 255, 1); padding: 3rem 2rem; } #hero .text-container h2 { font-size: 1.5rem; line-height: 2rem; position: relative; } #hero .text-container h2 svg { color: hsla(162, 47%, 50%, 1); height: 2rem; left: -0.25rem; position: absolute; top: 0; width: 2rem; } #hero .text-container h2 span { margin-left: 2.5rem; } #hero .text-container a { background-color: rgba(255, 255, 255, 1); border-radius: 0.75rem; color: rgba(55, 65, 81, 1); display: inline-block; margin-top: 1.5rem; padding: 1rem 2rem; text-decoration: inherit; } #hero .logo-container { display: none; justify-content: center; padding-left: 2rem; padding-right: 2rem; } #hero .logo-container svg { color: rgba(255, 255, 255, 1); width: 66.666667%; } #middle-content { align-items: flex-start; display: grid; gap: 4rem; grid-template-columns: 1fr; margin-top: 3.5rem; } #learning-materials { padding: 2.5rem 2rem; } #learning-materials h2 { font-weight: 500; font-size: 1.25rem; letter-spacing: -0.025em; line-height: 1.75rem; padding-left: 1rem; padding-right: 1rem; } .list-item-link { align-items: center; border-radius: 0.75rem; display: flex; margin-top: 1rem; padding: 1rem; transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; width: 100%; } .list-item-link svg:first-child { margin-right: 1rem; height: 1.5rem; transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; width: 1.5rem; } .list-item-link > span { flex-grow: 1; font-weight: 400; transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .list-item-link > span > span { color: rgba(107, 114, 128, 1); display: block; flex-grow: 1; font-size: 0.75rem; font-weight: 300; line-height: 1rem; transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .list-item-link svg:last-child { height: 1rem; transition-property: all; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; width: 1rem; } .list-item-link:hover { color: rgba(255, 255, 255, 1); background-color: hsla(162, 47%, 50%, 1); } .list-item-link:hover > span {} .list-item-link:hover > span > span { color: rgba(243, 244, 246, 1); } .list-item-link:hover svg:last-child { transform: translateX(0.25rem); } #other-links {} .button-pill { padding: 1.5rem 2rem; margin-bottom: 2rem; transition-duration: 300ms; transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); align-items: center; display: flex; } .button-pill svg { transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; flex-shrink: 0; width: 3rem; } .button-pill > span { letter-spacing: -0.025em; font-weight: 400; font-size: 1.125rem; line-height: 1.75rem; padding-left: 1rem; padding-right: 1rem; } .button-pill span span { display: block; font-size: 0.875rem; font-weight: 300; line-height: 1.25rem; } .button-pill:hover svg, .button-pill:hover { color: rgba(255, 255, 255, 1) !important; } .nx-console:hover { background-color: rgba(0, 122, 204, 1); } .nx-console svg { color: rgba(0, 122, 204, 1); } #nx-repo:hover { background-color: rgba(24, 23, 23, 1); } #nx-repo svg { color: rgba(24, 23, 23, 1); } #nx-cloud { margin-bottom: 2rem; margin-top: 2rem; padding: 2.5rem 2rem; } #nx-cloud > div { align-items: center; display: flex; } #nx-cloud > div svg { border-radius: 0.375rem; flex-shrink: 0; width: 3rem; } #nx-cloud > div h2 { font-size: 1.125rem; font-weight: 400; letter-spacing: -0.025em; line-height: 1.75rem; padding-left: 1rem; padding-right: 1rem; } #nx-cloud > div h2 span { display: block; font-size: 0.875rem; font-weight: 300; line-height: 1.25rem; } #nx-cloud p { font-size: 1rem; line-height: 1.5rem; margin-top: 1rem; } #nx-cloud pre { margin-top: 1rem; } #nx-cloud a { color: rgba(107, 114, 128, 1); display: block; font-size: 0.875rem; line-height: 1.25rem; margin-top: 1.5rem; text-align: right; } #nx-cloud a:hover { text-decoration: underline; } #commands { padding: 2.5rem 2rem; margin-top: 3.5rem; } #commands h2 { font-size: 1.25rem; font-weight: 400; letter-spacing: -0.025em; line-height: 1.75rem; padding-left: 1rem; padding-right: 1rem; } #commands p { font-size: 1rem; font-weight: 300; line-height: 1.5rem; margin-top: 1rem; padding-left: 1rem; padding-right: 1rem; } details { align-items: center; display: flex; margin-top: 1rem; padding-left: 1rem; padding-right: 1rem; width: 100%; } details pre > span { color: rgba(181, 181, 181, 1); display: block; } summary { border-radius: 0.5rem; display: flex; font-weight: 400; padding: 0.5rem; cursor: pointer; transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } summary:hover { background-color: rgba(243, 244, 246, 1); } summary svg { height: 1.5rem; margin-right: 1rem; width: 1.5rem; } #love { color: rgba(107, 114, 128, 1); font-size: 0.875rem; line-height: 1.25rem; margin-top: 3.5rem; opacity: 0.6; text-align: center; } #love svg { color: rgba(252, 165, 165, 1); width: 1.25rem; height: 1.25rem; display: inline; margin-top: -0.25rem; } @media screen and (min-width: 768px) { #hero { grid-template-columns: repeat(2, minmax(0, 1fr)); } #hero .logo-container { display: flex; } #middle-content { grid-template-columns: repeat(2, minmax(0, 1fr)); } } `, }} /> ); const InitSection = styled("section")(({ theme }) => ({ display: "flex", flexDirection: "column", flex: 1, alignItems: "center", justifyContent: "center", minHeight: "500px", paddingBottom: 50, paddingTop: 50, backgroundColor: "#FEFEF0", paddingLeft: 16, paddingRight: 16, [theme.breakpoints.up("lg")]: { minHeight: "592px", paddingLeft: 0, paddingRight: 0, }, })); export function NxWelcome({ title }: { title: string }) { const [value, setValue] = useState<number>(0); const handleChange = (event: React.SyntheticEvent, newValue: number) => { setValue(newValue); }; return ( <> {style} <InitSection> <Container maxWidth="sm"> <Paper elevation={24}> <Box sx={{ borderBottom: 1, borderColor: "divider" }}> <Tabs value={value} onChange={handleChange} aria-label="basic tabs example" centered variant="fullWidth" > <Tab label="Stake" {...a11yProps(0)} /> <Tab label="Unstake" {...a11yProps(1)} /> </Tabs> </Box> <Box> <Box> <TabPanel value={value} index={0}> <Stake /> </TabPanel> <TabPanel value={value} index={1}> <UnStake /> </TabPanel> </Box> </Box> </Paper> </Container> </InitSection> </> ); } export default NxWelcome;
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AuthGuard } from './guards/auth.guard'; import { HomeComponent } from './home/home.component'; import { BuscaComponent } from './busca/busca.component'; import { ArtistaComponent } from './artista/artista.component'; import { HistoricoComponent } from './historico/historico.component'; import { LoginComponent } from './login/login.component'; import { LogoutComponent } from './logout/logout.component'; const routes: Routes = [ { path: '', component: HomeComponent, canActivate : [AuthGuard] }, { path: 'busca', component: BuscaComponent, canActivate : [AuthGuard] }, { path: 'artista/:id', component: ArtistaComponent, canActivate : [AuthGuard] }, { path: 'historico', component: HistoricoComponent, canActivate : [AuthGuard] }, { path: 'login', component: LoginComponent }, { path: 'logout', component: LogoutComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } export const routingComponents = [HomeComponent, BuscaComponent, ArtistaComponent, HistoricoComponent, LoginComponent, LogoutComponent];
// // TestAppearView.swift // Mamaste // // Created by Jeremy Raymond on 15/11/23. // import SwiftUI struct TestAppearView: View { @State var selected: Color = .red let colors: [Color] = [.red, .blue, .green] var body: some View { VStack { Picker("Color Picker", selection: $selected) { ForEach(colors, id: \.self) { color in Text(color.description).tag(color) } } .pickerStyle(.segmented) Text(selected.description) .font(.largeTitle) // .contentTransition(.opacity) // .contentTransition(.identity) .contentTransition(.numericText()) LazyHStack { ForEach(colors, id: \.self) { color in if selected == color { Rectangle() .fill(color) .clipShape(.rect(cornerRadius: 12)) .frame(width: 360) // .transition(.opacity) .transition(.opacity.combined(with: .move(edge: .bottom))) // .transition(.move(edge: .bottom)) } } } } .padding() .animation(.easeInOut, value: selected) } } #Preview { TestAppearView() }