Vue and Javascript API/Object/Array manipulation for searching values Posted: 26 Aug 2021 08:26 AM PDT So I'm building an application for work which pulls from a third-pary API. I need the user to be able to search through the list of results by title. This is what the api response looks like: class: (...) facets: (...) numberFound: (...) results: Array(202) [0 … 99] 0: class: "SearchResult" contentGuid: "7f19462f-6c25-43a9-bdb5-479f5f42fbde" dateUpdated: "2018-03-27T16:46:31Z" description: "Converting a Word Document to Adobe Acrobat PDF Learning Services Converting a Word Document to Adobe Acrobat PDF Enterprise Converting a Word Document to Adobe Acrobat PDF / Reference ..." document: Object documentGuid: "035f5c69-d406-4c16-86ca-de12773a0963" documentId: 154424 documentVersionId: 44043 fileId: 74213 format: "PDF" id: "Document#1#44043" isFavorite: false languages: "English" name: "Converting a Word Document to Adobe Acrobat PDF" numberOfIndexedCoobs: 0 numberOfSharedLinks: 1 packageType: "PDF" previewId: 74213 publicLinkTokens: Array(1) resourceType: "Other" score: 0.0054571675 snippets: Object updatedById: 994 updatedByName: "Michael" versionName: "3" My thought was to get the document name split it, the do an includes() to check for the search term. This works but I can't seem to figure out how to get it all to work together and get the results on the screen, plus get additional information, such as document Id from the original results. this is what I have so far: async getResults() { return axios .get(this.url, { headers: { "Content-Type": "application/json", "Bravais-prod-us-Context": this.getCookie(), }, }) .then((res) => { this.search = res.data; this.search.results.forEach((doc) => { this.results = doc.document.name .toLowerCase() .split(" ") .includes(this.termSearch.toLowerCase()); console.log(doc.document.name.split(" ")); console.log(this.results); }); }) .catch((error) => console.log(error)); }, I need to show the original title(some words and acronyms are capitalized) plus the doc id(for url links) and a description, all of this info is in the initial api response. <div v-for="" v-bind:key=""> {{ ???? }} </div> That works in the console but how do I get this back together and on the screen?? Any help is appreciated, not looking for someone else to do my coding, just need some advice. |
Unable to parse org.apache.avro.util.Utf8 to java.time.ZonedDateTime Posted: 26 Aug 2021 08:26 AM PDT Hi I have tried below tests. But unable to parse the date format: 2020-04-19T19:00:54 Could you please suggest why I am facing this issue? ---------- public ZonedDateTime convert(Utf8 date) { String datee = ((String) date.toString()).replace("T", " ") LocalDateTime today = LocalDateTime.parse(datee, formatter) ZonedDateTime currentISTime = today.atZone(ZoneId.systemDefault()) ZonedDateTime currentETime = currentISTime.withZoneSameInstant(ZoneId.systemDefault()) return ZonedDateTime.parse(formatter.format(currentETime), formatter) } ---------- String datee = ((String) date.toString()).replace("T", " ") try{ var zoned = ZonedDateTime.from(DateTimeFormatter.ISO_DATE_TIME.parse(datee.toString())) return zoned.withZoneSameInstant(ZoneId.systemDefault()) } catch (DateTimeException e) { //no time zone information -> parse as LocalDate return ZonedDateTime.parse(datee.toString()) } ---------- Exception- Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-04-19 19:00:54' could not be parsed at index 10 at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046) at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948) at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:598) at java.base/java.time.ZonedDateTime.parse(ZonedDateTime.java:583) |
Pytorch mistake demo: Why this RuntimeError occurs the second time when running the backward() line? Posted: 26 Aug 2021 08:25 AM PDT I write a mistake demo that I know the reason why this error occurs. However, I have no idea why the error occurs the second time in the while loop instead of the first time. import torch from torch import nn class Model(torch.nn.Module): def __init__(self): super(Model, self).__init__() self.w1 = nn.Parameter(torch.tensor([2.], requires_grad=True)) self.w2 = nn.Parameter(torch.tensor([3.], requires_grad=True)) self.w3 = nn.Parameter(torch.tensor([4.], requires_grad=True)) def forward(self, a): s = a * self.w1 c = s * self.w2 d = s * self.w3 return c, d x = torch.tensor([1.]) y1 = torch.tensor([10.]) y2 = torch.tensor([12.]) model = Model() mse = torch.nn.MSELoss() # optim = torch.optim.Adam(model.parameters(), lr=0.5) optim = torch.optim.SGD(model.parameters(), lr=0.1) num = 0 torch.autograd.set_detect_anomaly(True) # For debugging. while True: num += 1 print(num) y1_pred, y2_pred = model(x) loss1 = mse(y1_pred, y1) loss2 = mse(y2_pred, y2) optim.zero_grad() loss1.backward(retain_graph=True) optim.step() optim.zero_grad() loss2.backward(retain_graph=True) # The RuntimeError occurs. But why does it occur in the second iteration in the loop instead of the first iteration? optim.step() The error information: RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [1]] is at version 2; expected version 1 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck! Pytorch version: 1.9.0 |
Hasura Computed no schema has been selected to create in. null Posted: 26 Aug 2021 08:25 AM PDT So basiclly i want to create a computed field which is very basic, Get the full name from the database. CREATE FUNCTION author_full_name(user_row users) RETURNS TEXT AS $$ SELECT user_row.firstName || ' ' || user_row.lastName $$ LANGUAGE sql STABLE; Here is the users table: users id int, firstName text, lastName text db ss: https://ibb.co/gm1xzK2 I always end up with this error : "SQL Execution Failed no schema has been selected to create in. null" |
Bootsrap-Vue Modal hide method not working Posted: 26 Aug 2021 08:25 AM PDT I have a simple bootstrap-vue modal with a input text . I want that pressing the Ok button does not close automatically, so I use "prevent". Then I do some validation and then I want it to close with the "hide" method. However it doesn't work for me. The weird thing is that the show method does work perfectly. I have looked at the documentation and can't find where the error is. How do I make the hide method work for me at that point? There is my code. <template> <div> <b-button size="sm" class="m-2" variant="primary" @click="grfGuardarBtnPredefAccions()" >Guardar gráfica personalizada</b-button > <b-modal id="grfModalGuardar" ref="grfGuardarModal" title="Insertar nombre" @ok.prevent="grfModalOk" @cancel="grfModalCancel" > <p> Debe asignar un nombre a la gráfica personalizada que desea guardar. </p> <b-form-input v-model="grfModalPersoName" placeholder="Escriba aquí ..." ></b-form-input> </b-modal> </div> </template> <script> export default { name: "GrafTopMenu", components: { GrafEditor, }, data() { return { // almacena el nombre que el usuario le pone a la gráfica personalizada que va a guardar. grfModalPersoName: "", }; }, computed: {}, methods: { /** acciónes que realiza el botón de guardar gráfica personalizada*/ grfGuardarBtnPredefAccions() { let errormsg = ""; if (this.grfTableGrafica.tableConf.items.length == 0) { errormsg += errormsg + "No puede guardar una gráfica vacía"; } if (!errormsg) { this.$refs.grfGuardarModal.show(); } else { generalUtils.makeToast( "danger", 3000, "No puede guardar una gráfica vacía" ); } }, grfModalOk() { if (!this.grfModalPersoName.trim()) { generalUtils.makeToast( "danger", 3000, "El nombre no puede estar vacío" ); } else { console.log("ok"); console.log("this.grfModalPersoName :>> ", this.grfModalPersoName); console.log("this.grfTableGrafica", this.grfTableGrafica); this.$refs["grfGuardarModal"].hide(); // this.$refs.grfGuardarModal.hide(); } }, grfModalCancel() { this.grfModalPersoName = ""; }, }, }; </script> <style> </style> |
[Vue warn]: Error in render: "TypeError: Cannot read property of undefined" Posted: 26 Aug 2021 08:25 AM PDT i'm using vuex on my app, i want to list all my lineproduction data in a select option, a created state, store,..., i have [Vue warn]: Error in render: "TypeError: Cannot read property 'productinLineState' of undefined", t think some hink wrong with my productinLineState state on mycomponent vue, the action, mutations are ok it returns data on console log component.vue: <template> <select class="form-control form-control-sm mt-2" id="exampleFormControlSelect1" name="productionLine" @change="onChange($event)" > <option v-for="Item in productLines: :key="Item.id" :value="Item.id" >{{ Item.name }}</option > </select> </div> </template> <script> import { mapActions,mapState } from "vuex"; export default { computed: { ...mapState({ productLines: (state) => state.productinLineState.productinLineState, }), }, created() { this.getProductionLineItems(); methods: { ...mapActions("productionline", ["getProductionLineItems"]), } } </script> state.js: export default { cartState: [], } mutations.js: export const SET_PRODUTION_LINE = (state, productionLineItems) => { state.productionLineState = productionLineItems console.log('ddt is',state.productionLineState ) } actions.js: import ProductionLine from "../../../apis/ProductionLine" export const getProductionLineItems = ({ commit }) => { ProductionLine.all().then(response => { commit("SET_PRODUTION_LINE",response.data) }); }; |
Redux-saga - TypeScript error with TakeEvery: TakeableChannel<unknown> Posted: 26 Aug 2021 08:24 AM PDT I have a simple redux saga. import { api } from '../api'; import * as screen from './slice'; import { fetchScreenSuccess } from './slice'; interface fetchScreenPayload { screenName: string; } interface fetchScreenAction { type: string; payload: fetchScreenPayload; } function* fetchScreen(api: any, action: fetchScreenAction) { ... } export default function* watchDataSource() { yield takeEvery(screen.fetchScreen, fetchScreen, api); ^^^^^^^^^^^^^^^^^^ Argument of type 'ActionCreatorWithoutPayload<string>' is not assignable to parameter of type 'TakeableChannel<unknown>'. Property 'take' is missing in type 'ActionCreatorWithoutPayload<string>' but required in type 'TakeableChannel<unknown>'. } The slice is: export const screenSlice = createSlice({ name: 'screen', // `createSlice` will infer the state type from the `initialState` argument initialState, reducers: { fetchScreen(state): any { state.screen = initialState.screen; state.isLoading = true; }, }, }); Any idea of how to remove the typescript error? |
dplyr Find records that have specifc set of values Posted: 26 Aug 2021 08:24 AM PDT I have a dataset that has some ID and associated timepoints. I want to filter out IDs that have a specific combination of timepoints. If I filter using %in% or |, I get IDs out of the specific combination. How do I do this in R ? ID | Timepoint | 1 | 1 | 1 | 6 | 1 | 12 | 2 | 1 | 3 | 1 | 3 | 6 | 3 | 12 | 3 | 18 | 4 | 1 | 4 | 6 | 4 | 12 | I want to filter IDs that have timepoints 1,6 and 12 and exclude other IDs. Result would be IDs 1,3 and 4 |
How can I attach in each header of a fasta file the filename? Posted: 26 Aug 2021 08:25 AM PDT Dear all I have thousands of fasta files. When you open each of the files you see headers that look like this: >LOC_1_22 # 16427 # 16873 # 1 # ID=1_22;partial=00;start_type=ATG;rbs_motif=GGAG/GAGG;rbs_spacer=5-10bp;gc_cont=0.635 ATGTTCTTTTATTGCCCGAAGACTGGCGGCTTTTACTCTCCAGAGGTACATGGTGAACAAATGCCAGCGG >LOC_1_23 # 16964 # 18139 # 1 # ID=1_23;partial=00;start_type=ATG;rbs_motif=GGA/GAG/AGG;rbs_spacer=5-10bp;gc_cont=0.651 ATGGCCGCTGACCAATATCATCACGGTGTCCGGGTCCAAGAGATCAATGACGGGACCCGCCCCATTCGCA I want to attach to the headers of each file the filename. Imagine that my filename is NC_003245 then I would like the headers of this file when I open the file to look like this >NC_003245 LOC_1_22 # 16427 # 16873 # 1 # ID=1_22;partial=00;start_type=ATG;rbs_motif=GGAG/GAGG;rbs_spacer=5-10bp;gc_cont=0.635 ATGTTCTTTTATTGCCCGAAGACTGGCGGCTTTTACTCTCCAGAGGTACATGGTGAACAAATGCCAGCGG >NC_003245 LOC_1_23 # 16964 # 18139 # 1 # ID=1_23;partial=00;start_type=ATG;rbs_motif=GGA/GAG/AGG;rbs_spacer=5-10bp;gc_cont=0.651 ATGGCCGCTGACCAATATCATCACGGTGTCCGGGTCCAAGAGATCAATGACGGGACCCGCCCCATTCGCA My knowledge in bash/awk language in limited, Any help or advice are hugely appreciated |
Run a python script forever Posted: 26 Aug 2021 08:25 AM PDT I want to run my script control_as_py forever. I tried while True: import control_as_py but for some reasons, it runs the script ones and then stopps. How can I change that? |
Postgresql date difference in hours for a calculated column Posted: 26 Aug 2021 08:25 AM PDT Hello I created a view in Postgresl that works except for one column. I need it subtract reported_date from the previous reported_date and give my answer in hours based on well_id. I am super lost I would not even mind kicking a few bucks to have a solution. COALESCE(g.Delta_Hours, hours_diff*24 + DATE_PART('hour',p.reported_date,'hh,start'-'hh,end')) AS Delta_Hours group by p.well_id, p.reported_date, |
Is there a better way to check if more than two strings exists on Typo3 fluid? Posted: 26 Aug 2021 08:24 AM PDT Here is my working not DRY code (using VHS ViewHelper): <v:condition.string.contains haystack="{pathFile}" needle=".jpg"> <f:then>JPG ICON</f:then> <f:else> <v:condition.string.contains haystack="{pathFile}" needle=".svg"> <f:then>SVG ICON</f:then> <f:else> <v:condition.string.contains haystack="{pathFile}" needle=".pdf"> <f:then>PDF ICON</f:then> <f:else>SOME OTHER ICON</f:else> </v:condition.string.contains> </f:else> </v:condition.string.contains> </f:else> </v:condition.string.contains> I used v:iterator.explode as well to get the string I want, but may be there is a simpler way using v:condition.string.contains |
How can I prevent two onscroll event listeners that call each other from making the resulting action jerky? Posted: 26 Aug 2021 08:26 AM PDT I have a faux scrollbar I've created with JS, and a table I want it to scroll. There's two possible scenarios: I want the scrollbar to move when I scroll the table (using a finger on mobile or two-touch on touchpad) I want the table to move when I use the scrollbar This is what I have so far. tableContainerDiv.addEventListener('scroll', function(e) { document.getElementById('faux-scrollbar').scrollLeft = this.scrollLeft; }); fauxScrollbar.addEventListener('scroll', function(e) { document.getElementById('table-container-div').scrollLeft = this.scrollLeft; }); It works perfectly, but is predictably a bit janky, as they fire each other off repeatedly. If I comment out either listener, the effect works smoothly, albeit only one way, not both ways. I'm not sure how to fix this, but I assume it can be fixed...? I've tried setting a variable in each event listener, that gets set on the first fire to identify the originator, and checked in each listener, but tied myself in knots... I also tried e.originalEvent , before discovering that was jQuery only, and it seems the vanilla option is isTrusted always says true, for some reason. Thank you |
Google account generator in python Posted: 26 Aug 2021 08:24 AM PDT Python script to generate google account and save the credentials in a text file or print to the console on VSCode, the account should be usable in different services of Google like YouTube, I really need it for a project I am currently working on... |
how to loop inside object array Angular Posted: 26 Aug 2021 08:25 AM PDT I want to display values from my json but I don't know how to do it. Is it possible to loop inside an object array ? i don't know if the keyvalue pipe can help me but I want to do without. how to get the student2 and also the name to display it ? thanks everyone. json { "student": { "student1": [], "student2": [ { "id": "123", "name": "boot" }, "student3": [], ] } } ts.file get(){ this.service.getAll().subscribe((data:any) => { object.keys(data).length > 0; }) } |
Delete CosmosDB Container Items Posted: 26 Aug 2021 08:25 AM PDT I am trying to create an Azure Function (implemented in Python) to delete an item in a CosmosDB container. Using Azure Cosmos DB Input & Output bindings, I was able to add, query and update items but I was not able to find a method that could delete one. Is it possible to delete an item using the binding methods? The following code is what I am currently using to do a simple update. _init_.py file import logging import azure.functions as func def main(req: func.HttpRequest, doc: func.Out[func.Document]) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') departure_time = "" arrival_time = "" try: req_body = req.get_json() except ValueError: pass else: bc_id_no = req_body.get('bc_id_no') trip_id = req_body.get('trip_id') departure_time = req_body.get('departure_time') arrival_time = req_body.get('arrival_time') if bc_id_no and trip_id: newdocs = func.DocumentList() input_dict = { "bc_id_no": bc_id_no, "id": trip_id, "departure_time": departure_time, "arrival_time": arrival_time } newdocs.append(func.Document.from_dict(input_dict)) doc.set(newdocs) return func.HttpResponse(f"This HTTP triggered function executed successfully.") else: return func.HttpResponse( "bc_id_no or trip_id not available", status_code=200 ) function.json { "scriptFile": "__init__.py", "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get", "post" ], "route": "update_rec" }, { "type": "cosmosDB", "direction": "out", "name": "doc", "databaseName": "mockDB", "collectionName": "mockCollection", "connectionStringSetting": "AzureCosmosDBConnectionString" }, { "type": "http", "direction": "out", "name": "$return" } ] } Understand that it may be possible to use the sqlQuery configuration properties for the input binding to specify a delete statement (not too sure if this is a good practice even..) but just wondering if another method for deletion is available. |
Plotting graphs in MATLAB Posted: 26 Aug 2021 08:26 AM PDT I was studying MATLAB and found this code for plotting a 3d graph x=-8:0.1:8 y=x [X,Y]=meshgrid(x,y) R=sqrt(X.^2+Y.^2)+eps Z=sin(R)./R mesh(x,y,Z,'-') Being confused about the use of the meshgrid function, I decided to try to avoid it and instead wrote x=-8:0.1:8 y=x r=sqrt(x.^2+y.^2)+eps z=sin(r)./r mesh(x,y,z) and to my surprise, it showed an error as Z must be a matrix, not a scalar or vector Now, as far as I understand, to draw a 3d graph, you only need to mark the points (x,y,z) accordingly as the values are given (in case of 2d, that's what it does). To do that, it only needs a list of values for x , y and z . So, what exactly is the problem with having z as a list? I would prefer a detailed answer. |
How to discard Promise type in TypeScript? Posted: 26 Aug 2021 08:25 AM PDT I am using TypeScript and I have the following promise chain: function bar(): Promise<boolean> { globalVar = doSomething(); return Promise.resolve(true); } return foo() .then(() => { return bar(); }).then(() => { return bas(); } In most cases, I need the return value of bas , but in one case I don't need it. What is the best way to discard the boolean type? I tried a cast like as Promise<void> but it doesn't work as the types void and boolean don't intersect. Here is a minimal MVCE: let globalVar: string = 'hello'; function bar(): Promise<boolean> { globalVar = 'world'; return Promise.resolve(true); } function xyz(): Promise<void> { return bar(); } TS Playground |
retrieve parent component ref for a hook Posted: 26 Aug 2021 08:25 AM PDT I've found myself needing to retrieve the element ref for every parent component that my hook, useExample , is used in. However, I'm stumped as to how I might be able to retrieve something like this or how to even check if there is an element to target? Usually I would just do something a little "hacky" in a functional component like so: const Example = WrappedComponent => { const ref = createRef(); return <WrappedComponent ref={ref} />; }; However, due to it being a hook and returning information and not a component, I can't target any component, and thus I'm very stumped. My current code: const useExample = () => { const [stateValue, setStateValue] = useState("example"); useEffect(() => { // Run some code... }, []); return stateValue; }; const Component = () => { const data = useExample(); return ( <div> /* <--- How do I gain access to this element */ <span>{ data }</span> </div> ); }; I could probably pass a created ref which has been attached to the parent div as a parameter to useExample , however this feels cheap and hacky, and I feel there should be a much easier solution. In the ideal world something like this would be amazing: const ref = React.getParentRef(); Apologies if there is an obvious answer in the documentation, I'm very new to React and am unsure of the correct question to be asking or what to be looking for in order to find it in the docs. |
Download images from IPFS Posted: 26 Aug 2021 08:25 AM PDT I have a nice set of URLs saved in this format Number Link 0 https://ipfs.io/ipfs/QmRRPWG96cmgTn2qSzjwr2qvfNEuhunv6FNeMFGa9bx6mQ 1 https://ipfs.io/ipfs/QmPbxeGcXhYQQNgsC6a36dDyYUcHgMLnGKnF8pVFmGsvqi 2 https://ipfs.io/ipfs/QmcJYkCKK7QPmYWjp4FD2e3Lv5WCGFuHNUByvGKBaytif4 3 https://ipfs.io/ipfs/QmYxT4LnK8sqLupjbS6eRvu1si7Ly2wFQAqFebxhWntcf6 4 https://ipfs.io/ipfs/QmSg9bPzW9anFYc3wWU5KnvymwkxQTpmqcRSfYj7UmiBa7 5 https://ipfs.io/ipfs/QmNwbd7ctEhGpVkP8nZvBBQfiNeFKRdxftJAxxEdkUKLcQ 6 https://ipfs.io/ipfs/QmWBgfBhyVmHNhBfEQ7p1P4Mpn7pm5b8KgSab2caELnTuV 7 https://ipfs.io/ipfs/QmRsJLrg27GQ1ZWyrXZFuJFdU5bapfzsyBfm3CAX1V1bw6 I am trying to use a loop to loop through all of the links and save the file import urllib.request for x,y in zip(link, num): url = str(x) name = str(y) filename = "%s.png" % name urllib.request.urlretrieve(url, filename) Everytime I run this code I get this error URLError: <urlopen error [WinError 10054] An existing connection was forcibly closed by the remote host> What is weird is that if I just run the code on one URL then it works fine. import urllib.request name = 1 filename = "%s.png" % name urllib.request.urlretrieve("https://ipfs.io/ipfs/QmcJYkCKK7QPmYWjp4FD2e3Lv5WCGFuHNUByvGKBaytif4", filename) How can this be fixed so that the code runs in a loop with no errors? thanks EDIT Here is some code that works for 1 image import pandas as pd import urllib.request links = [['number', 'link'], ['1', 'https://ipfs.io/ipfs/QmPbxeGcXhYQQNgsC6a36dDyYUcHgMLnGKnF8pVFmGsvqi'], ['2', 'https://ipfs.io/ipfs/QmcJYkCKK7QPmYWjp4FD2e3Lv5WCGFuHNUByvGKBaytif4'], ['3', 'https://ipfs.io/ipfs/QmYxT4LnK8sqLupjbS6eRvu1si7Ly2wFQAqFebxhWntcf6']] data = pd.DataFrame(links) link = data.get('Link', None) num = data.get('Number', None) name = 1 filename = "%s.png" % name urllib.request.urlretrieve("https://ipfs.io/ipfs/QmYxT4LnK8sqLupjbS6eRvu1si7Ly2wFQAqFebxhWntcf6", filename) |
How should I fix my ggplot boxplot code to get desired look? Posted: 26 Aug 2021 08:24 AM PDT I am aiming to produce a chart with a boxplot feature for that data that is grouped by year and by another factor (called status). My data set is in the data frame imf.cas and it consists of the records like these: country_iso_code year value status AFG 2019 11.705 Surplus AFG 2020 10.712 Surplus FRA 2019 -0.667 Mixed FRA 2020 -2.337 Mixed USA 2019 -2.241 Deficit USA 2020 -3.088 Deficit At the beginning my code was: ggplot(data = imf.cas, aes(x=year, y=value, group=year, fill=status))+ geom_boxplot(outlier.shape = 1, outlier.color = "grey") + coord_cartesian(ylim = c(-25,25)) + labs(x = "", y="(% of GDP)") It resulted in the follow look of the chart, which seems ignore my command of fill=status : Then, I extended my code in the following way in attempt to check whether fill=status works: ggplot(data = imf.cas, aes(x=year, y=value, group=year, fill=status))+ geom_boxplot(outlier.shape = 1, outlier.color = "grey") + coord_cartesian(ylim = c(-25,25)) + labs(x = "", y="(% of GDP)") + facet_wrap(~status,ncol = 3) + theme(axis.title.y = element_text(size = 9), legend.title = element_blank(), legend.background=element_blank(), legend.position = "bottom", plot.caption = element_text(hjust = 0, size = 8)) Indeed, it worked as the resulted chart shows the difference of data by status column: I am struggling to get why my initial code did not depict the data in the breakdown by status column. Any help is very much appreciated! P.S. In extended version of the code, the geom_smooth() command is added (below). However, the smoothing lines are not visible for each of three parts of the chart (below). Why? ggplot(data = df, aes(x=year, y=value, group = interaction(year, status), fill=status))+ geom_boxplot(outlier.shape = 1, outlier.color = "grey") + geom_smooth(data = df, aes(x=year, y=value), method = "loess", se=TRUE, color = "orange") + coord_cartesian(ylim = c(min(lims$min),max(lims$max))) + labs(x = "", y="(% of GDP)") + facet_wrap(~status, ncol = 3) + theme(axis.title.y = element_text(size = 9), legend.title = element_blank(), legend.background=element_blank(), legend.position = "bottom", plot.caption = element_text(hjust = 0, size = 8)) |
Woocommerce - specific products add free shipment for physic store shipping address Posted: 26 Aug 2021 08:25 AM PDT Into a wordpress site i need to add the possibility to ship some specific products to a specific shipping address (store physic address) with free shipping/cost 0. So, on that way customers can get the shipped products directly on store. Is is possible to add that functionality into Woocommerce and what would be the simplest way? Can woocommerce Local Pickup help on that case? How can i make that shipping option available only for some products? Please can you suggest any plugins that can help to achieve that part? Thanks in advance |
TensorFlow text generation RNN example failing on TF 2.6, tf.sparse.to_dense(), Invalid argument: indices[1] = [0] is repeated Posted: 26 Aug 2021 08:24 AM PDT I am trying to run through the TensorFlow text generation RNN example, https://github.com/tensorflow/text/blob/master/docs/tutorials/text_generation.ipynb Running on a local Windows computer with TensorFlow 2.6 installed. I was able to run through and train the RNN model successfully. I was getting a "Tensor' object has no attribute 'numpy" error but added, tf.compat.v1.enable_eager_execution() and this resolved it. But now trying to test the model with some text I am getting the error, Invalid argument: indices[1] = [0] is repeated This occurs in tf.sparse.to_dense inside the OneStep function. class OneStep(tf.keras.Model): def __init__(self, model, chars_from_ids, ids_from_chars, temperature=1.0): super().__init__() self.temperature = temperature self.model = model self.chars_from_ids = chars_from_ids self.ids_from_chars = ids_from_chars print(len(ids_from_chars.get_vocabulary())) # Create a mask to prevent "[UNK]" from being generated. skip_ids = self.ids_from_chars(['[UNK]'])[:, None] sparse_mask = tf.SparseTensor( # Put a -inf at each bad index. values=[-float('inf')]*len(skip_ids), indices=skip_ids, # Match the shape to the vocabulary dense_shape=[len(ids_from_chars.get_vocabulary())]) print(sparse_mask) self.prediction_mask = tf.sparse.to_dense(sparse_mask) I added some debug to print the ids_from_chars 76 SparseTensor(indices=tf.Tensor( [[0] [0]], shape=(2, 1), dtype=int64), values=tf.Tensor([-inf -inf], shape=(2,), dtype=float32), dense_shape=tf.Tensor([76], shape=(1,), dtype=int64)) 2021-08-25 15:28:23.935194: W tensorflow/core/framework/op_kernel.cc:1692] OP_REQUIRES failed at sparse_to_dense_op.cc:162 : Invalid argument: indices[1] = [0] is repeated Traceback (most recent call last): File "app.py", line 1041, in test_nlp_text_generation result = text_generation.predictionfunction(text, analytic_id) File "D:\Projects\python-run-2\text_generation.py", line 238, in predictionfunction one_step_model = OneStep(model, chars_from_ids, ids_from_chars) File "D:\Projects\python-run-2\text_generation.py", line 166, in __init__ self.prediction_mask = tf.sparse.to_dense(sparse_mask) File "D:\Users\james\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\ops\sparse_ops.py", line 1721, in sparse_tensor_to_dense name=name) File "D:\Users\james\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\ops\gen_sparse_ops.py", line 3161, in sparse_to_dense _ops.raise_from_not_ok_status(e, name) File "D:\Users\james\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\ops.py", line 6941, in raise_from_not_ok_status six.raise_from(core._status_to_exception(e.code, message), None) File "<string>", line 3, in raise_from tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[1] = [0] is repeated [Op:SparseToDense] Also, I had this example running fine on my computer previously. Just had reinstalled TensorFlow and was trying the demo from scratch again. Any idea what is causing this error, or how to fix it? |
How to prevent users from checking not existing urls, how to hide routes in Laravel 8.* Posted: 26 Aug 2021 08:24 AM PDT First question was solved with findOrFail method Is there any way to prevent users from checking non-existing routes? Example I've got route to http://127.0.0.1:8000/event/9 but event with id 8 does not exist, if user would go to that id there is a massage: Attempt to read property "photo_patch" on null (View: C:\xampp\htdocs\Laravel1\resources\views\frontend\eventView.blade.php) Or any other error from db that record does not exist. Second question How to turn on preety URLs in laravel So my page with display http://127.0.0.1:8000 not http://127.0.0.1:8000/events something... I know that its somewere in config files but I cant find it. Example class and route that uses it: -----------------------------Class---------------- public function eventView($id) { $notDisplay = Auth::user(); $eventView = Event::findOrFail($id); if(!$notDisplay){ $eventView->displayed = $eventView->displayed +1; $eventView->save(); } return view('frontend/eventView', ['eventView' => $eventView]); } ----------------Route----------------- Route::get('event/' . '{id}', [App\Http\Controllers\FrontendController::class, 'eventView'])->name('eventView'); |
Trying to setup Xdebugger on docker-compose #using (visual studio code) IDE Posted: 26 Aug 2021 08:24 AM PDT I am trying to use xdebugger on docker container with vscode IDE. I had follow online tutorial but the xdebugger jus no working. Can anyone help me with this ? I pressed F5 and refresh browser start to debug and nothing happend... My file : docker-compose.yml php-apache-environment: container_name: php-apache build: context: ./ dockerfile: Dockerfile depends_on: - db volumes: - ./:/var/www/html/ ports: - 8000:80 Dockerfile FROM php:8.0-apache RUN docker-php-ext-install mysqli && docker-php-ext-enable mysqli RUN pecl install xdebug && docker-php-ext-enable xdebug \ && echo "\n\ xdebug.remote_host=host.docker.internal \n\ xdebug.default_enable = 1 \n\ xdebug.remote_autostart = 1 \n\ xdebug.remote_connect_back = 0 \n\ xdebug.remote_enable = 1 \n\ xdebug.remote_handle = "dbgp" \n\ xdebug.remote_port = 9003 \n\ xdebug.remote_log = /var/www/html/xdebug.log \n\ " >> /usr/local/etc/php/conf.d/dokcer-php-ext-xdebug.ini RUN apt-get update && apt-get upgrade -y launch.json { // Utilisez IntelliSense pour en savoir plus sur les attributs possibles. // Pointez pour afficher la description des attributs existants. // Pour plus d'informations, visitez : https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Listen for XDebug on Docker App", "type": "php", "request": "launch", "port": 9003, "log": true, "pathMappings": { "/var/www/html": "${workspaceFolder}" } }, ] } |
Prismjs not working error Prism is not defined Posted: 26 Aug 2021 08:25 AM PDT I'm trying to use prism to make a code editor, I copied a template from this codesandbox here. The error is: ./node_modules/prismjs/components/prism-clike.js E:/Trabajos/Personal projects/OpenAI/Code translator/code-tranlator/node_modules/prismjs/components/prism-clike.js:1 > 1 | Prism.languages.clike = { 2 | 'comment': [ 3 | { 4 | pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/, For some context I'm using React, the code worked at first, then it stopped working, then started working again without me doing anything, which is odd, I tried uninstalling dependencies and reinstalling them with no success, I've searched the entire internet but there isn't much info on the subject (if any) so I'm stuck. This is the relevant code from the component: import React, { useState } from 'react' import Editor from 'react-simple-code-editor' import 'prismjs/components/prism-clike' import 'prismjs/components/prism-javascript' import 'prismjs/themes/prism.css' import {useCodex} from '../Context/CodexContext' export default function CodeEditor() { const { getCompletion } = useCodex(); const code = `function add(a, b) { return a + b; } const a = 123; ` const hightlightWithLineNumbers = (input) => input .split('\n') .map( (line, i) => `<span class='editorLineNumber'>${i + 1}</span>${line}` ) .join('\n') const [codeValue, setCodeValue] = useState(code) function handleSubmit(e) { e.preventDefault() getCompletion("translate this code from javascript to python " + codeValue); console.log("code value: ", codeValue); } return ( <div className="container"> <div className="row justify-content-center align-items-center"> <Editor value={codeValue} onValueChange={(code) => setCodeValue(code)} highlight={(code) => hightlightWithLineNumbers(code)} padding={10} textareaId="codeArea" className="editor" style={{ fontFamily: '"Fira code", "Fira Mono", monospace', fontSize: 18, outline: 0, }} /> <button className="btn btn-primary rounded w-25 my-5">asd</button> </div> </div> ) } note1: I don't know if this is relevant but I'm using bootstrap installed with node. |
get the value of ngModel typed element in a loop Posted: 26 Aug 2021 08:25 AM PDT I have a table of products for which I want to calculate a discount. I don't have the discount type in my class for the product which made it difficult because whenever I calculate the discounts it gets applicated to all the elements of the loop. My question is: is there any way to get the value of the only input typed and not loop over all of the elements? I did the following: <table> <thead> <tr> <th>product</th> <th>price</th> <th>discount</th> </tr> </thead> <tbody> <tr *ngFor="let prod of products"> <td>{{prod.name}}</td> <td>{{prod.price}}Dhs</td> <td> <input type="number" (keyup.enter)="calculateDiscount(prod.price)" [(ngModel)]="discount" placeholder="0" > </td> </tr> </tbody> </table> And this is how I calculate the discount calculateDiscount(price?: number): void { this.pricepr = price; if (this.pricepr !== undefined) { this.discounttotal=((this.pricepr*(this.discount))/100); console.log(this.discounttotal) this.totalwithDiscount=this.total-this.discounttotal; } } |
Converting lists into columns with boolean values in PowerQuery Posted: 26 Aug 2021 08:26 AM PDT I have a table that contains a column which contains a list with numbers in them. One such list could contain values like [4, 7, 13]. How can this be transformed into columns that have a predefined prefix (e.g. "vendor.") and then the value (e.g. 4) as the column name? Also, for all generated columns, the value should be true if the number was in the values list and false if it wasn't in the values list. E.g. given the following table: row_id | vendors | 1 | [4,7,13] | 2 | [1,7,13] | The following should be created: row_id | vendor.1 | vendor.4 | vendor.7 | vendor.13 | 1 | false | true | true | true | 2 | true | false | true | true | Is this possible in PowerQuery? |
Typescript eslint is flagging 'google' is not defined for google.maps.Marker[] Posted: 26 Aug 2021 08:25 AM PDT const google = window.google; let markers: google.maps.Marker[] = []; // Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox.addListener("places_changed", () => { const places = searchBox.getPlaces(); if (places.length === 0) { return; } // Clear out the old markers. markers.forEach((marker) => { marker.setMap(null); }); markers = []; // For each place, get the icon, name and location. const bounds = new google.maps.LatLngBounds(); places.forEach((place) => { if (!place.geometry || !place.geometry.location) { return; } const icon = { url: place.icon as string, size: new google.maps.Size(71, 71), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(17, 34), scaledSize: new google.maps.Size(25, 25), }; // Create a marker for each place. markers.push( new google.maps.Marker({ map, icon, title: place.name, position: place.geometry.location, }) ); if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } }); map.fitBounds(bounds); }); This is some code from google maps API. It compiles and runs just fine. The issue is that when a linter checks it, it gives me this error: 222:22 error 'google' is not defined no-undef I added const google = window.google; to the top of the code as this answer explains. google is not defined in react app using create-react-app But this only helps with instances where the 'new' keyword is used. It did not help for this case let markers: google.maps.Marker[] = []; where a type is being assigned to a variable. |
Response cache not working in asp.net core project Posted: 26 Aug 2021 08:26 AM PDT I try to implement Response cache in asp.net core project but its not working.This is startup.cs public void ConfigureServices(IServiceCollection services) { services.AddResponseCaching(); services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseResponseCaching(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } and this is my controller. [ResponseCache(Duration = 30)] public IActionResult Index() { ViewBag.IsMobile = RequestExtensions.IsMobileBrowser(ContextAccessor.HttpContext.Request); return View(); } but still cache control header id cache-control →no-cache, no-store Where i am lacking please help.This response cache is not working and i take guidance from Microsoft document |
No comments:
Post a Comment