instruction
stringlengths
0
30k
I'm using a WDM driver project in VS 2022. In case of the following code snippet: extern "C" NTSTATUS NTAPI DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) { DbgPrint("v=%s", 123); return STATUS_SUCCESS; } The `DbgPrint` has an incorrect `%s` specifier, which will cause that driver to crash. The VS editor can see it and shows me an underlined [warning C6067][1]: [![enter image description here][2]][2] But when I compile it, that warning is not shown and the project compiles successfully, even though the settings for my project are set to "Level4 (/W4)". Any idea how to enable that warning C6067 during compilation? [1]: https://learn.microsoft.com/en-us/cpp/code-quality/c6067?view=msvc-170 [2]: https://i.stack.imgur.com/eVEuR.png
How to enable warning C6067 during (WDM) Windows driver compilation in VS 2022?
|c++|visual-studio-2022|wdm|windows-driver|
You also can use validator with some actions on raw data for field. from pydantic import BaseModel, UUID4, SecretStr, EmailStr, constr, validator class UserCreate(BaseModel): email: EmailStr password: SecretStr first_name: str last_name: str @validator("email", "password", "first_name", "last_name", pre=True) def strip_whitespaces(cls, v: str) -> str: return v.strip()
Here’s an example of what it might look like: ``` add_filter( 'login_redirect', 'custom_login_redirect', 10, 3 ); function custom_login_redirect( $url, $request, $user ) { if ( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) { if ( $user->has_cap( 'administrator' ) ) { $url = home_url(); } } return $url; } ``` Note: You have to put this code into your functions.php
I have the following entities ``` @Builder @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Entity(name = "Employee") @Table(schema = "core", name = "employee") public class EmployeeEntity { @Id @SequenceGenerator(schema = "core", name = Sequence.EMPLOYEE_ID_SEQ, sequenceName = Sequence.EMPLOYEE_ID_SEQ) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Sequence.EMPLOYEE_ID_SEQ) @Column(name = "id", nullable = false, updatable = false) private Integer id; @Column(name = "person_id", nullable = false) private Integer personId; @Column(name = "user_account_id") private Integer userAccountId; @Column(name = "employee_type_id", nullable = false) private Integer employeeTypeId; @OneToOne(fetch = FetchType.EAGER) @JoinColumn(name = "person_id", insertable = false, updatable = false) private PersonEntity person; @ManyToOne(fetch = FetchType.EAGER, targetEntity = EmployeeTypeEntity.class) @JoinColumn(name = "employee_type_id", insertable = false, updatable = false) private EmployeeTypeEntity employeeType; } ``` and ``` @Builder @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Entity(name = "EmployeeType") @Table(schema = "type", name = "employee_type") @Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_ONLY) public class EmployeeTypeEntity implements TypeTable { @Id @Column(name = "id", nullable = false, updatable = false) private Integer id; @Column(name = "name", length = 100, nullable = false) private String name; @Column(name = "abbreviation", length = 10) private String abbreviation; @Column(name = "description", length = 100) private String description; @Builder.Default @Enumerated(EnumType.STRING) @Column(name = "active", length = 1, nullable = false) private Active active = Active.Y; @OneToMany(fetch = FetchType.LAZY, mappedBy = "employeeType", targetEntity = EmployeeEntity.class) private List<EmployeeEntity> employees; } ``` Im using JPA Hibernate with panache in Quarkus and Im using the following method ``` @Override public Pageable<EmployeeEntity> findAll(PageRequest request) { var query = employeePanacheRepository.findAll( Sort.by(request.getSortBy(), Direction.valueOf(request.getSortDirection())) ) .page(Page.of(request.getPage(), request.getSize())); return Pageable.<EmployeeEntity>builder() .content(query.list()) .totalPages(query.pageCount()) .hasPrevious(query.hasPreviousPage()) .hasNext(query.hasNextPage()) .build(); } ``` The question here is why when ```query.list()``` is call Hibernate makes two Select ``` Hibernate: select ee1_0.id, ee1_0.employee_type_id, ee1_0.person_id, ee1_0.user_account_id from core.employee ee1_0 order by ee1_0.id offset ? rows fetch first ? rows only Hibernate: select ete1_0.id, ete1_0.abbreviation, ete1_0.active, ete1_0.description, ete1_0.name from type.employee_type ete1_0 where ete1_0.id = any (?) ``` And things become more confusing for me when i have this other entity which is parent of EmployeeEntity and get all types table in one select ``` @Builder @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Entity(name = "Person") @Table(schema = "core", name = "person") public class PersonEntity { @Id @SequenceGenerator(schema = "core", name = Sequence.PERSON_ID_SEQ, sequenceName = Sequence.PERSON_ID_SEQ) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Sequence.PERSON_ID_SEQ) @Column(name = "id", nullable = false, updatable = false) private Integer id; @Column(name = "first_name", length = 100, nullable = false) private String firstName; @Column(name = "last_name", length = 100, nullable = false) private String lastName; @Column(name = "document_number", length = 50, nullable = false) private String documentNumber; @Column(name = "document_type_id", nullable = false) private Integer documentTypeId; @Column(name = "gender_type_id", nullable = false) private Integer genderTypeId; @Column(name = "birth_date", nullable = false) private LocalDate birthDate; @Column(name = "email", nullable = false) private String email; @Column(name = "mobile_number", nullable = false) private String mobileNumber; @UpdateTimestamp @Column(name = "update_date", nullable = false) private LocalDateTime updateDate; @CreationTimestamp @Column(name = "create_date", nullable = false) private LocalDateTime createDate; @Builder.Default @Enumerated(EnumType.STRING) @Column(name = "active", length = 1, nullable = false) private Active active = Active.Y; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "document_type_id", insertable = false, updatable = false) private DocumentTypeEntity documentType; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "gender_type_id", insertable = false, updatable = false) private GenderTypeEntity genderType; } ``` ``` Hibernate: select pe1_0.id, pe1_0.active, pe1_0.birth_date, pe1_0.create_date, pe1_0.document_number, dt1_0.id, dt1_0.abbreviation, dt1_0.active, dt1_0.description, dt1_0.name, pe1_0.document_type_id, pe1_0.email, pe1_0.first_name, gt1_0.id, gt1_0.abbreviation, gt1_0.active, gt1_0.description, gt1_0.name, pe1_0.gender_type_id, pe1_0.last_name, pe1_0.mobile_number, pe1_0.update_date from core.person pe1_0 left join type.document_type dt1_0 on dt1_0.id=pe1_0.document_type_id left join type.gender_type gt1_0 on gt1_0.id=pe1_0.gender_type_id where pe1_0.id = any (?) ``` Someone can explain to me why this strange behavior with EmployeeEntity but no with PersonEntity
Why does Hibernate execute two SELECT queries instead of one when using @ManyToOne(fetch = FetchType.EAGER)
|java|hibernate|jpa|quarkus|quarkus-panache|
I have a dataset with monthly sales data by brand. I have a measure which calculates market share %. I want to add an additional measure which calculates the growth in market share % between the most recent month and the second most recent month. Is this possible
Market share growth versus last month, last year
|date|powerbi|
- <kbd>Ctrl</kbd>+<kbd>H</kbd> - Find what: `,[^,\r\n]$` - Replace with: `LEAVE EMPTY` - **TICK** *Wrap around* - **SELECT** *Regular expression* - <kbd>Replace all</kbd> `\h+` stands for 1 or more horizontal spaces.
Is there any way to tell Notepad please do this... FROM THIS 15.63387,46.42795,1,130,1,210,Sele pri Polskavi TO THIS 15.63387,46.42795,1,130,1,210 I would like to remove everything after the last , So that in the end it looks like 15.63387,46.42795,1,130,1,210 Thing is when I try it using Notepad++ with the command FIND = [[:alpha:]] or [\u\l] REPLACE = (leave it empty) It removed all alphabetical charachters but it leaves , signs at the end, which I can remove with .{1}$ but for some reason some lines have empty spaces after...some one or more and this command does not work since notepad++ sees empty space as a character and therefore does not remove all the , signs at the end of each line.
I'm going through [this][1] azure exercises and have a question regarding this statement: > From the All resources view in the Azure portal, go to the Overview page of the production slot of the web app. I have 2 deployment slots in my newly created test app services. Creating a `training-Staging` slot is the only configuration change I did for this app settings.: Name | Status | App service plan | Traffic % _________________________________________________________________________ training (Production) | Running | ASP-Training-a8b0 | 100 training-Staging | Running | ASP-Training-a8b0 | 0 However in the `All Resources` windows, I don't see a production slot (created by default) slot, only `training-Staging`: Name | Type | Resource group | Location | Subscription -------------------------------------------------------------------------------------------------------------------- Application Insights Smart Detection Action group Training Global ... ASP-Training-a8b0 App Service plan Training East US ... Training App Service Training East US ... Training Application Insights Training East US ... Staging (training/Staging) App Service (Slot) training East US ... There is no link or button to go into configuration for production slot in `Deployment slots` configuration too (but such link exists for staging slot). Where can I find the production slot resource? [1]: https://learn.microsoft.com/en-us/training/modules/stage-deploy-app-service-deployment-slots/5-exercise-deploy-a-web-app-by-using-deployment-slots
Application settings for production deployment slot in Azure App Services
Since mod_dav_svn.so and mod_authz_svn.so were not present in SVN (TortoiseSVN), I downloaded the files from https://github.com/nono303/win-svn/tree/master/vc15/x64 and moved them to "C:\Apache24\modules". I then added the following lines to the httpd.conf file in Apache24: `# Subversion Configuration LoadModule dav_svn_module modules/mod_dav_svn.so LoadModule authz_svn_module modules/mod_authz_svn.so` However, upon doing so, the service failed to start. Subsequently, the following error occurred: `httpd.exe: Syntax error on line 188 of C:/Apache24/conf/httpd.conf: Cannot load modules/mod_dav_svn.so into server: \x8ew\x92\xe8\x82\xb3\x82\xea\x82\xbd\x83\x82\x83W\x83\x85\x81[\x83\x8b\x82\xaa\x8c\xa9\x82\xc2\x82\xa9\x82\xe8\x82\xdc\x82\xb9\x82\xf1\x81` I am using Windows 11 with x64 architecture. These comments are enabled: `LoadModule dav_module modules/mod_dav.so LoadModule dav_fs_module modules/mod_dav_fs.so `
Cannot load modules/mod_dav_svn.so into server
|windows|apache|svn|module|webdav|
null
`flipped_image = image[:, ::-1, :]`
I'm using React Native Expo, and I want to open the default phone Contacts app. **On Android, I used:** await Linking.openURL("content://contacts/people/"); and that's worked. On iOS that doesn't work. **I tried:** await Linking.openURL('contacts://'); but it doesn't work. How do I do that on IOS? I want to open the contacts app on the iPhone only. Not getting contact data from the device through my app as suggested in some answers.
```python T = TypeVar("T", bound=str) def foo(a: T, b: T) -> T: return a + b print(foo("1", "2")) ``` mypy: `error: Incompatible return value type (got "str", expected "T") [return-value]` I dont understand how to fix this problem(using bound).
|python|mypy|typing|
I'm trying to populate a 2D array of objects and get a result like this example: ``` Guid guid = Guid.NewGuid(); var data = new[] { new object[] { 22, "cust1_fname","cust1_lname",guid }, new object[] { 23, "cust2_fname","cust2_lname",guid }, new object[] { 24, "cust3_fname","cust3_lname",guid }, }; ``` [![enter image description here][1]][1] I tried this way: [![enter image description here][2]][2] But the objects are not added as direct children under the 2D array as in the first example [1]: https://i.stack.imgur.com/IyIVn.png [2]: https://i.stack.imgur.com/nu6Fp.png
You can scroll to a particular view in a `ScrollView` by using its id. This can either be done using a `ScrollViewReader` (as suggested in a comment) or by using a `.scrollPosition` modifier on the `ScrollView` (requires iOS 17). Here is an example of how it can be done using `.scrollPosition`. - The images used here are just system images (symbols). The symbol name is used as its id. - The images in the scrolled view all have different heights. This makes it difficult for a `LazyVStack` to predict the scroll distance correctly, so a `VStack` is used instead. But if your images all have the same height then you could try using a `LazyVStack`. - Set the target to scroll to in `.onAppear`. - If you use `.center` as the anchor for scrolling then images in the middle of the list should be centered vertically in the display. ```swift struct ContentView: View { private let imageNames = ["hare", "tortoise", "dog", "cat", "lizard", "bird", "ant", "ladybug", "fossil.shell", "fish"] private let threeColumnGrid: [GridItem] = [.init(), .init(), .init()] var body: some View { NavigationStack { LazyVGrid(columns: threeColumnGrid, alignment: .center, spacing: 20) { ForEach(imageNames, id: \.self) { imageName in NavigationLink(destination: ScrollPostView(imageNames: imageNames, selectedName: imageName)){ Image(systemName: imageName) .resizable() .scaledToFit() .padding() .frame(maxHeight: 100) .background(.yellow) .clipShape(RoundedRectangle(cornerRadius: 15)) } .overlay( RoundedRectangle(cornerRadius: 15) .stroke(Color.black, lineWidth: 2) ) } } } } } struct ScrollPostView: View { let imageNames: [String] let selectedName: String @State private var scrollPosition: String? var body: some View { ScrollView { VStack { ForEach(imageNames, id: \.self) { imageName in Image(systemName: imageName) .resizable() .scaledToFit() .padding() .background(selectedName == imageName ? .orange : .yellow) .clipShape(RoundedRectangle(cornerRadius: 15)) } } .scrollTargetLayout() } .scrollPosition(id: $scrollPosition, anchor: .center) .onAppear { scrollPosition = selectedName } } } ``` ![Animation](https://i.stack.imgur.com/ZLfpN.gif)
i built an AR project using Unity 2022.3.22f1 and Vuforia 10.22, the app is working just fine in the my pc using webcam but after building it and Install it in my Samsung A21S (that have android 12) the camera permission pop up after allows it the app gose black screen any help please i've tried many tricks that I found in the internet but still not working
unity + Vuforia balck screen in android AR app
|android|android-studio|unity-game-engine|augmented-reality|vuforia|
null
For me, using a .json file rather than a .js file for .eslintrc allowed `eslint .` to operate as it should in a module-based project. Failed attempts (.eslintrc.js): ```js export default { // also tried: export { // also tried: module.exports = { "env": { "browser": true, "es2021": true }, "extends": "eslint:recommended", "overrides": [ { "env": { "node": true }, "files": [ ".eslintrc.{js,cjs}" ], "parserOptions": { "sourceType": "script" } } ], "parserOptions": { "ecmaVersion": "latest", "sourceType": "module" }, "rules": { } } ``` All of the above trigger: ```none Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/.eslintrc.js from /home/me/.nvm/versions/node/v20.11.1/lib/node_modules/eslint/node_modules/@eslint/eslintrc/dist/eslintrc.cjs not supported. ``` This works (rename to .eslintrc.json, remove the `export` syntax and ensure valid JSON): ```json { "env": { // ... same content above onward ... } ``` package.json: ```json { "type": "module", "devDependencies": { "eslint": "^8.57.0" } } ``` Removing `"type": "module"` from the package.json and using CJS works, but my project requires `"type": "module"`, so this wasn't a good option. There's probably a more direct solution, but [the accepted answer](https://stackoverflow.com/a/70458446/6243352) didn't seem to help in my case (or I'm doing something wrong).
I have been trying to watch my tests WITH test coverage without much of a success. My best attempt sofar is to install packaeges `pip install pytest pytest-watch pytest-cov` and run on separate terminals or tabs these commands, below Watch tests: `ptw --quiet --spool 200 --clear --nobeep --config pytest.ini --ext=.py --onfail="echo Tests failed, fix the issues" -v` Coverage: coverage run --rcfile=.coveragerc -m pytest && coverage report --omit="tests/*,src/main.py,*/__init__.py,*/constants.py" --show-missing An alternative to this approach is the shell script below. To run it, run command `chmod +x watch.sh && ./watch` ``` #!/bin/bash clear while true; do coverage run --rcfile=.coveragerc -m pytest coverage report --omit="tests/*,src/main.py,*/__init__.py,*/constants.py" --show-missing sleep 5 # Adjust delay between test runs if needed clear done ``` It renders slower compared to command run `ptw`, but outputs exactly what I want. Would you please, provide maybe more effective alternatives than mine? Thanks. :)
Alternatives to pytest-watch on python unit test with pytest
|pytest|pytest-cov|
null
|python|matplotlib|draw|
null
I think this should always work: ```go string(norm.NFD.String(char)[0]) ```
Perform an inner-[`merge`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html): ``` index = df1.reset_index().merge(df2)['index'].tolist() ``` Or, if you have more columns but only want to consider a/b: ``` index = df1.reset_index().merge(df2, on=['a', 'b'])['index'].tolist() ``` If you can have duplicated combinations of a/b in either DataFrame: ``` index = df1.reset_index().merge(df2)['index'].unique().tolist() ``` Output: `[1, 3]`
I think you just need to change how you call pagination, if your code sample is accurate: `page = RawQuerySetPaginator(queryset, 15)` Pagination should have no issue with _most_ raw queries. Ordering and searching are, of course, an issue. ```py class MyPagination(PageNumberPagination): page_size = 1 qs = User.objects.raw("select email from user order by id desc") paginator = MyPagination() # page is a list of user objects here page = paginator.paginate_queryset(qs, request=req) # generate the list of dict objects for output serialized_data = UserSerializer(page, many=True).data # create a Response(), with the `count` and next/prev links output = paginator.get_paginated_response(serialized_data) ``` Paginators are confusing, since they internally use a django paginator, and thus have a page, which has a paginator, which does the `.count`. How that does it I don't know, it's magic. `RawQuerySet` does not have a `count()` method but this still works somehow. ``` print(f"total records => {paginator.page.paginator.count}") ``` It may help you in testing, so here is the snippet I use to generate fake requests - you can't just use the output of the APIRequestFactory directly. ``` def make_request(): from rest_framework.test import APIRequestFactory from rest_framework.request import Request from rest_framework.parsers import JSONParser req = APIRequestFactory().get("/", {"page": "1"}) return Request(req, parsers=[JSONParser()]) ```
I aim to select full name of employees that either have no boss or their boss lives on a street that contains letter 'o' or letter 'u'. Then, I want to list them in descending order by full name. The problem comes in the ordering, because by queries that I think are the same I get different answers. When I introduce in MySQL Workbench the following command: ``` select concat(surnames,', ',name) as 'Full Name', street from employee where boss is null or (boss is not null and (street like'%u%' or steet like '%o%')) order by concat(surnames,', ',name) desc; ``` By this command I get the answer I want, that is: Full Name Street Suárez García, Juan Juan Valdés 25 Sarasola Goñi, Vanesa Austria Requena Santos, Pilar Alicante 3 Puertas Elorza, Marta Lope de Vega 3 Piedra Trujillo, Ramón Madre Vedruna 21 Narváez Alonso, Alba Vara de Rey 22 Gómez de la Sierra, Francisco Loscertales 9 Chávarri Díez, Lorea Arrieta Alcorta, Kepa Urbieta 33 Álvarez González, Ana Graus 19 But when I change the ordering by another that looks the same to me: ``` select concat(surnames,', ',name) as 'Full Name', street from employee where boss is null or (boss is not null and (street like'%u%' or steet like '%o%')) order by 'FullName' desc; ``` I get a wrong answer that looks like: Full Name Street Suárez García, Juan Juan Valdés 25 Puertas Elorza, Marta Lope de Vega 3 Chávarri Díez, Lorea Narváez Alonso, Alba Vara de Rey 22 Gómez de la Sierra, Francisco Loscertales 9 Piedra Trujillo, Ramón Madre Vedruna 21 Sarasola Goñi, Vanesa Austria Requena Santos, Pilar Alicante 3 Álvarez González, Ana Graus 19 Arrieta Alcorta, Kepa Urbieta 33 Can somebody tell me what's going on here?
Perhaps the easiest thing to do is to save the next group that would be generated. Then a future run can rebuild a new product instance that starts with that group: def restart_product_at(start_group, *pools): n = 0 # Position of the start_group for element, pool in zip(start_group, pools): n *= len(pool) n += pool.index(element) p = product(*pools) # New fresh iterator next(islice(p, n, n), None) # Advance n steps ahead return p For example: >>> p = restart_product_at(('c', 'e', 'm'), 'abcd', 'efg', 'hijklm') >>> next(p) ('c', 'e', 'm') >>> next(p) ('c', 'f', 'h') >>> next(p) ('c', 'f', 'i')
I'm attempting to implement the case change feature available in Microsoft Word with Shift + F3 into a TinyMCE React editor. The problem I'm running into is the last part where it should keep the same text selected/highlighted. The below works fine, as long as I haven't highlighted the last character of a node. If I have selected the end of a line, I get an error: `Uncaught DOMException: Index or size is negative or greater than the allowed amount` So far I have the following: ```typescript const handleCaseChange = (ed: Editor) => { ed.on("keydown", (event: KeyboardEvent) => { if (event.shiftKey && event.key === "F3") { event.preventDefault(); const selection = ed.selection.getSel(); const selectedText = selection?.toString(); const startOffset = selection?.getRangeAt(0).startOffset; const endOffset = selection?.getRangeAt(0).endOffset; if (selectedText !== undefined && selectedText.length > 0) { let transformedText; if (selectedText === selectedText.toUpperCase()) { transformedText = selectedText.toLowerCase(); } else if (selectedText === selectedText.toLowerCase()) { transformedText = capitalizeEachWord(selectedText); } else { transformedText = selectedText.toUpperCase(); } ed.selection.setContent(transformedText); const range = ed.getDoc().createRange(); // This is what's currently erroring range.setStart(selection.anchorNode, startOffset); if (endOffset === selection?.anchorNode?.textContent?.length) { range.setEndAfter(selection.anchorNode); } else { range.setEnd(selection.anchorNode, endOffset); } selection.removeAllRanges(); selection.addRange(range); } } } } const capitalizeEachWord = (str: String) => str.replace(/\b\w/g, (char: string) => char.toUpperCase()); ``` What else could I try in the `range.setStart` to get this to work correctly?
I am using Svelte with [Ultralight][1], communication is handled with JavaScriptCore so Ultralight set / call functions on the global javascript object (which I believe is window). Now I want to call these functions in my svelte app, but I am using modules and so I can't set / use global functions. So for now I am stuck to something like this : `CppInterop.js` module : import { notification } from "./lib/store"; // Expose store globally window.store = { notification } // Expose the C++ functions export default { test: () => window.Test() } `cpp.js` that I include directly in my html file with `<script src="/cpp.js"></script>` : // From JS to C++ window.Test = Test; // From C++ to JS function notification(message, type) { window.store.notification.notify(message, type); } Interop doesn't seems to work then I try to access the functions via `window` so that's why I do `window.Test = Test`. What I would like is to call / define global function while still having access to modules (to call my own functions and stores), is that possible ? Here is how the C++ set the interop functions : JSValueRef JavascriptInterop::execute(const JSContextRef &ctx, const std::string &functionName, const std::vector<JSValueRef> &args) { JSObject global = JSGlobalObject(); JSValueRef exception = nullptr; JSValueRef function = global[functionName.c_str()]; if (!JSValueIsObject(ctx, function)) { throw std::runtime_error("Function not found"); } JSObject functionObj = JSValueToObject(ctx, function, &exception); if (exception) { throw std::runtime_error("Function not found"); } JSValueRef result = JSObjectCallAsFunction(ctx, functionObj, nullptr, args.size(), args.data(), &exception); // Handle any exceptions that were thrown. if (exception) { // Get exception description return result; } void UIHandler::register_callbacks() { RefPtr<JSContext> context = _view->LockJSContext(); SetJSContext(context->ctx()); JSObject global = JSGlobalObject(); global["Test"] = BindJSCallbackWithRetval(&UIHandler::Test); } [1]: https://ultralig.ht/
```r library(tidyverse) library(shiny) library(DT) ui <- sidebarLayout( sidebarPanel( numericInput("price", label = "Price ($)", value = 4.31, min = 0), numericInput("sqft", label = "Average Square Footage", value = 4400, min = 0), numericInput("delivery", label = "Delivery Cost", value = 2.60, min = 0), numericInput("avg_use", label = "Average Annual Use", value = 88000, min = 0), numericInput("turf", label = "Percentage (%)", value = 0, min = 0) ), mainPanel( DTOutput("table1") ) ) dat00 <- data.frame( behavior = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"), average = c(2541, 11913, 12707, 16995, 23668, 2859, 2224, 10483, 22555, 8259, 5718), ppl = c(72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72) ) makeData <- function(dat0, turf, sqft, price, delivery, avg_use) { dat0 |> # If there is an input for 'Percentage', modify E's total_land value by using the input mutate(total_land = ifelse(str_detect(behavior, "E") & turf > 0, ppl * sqft * turf, ppl * sqft), all_w = average * (total_land / 1000), all_ut = price * (all_w / 1000), annual_w = all_w / ppl, mon_w = annual_w / 12, annual_ut = all_ut / ppl, mon_ut = annual_ut / 12, deliv = (all_w / 1000) * delivery, supply = all_w / avg_use ) } server <- function(input, output, session) { Dat0 <- reactiveVal(dat00) output$table1 <- renderDT({ dat <- makeData( isolate(Dat0()), input$turf, input$sqft, input$price, input$delivery, input$avg_use ) datatable( dat, rownames = FALSE, selection = "none", editable = list(target = "cell", disable = list(columns = c(0:1, 3:12))) ) }, server = TRUE) proxy <- dataTableProxy("table1") observeEvent(input[["table1_cell_edit"]], { info <- input[["table1_cell_edit"]] # update Dat0 dat0 <- editData(Dat0(), info, rownames = FALSE) Dat0(dat0) # update the data in the table dat <- makeData( dat0, input$turf, input$sqft, input$price, input$delivery, input$avg_use ) replaceData(proxy, dat, resetPaging = FALSE, rownames = FALSE) }) } shinyApp(ui, server) ```
I want to create a simple bar chart for a specific key and its values in a json data in FastAPI. The data is as shown below. I want to make a chart where indexes are in the x-bar and values of Blue in the y-bar. Can you please help me or lead me somewhere where I can learn that? {"1": {"Red": 14, "Blue": 12}, "2": {"Red": 58, "Blue": 54}, "3": {"Red": 26, "Blue": 65}}
I'm using Composables in Android Studio Kotlin, It creates a spanned string via specified keywords via looking up within foreach loop, How to make it append just one time or remove duplicated appended text? ``` buildAnnotatedString { note.value.title.forEachIndexed { index, character -> append(character) if (index > queryString.count() - 1 && note.value.title.substring( index - (queryString.count() + 1 - 1), index ) == queryString ) { withStyle(style = SpanStyle(color = Color.Blue)) { append(queryString) } } } } ``` Actually its not possible to avoid writing two times or reverse code and delete duplicates
**I was facing the same issue with the Footer component.** [![enter image description here][1]][1] I dynamically added the Footer component and this is how I resolved this error: import dynamic from "next/dynamic"; const Footer = dynamic( async () => await import("../../components/footer/footer"), { ssr: false, } ); export default function Main() { return ( <> <Footer /> </> ); } [![enter image description here][2]][2] [1]: https://i.stack.imgur.com/Kcecb.png [2]: https://i.stack.imgur.com/Q32b0.png
For those using old LTS ***eclipse-temurin:17-jre-alpine*** or current LTS ***eclipse-temurin:21-jre-alpine*** the `wget` is included in default image, thus out of box **healthcheck** for docker compose would look like: ```yaml healthcheck: test: "wget -T5 -qO- http://localhost:8080/actuator/health | grep UP || exit 1" interval: 15s timeout: 5s retries: 5 start_period: 20s ``` for kubernetes it would be ```yaml spec: containers: ... livenessProbe: httpGet: path: /actuator/health port: 8080 initialDelaySeconds: 20 periodSeconds: 15 failureThreshold: 5 timeoutSeconds: 5 ``` The httpGet healthcheck probe will consider the application healthy when the status code is between 200 and 399. In case the application is reporting a healthy state, /actuator/health API will respond with 200 and 503 when it’s down, thus will satisfy k8s healthcheck probe.
I'm using PostgreSQL in my project. The primary key column in my table is a character type with length of 36. I generate guids in the backend and store them in the table. Do I need to change the column type as uuid? Can it have the same performance?
Use data type uuid or varchar(36) for my UUID column?
|postgresql|database-design|uuid|
I have been trying to watch my tests WITH test coverage without much of a success. My best attempt sofar is to install packaeges `pip install pytest pytest-watch pytest-cov` and run on separate terminals or tabs these commands, below 1. Watch tests: `ptw --quiet --spool 200 --clear --nobeep --config pytest.ini --ext=.py --onfail="echo Tests failed, fix the issues" -v` 2. Coverage: `coverage run --rcfile=.coveragerc -m pytest && coverage report --omit="tests/*,src/main.py,*/__init__.py,*/constants.py" --show-missing` An alternative to this approach is the shell script below. To run it, run command: `chmod +x watch.sh && ./watch` ``` #!/bin/bash clear while true; do coverage run --rcfile=.coveragerc -m pytest coverage report --omit="tests/*,src/main.py,*/__init__.py,*/constants.py" --show-missing sleep 5 # Adjust delay between test runs if needed clear done ``` It renders slower compared to command run `ptw`, but outputs exactly what I want. Would you please, provide maybe more effective alternatives than mine? Thanks. :)
You could try using the following formulas, this assumes there is no `Excel Constraints` as per the tags posted: [![enter image description here][1]][1] ---------- =TEXT(MAX(--TEXTAFTER(B$2:B$7,"VUAM")*($A2=A$2:A$7)),"V\U\A\M\00000") ---------- Or, using the following: =TEXT(MAX((--RIGHT(B$2:B$7,5)*($A2=A$2:A$7))),"V\U\A\M\00000") ---------- Or, you could use the following as well using `XLOOKUP()` & `SORTBY()`: [![enter image description here][2]][2] ---------- =LET( x, SORTBY(A2:B7,--RIGHT(B2:B7,5),-1), y, TAKE(x,,1), XLOOKUP(A2:A7, y, TAKE(x,,-1))) ---------- <sup> § Notes On **`Escape Characters`**: The use of `backslash` before & after the `V`, `U`, `A` & `M` is an **`escape character`**. Because the `V`, `U`, `A` & `M` on its own serves a different purpose, we are escaping it meaning hence asking Excel to **`literally form text`** with that character. </sup> ---------- Here is the **`Quick Fix`** to your **`existing formula`**, escape characters are not placed correctly, info on the same refer `§` [![enter image description here][3]][3] ---------- =TEXT(MAX(IF($A$2:$A$100=A2, MID($B$2:$B$100, 5, 5)+0)),"V\U\A\M\00000") ---------- [1]: https://i.stack.imgur.com/K0j2K.png [2]: https://i.stack.imgur.com/ovCkj.png [3]: https://i.stack.imgur.com/82vOL.png
preventing duplicate text
|kotlin|android-studio|android-jetpack-compose|composable|
null
I received a data dump of the SQL database. The data is formatted in an .sql file and is quite large (3.3 GB). I have no access to the actual database and I don't know how to handle this .sql file in Python. I am looking for specific steps to take so I can use this SQL file in Python and analyze the data.
The function `execute` works in Qiskit 0.* and it was removed in Qiskit 1.*. See the migration guide [here][1]. [1]: https://docs.quantum.ibm.com/api/migration-guides/qiskit-1.0-features#execute
The plan is to create a new product Im a full stack developer The business idea is ready in mind I created a google drive and Github repos Multiple juniors might work on the project I still don't know and failed to find the next steps What is the recommended way to continue...Do I start by creating UML diagrams? or documents to list technologies and add business details about the business.. What should I name the files on Google drive(this may help) Is there any course that helps in teaching this specific part? I expect to have a list of missions to accomplish that include details about what must be done for the app to be created in the best practices
steps to create a web app with backend and database and web
|database-design|uml|documentation|react-fullstack|planning|
null
i cloned yolo5 and - setted up an virtenv - pip install -r requirements.txt - `python export.py --weights yolov5s-seg.pt --include torchscript --img 640 --device cpu` all went fine: `TorchScript: export success ✅ 1.6s, saved as yolov5s-seg.torchscript` But if i use this Model, i get `panic: libtorch API Error: PytorchStreamReader failed locating file constants.pkl: file not found` The archive `yolov5s-seg.pt` contains no `constants.pkl`. How can i generate `constants.pkl`?
yolo v5 export to torchscript: how to generate constants.pkl
|pytorch|yolov5|
I'm slowly learning .NET Core 8, and I'm using Identity with individual user accounts. I've recently learned how to add custom properties to the user account such as `FirstName` and `LastName`. I would like to add a property called departments, however, each user may belong to several departments and so the `AspNetUsers` database table structure will not do. Ideally, I would have a separate table for departements (`Deptid, DeptName`) and another table for users in those departements (`userId, DeptId`) that can have multiple entries. I know how to create such tables manually using SQL Server Management Studio and how to write the queries, but I am wondering if there is a way to add this with migrations and also have the usermanger return a list of departments for the user. Can someone point me in the right direction. I'm not exactly sure what to even search for. I am looking for information on this topic.
I basically have to create a method that takes in a string array and a 2D array consisting of three double arrays and puts the first string with the first array, second string with the second array, etc. public static void printData(String[] c, double[][] d) { String cname = ""; for(int i = 0; i < c.length; ++i) { cname = c[i]; for(int row = 0; row < d.length; ++row) { for(int col = 0; col < d[0].length; ++col) { System.out.print(d[row][col] + " "); } System.out.println(); } } Printed out the array a few times //String word = ""; //for(int i = 0; i < c.length; ++i) //{ //for(int row = 0; row < d.length; ++row) //{ //System.out.println(); //for(int col = 0; col < d[0].length; ++col) //{ //word = c[i]; //System.out.println(d[i][col]); //} //} //} I did get to the point where I was able to print the city names out with the entire 2D array under them.
How could you print a specific String from an array with the values of an array from a double array on the same line, using iteration to print all?
|java|multidimensional-array|
null
You can store the value of mbserial number in cell c4 in sheet1 and then run workbook_open
It is indeed correct to type the property decorated with `ElementRef`, but it is just not enough: just add the generic type to `ElementRef`. ```typescript @ViewChild("userSelector") userSelector: ElementRef<HTMLInputElement>; ... onClickUser(user: User) { this.userSelector.nativeElement.value = user.name; ... } ``` The `ViewChild` decorator give you access to a typed `ElementRef` (in this case of `HTMLInputElement` => `ElementRef<HTMLInputElement>`), not an HTMLInputElement one! If you want to observe a child component, you will directly get the component instance (so, no need to type the property to `ElementRef<My child component>>`). In that case you can just do the following: ```typescript @ViewChild(MyComponent) myComponent?: MyComponent; ```
There is nothing you are missing. The assert can fail. In particular, the compiler or CPU are permitted to do the store to `y` before the one to `x` in `write_x_then_y`, because the order of the two statements doesn't imply any additional happens-before constraint. Then the other thread may do both loads in-between the two stores, so that the `if` condition will evaluate to `false`. That you are not actually seeing this happen doesn't change that it is a permitted output and you have no guarantee that it won't behave differently after another compilation or even if you run the same binary often enough. It may happen only every one in a million or one in a billion runs or anything else.
I had the same error when trying to run the application. **------ start of error snippet -----------** warning: default scripting plugin is disabled: The provided plugin org.jetbrains.kotlin.scripting.compiler.plugin.ScriptingCompilerConfigurationComponentRegistrar is not compatible with this version of compiler error: unable to evaluate script, no scripting plugin loaded **----- end of error snippet ------------** The following steps worked for me **(Android Studio Iguana | 2023.2.1 Patch 1)** **1.** Open up "\.idea\workspace.xml" file under your project **2.** Search the "workspace.xml" file for "RunManager". The <component> tag in the XML file looked like this: <component name="RunManager" selected="Kotlin script (Beta).build.gradle.kts"> <configuration name="app" type="AndroidRunConfigurationType" factoryName="Android App"> **Changed the XML to as shown below:** <component name="RunManager" selected="Android App.app"> <configuration name="app" type="AndroidRunConfigurationType" factoryName="Android App"> **Another option for Step 2** is to delete the "selected" attribute and the IDE's auto update feature will add the correct "selected" attribute to the "component" tag. **3.** Then perform this -> "clean project", "build project" and "run" the application and the error went away. App started running from the IDE.
In the C++ standard, `max_size()` is defined as > *Returns*: `distance(begin(), end())` for the largest possible container. \- [[container.reqmts] `max_size`](https://eel.is/c++draft/container.reqmts#lib:max_size,containers) Initially, this looks good, and there is no *Preconditions* paragraph. However, `std::distance` returns `(last - first)` ([[iterator.operations] p5](https://eel.is/c++draft/iterator.operations#5)) and this is possibly undefined behavior for random access iterators (note the *Preconditions* in [[iterator.requirements] `b - a`](http://eel.is/c++draft/iterator.requirements#tab:randomaccessiterator-row-7)). What is the standard actually trying to say here? 1. `max_size()` has no preconditions, so while it isn't *explicitly* stated, the largest possible container is required to have a `max_size()` so that `distance(begin(), end())` is well-defined. 2. `max_size()` is missing a *Preconditions* paragraph, and it's possible for `max_size()` to be undefined behavior if `end() - begin()` and by proxy, `std::distance(begin(), end())` is UB. 3. Something else. The underlying question is: > Does the absence of a *Preconditions* paragraph impose requirements on the implementation, or is it an editorial mistake?
{"OriginalQuestionIds":[50499],"Voters":[{"Id":523612,"DisplayName":"Karl Knechtel","BindingReason":{"GoldTagBadge":"python"}}]}
I read a little bit everywhere that the in operator have a time complexity of O(n), yet I used it in a code and idk why but it's acting as if it have the time complexity O(1) So I was solving a problem on leetcode and ended up having this algorithm ``` class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ i=0 n=len(nums) for i in range (0, n-1): if (target-nums[i]) in nums: for j in range (i+1, n): if nums[i]+nums[j]==target: return[i, j] ``` and I ended up having runtime pretty similar to code like these that involve hashmaps: ``` class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ hash_map = {} for i in range(len(nums)): complement = target - nums[i] if complement in hash_map.keys(): return [i, hash_map[complement]] hash_map[nums[i]] = i ``` It's weird because I read everywhere that the time complexity of the in operator for list is O(n), so I assumed this line `if (target-nums[i]) in nums:` would make my code equivalent to ``` class Solution(object): def twoSum(self, nums, target): self=list() n=len(nums) for i in range(n-1): for j in range(i+1,n): if nums[i]+nums[j]==target: return [i,j] ``` yet it has the runtime of a code using hashmaps, and uses the memory of the code using the same list so O(1), anyone could explain that to me please?
Time Complexity of "in" keyword in python when using a list? Leetcode
|python|time-complexity|space-complexity|code-complexity|
null
.NET Core 8, how can I add properties to user account that contains multiple values?
struct MyStruct { var a = 0 func foo() { print("Ok") } mutating func increase() { a += 1 } } func runner(_ function: () -> Void) { function() } var myStruct = MyStruct() runner(myStruct.foo) // Ok runner(myStruct.increase) // Escaping autoclosure captures 'inout' parameter 'self' How to make it works? By the way, where is `autoclosure` here? And why is it escaping? P.S. I know I can just pass a "normal" closure: `runner { myStruct.increase() }` and it would work, but it's important for me to be able only to pass a name of a function to the `runner`. P.S. Actually there are a lot of similar questions on SOF already. I've read them all, and as far as I understand, it's impossible to do. Which is the answer that doesn't suit me
"Escaping autoclosure captures 'inout' parameter 'self'" Swift compilation error
|swift|escaping|inout|auto-close|mutating-function|
|c#|entity-framework-core|asp.net-core-mvc|asp.net-core-identity|
I have a frame layout that wants to fill 50% of the screen reso, then a tablayout below and a viewpager with 3 different fragment layouts based on the tabs. The tabs/viewpager works and shows the layouts when i remove scrollview, otherwise using this code it just show a blank viewpager. Can someone help me to enable a scrolling function for the viewpager without the viewpager from disappearing/not showing? The viewpager adapters are functional but adding a scrollview to scroll the fragment layouts of the viewpager makes the whole viewpager disappear. ``` <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:id="@+id/templateContainer" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toTopOf="@id/newjobcardtabLayout" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHeight_percent="0.5"> <ImageView android:id="@+id/templateLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitCenter" app:srcCompat="@drawable/veh_cond_template" /> </FrameLayout> <com.google.android.material.tabs.TabLayout android:id="@+id/newjobcardtabLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabTextAppearance="@style/TabLayoutTextStyle" app:layout_constraintTop_toBottomOf="@id/templateContainer"/> <androidx.core.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintTop_toBottomOf="@id/newjobcardtabLayout"> <androidx.viewpager.widget.ViewPager android:id="@+id/newjobcardviewPager" android:layout_width="match_parent" android:layout_height="wrap_content"/> </androidx.core.widget.NestedScrollView> </androidx.constraintlayout.widget.ConstraintLayout> ```
What is the advantages of Leacky ReLU over ReLU? I have read some research paper but found nothing or more precious answer. Sometimes found that ReLU and Pre-ReLU helps more model optimization as compared to Leacky ReLU. Why?
ReLu, PreReLu, Leacky ReLU
|machine-learning|
null
Unfortunately, Flutter doesn't have `controller.jumpToIndex(index);` you can achieve this by adding a third-party library which is called [**scrollable_positioned_list**][1]. It is exactly like ListView but you can use `controller.jumpToIndex(index);` For Example: Init controller: final ItemScrollController itemScrollController = ItemScrollController(); Add widget: ScrollablePositionedList.builder( itemCount: 500, itemBuilder: (context, index) => Text('Item $index'), itemScrollController: itemScrollController, scrollOffsetController: scrollOffsetController, itemPositionsListener: itemPositionsListener, scrollOffsetListener: scrollOffsetListener, ); Call `scrollTo` method: itemScrollController.scrollTo( index: 150, duration: Duration(seconds: 2), curve: Curves.easeInOutCubic); **Happy Coding :)** [1]: https://pub.dev/packages/scrollable_positioned_list
Change this line: ``` output = p4.run("print", "-o", temp_file, f"{file_path}@{changelist_number}") ``` to: ``` output = p4.run("print", "-o", temp_file, f"{file_path}@={changelist_number}") ``` and make sure that your trigger is running as `change-content` rather than `change-submit`. The important detail is the `@=` revision specifier, which can be used to refer to unsubmitted files on the server (i.e. a midflight submit in a `change-content` trigger, or a shelved change -- note that at the time `change-submit` fires, the files are not yet on the server). Normally a revision specifier can only ever refer to *submitted* revisions, but `@=` is a special exception when it refers to a pending change that contains either mid-submit or shelved files.
### Strategy for Answering Exactly what the `conda init` command does and its consequences are shell-specific. Instead of trying to cover all cases, let's walk through a case, noting along the way that one can replicate this analysis by substituting their shell of interest. --- # Case Study: `conda init zsh` Let's look at `zsh` as the shell. This is a common shell (default for macOS 10.15+) and very close to bash. Plus, I don't already have it configured. ## Probing the Command: Dry Run Many Conda commands include some form of dry run functionality via a `--dry-run, -d` flag, which - combined with verbosity flags - enables seeing what this would do without doing them. For the `init` command, dry run alone will only tell us what files it *would* modify: ``` lang-bash $ conda init -d zsh no change /Users/mfansler/miniconda3/condabin/conda no change /Users/mfansler/miniconda3/bin/conda no change /Users/mfansler/miniconda3/bin/conda-env no change /Users/mfansler/miniconda3/bin/activate no change /Users/mfansler/miniconda3/bin/deactivate no change /Users/mfansler/miniconda3/etc/profile.d/conda.sh no change /Users/mfansler/miniconda3/etc/fish/conf.d/conda.fish no change /Users/mfansler/miniconda3/shell/condabin/Conda.psm1 no change /Users/mfansler/miniconda3/shell/condabin/conda-hook.ps1 no change /Users/mfansler/miniconda3/lib/python3.7/site-packages/xontrib/conda.xsh no change /Users/mfansler/miniconda3/etc/profile.d/conda.csh modified /Users/mfansler/.zshrc ==> For changes to take effect, close and re-open your current shell. <== ``` Here we can see that it plans to target the user-level resources file for zsh, `/Users/mfansler/.zshrc`, but it doesn't tell us how it will modified it. Also, OMG! the UX here is awful, because it in no way reflects the fact that I used the `-d` flag. But don't worry: as long as the `-d` flag is there it won't actually change things. ### Patch Preview To see what exactly it will do, add a single verbosity flag (`-v`) to the command. This will give everything from the previous output, but will now shows us the diff it will use to patch (update) the `.zshrc` file. ``` lang-bash $ conda init -dv zsh /Users/mfansler/.zshrc --- +++ @@ -0,0 +1,16 @@ + +# >>> conda initialize >>> +# !! Contents within this block are managed by 'conda init' !! +__conda_setup="$('/Users/mfansler/miniconda3/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)" +if [ $? -eq 0 ]; then + eval "$__conda_setup" +else + if [ -f "/Users/mfansler/miniconda3/etc/profile.d/conda.sh" ]; then + . "/Users/mfansler/miniconda3/etc/profile.d/conda.sh" + else + export PATH="/Users/mfansler/miniconda3/bin:$PATH" + fi +fi +unset __conda_setup +# <<< conda initialize <<< + # ...the rest is exactly as above ``` That is, the plan of action is to add these 16 lines to the `.zshrc` file. In this case, I don't have an existing `.zshrc` file, so it plans to add it at line 1. If the file had already existed, it would append these lines. --- ## Interpreting the Shell Code Let's overview this code, before focusing on the details. Essentially, this is a redundant sequence of attempts to set up some shell functionality. They are ordered from most to least functional. ### What Conda Hopes To Do The code ``` __conda_setup="$('/Users/mfansler/miniconda3/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)" if [ $? -eq 0 ]; then eval "$__conda_setup" ``` gets something from `conda` itself, storing the result to a string, and then evaluates that string if the command had a clean exit (`$? -eq 0`). The neat engineering here is that the subprocess (technically `python -m conda`) passes back a result that can be run within this current process (`zsh`), allowing it to define shell functions. I'll dig deeper into what is going on here in a second. ### Fallback 1: Hardcoded Shell Functions If that strange internal command fails, the devs included a hardcoded version of some essential shell functions (specifically `conda activate`). This is in: miniconda3/etc/profile.d/conda.sh and they simply check the file exists and source it. Let's hit that last option, then we'll swing back to look at the functionality. ### Fallback 2: The Last Resort The absolute last resort is to literally violate the standing recommendation since Conda v4.4, which is to simply put the **base** environment's `bin` directory on `PATH`. In this case, there is no `conda activate` functionality; this only ensures that Conda is on your PATH. --- ## Details: Shell Functionality Coming back to the intended case, we can inspect exactly what it would evaluate by simply getting that string result: ``` lang-bash $ conda shell.zsh hook __add_sys_prefix_to_path() { # In dev-mode CONDA_EXE is python.exe and on Windows # it is in a different relative location to condabin. if [ -n "${_CE_CONDA}" ] && [ -n "${WINDIR+x}" ]; then SYSP=$(\dirname "${CONDA_EXE}") else SYSP=$(\dirname "${CONDA_EXE}") SYSP=$(\dirname "${SYSP}") fi if [ -n "${WINDIR+x}" ]; then PATH="${SYSP}/bin:${PATH}" PATH="${SYSP}/Scripts:${PATH}" PATH="${SYSP}/Library/bin:${PATH}" PATH="${SYSP}/Library/usr/bin:${PATH}" PATH="${SYSP}/Library/mingw-w64/bin:${PATH}" PATH="${SYSP}:${PATH}" else PATH="${SYSP}/bin:${PATH}" fi \export PATH } __conda_exe() ( __add_sys_prefix_to_path "$CONDA_EXE" $_CE_M $_CE_CONDA "$@" ) __conda_hashr() { if [ -n "${ZSH_VERSION:+x}" ]; then \rehash elif [ -n "${POSH_VERSION:+x}" ]; then : # pass else \hash -r fi } __conda_activate() { if [ -n "${CONDA_PS1_BACKUP:+x}" ]; then # Handle transition from shell activated with conda <= 4.3 to a subsequent activation # after conda updated to >= 4.4. See issue #6173. PS1="$CONDA_PS1_BACKUP" \unset CONDA_PS1_BACKUP fi \local ask_conda ask_conda="$(PS1="${PS1:-}" __conda_exe shell.posix "$@")" || \return \eval "$ask_conda" __conda_hashr } __conda_reactivate() { \local ask_conda ask_conda="$(PS1="${PS1:-}" __conda_exe shell.posix reactivate)" || \return \eval "$ask_conda" __conda_hashr } conda() { \local cmd="${1-__missing__}" case "$cmd" in activate|deactivate) __conda_activate "$@" ;; install|update|upgrade|remove|uninstall) __conda_exe "$@" || \return __conda_reactivate ;; *) __conda_exe "$@" ;; esac } if [ -z "${CONDA_SHLVL+x}" ]; then \export CONDA_SHLVL=0 # In dev-mode CONDA_EXE is python.exe and on Windows # it is in a different relative location to condabin. if [ -n "${_CE_CONDA:+x}" ] && [ -n "${WINDIR+x}" ]; then PATH="$(\dirname "$CONDA_EXE")/condabin${PATH:+":${PATH}"}" else PATH="$(\dirname "$(\dirname "$CONDA_EXE")")/condabin${PATH:+":${PATH}"}" fi \export PATH # We're not allowing PS1 to be unbound. It must at least be set. # However, we're not exporting it, which can cause problems when starting a second shell # via a first shell (i.e. starting zsh from bash). if [ -z "${PS1+x}" ]; then PS1= fi fi conda activate base ``` I'm not going to walk through all this, but the main part is that instead of directly putting `bin` on PATH, it defines a shell function called `conda` and this serves as a wrapper for the `condabin/conda` entrypoint. This also defines a new functionality `conda activate`, which uses a shell function, `__conda_activate()`, behind the scenes. At the final step, it then activates the **base** environment. **Why do it this way?** This is engineered like this in order to be responsive to the configuration settings. Configuration options like `auto_activate_base` and `change_ps1` affect how Conda manipulates the shell, and so that changes what functionality Conda includes in its shell functions. --- # Does Conda "Pollute the Environment"? Not really. The main behavioral things like auto-activation and prompt modification can be disabled through configuration settings, so that `conda init` ultimately just adds the `conda activate` function to the shell, enabling clean switching between environments without ever having to manually manipulate PATH.
I see two possible options here. First is "more formally correct", but way too permissive, approach relying on `partial` hint: ```python from __future__ import annotations from functools import partial from typing import Callable, TypeVar, ParamSpec, Any, Optional, Protocol, overload, Concatenate R = TypeVar("R") P = ParamSpec("P") class YourCallable(Protocol[P, R]): @overload def __call__(self, value: float, *args: P.args, **kwargs: P.kwargs) -> R: ... @overload def __call__(self, value: None = None, *args: P.args, **kwargs: P.kwargs) -> partial[R]: ... def lazy(func: Callable[Concatenate[float, P], R]) -> YourCallable[P, R]: def wrapper(value: float | None = None, **kwargs: P.kwargs) -> R | partial[R]: if value is not None: return func(value, **kwargs) else: return partial(func, **kwargs) return wrapper # type: ignore[return-value] @lazy def test_multiply(value: float, *, multiplier: float) -> float: return value * multiplier @lazy def test_format(value: float, *, fmt: str) -> str: return fmt % value print('test_multiply 5*2:', test_multiply(value=5, multiplier=2)) print('test_format 7.777 as .2f:', test_format(value=7.777, fmt='%.2f')) func_mult_11 = test_multiply(multiplier=11) # returns a partial function print('Type of func_mult_11:', type(func_mult_11)) print('func_mult_11 5*11:', func_mult_11(value=5)) func_mult_11(value=5, multiplier=5) # OK func_mult_11(value='a') # False negative: we want this to fail ``` Last two calls show hat is good and bad about this approach. `partial` accepts any input arguments, so is not sufficiently safe. If you want to override the arguments provided to lazy callable initially, this is probably the best solution. Note that I slightly changed signatures of the input callables: without that you will not be able to use `Concatenate`. Note also that `KwArg`, `DefaultNamedArg` and company are all deprecated in favour of protocols. You cannot use paramspec with kwargs only, args must also be present. If you trust your type checker, it is fine to use kwarg-only callables, all unnamed calls will be rejected at the type checking phase. However, I have another alternative to share if you do not want to override default args passed to the initial callable, which is fully safe, but emits false positives if you try to. ```python from __future__ import annotations from functools import partial from typing import Callable, TypeVar, ParamSpec, Any, Optional, Protocol, overload, Concatenate _R_co = TypeVar("_R_co", covariant=True) R = TypeVar("R") P = ParamSpec("P") class ValueOnlyCallable(Protocol[_R_co]): def __call__(self, value: float) -> _R_co: ... class YourCallableTooStrict(Protocol[P, _R_co]): @overload def __call__(self, value: float, *args: P.args, **kwargs: P.kwargs) -> _R_co: ... @overload def __call__(self, value: None = None, *args: P.args, **kwargs: P.kwargs) -> ValueOnlyCallable[_R_co]: ... def lazy_strict(func: Callable[Concatenate[float, P], R]) -> YourCallableTooStrict[P, R]: def wrapper(value: float | None = None, **kwargs: P.kwargs) -> R | partial[R]: if value is not None: return func(value, **kwargs) else: return partial(func, **kwargs) return wrapper # type: ignore[return-value] @lazy_strict def test_multiply_strict(value: float, *, multiplier: float) -> float: return value * multiplier @lazy_strict def test_format_strict(value: float, *, fmt: str) -> str: return fmt % value print('test_multiply 5*2:', test_multiply_strict(value=5, multiplier=2)) print('test_format 7.777 as .2f:', test_format_strict(value=7.777, fmt='%.2f')) func_mult_11_strict = test_multiply_strict(multiplier=11) # returns a partial function print('Type of func_mult_11:', type(func_mult_11_strict)) print('func_mult_11 5*11:', func_mult_11_strict(value=5)) func_mult_11_strict(value=5, multiplier=5) # False positive: OK at runtime, but not allowed by mypy. E: Unexpected keyword argument "multiplier" for "__call__" of "ValueOnlyCallable" [call-arg] func_mult_11_strict(value='a') # Expected. E: Argument "value" to "__call__" of "ValueOnlyCallable" has incompatible type "str"; expected "float" [arg-type] ``` You can also mark `value` kw-only in `ValueOnlyCallable` definition if you'd like, I just don't think it is reasonable for a function with only one argument. You can compare both approaches in [playground](https://mypy-play.net/?mypy=master&python=3.11&flags=strict&gist=52aefd1e46c49e73206e0efbca17b193).
I am learning Spark, so as a task we had to create a wheel locally and later install it in Databricks (I am using Azure Databricks), and test it by running it from a Databrick Notebook. This program involves reading a CSV file (timezones.csv) included inside the wheel file. The file *is* inside the wheel (I checked it) and also the wheel works properly when I install it and run it from a local PC Jupyter Notebook. However, when I install it in Databricks Notebook it gives this error, as you can see below in the snapshot: ```lang-py [PATH_NOT_FOUND] Path does not exist: dbfs:/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/motor_ingesta/resources/timezones.csv. SQLSTATE: 42K03 File <command-3771510969632751>, line 7 3 from pyspark.sql import SparkSession 5 spark = SparkSession.builder.getOrCreate() ----> 7 flights_with_utc = aniade_hora_utc(spark, flights_df) File /local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/motor_ingesta/agregaciones.py:25, in aniade_hora_utc(spark, df) 23 path_timezones = str(Path(__file__).parent) + "/resources/timezones.csv" 24 #path_timezones = str(Path("resources") / "timezones.csv") ---> 25 timezones_df = spark.read.options(header="true", inferSchema="true").csv(path_timezones) 27 # Concateno los datos de las columnas del timezones_df ("iata_code","iana_tz","windows_tz"), a la derecha de 28 # las columnas del df original, copiando solo en las filas donde coincida el aeropuerto de origen (Origin) con 29 # el valor de la columna iata_code de timezones.df. Si algun aeropuerto de Origin no apareciera en timezones_df, 30 # las 3 columnas quedarán con valor nulo (NULL) 32 df_with_tz = df.join(timezones_df, df["Origin"] == timezones_df["iata_code"], "left_outer") File /databricks/spark/python/pyspark/instrumentation_utils.py:47, in _wrap_function.<locals>.wrapper(*args, **kwargs) 45 start = time.perf_counter() 46 try: ---> 47 res = func(*args, **kwargs) 48 logger.log_success( 49 module_name, class_name, function_name, time.perf_counter() - start, signature 50 ) 51 return res File /databricks/spark/python/pyspark/sql/readwriter.py:830, in DataFrameReader.csv(self, path, schema, sep, encoding, quote, escape, comment, header, inferSchema, ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace, nullValue, nanValue, positiveInf, negativeInf, dateFormat, timestampFormat, maxColumns, maxCharsPerColumn, maxMalformedLogPerPartition, mode, columnNameOfCorruptRecord, multiLine, charToEscapeQuoteEscaping, samplingRatio, enforceSchema, emptyValue, locale, lineSep, pathGlobFilter, recursiveFileLookup, modifiedBefore, modifiedAfter, unescapedQuoteHandling) 828 if type(path) == list: 829 assert self._spark._sc._jvm is not None --> 830 return self._df(self._jreader.csv(self._spark._sc._jvm.PythonUtils.toSeq(path))) 831 elif isinstance(path, RDD): 833 def func(iterator): File /databricks/spark/python/lib/py4j-0.10.9.7-src.zip/py4j/java_gateway.py:1322, in JavaMember.__call__(self, *args) 1316 command = proto.CALL_COMMAND_NAME +\ 1317 self.command_header +\ 1318 args_command +\ 1319 proto.END_COMMAND_PART 1321 answer = self.gateway_client.send_command(command) -> 1322 return_value = get_return_value( 1323 answer, self.gateway_client, self.target_id, self.name) 1325 for temp_arg in temp_args: 1326 if hasattr(temp_arg, "_detach"): File /databricks/spark/python/pyspark/errors/exceptions/captured.py:230, in capture_sql_exception.<locals>.deco(*a, **kw) 226 converted = convert_exception(e.java_exception) 227 if not isinstance(converted, UnknownException): 228 # Hide where the exception came from that shows a non-Pythonic 229 # JVM exception message. --> 230 raise converted from None 231 else: 232 raise ``` Databricks Error Snapshot 1: ![Databricks Error Snapshot 1](https://i.stack.imgur.com/e3QPP.png) Databricks Error Snapshot 2: ![Databricks Error Snapshot 2](https://i.stack.imgur.com/r98sN.png) Has anyone experienced this problem before? Is there any solution? I tried installing the file both with pip and from Library, and I got the same error, also rebooted the cluster several times. Thanks in advance for your help. I am using Python 3.11, Pyspark 3.5 and Java 8 and created the wheel locally from PyCharm. If you need more details to answer, just ask and I'll provide them. I explained all the details above. I was expecting to be able to use the wheel I created locally from a Databricks Notebook. Sorry about my English is not my native tongue and I am a bit rusty. ----- Edited to answer comment: > Can u navigate to %sh ls > /dbfs/local_disk0/.ephemeral_nfs/cluster_libraries/python/lib/python3.10/site-packages/motor_ingesta/resources and share the folder content as image? – Samuel Demir 11 hours ago I just did what you asked for and I got this result (The file is actually there even if Databricks says it can't find it... [Snapshot of suggestion result][1] Edited to answer Samuel Demir: > Maybe the `package_data` is missing in your setup initialization?! > > This what I do to add my configuration files in the res folder to the > wheel. The files are then accessible exactly by the same piece of code > of yours. > > > setup( > name="daprep", > version=__version__, > author="", > author_email="samuel.demir@galliker.com", > description="A short summary of the project", > license="proprietary", > url="", > packages=find_packages("src"), > package_dir={"": "src"}, > package_data={"daprep": ["res/**/*"]}, > long_description=read("README.md"), > install_requires=read_requirements(Path("requirements.txt")), > tests_require=[ > "pytest", > "pytest-cov", > "pre-commit", > ], > cmdclass={ > "dist": DistCommand, > "test": TestCommand, > "testcov": TestCovCommand, > }, > platforms="any", > python_requires=">=3.7", > entry_points={ > "console_scripts": [ > "main_entrypoint = daprep.main:main_entrypoint", > ] > }, ) My `setup.py` file has the package _data line as well, here you can see an snapshot and the code for it. Do you catch any other detail that could be relevant there? Thanks in advance. [Snapshot of my setup.py file][2] from setuptools import setup, find_packages setup( name="motor-ingesta", version="0.1.0", author="Estrella Adriana Sicardi Segade", author_email="esicardi@ucm.es", description="Motor de ingesta para el curso de Spark", long_description="Motor de ingesta para el curso de Spark", long_description_content_type="text/markdown", url="https://github.com/esicardi", python_requires=">=3.8", packages=find_packages(), package_data={"motor_ingesta": ["resources/*.csv"]}) [1]: https://i.stack.imgur.com/SnJ6M.png [2]: https://i.stack.imgur.com/epApF.png
so I have a problem where I can't make new table through MySQL Workbench, the name field is just not showing to me nor "Apply" button which should be in the bottom. Does anyone know how to fix this? [Screenshot from MYSQL Workbench](https://i.stack.imgur.com/Wxz6c.png) I don't know what should I do right now Best regards
MySQL Workbench [BUG]
|mysql|mysql-workbench|
null
Is there any way to tell Notepad please do this... FROM THIS 15.63387,46.42795,1,130,1,210,Sele pri Polskavi TO THIS 15.63387,46.42795,1,130,1,210 I would like to remove everything after the last , So that in the end it looks like 15.63387,46.42795,1,130,1,210 Thing is when I try it using Notepad++ with the command FIND = [[:alpha:]] or [\u\l] REPLACE = (leave it empty) It removed all alphabetical charachters but it leaves , signs at the end, which I can remove with .{1}$ but for some reason some lines have empty spaces after , sign. Some lines have one or more and this command .{1}$ does not work since notepad++ sees empty space as a character and therefore does not remove all the , signs at the end of each line.