id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23530000
My requirement is to roll the Y.log file also, after 4 MB. I am using rolling file appender for both X and Y logs. Y.log will be created in the same location where X.log is available. But it seems like now both the log files are not getting rolled over after 4 MB. It is keep on appending to the same logs and the size is increasing. Below is my log4j configuration. <appender name="Xlogfile" class="org.apache.log4j.RollingFileAppender"> <param name="append" value="true" /> <param name="file" value="/logs/X.log" /> <param name="MaxBackupIndex" value="200" /> <param name="MaxFileSize" value="4MB" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n"/> </layout> </appender> <appender name="Ylogfile" class="org.apache.log4j.RollingFileAppender"> <param name="append" value="true" /> <param name="file" value="/logs/Y.log" /> <param name="MaxBackupIndex" value="200" /> <param name="MaxFileSize" value="4MB" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{dd MMM yyyy HH:mm:ss} %5p %c{1} - %m%n"/> </layout> </appender> <root> <level value="INFO" /> <appender-ref ref=" Xlogfile " /> <appender-ref ref=" Ylogfile " /> </root> Could anyone please provide me a solution for this. Thanks in advance. A: Try adding a policy to your appender, like this: <Policies> <SizeBasedTriggeringPolicy size="4mb"/> </Policies>
doc_23530001
Header1, Header2, Header3 Value, Value, Value ... ... ... ... ... ... What I need is to pull in all the values from the second column (Header2) and read each value. Code below. @Bean @SuppressWarnings("unchecked") public IntegrationFlow fileIntegrationTesting() { Gson gson = new GsonBuilder().disableHtmlEscaping().create(); return IntegrationFlows .from(Files.inboundAdapter(new File(inputFilePath)) .filter(getFileFilters()) .autoCreateDirectory(true) , c -> c.poller(Pollers.fixedRate(1000)) ) .channel("fileInputChannel") .transform(Files.toStringTransformer()) .split(s -> s.applySequence(true).delimiters(",")) .aggregate(a -> a.releaseStrategy(g -> g.size() >= 10) .expireGroupsUponCompletion(true) ) .handle((p, h) -> gson.toJson(new RequestPayload((Collection<String>) p))) .enrichHeaders(eh -> eh.async(false) .header("accept", "application/json") .header("contentType", "application/json") ) .handle(Http.outboundGateway("URL") .httpMethod(HttpMethod.POST) .expectedResponseType(String.class) .extractPayload(true) ) .get(); } private FileListFilter<File> getFileFilters(){ ChainFileListFilter<File> cflf = new ChainFileListFilter<>(); cflf.addFilter(new LastModifiedFileListFilter(30)); cflf.addFilter(new AcceptOnceFileListFilter<>()); cflf.addFilter(new SimplePatternFileListFilter(fileExtention)); return cflf; } A: I think you should be using a FileSplitter, not a FileToStringTransformer which will load the whole file into a single String. Then, if you are discarding all the other columns, it would be most efficient to use .handle(myColumnSelector). With @Component public class MyColumnSelector { @ServiceActivator String getCol(String in) { return StringUtils.delimitedListToStringArray(in)[1]; } } (Adding some protection for badly formed rows).
doc_23530002
Driveboardapp is an app written in python and designed to run a lasersaur laser cutting machine.It make use of UART1, WiFi, and GPIOs. Developers recomend running the app into a beaglebone black board using an image based in Ubuntu 14.04 LTS with kernel 3.8 With this image I experience network stability problems and I found the more recent official beaglebone image based in debian 9.5 with kernel 4.14 much more reliable. Unfortunately I can't get the gpio functionality to work as expected with this new OS. This is the python code to set gpio pins: try: fw = file("/sys/class/gpio/export", "w") fw.write("%d" % (71)) fw.close() except IOError: # probably already exported pass # set the gpio pin to output # echo out > /sys/class/gpio/gpio71/direction fw = file("/sys/class/gpio/gpio71/direction", "w") fw.write("out") fw.close() # set the gpio pin high # echo 1 > /sys/class/gpio/gpio71/value fw = file("/sys/class/gpio/gpio71/value", "w") fw.write("1") fw.flush() fw.close() When I run the app in debian9.5 sometimes it breaks with this message: root@beaglebone:~/driveboardapp# python backend/app.py Traceback (most recent call last): File "backend/app.py", line 7, in <module> import config File "/root/driveboardapp/backend/config.py", line 194, in <module> fw = file("/sys/class/gpio/gpio71/direction", "w") IOError: [Errno 2] No such file or directory: '/sys/class/gpio/gpio71/direction' If i rerun the app it may break at the same point or it may succeed and eventually break at the next point in the code that make use of the gpio. So far I tried to add a small sleep before the file write attempt but it still fail. Driveboard app repo https://github.com/nortd/driveboardapp My edits at the code so far https://github.com/luky83/driveboardapp/blob/debian9.5/backend/config.py Thanks for any advice. A: Switching to Adafruit's BeagleBone IO Python Library seems to be the way to do it: import Adafruit_BBIO.GPIO as GPIO GPIO.setup("P8_46", GPIO.OUT) GPIO.output("P8_46", GPIO.HIGH)
doc_23530003
box.bind('mousedown' , function(event){ box.css('background-color' , '#ff00ff'); box.bind('mousemove' , movehandler); }); function movehandler(event){ box.css('background-color' , '#ffff00'); // do things to move div } But when I try the following and pass parameters to the movehandler function things don't seen to want to work. box.bind('mousedown' , function(event){ box.css('background-color' , '#ff00ff'); startY = event.pageY; boxtop = box.position().top; box.bind('mousemove' , boxhandler(startY, boxtop)); }); function boxhandler(a, b) { box.css('background-color' , '#ffff00'); dist = (event.pageY - a); var val = b + dist; box.css('WebkitTransform' , 'translate(0px, '+ val +'px)'); } So is it possible to pass arguments/parameters into a handler function and retain the info associated with the actual event? A: Please note that as you have box.bind('mousemove' inside box.bind('mousedown', then binding of mousemove will be done each time mousedown happens. You can try something like: var startY = null; var boxtop = null; // Start moving box.bind('mousedown' , function(event) { box.css('background-color' , '#ff00ff'); startY = event.pageY; boxtop = box.position().top; }); // Finish moving box.bind('mouseup', function() { startY = null; boxtop = null; }); // Handle moving box.bind('mousemove' , boxhandler); function boxhandler(event) { if (startY !== null) { box.css('background-color' , '#ffff00'); dist = (event.pageY - startY); var val = boxtop + dist; box.css('WebkitTransform' , 'translate(0px, '+ val +'px)'); } }
doc_23530004
I need it to work like Twitter and Facebook and load server side controls while appending new records to repeater control without paging. This is my .aspx code: <asp:repeater id="repStd" runat="server" onitemcommand="repStd_ItemCommand" onitemdatabound="rptCore_ItemDataBound"> <HeaderTemplate> <asp:Label ID="lnkStdName" runat="server" CommandName="Name" CssClass="hrefclass">Name</asp:Label> </HeaderTemplate> <ItemTemplate> <div class="headParent" id="STHeader" runat="server"> <asp:Label ID="lblStdName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Project_Name") %>'></asp:Label> </div> <div class="contentParent" id="STcontent" runat="server"> <asp:UpdatePanel ID="UpdatePanelST" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false"> <ContentTemplate> <cc1:AsyncFileUpload ID="STAsyncFileUpload_Pdf" runat="server" Width="500px" CompleteBackColor="White" OnClientUploadError="STuploadError" OnClientUploadComplete="STuploadComplete" OnClientUploadStarted="STUploadedStartedPdfFile" UploadingBackColor="#CCDDEE" UploaderStyle="Modern" ThrobberID="STinProgress" OnUploadedComplete="STPdf_FileUploadComplete" /> </ContentTemplate> </asp:UpdatePanel> </div> </ItemTemplate> </asp:repeater> My itemdatabound: public void rptCore_ItemDataBound(object sender, RepeaterItemEventArgs e) { //load controls data and calculations here.. like fileupload control etc } A: According to your requirement use for/Foreach loop by calling table/div structure in place of repeater.. For your logic call 10 records from last index and add in your table/div. This will solve your problem and it is very effective without making any performance issue.. For eg. follow below logic - DataTable dt = GetYourRows(); String html = ""; foreach(DataRow dr in dt.Rows) { html += "<div>"+dr["column"].ToString();+"</div>"; } then use your html anywhere in your existing HTML code
doc_23530005
var dataSet = [ ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"], ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"], ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"], ["Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060"], ["Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700"] ]; $(document).ready(function () { $("#gvDetails").dataTable({ data: dataSet, //bJQueryUI: true //,sPaginationType: "full_numbers" }); A: Remember import Jquery and DataTables. That's work: <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script> HTML <table id="gvDetails" class="display DataTable" cellspacing="0" width="100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tbody> </tbody> </table> JS var dataSet = [ ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"], ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"], ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"], ["Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060"], ["Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700"] ]; $(document).ready(function () { $("#gvDetails").dataTable({ data: dataSet, //bJQueryUI: true //,sPaginationType: "full_numbers" }); }); Result: https://jsfiddle.net/cmedina/7kfmyw6x/53/
doc_23530006
<a class="" href="#" style="text-decoration: none; color: #1b1b1b;" onclick="toDetailOrUrl(event, '1641438','')">[안내] 빗썸 - 빗썸 글로벌 간 간편 가상자산 이동 서비스 종료 안내</a> In ordinary case, the link url i want to get is in just beside 'href=', but there is just "#" in that html. When i run the code below that is usual way to using selenium to scrape the given html, it returns a https://cafe.bithumb.com/view/boards/43. But is just what i entered in 'driver.get()', and i don't want. url = "https://cafe.bithumb.com/view/boards/43" driver=webdriver.Chrome('chromedriver.exe') driver.get(url) driver.implicitly_wait(30) bo =driver.find_element_by_xpath("//tbody[1]/tr[@style='cursor:pointer;border-top:1px solid #dee2e6;background-color: white']/td[2]/a") print(bo.get_attribute('href')) What i want is https://cafe.bithumb.com/view/board-contents/1641438. You can get this url when you click a item corresponding with the xpath i wrote above. I want this url using selenium or other programmatic ways, no need to open a chrome and enter the url in addressbar, and click using mouse... like that. good A: You can use, bo.click() in order to click the element you want (I assumed you want to click bo) A: print(driver.execute_script('return arguments[0].getAttribute("href")',bo)) selenium , bo.get_attribute('href') is actually doing document.getElementById("somelocaator").href which returns full href , as '#' indicates current page you get current URL you provided in get() If you just need # you can use the execute_script
doc_23530007
import "fmt" type Pet interface { Bark() } type Dog int func (d Dog) Bark() { fmt.Println("W! W! W!") } type Cat int func (c Cat) Bark() { fmt.Println("M! M! M!") } type AdoptFunc func(pet Pet) func adoptDog(dog Dog) { fmt.Println("You live in my house from now on!") } func adoptCat(cat Cat) { fmt.Println("You live in my house from now on!") } func main() { var adoptFuncs map[string]AdoptFunc adoptFuncs["dog"] = adoptDog // cannot use adoptDog (type func(Dog)) as type AdoptFunc in assignment adoptFuncs["cat"] = adoptCat // the same as above } As the code above, is there a way to use a map or array to collect a bunch of similar functions adoptXxx? If not, what is right pattern to use for this situation? A: To use the map as a function collection you'll have to change the signature of your functions to match. func(Pet) is not the same type as func(Dog). You can re-write AdoptXXX functions to take in Pet and do a type select to ensure correct pet is being input: func adoptDog(pet Pet) { if _, ok := pet.(Dog); !ok { // process incorrect pet type } fmt.Println("You live in my house from now on!") }
doc_23530008
protected void imgbtn5_Click(object sender, EventArgs e) { Session["theme"] = lbl5.Text; foreach (ListViewItem item in theme5.Items) { Label country = (Label)item.FindControl("lblcountry"); Session["country"] = country.ToString(); Label price = (Label)item.FindControl("lblprice"); Session["price"] = price.ToString(); } } Here because of foreach Session Values get null again. please suggest some other way. aspx <asp:ListView ID="theme5" runat="server" DataSourceID="SqlDataSource5"> <ItemTemplate> <asp:Label ID="lblcountry" runat="server" Text='<%#Eval("Country") %>' /> </ItemTemplate> </asp:ListView> Here i want to get my label text value and transfer it to a session. I guess there is problem with: Label country = (Label)theme5.FindControl("lblcountry"); Here in country i get null value found while dubugging. A: you are adding label instead of label text protected void imgbtn5_Click(object sender, EventArgs e) { Session["theme"] = lbl5.Text; foreach (ListViewItem item in theme5.Items) { Label country = (Label)item.FindControl("lblcountry"); // here insted of country.ToString() you Should use Session["country"] = country.Text.ToString(); Label price = (Label)item.FindControl("lblprice"); Session["price"] = price.Text.ToString(); } } A: You can try with this code var index = ...; var result = (label)theme5.Items[index].FindControl("lblcountry"); You can use this code based on Itemcommand <asp:ListView ID="theme5" runat="server" DataSourceID="SqlDataSource5"> <ItemTemplate> <asp:Button ID="btn" Text="..." CommandName="YourCommand" CommandArgument='<%# Container.DataItemIndex %>' runat="server" ItemCommand="Test_ItemCommand" /> </ItemTemplate> </asp:ListView> protected void Test_ItemCommand(object sender, ListViewCommandEventArgs e) { if (e.CommandName.Equals("YourCommand")) { var result = (label)theme5.Items[Convert.ToInt32(e.CommandArgument)].FindControl("lblcountry"); } } A: I think you need to access the currently selected item of theme5 and get the Label in that item: Label lblcountry = (Label)theme5.Items[theme5.SelectedIndex].FindControl("lblcountry");
doc_23530009
I understand the basics of Flex data connection/webservices/etc... , I just can't seem to get my head around how to use the sharepoint list services. Does anybody out there have a nice detailed example of what I'm trying to achieve? Simple examples work too! :) Thanks so much Everyone! -E. A: Look at the "SOAP query example" or the WSDL from the SharePoint web-service (e.g. .../_vti_bin/lists.asmx?op=GetListItems or ../_vti_bin/lists.asmx?op=GetListItems&WSDL) and then look at the corresponding MSDN documentation (such as GetListItems) on how to "use" the web-service. It takes a little bit of familiarity to "know" to map viewFields with <viewFields>...</viewFields> (most work like this), but... the MSDN documentation (if prodded carefully) says "what" to put in the XML where the WSDL just gives the near-useless outline. There are a number of examples in the tubes (and related SO questions) of hand-rolled SOAP access for SP for various tasks. Microsoft also has some Open Specifications -- the link is always hard for me to find. Lots of stuff under the SharePoint branch. YMMV and it's mostly white-paper, but a good resource. Not sure what tools Flex has but because of the limited WSDL support, most of the mapping has to be hand-coded or come from a better definition source -- hopefully "an existing library" which can be used directly or modified-to-suit. I would highly recommend using a tool for testing the service access -- e.g. soapUI, which actually has a horrid UI -- because even the littlest error will come back with a cryptic error messages. Also, make sure to use SOAP 1.2. Happy (less than maximal pain) coding. P.S. A more specific question about a specific web-service would likely yield better responses.
doc_23530010
Even i have setted the stringHttpMessageConverter to charset utf-8 but didnt work. My code like //restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-32"))); HttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-16")); List<HttpMessageConverter<?>> httpMessageConverter = new ArrayList(); httpMessageConverter.add(stringHttpMessageConverter); restTemplate.setMessageConverters(httpMessageConverter); responseEntity = restTemplate.exchange(/*new URI(*/targetUrl/*)*/, httpMethod, reqEntity, String.class); If you look at the response, it looks like an chinese chars.. A: You can add this to your headers httpHeaders.set("Accept-Charset", StandardCharsets.UTF_8.name()); A: You can try below code responseEntity = restTemplate.exchange(/*new URI(*/targetUrl/*)*/, httpMethod, reqEntity, Object.class); Instead of String.class When i used Object.class then its start working for me.
doc_23530011
$sqlRome.="SELECT distinct id_jeune FROM jeunes_rome WHERE code_rome IN ("; foreach ($liste_rome as $rome): $sqlRome.="'".$rome."'";//HERE if ($j < count($liste_rome) - 1): $sqlRome.=","; $sqlRome.=") GROUP BY id_jeune HAVING COUNT(*)=" . $j; I did it before, but I can not remember! It must be simple I guess. A: You are doing that just fine, apart from any potential sql injection problems. You do have a problem with your block-structure however, use { ... } or end your foreach (): and if (): statements with the correct block endings: $sqlRome="SELECT distinct id_jeune FROM jeunes_rome WHERE code_rome IN ("; // ^ no concatenation here foreach ($liste_rome as $rome): $sqlRome.="'".$rome."'";//HERE if ($j < count($liste_rome) - 1): $sqlRome.=","; // end the if statement endif; // end the foreach loop endforeach; $sqlRome.=") GROUP BY id_jeune HAVING COUNT(*)=" . $j; And where does $j come from? As it does not change in the loop, it is either always adding a comma or never. That is probably not what you want. A: Try with - $sqlRome.="SELECT distinct id_jeune FROM jeunes_rome WHERE code_rome IN ("; foreach ($liste_rome as $rome) { $var[] = "'".$rome."'"; } $sqlRome.= implode(',', $var); $sqlRome.=") GROUP BY id_jeune HAVING COUNT(*)=" . $j;
doc_23530012
customCSS:'body { ^^^^^^^ SyntaxError: Unexpected token ILLEGAL My code is as following: var options = { siteType: "html", //defaultWhiteBackground: true, customCSS:"body { background-color: #b0c4de; }" }; webshot(svgsrc,'graphy2.png',options,function(err) { if(err) { console.log('error saving document', err) } else { console.log('The file was saved!'); } }); I can save image with no problem is just that I cannot find a way to apply custom css before saving an image, so any help would be appreciated. Thanks A: Try this instead (single quoted and in one line): var options = { siteType: 'html', customCSS: 'body {background-color: #b0c4de;}' } A: With reference to: link and this I found that I needed to specify (for example) : -webkit-justify-content for: justify-content A: you can also escape your lines var options = { siteType: "html", //defaultWhiteBackground: true, customCSS:"body { \ background-color: #b0c4de; \ }" };
doc_23530013
At one point I was able to get this working, but I did that by essentially calling, 'componentDidMount' after the promise was pushed into the call back clause of the setState funciton of the push function - which was essentially causing the entire component to re-render. I'm a fairly new coder, but my understanding is is that that is a fairly unconventional way to code something, and contrary to good coding methodologies. I believe I should be able to push it into state, and then have it change automatically. I have attached the relevant code below for you to examine. If you believe you need more please let me know. If someone could please tell me why I am getting this weird promise instead of the proper response object, so that I can then insert that into state, I would greatly appreciate it. I've attached some images below the code snippets that I hope will be helpful in providing an answer. I have also left brief descriptions of what they are. : class Companies extends React.Component { constructor(props) { super(props); this.state = { Companies: [], formData: { label: "", value: 0 }, }; } componentDidMount = () => { this.getListCompanies(); }; getListCompanies = () => { getAll().then(this.listOfCompaniesSuccess); }; listOfCompaniesSuccess = (config) => { let companyList = config.items; this.setState((prevState) => { return { ...prevState, Companies: companyList, }; }); }; onCompListError = (errResponse) => { _logger(errResponse); }; mapCompanies = (Companies) => ( <CompaniesList Companies={Companies} remove={remove} /> ); handleSubmit = (values) => { if (values.companyName === "PPP") { this.toastError(); //THIS IS FOR TESTING. } else { add(values) .getById(values.item) //I HAVE TRIED IN TWO DIFFERENT PLACES TO GET THE NEW COMPANY IN. HERE .then(this.newCompanyPush) .then(this.toastSuccess) .catch(this.toastError); } }; //THIS CODE RIGHT HERE IS THE CODE CAUSING THE ISSUE. newCompanyPush = (response) => { let newCompany = getById(response.item); // THIS IS THE OTHER PLACE I HAVE TRIED. this.setState((prevState) => { let newCompanyList = [...prevState.Companies]; newCompanyList.push(newCompany); return { Companies: newCompanyList, }; }); }; toastSuccess = () => { toast.success("Success", { closeOnClick: true, position: "top-right", }); }; toastError = (number) => { toast.error(`Error, index is ${number}`, { closeOnClick: true, position: "top-center", }); }; This is the axios call I am using. const getById = (id) => { const config = { method: "GET", url: companyUrls + id, withCredentials: true, crossdomain: true, headers: { "Content-Type": "application/json" }, }; return axios(config).then(onGlobalSuccess).catch(onGlobalError); }; After the promise is pushed into the array, this is what it looks like. Which is I guess good news because something is actually rendering in real time. This is the 'promise' that is being pushed into the array. Please note, when I make the same call in post-man, I get an entirely different response, see below. This is the outcome I get in postman, when I test the call.
doc_23530014
post :create, params: { account_id: 123, user: { ... } }, as: :json Is there a way to configure this behavior globally, so that I don't need to specify the content type on each test? I'm upgrading from Rails 4.2 and realised that without this attribute all my requests are treated as URL encoded forms, including my payload being URL encoded. This is causing many failures when I run my test suite and for some reason was working just fine in Rails 4.2. A: You can specify in your routes the default format for them, like so: defaults format: :json do resources :photos end as can be seen here: https://guides.rubyonrails.org/routing.html#defining-defaults You can always use a before_action as well: before_action :set_format def set_format request.format = 'json' end A: You could always just override ActionDispatch::Integration::RequestHelpers#process. module JSONRequestHelper alias_method :original_process, :process def process(method, path, **args) original_process(method, path, args.merge(as: :json)) end end require 'test_helper' class ApiTest < ActionDispatch::IntegrationTest include JSONRequestHelper end
doc_23530015
public class Input { private Map<String, String> parameters; public Input() { parameters = new HashMap<>(); } // getters and setters } In my Spring MVC controller I created a list which is to contain the inputs and pass it into my model. @RequestMapping(value = "/add", method = RequestMethod.GET) public String add(Model model) { List<Input> inputs = new ArrayList<>(); // Creating objects and adding them to the list. model.addAttribute("inputs", inputs); return "add"; } I've checked and all objects are created correctly. I have a problem with printing them out in the right way in the jsp <c:forEach var="input" items="${inputs}"> <div class="form-group"> <label for="${input.parameters['id']}">${input.parameters['title']</label> <input <c:forEach var="param" items="${input.parameters}"> <c:out value="${param.key}" />=<c:out value="${param.value}" /> </c:forEach> /> <form:errors path="${input.parameters['name']}" /> </div> </c:forEach> However, the input attributes are not rendered: <input =="="></input> It is not what I expect. What is wrong with my syntax? A: Ignoring the bad architectural design, your logic looks fine. Only, the ${param} is a reserved EL variable representing the HTTP request parameter map. E.g. ${param.foo} prints the bar value of http://example.com/context/page?foo=bar. See also our EL wiki page. Rename var="param" to something else and retry. Using "attributes" and "attribute" instead of "parameters" and "param" would make more sense and the code better readable. <c:forEach var="attribute" items="${input.attributes}"> <c:out value="${attribute.key}" />=<c:out value="${attribute.value}" /> </c:forEach>
doc_23530016
Example code of something the project uses: ` EasyTracker.getInstance().setContext(getActivity()); Tracker tracker = EasyTracker.getTracker(); if (tracker != null) tracker.sendView("Map"); super.onStart(); ` I have tried importing different modules and trying to find the correct package but I have not had any luck.
doc_23530017
For example, 273.900 needs to be 273.9 17.580 needs to be 17.58 116.000 needs to be 116 I have the following but this is not complete: def qTY = context.expand( '${Stock DataSource#QTY}' ) qTY = qTY.replaceAll('.000', '') qTY = qTY.replaceAll('00', '') return qTY Could someone help me tp write this more efficient? Thank you A: Something like this should do it: def elideZeros(s) { s.reverse().dropWhile { it in ['0', '.'] }.reverse() } assert elideZeros('273.900') == '273.9' assert elideZeros('17.580') == '17.58' assert elideZeros('116.000') == '116' A: You can use relatively simple regex for this: '273.002000'.replaceFirst( /((?<=(\..{0,20}))0+)$/, '' ).replaceFirst( /\.$/, '' ) prints 273.002
doc_23530018
sc.parallelize(Array(("red", "zero"), ("yellow", "one"), ("red", "two"))).groupByKey().collect.foreach(println) (red,CompactBuffer(zero, two)) (yellow,CompactBuffer(one)) But I noticed a blog post from Databricks and it's recommending not to use groupByKey for large dataset. Avoid GroupByKey Is there a way to achieve the same result using reduceByKey? I tried this but it's concatenating all values. By the way, for my case, both key and value are string type. sc.parallelize(Array(("red", "zero"), ("yellow", "one"), ("red", "two"))).reduceByKey(_ ++ _).collect.foreach(println) (red,zerotwo) (yellow,one) A: Use aggregateByKey: sc.parallelize(Array(("red", "zero"), ("yellow", "one"), ("red", "two"))) .aggregateByKey(ListBuffer.empty[String])( (numList, num) => {numList += num; numList}, (numList1, numList2) => {numList1.appendAll(numList2); numList1}) .mapValues(_.toList) .collect() scala> Array[(String, List[String])] = Array((yellow,List(one)), (red,List(zero, two))) See this answer for the details on aggregateByKey, this link for the rationale behind using a mutable dataset ListBuffer. EDIT: Is there a way to achieve the same result using reduceByKey? The above is actually worse in performance, please see comments by @zero323 for the details. A: sc.parallelize(Array(("red", "zero"), ("yellow", "one"), ("red", "two"))) .map(t => (t._1,List(t._2))) .reduceByKey(_:::_) .collect() Array[(String, List[String])] = Array((red,List(zero, two)), (yellow,List(one)))
doc_23530019
[one, two, three] Now I want to add double quotes to the strings of this array so that the final result would be: ["one", "two", "three"] Note that I do want the square brackets to be included as well. How can I do that in Groovy in the most comprehensive way? EDIT: I'm using groovy templating inside html code and I just want a string in the exact format I described above A: so if you have: def list = ['one', 'two', 'three'] Then you can do: String strList = list.inspect() To get the list quoted and with square brackets An alternative would also be to do: String strList = new groovy.json.JsonBuilder(list).toString() Which will give you the same, but in json format (with double quotes) A: so if you have: def list = ['one', 'two', 'three'] Then you can do: List modifiedList = list.collect{ '"' + it + '"'} output : ["one", "two", "three"] A: Since inspect() method adds single quotes instead of doubles in groovy templating for some reason, best solution I came up with is this ${myList.inspect().replaceAll("\'", "\"")} output: ["one", "two", "three"] My solution along with Prakash solution are the only ones that worked for me.
doc_23530020
I know that there are examples of using a server rendering framework with Material-UI. However, those examples assume that you're running NextJS' default server (next <whatever command>). In my case, I'm doing a custom NextJS server. I'm currently trying to implement Tab functionality and I'm noticing two problems: 1) When NextJS' development flag is set to true, nothing is rendered on the browser. 2) If I build a production version, I can generate content. However, I can't interact with the GUI. When using NextJS' default server, the Tab example code works fine. I have a feeling that I did something wrong with the configuration of NextJS and Material-UI, but can't quite pinpoint where I went wrong. Here an example repository that I created to demonstrate this problem. Most of the code is just copy past from Material-UI's NextJS repository. A: you are using koa routing and next.js file system routing same time in your application it would be good if you can disable one of them. To disable next.js file system routing paste below code in next.config.js useFileSystemPublicRoutes: false To solve your Material-UI static issue goto your server.js file and change your route from await ctx.render('about') to await ctx.render('/about') this will solve your problem
doc_23530021
To do this I created 3 hidden fields each of which copies the value from the password field and validates it against one of the 3 criteria it requires. Ie one of the criteria requires the user to input a number, once they do this the text stating a number is required turns green. Same thing happens for the other two hidden fields. these hidden fields can be seen below: <!--7-25 characters --> <input required ng-model="password" ng-pattern="/.{7,25}/" name="length" type="text" /> <!--Contain at least 1 letter --> <input required ng-model="password" ng-pattern="/[a-zA-Z]+/" name="letter" type="text" /> <!--Contain at least 1 number --> <input required ng-model="password" ng-pattern="/[0-9]+/" name="number" type="text" /> For the actual password field I then wanted to create a directory which would only set that field as valid if the three hidden fields are also valid. My directory looks like this (my form is named registration and to begin with im only testing it against the length hidden field): app.directive('validPwd', function() { return { restrict: 'A', require: '?ngModel', link: function(scope, elem, attrs, ngModel) { if(!ngModel) return; scope.$watch(attrs.ngModel, function() { validate(); }); var validate = function() { // set validity ngModel.$setValidity('validPwd', registration.length.$valid); }; } } }); My issue with this is that my directive is giving me the error that it cannot read property length of undefined. Am I not referring to it correctly or what? I cant seem to figure it out. Any help would be greatly appreciated. A: That's a very convoluted way to validate your field. You shouldn't pollute your view with 3 hidden fields just to validate a 4th one. Why don't you simply check each condition inside a custom validator, as explained in the documentation? app.directive('validPwd', function() { return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { var containsLetter = containsLetter(viewValue); var containsDigit = containsDigit(viewValue); var hasCorrectLength = hasCorrectLength(viewValue); ctrl.$setValidity('containsLetter', containsLetter); ctrl.$setValidity('containsDigit', containsDigit); ctrl.$setValidity('hasCorrectLength', hasCorrectLength); if (containsLetter && containsDigit && hasCorrectLength) { return viewValue; } else { return undefined; } }); } }; });
doc_23530022
SQL: ALTER PROCEDURE [dbo].[ASSET_insert] @iproduct varchar(55), @imanufact varchar (55), @itype varchar (30), @ipart_num varchar(50), @iversion varchar(50), @iprice float, @iwarranty varchar(30), @isupport varchar(12), @imaintenanc varchar(30), @icontact varchar(30), @icomments text, @inextproduct_id int, @iVENDOR varchar(50) AS BEGIN SET NOCOUNT ON set @inextproduct_id =(select top 1 nextidvalue from TI_IdGenerator where TableName='PRODUCT.PRODUCT_ID') set @inextproduct_id = @inextproduct_id + 1 update TI_IdGenerator set NextIdValue = @inextproduct_id where TableName='PRODUCT.PRODUCT_ID' -- ADD the Product type from ProdType - allows us to get the product type and connect to product. // works but may need to connect to AssetTup --declare @itype varchar (30) select @itype=p.AssetType from IN_AssetType p where p.AssetTypeId=@itype -- Get some of the info we need // Getting the information form the AssetType select @itype = a.AssetType from IN_AssetType a where a.AssetTypeId=@itype -- Get more.// Get Vendor Information - allows us to get create drop-down box declare @iVENDOR varchar(50) select @iVENDOR=v.COMPANY from VENDOR v where v.ID=@iVENDOR --INSERT into the web inventory form iTemplates into the PRODUCT INSERT INTO PRODUCT (PRODUCT_ID,PRODUCT,MANUFACT,TYPE,PART_NUM,VERSION,VENDOR,PRICE,WARRANTY,SUPPORT,MAINTENANC,CONTACT,COMMENTS) VALUES(@inextproduct_id,@iPRODUCT,@iMANUFACT,@itype,@iPART_NUM,@iVERSION,@iVENDOR,@iPRICE,@iWARRANTY,@iSUPPORT,@iMAINTENANC,@iCONTACT,@iCOMMENTS) Return @inextproduct_id END CODE USED TO CALL stored procedure newproduct_name=Request.Form("iproduct") newmanufacture_name=Request.Form("imanufact") newproudct_partnum=Request.Form("ipart_num") newproduct_version=Request.Form("iversion") newproduct_price=Request.Form("iprice") newproudct_warranty=Request.Form("iwarranty") newproduct_support= Request.Form("isupport") newproduct_maintenanc= Request.Form("imaintenanc") newproduct_contact= Request.Form("icontact") newproduct_comments= Request.Form("icomments ") if request.form("submit")="addnewproduct " then 'Add product to the Trackit Database into the PRODUCT sqltext="EXEC Asset_insert " sqltext=sqltext & cstr(inextproduct_id) & "," sqltext=sqltext & cstr(product_id) & "," sqltext=sqltext & cstr(vendor_id) & "," sqltext=sqltext & cstr(assetTypeId) & "," sqltext=sqltext & "'" & newproduct_name & "'" & "," sqltext=sqltext & "'" & newmanufacture_name & "'" & "," sqltext=sqltext & "'" & newproudct_partnum & "'" & "," sqltext=sqltext & "'" & newproduct_version & "'" & "," sqltext=sqltext & "'" & newproduct_price & "'" & "," sqltext=sqltext & "'" & newproudct_warranty & "'" & "," sqltext=sqltext & "'" & newproduct_support & "'" & "," sqltext=sqltext & "'" & newproduct_MAINTENANC & "'" & "," sqltext=sqltext & "'" & newproduct_contact & "'" & "," sqltext=sqltext & "'" & newproduct_comments & "'" 'response.write("<br>" & sqltext) set rsTrack=connTrack.Execute(sqlText) end if HTML CODE That it is being used is as follows <body onLoad="self.focus();document.form2.product.focus();" > <FORM METHOD="POST" ACTION="" id="form2" name="form2" target="_self"> <table title="Add New Product " bgcolor="DarkTurquoise"> <thead> <tr> <th> Product </th> <th> Manufacture </th> <th> Select Type </th> </tr> </thead> <tbody> <tr> <td> <input tabindex="3" type="text" name="iproduct" id=iproduct /> </td> <td> <input tabindex="4" type="text" name="imanufact"id=imanufact /> </td> <td> <%=ASSETNAME%> </td> <thead> <tr> <th> Part Number </th> <th> Version </th> <th> Vendor </th> </tr> </thead> <td> <input tabindex="5" type="text" name="ipart_num" id=ipart_num /> </td> <td> <input tabindex="6" type="text" name="iversion" id=iversion /> </td> <td> <%=displayown%> </td> <thead> <tr> <th> Price </th> <th> Support # </th> <th> Maintenance </th> </tr> </thead> <td> <input tabindex="7" type="text" name="iprice" id=iprice/> </td> <td> <input tabindex="8" type="text" name="isupport" id=isupport/> </td> <td> <input tabindex="9" type="text" name="imaintenanc" id=imaintenanc/> </td> </tr> </tbody> <thead> <tr> <th> Warranty: </th> </tr> </thead> <td> <input tabindex="10" type="text" name="iwarranty" id=iwarranty onclick="JACS.show(document.getElementById('iwarranty'),event);" value=" <%=iwarranty%> " > </td> <tr> <tr> <th> Contact (Telephone Number): </th> </tr> <td> <input tabindex="11" type="text" name="icontact" id=icontact /> </td> <br /> <tr> <th> Comments: </th> </tr> <td> <input tabindex="12" type="text" name="icomments" id=icomments /> </td> </tr> <td> <input TYPE="submit" NAME="addnewproduct" VALUE="Add Product" ID=addnewproduct /> <br /> </td> <br /> <td> <input type= button onclick='history.go(0)' name="refresh" value="Refresh" /> <br /> </td> </table> </FORM> A: The issue is you check for if request.form("submit") = "addnewproduct " then you should check for (without space) if request.form("submit") = "addnewproduct" then But, your code is very vulnerable to bug and SQL Injection. You should do at least 1 - Validate id ARE integer before using in the query : if not isnumeric(inextproduct_id) then inextproduct_id = 0 sqltext = sqltext & cstr(inextproduct_id) & "," 2 - Double quote your string variable : sqltext = sqltext & "'" & replace(newmanufacture_name, "'", "''") & "'" & ","
doc_23530023
let view1sub = UIView(frame: CGRect(x: 50, y: 50, width: 90, height: 90)) view1.addSubview(view1sub) view1sub.backgroundColor = UIColor.yellow view1.backgroundColor = UIColor.blue view1sub.backgroundColor = UIColor.red view1.layer.borderWidth = 3.0 view1.layer.borderColor = UIColor.purple.cgColor view1sub.layer.borderWidth = 2.0 view1sub.layer.borderColor = UIColor.red.cgColor I use the code above to add a border to view1. I want to add a border to the view1sub by using the same code. To my surprise, the background color of view1sub is changed too. A: layer.border is working for view1sub. you're just not able to see because your view1sub background color is red. Change background to other color you can see then.
doc_23530024
However, I wanted to do it for folders. the problem is that for each day I have a different name for the folder. like: 20170530.daily 20170529.daily and on... I've attached the batch I already wrote, can you look into this? `@echo off :: BatchGotAdmin (Run as Admin code starts) REM --> Check for permissions >nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" REM --> If error flag set, we do not have admin. if '%errorlevel%' NEQ '0' ( echo Requesting administrative privileges... goto UACPrompt ) else ( goto gotAdmin ) :UACPrompt echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs" echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs" "%temp%\getadmin.vbs" exit /B :gotAdmin if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" ) pushd "%CD%" CD /D "%~dp0" :: BatchGotAdmin (Run as Admin code ends) :: Your codes should start from the following line @echo off for %%A in ("E:\Logs\SmartLogger\*") do (if /I not "%%~xA" == ".zip" 7za.exe a -tzip -mx5 -y -- "%%~dpnA.zip" "%%~A" >nul && del /Q /F "%%~A")`
doc_23530025
IntelliJ IDEA 2022.2.2 Erlang plugin 0.11.1144 SDK: Erlang OTP 25, erts-13.0 Project Imported: https://github.com/FlowForwarding/enetconf When I mouse over some variables, I get the message "Cannot find declaration to go to". As a result, I am unable to do a code walk-through. Please help me in resolving the issue. A: The issue got resolved after configuring Content roots as explained in https://www.jetbrains.com/help/idea/content-roots.html. The ContentRoot looked as follows.
doc_23530026
in onCreate() i'm building the fire db and in onStop() I'm removing the user from online table. i just want to destroy user presence only if it leaves the app and maintain presence all over the app activities. here is my code @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rps_landing_page); databaseReference.child("Online-users").child(userId).setValue( new User(getIntent().getStringExtra("userName"), image));} } @Override protected void onStop() { super.onStop(); String userId = getIntent().getStringExtra("userId"); database = FirebaseDatabase.getInstance(); databaseReference = database.getReference(); databaseReference.child("Online-users").child(userId).removeValue(); }
doc_23530027
At the moment I'm using a UITapGestureRecognizer but in my opinion it's not the most suitable way. tableViewController.StaticCell.AddGestureRecognizer(new UITapGestureRecognizer(() => { if (ViewModel.SomeCommand.CanExecute()) { ViewModel.SomeCommand.Execute(null); } })); A: You can bind a Tap straight to a command: using MvvmCross.Binding.iOS.Views.Gestures; set.Bind(this.SomeView.Tap()).For(vm => vm.Command) A: You can use the Tap() like that: set.Bind(myView.Tap()).For(v=>v.Command).To(vm => vm.myViewModelCommand);
doc_23530028
views.py class PostDetail(DetailView): model = Post def get_context_data(self, **kwargs): data = super(PostDetail, self).get_context_data(**kwargs) vc = self.object.view_count self.object.view_count = F('view_count') + 1 self.object.save() self.object.view_count = vc + 1 initial_comment_data = { 'post': self.get_object(), } data['comment_form'] = CommentModelForm(initial=initial_comment_data) return data class CommentCreate(LoginRequiredMixin,CreateView): model = Comment form_class = CommentModelForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) models.py class Post(models.Model): title = models.CharField(max_length=100)#title of a post content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) #if a user is deleted all of their post will be as well view_count = models.IntegerField(default=0) post_files = models.FileField(null = True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Comment(models.Model): post = models.ForeignKey('forum.Post', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(null=True) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.text def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I want the comment to go into the correct post like it does, but with out the page not found error. A: The Comment.get_absolute_url method is passing in the pk of the comment instead of the post. Try this instead: class Comment(models.Model): ... def get_absolute_url(self): # notice I use self.post.pk here instead of self.pk return reverse('post-detail', kwargs={'pk': self.post.pk}) I think it'd be best practice for the Comment.get_absolute_url to return the URL of the comment. On your CreateView you can define a get_success_url [1] that instead redirects to the Post. class CommentCreate(LoginRequiredMixin,CreateView): def get_success_url(self): return self.object.post.get_absolute_url() [1] https://docs.djangoproject.com/en/2.2/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.get_success_url
doc_23530029
I did research and found example on page-transition animation using Reach-Router and React-Transition-Group https://reach.tech/router/example/animation This example uses CSS to animate, But I wanted to animate it with GSAP and it uses is pure JavaScript not CSS. So, it mean I wouldn't need to use TransitionGroup and CSSTransition. Later on I found another example on page transition animation with GSAP. https://stackblitz.com/edit/gsap-react-route-animation But it uses react-router not reach-router. Since react-router and reach-router look almost close to each other. I decide to go on my own experiment starting with GSAP, RTG and React-Router so I can have better understanding how it work... Here's my sandbox. https://codesandbox.io/s/react-router-gsap-pgu24 Animation worked! Then, I did another experiment getting exactly copy of code and convert some area to make it compatible with Reach-Router. Here's my sandbox. https://codesandbox.io/s/reach-router-gsap-h5rny?fontsize=14 Everything works except for animation. Its been struggling for me to find what's the problem and I not understanding here. Did I missing something? Please need help?
doc_23530030
I'm using an AuthContext for the whole user authentication across the webapp. I save all the user-data inside a state. With the help of useEffect and the sessionStorage I store the user object so It can be used after a page reload. [...] export const AuthProvider = ({ children }) => { const [user, setUser] = useState({}) useEffect(() => { const sessionUser = sessionStorage.getItem("user") if(!sessionUser) return changeUser(JSON.parse(sessionUser)) }, []) const hasRank = (ranks) => { if(!Object.keys(user).length > 0) return false const matchingPerms = ranks.filter(rank => user.rank.includes(rank)) return matchingPerms.length > 0 } const changeUser = (data) => { setUser(data) if(Object.keys(data).length > 0) { return sessionStorage.setItem("user", JSON.stringify(data)) } return sessionStorage.removeItem("user") } } [...] In order to protect certain pages I'm using a Protected Route Component that checks whether the user is logged in or not. [...] const auth = useContext(AuthContext) const isAuthorized = auth.hasRank(rest.rank) <Route {...rest} render={props => { return isAuthorized ? ( <Component {...props} /> ) : ( <Redirect to="/auth/login" /> ) }} /> The saving and fetching into and from the sessionStorage works fine until I want to render content that's inside a protected route - I always get redirected to the login page, because the user object is empty because of the reload and the state is not being updated early enough. Therefore the protected route checks for authentication with an empty object, which results in a redirect to the login page. How can I wait until the user state is being updated before checking the authentication inside the protected route? EDIT: App Component: return ( <Router> <Switch> <Route path="/auth/register" component={Register} /> <Route path="/auth/login" component={LogIn} /> <Route path="/err/404" component={Page404} /> <Route path="/" component={PanelRoutes}/> </Switch> </Router> ) PanelRoutes Component: return ( <div className="skin-default fixed-layout"> <div id="main-wrapper"> <Topbar /> <Sidebar /> <div className="page-wrapper"> <div className="container-fluid"> <Switch> <Route exact path="/" component={Homepage} /> <Route exact path="/legal/imprint" component={Imprint} /> <Route exact path="/legal/privacy" component={Privacy} /> <ProtectedRoute exact path="/mc/sounds" component={McSounds} rank={["ADMIN", "MC"]} /> <ProtectedRoute exact path="/admin/users" component={AdminUsers} rank={["ADMIN"]} /> </Switch> </div> </div> </div> </div> ) Kind Regards
doc_23530031
Integrating the Python to VBA seems to be fairly simple. I made a module in VBA using this code: Sub RunPythonScript() Dim objShell As Object Dim PythonExePath, PythonScriptPath As String Set objShell = VBA.CreateObject("Wscript.Shell") PythonExePath = """C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe""" PythonScriptPath = "E:\My Documents\Finance\Economy\excel2.py" objShell.Run PythonExePath & PythonScriptPath End Sub And for python: from openpyxl import load_workbook wb = load_workbook('Python_Button.xlsm') ws = wb["Sheet1"] for i in range (1,21): currentCell = "A" + str(i) ws[currentCell] = i wb.save('Python_Button.xlsm') wb.close() A: So this would be one way to do it: Option Explicit Sub RunPythonScript() Dim objShell As Object Dim PythonExe, PythonScript As String Set objShell = VBA.CreateObject("Wscript.Shell") PythonExe = """C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe""" PythonScript = """E:\My Documents\Finance\Economy\excel6.py""" objShell.Run PythonExe & PythonScript End Sub And on Python import xlwings as xw book.sheets["Sheet1"].range('A1').value = 100 Now one can add a button in the excel sheet and call the python script to populate the excel.
doc_23530032
First I tried this but after i clicked OK the box disappeared and nothing happened: Sub inputbox() Dim mlt As String Dim myString As String myString = ThisWorkbook.Sheets("Bericht_BOSCH").Cells(2, 6).Value mlt = Application.inputbox("Insert your age:") End Sub Then i tried to tell my code where the text from the Inputbox has to go and added 2 rows to my code: Range("B6").Select ActiveSheet.Paste Now my code selects the cell B6 after I click OK but it doesn't paste the code there. Now my question: What did I do wrong? Thank you in advance! A: Sub inputbox() Dim mlt As String Dim myString As String myString = ThisWorkbook.Sheets("Bericht_BOSCH").Cells(2, 6).Value mlt = Application.inputbox("Insert your age:") ActiveSheet.range("B6").value = mlt End Sub A: You can even do it in one line: Sub TestMe() ThisWorkbook.Sheets("Bericht_BOSCH").Cells(2, 6) = Application.inputbox("Insert age:") End Sub
doc_23530033
days_took_to_equip cumu_percent 1 0.017418302 2 0.020625735 3 0.023148307 4 0.025237133 5 0.026972115 6 0.028752754 7 0.030350763 8 0.032040087 9 0.033603853 10 0.035270349 11 0.036788458 12 0.037518976 13 0.038283738 14 0.039379516 15 0.040189935 16 0.040783481 17 0.041685215 18 0.042347247 19 0.043032109 20 0.043739798 21 0.044230616 22 0.04476709 23 0.045269322 24 0.045725896 25 0.046250956 26 0.046684701 27 0.047129861 28 0.047620678 29 0.047997352 30 0.048396854 Where my expected output is Range Avg cum Percent 1 to 10 0.027 1 to 20 0.033 1 to 30 0.038 Tried pivots tables and labelling is tricky here I would need this out put to plot a graph A: Try- =MAP(SEQUENCE(3,1,10,10),LAMBDA(x,AVERAGE(INDEX(B2:B31,SEQUENCE(x))))) A: I got three answers and the cells consists of formula E3: =AVERAGE(INDEX($B$2:$B$31,SEQUENCE(RIGHT($D3,2)))) F3: =AVERAGE(INDEX($B$2:$B$31,ROW(INDIRECT("1:"&RIGHT($D3,2))))) G3: =AVERAGE(OFFSET($A$1,1,1,RIGHT(D3,2)))
doc_23530034
I put location capturer before the segue in the override function, but it still went to homepage before the user had an opportunity to accept share location. This is not really unexpected since the entire override function is by definition an override function override func viewDidAppear(_ animated: Bool) { ////////////////////// func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let databaseRef = Database.database().reference() guard let uid = Auth.auth().currentUser?.uid else { return } guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return } print("locations = \(locValue.latitude) \(locValue.longitude)") latestLocation = ["latitude" : locValue.latitude, "longitude" : locValue.longitude] let lat = locValue.latitude let lon = locValue.longitude dict = CLLocation(latitude: lat, longitude: lon) print("dict", dict) if let locationDictionary = latestLocation { databaseRef.child("people").child(uid).child("Coordinates").setValue(locationDictionary) } } ////////////////////// if Auth.auth().currentUser != nil { self.performSegue(withIdentifier: "tohome", sender: nil) } } Update: This is how I login and register. @IBAction func RegisterPressed(_ sender: Any) { Auth.auth().createUser(withEmail: (emailField.text ?? ""), password: (passwordField.text ?? "")) { (user, error) in if let _eror = error { //something bad happning print(_eror.localizedDescription ) let alert = UIAlertController(title: "Error", message: "Invalid Entry or Duplicate.", preferredStyle: UIAlertController.Style.alert) let action = UIAlertAction(title: "Ok", style: .default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) }else{ //user registered successfully print(user as Any) if let userID = user?.user.uid { KeychainWrapper.standard.set((userID), forKey: "uid") let databaseRef = Database.database().reference() databaseRef.child("A1").child(userID).child("users").setValue(self.emailField.text!) databaseRef.child("people").child(userID).child("postID").setValue(userID) let components = self.emailField.text!.split(separator: "@") let child1 = components[0] //will be jake let child2 = components[1] //will be aol.com print(components, child1, child2, "childs") databaseRef.child("people").child(userID).child("e2").setValue(child2) components.forEach { print($0) } self.performSegue(withIdentifier: "tohome", sender: nil) } } } } @IBAction func loginInPressed(_ sender: Any) { Auth.auth().signIn(withEmail: (emailField.text ?? ""), password: (passwordField.text ?? "")) { (user, error) in if let _eror = error { //something bad happning print(_eror.localizedDescription ) let alert = UIAlertController(title: "Error", message: "Incorrect Email or Password.", preferredStyle: UIAlertController.Style.alert) let action = UIAlertAction(title: "Ok", style: .default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) }else{ //user registered successfully print(user as Any) if let userID = user?.user.uid { KeychainWrapper.standard.set((userID), forKey: "uid") self.performSegue(withIdentifier: "tohome", sender: nil) } } } } A: If I understand it correctly in viewDidAppear(_:) you have one condition. If it's true you immediately trying to perform the segue. if Auth.auth().currentUser != nil { self.performSegue(withIdentifier: "tohome", sender: nil) } As location is must to move into HomeScreen, why don't you do the navigation(segue) when you receive the first location update inside CLLocationManagerDelegate? func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { // check for existing location if we received earlier guard self.latestLoc == nil else { // we received one location earlier, navigation to Home completed. no need to proceed // If we no longer need to listen for loc updates, we can stop listening further manager.stopUpdatingLocation() return } // ... Your exiting data base update code guard let latestLoc = locations.last else { return } self.latestLoc = latestLoc // If you want to pass this location to destination view controller in `prepare(for: UIStoryboardSegue, sender: Any?)` // Also it will good practice to call manager.stopUpdatingLocation() if you need location only for once // Now move to HomeScreen self.performSegue(withIdentifier: "tohome", sender: nil) // If we no longer need to listen for loc updates, we can stop listening further manager.stopUpdatingLocation() }
doc_23530035
CREATE TABLE individual ( ID INTEGER PRIMARY KEY, NAME VARCHAR2(100) NOT NULL, ENTERPRISE_ID VARCHAR2(25) NOT NULL UNIQUE ); CREATE TABLE business ( ID INTEGER PRIMARY KEY, NAME VARCHAR2(100) NOT NULL, ENTERPRISE_ID VARCHAR2(25) NOT NULL UNIQUE ); CREATE TABLE ind_to_business ( ID INTEGER PRIMARY KEY, IND_ID REFERENCES individual(id), BUS_ID REFERENCES business(id), START_DT DATE NOT NULL, END_DT DATE ); I'm looking for the best way to display one row for each person. If they are linked to one business, I want to display the the business's ENTERPRISE_ID. If they are linked to more than one business, I want to display the default value 'Multiple'. They will always be linked to a business, so there is no LEFT JOIN necessary. They can also be linked to a business more than once (Leaving and coming back). Multiple records for the same business would be aggregated. So for the following sample data: Individual: +----+------------+---------------+ | ID | NAME | ENTERPRISE_ID | +----+------------+---------------+ | 1 | John Smith | 53a23B7 | | 2 | Jane Doe | 63f2a35 | +----+------------+---------------+ Business: +----+----------+---------------+ | ID | NAME | ENTERPRISE_ID | +----+----------+---------------+ | 3 | ABC Corp | 2a34d9b | | 4 | XYZ Inc | 34bf21e | +----+----------+---------------+ ind_to_business +----+--------+--------+-------------+-------------+ | ID | IND_ID | BUS_ID | START_DT | END_DT | +----+--------+--------+-------------+-------------+ | 5 | 1 | 3 | 01-JAN-2000 | 31-DEC-2002 | | 6 | 1 | 3 | 01-JAN-2015 | | | 7 | 2 | 3 | 01-JAN-2000 | | | 8 | 2 | 4 | 01-MAR-2006 | 05-JUN-2010 | | 9 | 2 | 4 | 15-DEC-2019 | | +----+--------+--------+-------------+-------------+ I would expect the following output: +---------+------------+------------+ | IND_ID | NAME | LINKED_BUS | +---------+------------+------------+ | 53a23B7 | John Smith | 2a34d9b | | 63f2a35 | Jane Doe | Multiple | +---------+------------+------------+ Here is my current query: SELECT DISTINCT sub.ind_id, sub.name, DECODE(sub.bus_count, 1, sub.bus_id, 'Multiple') AS LINKED_BUS FROM (SELECT i.enterprise_id AS IND_ID, i.name, b.enterprise_id AS BUS_ID, COUNT(DISTINCT b.enterprise_id) OVER (PARTITION BY i.id) AS BUS_COUNT FROM individual i INNER JOIN ind_to_business i2b ON i.id = i2b.ind_id INNER JOIN business b ON i2b.bus_id = b.id) sub; My query works, but this is running on a large dataset and taking a long time to run. I'm wondering if anyone has any ideas on how improve this so that there isn't so much wasted processing (i.e Needing to do a DISTINCT on the final result or doing COUNT(DISTINCT) in the inline view only to use that value in the DECODE above). I've also created a DBFiddle for this question. (Link) Thanks in advance for any input. A: You could try and use a correlated subquery. This removes the need for outer distinct: SELECT i.enterprise_id ind_id, i.name, ( SELECT DECODE(COUNT(DISTINCT b.enterprise_id), 1, MIN(bus_id), 'Multiple') FROM ind_to_business i2b INNER JOIN business b ON i2b.bus_id = b.id WHERE i2b.ind_id = i.id ) linked_bus FROM individual i A: You can join with the aggregated ind_to_business per individual. One way to do this: select i.id, i.name, coalesce(b.enterprise_id, 'Multiple') from individual i join ( select ind_id, case when min(bus_id) = max(bus_id) then min(bus_id) else null end as bus_id from ind_to_business group by ind_id ) ib on ib.ind_id = i.id left join business b on b.id = ib.bus_id order by i.id; A: No need of using DISTINCT twice. You could use subquery factoring and put the in-line view in WITH clause, and make the data set DISTINCT in the subquery itself. WITH data AS ( SELECT distinct i.enterprise_id AS IND_ID, i.name, b.enterprise_id AS BUS_ID FROM individual i JOIN ind_to_business i2b ON i.id = i2b.ind_id JOIN business b ON i2b.bus_id = b.id ) SELECT ind_id, name, case when count(*) = 1 then MIN(bus_id) else 'Multiple' end AS LINKED_BUS FROM data GROUP BY ind_id, name; IND_ID NAME LINKED_BUS ---------- ---------- ------------------------- 53a23B7 John Smith 2a34d9b 63f2a35 Jane Doe Multiple A: First you should sub-query to get all needed dimensions and then do all your final aggregation using CASE statement. select ind_id, name, case when count(*) > 1 then 'Multiple' else ind_id end as linked_bus from ( select distinct i.enterprise_id as ind_id, i.name, b.enterprise_id as bus_id from individual i join ind_to_business i2b on i.id = i2b.ind_id join business b on i2b.bus_id = b.id ) vals group by ind_id, name order by ind_id
doc_23530036
unnested = left_join(unnested, X3g_data[,c(1:6)], by = c("Country" = "CountryName"), all.x = TRUE) unnested = left_join(unnested, new_data, by = "Country", all.x = TRUE) I want to combine them into one left_join command, I found this answer, but it assumes that the column names are the same, which is not the case for me. How can combine these two operations into a single operation? A: You could pipe (%>%) these together: library(tidyverse) unnested %>% left_join(X3g_data[,c(1:6)], by = c("Country" = "CountryName")) %>% left_join(new_data, by = "Country") Another option is to adjust the input data so the merging columns are the same for all and then use purrr::reduce(): list(unnested, rename(X3g_data[,c(1:6)], Country = CountryName), new_data) %>% reduce(left_join)
doc_23530037
As you can see in the below image , the girl & the dog is not completely shown: original image Is there any css property to completely so the image as the background ? or I have to resize the image ? Here's my css: *{ margin: 0; padding: 0; } body{ background-image: url('../public/images/bg0.jpg'); height: 100vh; background-repeat: no-repeat; background-size: cover; object-fit: contain; transition: background-image 1.5s linear; } #__next{ height: 100%; } A: You are using background-size: cover; so the image will try to fit itself to the element. You may change properties to background-repeat:no-repeat; background-size:contain;. or using background-position: bottom. I hope this solve your problem. Check this W3 out background-size background-image A: Using "background-size: cover;" the browser will expand the background photo so it will cover the whole website body. You could use "background-size: contain;" to see the whole image, but it will not cover the whole website. The best solution is to resize the image.
doc_23530038
However this does not work. %ifort -v ifort version 16.0.1 %ifort -v | grep "version" ifort version 16.0.1 %ifort -v | grep "xyz" ifort version 16.0.1 It appears as if the output is getting printed irrespective of my pattern. So to test it out I tried the following redirection to null and it still printed. It seems likes the output is not going to the stdout. %ifort -v > /dev/null ifort version 16.0.1 %ifort -v 2>/dev/null ifort: error #10236: file not found: '2' ifort version 16.0.1 Is it possible that the information i see in shell is actually being written by a different process than the current executing ifort command and thats the reason I am unable to capture it? How can I capture this and grep it? A: Apparently the ifort -v writes to stderr. On bash redirecting stderr to stdout helps with that. The version could be obtained then for example using ifort -v 2>&1 | awk '{ print $2}'. It looks like it is not trivial to redirect stderr to stdout on (t)csh and that csh family of shells is not well suited for scripting.
doc_23530039
I'm looking to have an import function where the user can import workbook B that contains 1 sheet into workbook A. workbook A would check to see how many "non system sheets" that currently exists and insert the new sheet at the end with a sheet number that is 20+. For example: Total sheets in workbook A = 18 Total "system sheets" in A = 13 (sheet 1-sheet 13) Total "non system sheets" in A = 5 (sheet 20-sheet 24) If I were to import a new sheet workbook A would assign it as sheet 25 I want VBA to change the code name(sheet number) and not the name of the sheet. I've tried searching for hows, can someone please point me in the right direction on how to do this? thanks! A: In the Excel object model a Worksheet has 2 different name properties: Worksheet.Name Worksheet.CodeName the Name property is read/write and contains the name that appears on the sheet tab. It is user and VBA changeable the CodeName property is read-only You can reference a particular sheet as Worksheets("Data").Range("A1") where Data is the .Name property or as Sheet1.Range("A1") where Sheet1 is the codename of the worksheet. edit: You can change the CodeName Property by accessing the VBA Project Model Components Extensibility. ThisWorkbook.VBProject.VBComponents(Sheets("Sheetname").CodeName).Name = "Sheet" & Workbook.Sheets.Count Just be sure to have the programmatic access to visual basic project. File -> Options -> Trust Center -> Trust Center Setttings -> Macro Settings -> Trust Access to the VBA Project object model. A: In your specific example, you could modify the CodeName in Workbook B before the user imports it to Workbook A - because if you copy a sheet to another workbook, it retains its CodeName. Otherwise you have to get into modifying the VBProject itself, e.g.: <Workbook>.VBProject.VBComponents(<Workbook>.Sheets(<SheetName>).CodeName).Properties("_Codename").value = <CodeName> I came up with (and tested) the copying solution for a slightly different case, where the workbook into which I'm copying the sheet has its VBAProject password-protected, which means that the above code throws: 50289 : Can't perform operation since the project is protected.
doc_23530040
I'm honestly not sure where to ask this so I figured I'd start here. Sorry in advance if it's not. At work we have this older system. I say older because it was put in place before I was got here, not because it's actually old. It stores documents that we process into a mssql database. The file types are pdf, excel, msg, and probably more. An example row from the DB. id 7 docid 7 filename Medical benefits and rates.pdf filesize 50669 filetype pdf path NULL image 2030206F626A0D0A3C3C202F54797065202F50616765202F506172... created 2009-06-02 18:45:15.483 modified NULL isdeleted 0 session NULL isencrypted 0 Obviously I've shortened the image cell for security reasons. It's length is 43436. But given that information, is there anyway I can render this out to a user in it's original format? Be it a 3rd party program, or library. I'm fairly proficient with python, and web development.
doc_23530041
A: It would be something like string *xyz = new string (...) which is a string pointer. Can you please post the part of a code here of what you saw/made.
doc_23530042
Here's an print how the database is organized: A: For updating some fields of a document, use the update() method. If you want to remove a specific item from an Arraylist, you can use a call to: .update("arrayfield", FieldValue.arrayRemove("itemtoremove")) For example if you have an arraylist that contains three items as “abc”, “efg”, “xyz”. And if you want to remove specific item called “efg” from an arraylist you should use a call to: .update("arrayfield", FieldValue.arrayRemove("efg")) Please also take a look at this Stackoverflow Link which explains clearly on how to remove specific items from the array list in the firestore using kotlin.
doc_23530043
<div id="hero"></div> #hero { height: 50vh; background-image: url(hero.jpg); } tried with '' with "" without .. don't know what to do anymore A: Make sure your image location. (you just imported the image name, so your image should be in the same file of your html file) #hero { height: 50vh; background-image: url(https://cdn4.vectorstock.com/i/1000x1000/66/48/gradient-colors-background-vector-22266648.jpg); background-size: cover; } <div id="hero"></div>
doc_23530044
ALTER TABLE table_name DROP IF EXISTS PARTITION (partition_col= val) But it is not working with operators like > or <. The error thrown is : mismatched input '<' expecting {')', ','}(line 1, pos 81)
doc_23530045
A: You can listen Logout event and update field. First - create a Listener: php artisan make:listener UpdateLogoutTime Than, register it in EventServiceProvider use App\Listeners\UpdateLogoutTime; use Illuminate\Auth\Events\Logout; class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ Logout::class => [ UpdateLogoutTime::class ] ]; } Than, make update logic in listener: class UpdateLogoutTime { public function handle(Logout $event) { $user = $event->user; //update time logic } } A: You can do like this: Auth::user()->update([ 'logout_time' => now() ]); Auth::logout(); Or, $id = Auth::id(); if(Auth::logout()) { User::where('id', $id)->update([ 'logout_time' => now() ]); }
doc_23530046
A: I don't recommend your user access directly to app/assets. File in app/assets are source to be precompiled and will be put in /public/assets (default directory for precompiled assets). So if you put image in app/assets/img, when precompiled it will be put in public/assets/img. You can configure location for precompiling destination folder using: config.assets.prefix See rails edge guide for more info about assets pipeline
doc_23530047
I have made a service-based database dtbTrial and created the following tables: for tblTestMain: CREATE TABLE [dbo].[tblTestMain] ( [TestNumber] NUMERIC(8) NOT NULL PRIMARY KEY, [TestDate] DATE NOT NULL, [AmbientTemp] INT NOT NULL, [Test1] BIT NOT NULL, [Test2] BIT NOT NULL, [Test3] BIT NOT NULL ) for tblTest1 (also similar with tblTest2 and tblTest3): CREATE TABLE [dbo].[tblTest1] ( [TestNumber] NUMERIC(8) NOT NULL PRIMARY KEY, [ParameterA] REAL NULL, [ParameterB] REAL NULL, CONSTRAINT [FK_tblTest1_tblTestMain] FOREIGN KEY ([TestNumber]) REFERENCES [tblTestMain]([TestNumber]) ) The main table is in Form1 and the three others are in Form2, Form3, and Form4. The main form has a TabControl containing these three forms and functions like my previous question. Now, what I am trying to do is that the data contained in the three sub forms or child forms navigate together with the parent form such that when Form1 navigates from test number 10000000 to 10000001, the three other forms follow suit when open. I tried using this query to dtbTrialDataSet: SELECT tblTestMain.TestNumber, tblTestMain.TestDate, tblTestMain.AmbientTemp, tblTestMain.Test1, tblTestMain.Test2, tblTestMain.Test3, tblTest1.ParameterA, tblTest1.ParameterB, tblTest2.ParameterC, tblTest2.ParameterD, tblTest3.ParameterE, tblTest3.ParameterF FROM tblTestMain LEFT OUTER JOIN tblTest1 ON tblTestMain.TestNumber = tblTest1.TestNumber LEFT OUTER JOIN tblTest2 ON tblTestMain.TestNumber = tblTest2.TestNumber LEFT OUTER JOIN tblTest3 ON tblTestMain.TestNumber = tblTest3.TestNumber and used the resulting dataset to the forms above but to no avail. What did I miss or what should I do to rectify it? PS I haven't made any related codes to the main form yet since I'm at loss as to which commands I shall be needing. A: Your sub forms don't know anything about what happens in the main form unless you specifically tell them. There are a couple of ways you can do that: * *You create an event on your main form (call it DataChanged or something like that) that is fired every time you retrieve data. Then your subforms subscribe to this event and read the updated data as appropriate. *You have a public property on your subforms to hold the data loaded to those forms. Then, after retrieving data in your main from, you set that data property on the sub-forms.
doc_23530048
apiVersion: v1 data: server.properties: |+ server.hostname=test.com kind: ConfigMap metadata: name: my-config And I tried to read this config inside a container. containers: - name: testserver env: - name: server.hostname valueFrom: configMapKeyRef: name: my-config key: server.properties.server.hostname However, these configs are not passing to the container properly. Do I need do any changes to my configs? A: What you have in there isn't the right key. ConfigMaps are strictly 1 level of k/v pairs. The |+ syntax is YAML for a multiline string but the fact the data inside that is also YAML is not something the system knows. As far as Kubernetes is concerned you have one key there, server.properties, with a string value that is opaque.
doc_23530049
"SELECT inc FROM MessageDtl inc WHERE inc.createdTime >= :dateFrom AND inc.createdTime <= :dateTo " where dateTo=03/27/2017 & dateFrom=03/29/2017 In response, this will fetch all the records 0n 03/27/2017 & 03/28/2017. Even though I had given <= condition, records on 03/29/2017 is not fetched. There can be a work around to dateTo plusOne day. Would like to know how can I fix without using plus one, what is the reason for this behavior ?
doc_23530050
when i retrieve data in php page $date=$_POST['date']; echo $date; it return the output in this format 13 November 2015 i want to convert it to store in mysql table how can i convert it to sql format to store because when i am trying to store this date mysql stores 0000-00-00 by default. i can not take data type varchar because i have to create views according to date. also i need the code to convert it again to this format to show data in this format. A: use MySQL Str_To_Date :- SELECT str_to_date('13 November 2015','%d %M %Y') or try :- $date=$_POST['date']; insert into table (col) values (str_to_date($date,'%d %M %Y')) or use PHP strtotime $time = strtotime('13 November 2015'); $newformat = date('Y-m-d',$time); A: If you are using PHP > 5.2, then you should use following way. $date=$_POST['date']; //13 November 2015 echo $date; $myDateTime = DateTime::createFromFormat('j F Y', $date); $newDateString = $myDateTime->format('Y-m-d'); echo $newDateString; //2015-11-13 You should use this in try...catch block as it throw exception on failure. A: You can convert your date to timestamp with strtotime. Then you can convert it to format you like with date function. $date = $_POST['date']; $timestamp = strtotime($date); $converted_date = date("Y-m-d H:i:s", $timestamp); // var_dump($converted_date); A: Step 1: Extract time variables(used in step #2) Step 2: Create timestamp using the above info $timestamp = mktime($hour, $min, $sec, $month, $day, $year); Step 3: Use PHP's date function: echo date("Y-m-d", $timestamp); Reference: http://php.net/manual/en/function.date.php#example-2514
doc_23530051
I am unable to call the addFunc function from within my RenderItem function because they are in different components. How do I get past this? This is a summary of my code: const selectedData = [] class Search extends Component { constructor(props) { super(props); this.addFunc = this.addFunc.bind(this); } addFunc(resultdata){ console.log(resultdata) selectedData = [...selectedData, resultdata] console.log(selectedData) }; render() { return ( <ReactiveList componentId="results" dataField="_score" pagination={true} react={{ and: ["system", "grouping", "unit", "search"] }} size={10} noResults="No results were found..." renderItem={RenderItem} /> ); const RenderItem = (res, addFunc) => { let { unit, title, system, score, proposed, id } = { title: "maker_tag_name", proposed: "proposed_standard_format", unit: "units", system: "system", score: "_score", id: "_id" }; const resultdata = {id, title, system, unit, score, proposed} return ( <Button shape="circle" icon={<CheckOutlined />} style={{ marginRight: "5px" }} onClick={this.addFunc()} /> ); } A: You can wrap RenderItem component with another component and then render it, const Wrapper = cb => { return (res, triggerClickAnalytics) => ( <RenderItem res={res} triggerClickAnalytics={triggerClickAnalytics} addFunc={cb} /> ); }; and renderItem of ReactiveList would be: renderItem={Wrapper(this.addFunc)} then RenderItem component would be const RenderItem = ({ res, triggerClickAnalytics, addFunc }) => { ... see sandbox: https://codesandbox.io/s/autumn-paper-337qz?fontsize=14&hidenavigation=1&theme=dark A: You can pass a callback function defined in the parent as a prop to the child component class Parent extends React.Component { sayHello(name) => { console.log("Hello " + name) } render() { return <Child1 parentCallback = {this.sayHello}/> } } and then call it from the child component class Child1 extends React.Component{ componentDidMount() { this.props.parentCallback("Foo") } render() { return <span>child component</span> } };
doc_23530052
A: You can express such queries in logic, but maybe you can just use a dedicated algorithm (Dijktra or variants) for such problems. For an introduction to using Z3, take a look at the tutorial linked from http://rise4fun.com/z3
doc_23530053
A: my $substr = (split /#/, $originalString)[1]; A: /#([^#]+)#/ works for me. Some syntax notes: * *// delimiter characters marking the start and end of the regexp *# literal hash mark *[] a character class Explanation of the regexp above: * *[^#] any character that isn't a hash mark *[^#]+ one or more such characters *([^#]+) a capturing group of the above In this case, the regexp looks for any non-# characters between two #'s. Here's a full example: my $foo = "#SomeWord# More words"; if ($foo =~ /#([^#]+)#/) { print "$1\n"; } else { print "no match\n"; } A: You can also use regular expressions: $originalString=~ /\#([^#]+)\#/; # Now $1 holds your required string
doc_23530054
I can do a logElementTree on the window and this shows my labels for staticText and elements but not for the images. Instead for images I see the file path, i.e. UIAImage: name:/var/mobile/Applications... I can access images via their numeric index but I would rather use their labels. Works: window.images()[1] Does not work: window.images()["Next"] Why are my labels not showing up for images in Instruments but Accessibility Inspector can see them?
doc_23530055
infos = [{type: 'phone', val: '2222222'} {type: 'email', val: 'abc@abc.com'}] Here is the state constructor(props) { super(props); this.state = { rows: [], //this is used for the add component contactDetails: [{type: '', val: ''}], // where i will add the values }; } So I have a two TextInput <View> <TextInput label='Type'/> <TextInput label='Details'/> </View> This View can be dynamically added when a button is clicked and can also be deleted. Here is my code for the add and delete button: addRow(){ this.state.rows.push(index++) this.setState({ rows: this.state.rows }) } deleteRow(key){ this.state.rows.splice(key, 1) this.setState({ rows: this.state.rows }) } <TouchableOpacity onPress={ this.addRow.bind(this) } > <Text style={{textAlign: 'center',}}>Add</Text> </TouchableOpacity> ... <TouchableOpacity onPress={ () => this.deleteRow(i) } > <Image source={require('./../img/delete.png')} style={{width:32, height: 32 }} /> </TouchableOpacity> How can I get the value of it correctly and add it to my Array? Thank you. Update In my TextInput I tried doing this <TextInput onChangeText={(text)=>{ let cd = this.state.contactDetails; cd[i].val = text ; this.setState({cd}); }} value={this.state.contactDetails[i]} label='Details' /> but I'm always having an error undefined is not an object (evaluating 'cd[i].val = text') A: You can't manipulate state by declaring this.state.rows.push(index++), but you must do it with concat() and return the value to new variable. For instance (I actually don't know what index represents in your case, but let's give it a try: addRow() { const rows = this.state.rows.concat(index++) this.setState({rows}) } Here's a working example what I assume you're trying to achieve: https://snack.expo.io/HySVtag6g A: In my state, I added an array like this info: { type: '', val: '', } And then I added this to my addRow addRow(){ //add new array in contactDetails var arrayvar = this.state.contactDetails.slice() arrayvar.push(this.state.info) this.setState({ contactDetails: arrayvar }) //add new component row this.state.rows.push(index++); this.setState({ rows: this.state.rows}); } Where every time the add button is clicked the Array named info with empty values will be added to the contactDetails and then I update the values of the added array.
doc_23530056
But I wonder how can I get the metadata of the Pub/Sub message in the Cloud Functon. The Google Cloud Function documentation says that This metadata is accessible via the context object that is passed to your function when it is invoked. How can I access this metadata (or the context object) in a Spring Cloud Function application? UPDATE :- Version spring-cloud-function-adapter-gcp:3.1.2 UPDATE 2:- I raised an issue in github and got the issue resolved. Thanks to Spring Cloud Function team. A: When you use background function, the PubSub message and context are extracted and provided in the PubSub message. If you have a look to the PubSub object here; you have the Published Time and the Message ID embedded in it. You only have to use them! A: Got the issue resolved as per the advice from spring-cloud-function team. The Consumer function needs to accept the parameter of type Message<PubSubMessage> instead of PubSubMessage to get the Context object. @Bean public Consumer<Message<PubSubMessage>> pubSubFunction() { return message -> { // The PubSubMessage data field arrives as a base-64 encoded string and must be decoded. // See: https://cloud.google.com/functions/docs/calling/pubsub#event_structure PubSubMessage payload = message.getPayload(); String decodedMessage = new String( Base64.getDecoder().decode(message.getPayload().getData()), StandardCharsets.UTF_8); System.out.println("Hello!!! Received Pub/Sub message with data: " + decodedMessage); // Print out timestamp and event id Context ctx = message.getHeaders().get("gcf_context", Context.class); System.out.println(ctx.eventId()); System.out.println(ctx.timestamp()); }; } Ref :- github issue #695
doc_23530057
(555) 555-5555 I have found around this \(?\b[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}\b I know that is the correct way but in the platform that I am using there is a bug that removes the {} brackets out of the regex code. I have already reported the bug but it might take a while for them to fix it and release the update so I am wondering if there is another way to accomplish the same with out using brackets. A: [0-9]{3} is the same thing as [0-9][0-9][0-9] or \d\d\d In full that would look like this: \(?\b[0-9][0-9][0-9]\)?[-. ]?[0-9][0-9][0-9][-. ]?[0-9][0-9][0-9][0-9]\b or \(?\b\d\d\d\)?[-. ]?\d\d\d[-. ]?\d\d\d\d\b A: just use \d for each characcter you need to match [0-9]{3} is \d\d\d [0-9]{4} is \d\d\d\d A: Well, sure. Instead of saying "apply pattern {n} times", write "patternpatternpattern..." n times: \(?\b[0-9][0-9]0-9]\)?[-. ]?[0-9][0-9][0-9][-. ]?[0-9][0-9][0-9][0-9]\b A: Simply replace the brackets with the given number of iterations of the sequence before the bracket. \(?\b[0-9][0-9][0-9]\)?[-. ]?[0-9][0-9][0-9][-. ]?[0-9][0-9][0-9][0-9]\b
doc_23530058
$VSS = Get-VssConnection -TaskContext $distributedTaskContext $Client = $VSS.GetClient(...) Question: what kind of security context does the task get? It's definitely not the agent account. To make sure, I've set up a temporary agent instance that runs as me, the TFS admin, and the custom task running on that agent doesn't have the full admin. The underlying problem is - I'm trying to get the current agent record from a task, and the task only sees one pool, even though we have several. See this answer. A: I'm trying to get the current agent record from a task, and the task only sees one pool, even though we have several. There is a Agent pool security roles concept, for example with Administrator Role, you can: Rregister or unregister agents from the pool and manage membership for all pools, as well as view and create pools. They can also use the agent pool when creating an agent queue in a team project. The system automatically adds the user that created the pool to the Administrator role for that pool. The default rights of a build agent running a release task should be the same as build service account. Please add your build service account to Agent pool security roles to Administrator from the collection-level admin context, Agent Pools page. Then try it again. Another possibility you are lacking of vso.agentpools scope in your customize release task. Grants the ability to view tasks, pools, queues, agents, and currently running or recently completed jobs for agents More details please take a look at Supported scopes A: First off, the distributedTaskContext doesn't connect to TFS with NTLM, like Patrick Lu's answer suggests. It connects with Authorization:Bearer and a token. I've used the same token to invoke the /_api/_common/GetUserProfile endpoint, which returns the current user, and got back the following identity record: { "IdentityType": "user", "FriendlyDisplayName": "Project Collection Build Service (TEAM FOUNDATION)", "DisplayName": "Project Collection Build Service (TEAM FOUNDATION)", "SubHeader": "Build\\233e4ccc-d129-4ba4-9c5b-ea82c7ae1d15", "TeamFoundationId": "7a3195ee-870e-4151-ba58-1e522732086c", "EntityId": "vss.ds.v1.ims.user.7a3195ee870e4151ba581e522732086c", "Errors": [], "Warnings": [], "Domain": "Build", "AccountName": "233e4ccc-d129-4ba4-9c5b-ea82c7ae1d15", "IsWindowsUser": false, "MailAddress": "" } It looks like some kind of artificial identity that TFS creates just for this purpose. Looking in the TFS database in the tbl_Identity table, there are numerous user records with names like that - one per collection, it seems, and also some that are project specific. This user belongs to a server-level group called "Security Service Group" (and also to a collection level group with the same name). Those groups belong, respectively, to Team Foundation Valid Users and Project Collection Valid Users and nothing else. At least on the collection level, the "Security Service Group" is visible and contains a lot of accounts. All those "Build Service" users belong to the domain called "Build". A domain is not a security principal though, you can't grant rights to a domain. Speaking of OAuth scopes. I've used the same token to invoke the homegrown "what are this token's scopes" page, and it turns out the distributedTaskContext token has exactly one - app_token. It's a valid scope that opens up all endpoints and all methods (see the dynamic scope list). The scopes parameter in the extension manifest has no bearing on that; it only affects the client-side contributions. When it comes to pool visibility, though, the story is tricky. Seems like all the "Project Collection Build Service" accounts belong to Valid Users, but granting the Reader role on all pools to Valid Users doesn't open them up to the REST API in tasks. Granting Reader explicitly to "Project Collection Build Service" does. However, there are numerous accounts like this (one per collection, it seems) - and granting Reader only opens the pools up to release definitions in the collection where it resides. In order to let tasks in releases in all collections read the pools, you need to go through all collections and grant Reader to the "Project Collection Build Service" from each.
doc_23530059
error: incompatible types: <anonymous BleReadCallback> cannot be converted to Runnable mHandler.postDelayed(this, 5000); code Handler mHandler = new Handler(); Runnable mToastRunnable = new Runnable() { @Override public void run() { if(manager.getConnectedDevices().size()<=0){ Toast.makeText(MainActivity.this,"No connected devices", Toast.LENGTH_LONG).show(); return; } BleDevice device = manager.getConnectedDevices().get(0); Map<String , String> reciveData = getSpecificServiceInfo(device , CHARACTERISTIC_READABLE); for (Map.Entry<String, String> e : reciveData.entrySet()){ manager.read(device, e.getKey(), e.getValue(), new BleReadCallback() { @Override public void onRead(byte[] data, BleDevice device) { Toast.makeText(MainActivity.this, "Read success! data: " + new String(data), Toast.LENGTH_LONG).show(); Intent intent = new Intent(MainActivity.this , BluetoothService.class); intent.putExtra("inputString" ,new String(data)); startService(intent); mHandler.postDelayed(this, 5000); // mHandler.postDelayed(MainActivity.this.getApplication() , 5000); TextView textView = findViewById(R.id.textView); textView.setText(new String(data)); } @Override public void onFail(int failCode, String info, BleDevice device) { // Toast.makeText(MainActivity.this, "Read fail! data: " + info, Toast.LENGTH_LONG).show(); } }); } } }; private void readData(){ mToastRunnable.run(); } Bluetooth_service: @Override public int onStartCommand(Intent intent, int flags, int startId) { String input = intent.getStringExtra("inputString"); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Bluetooth Services") .setContentText(input) .setSmallIcon(R.drawable.ic_android) .setContentIntent(pendingIntent) .build(); startForeground(1, notification); return START_NOT_STICKY; } A: Add a new method in a class. Ex: newMethod And replace this with mToastRunnable Call the created method from override method onRead void newMethod(byte[] data){ Toast.makeText(MainActivity.this, "Read success! data: " + new String(data), Toast.LENGTH_LONG).show(); Intent intent = new Intent(MainActivity.this , BluetoothService.class); intent.putExtra("inputString" ,new String(data)); startService(intent); mHandler.postDelayed(mToastRunnable, 5000);//use mToastRunnable instead of this // mHandler.postDelayed(MainActivity.this.getApplication() , 5000); TextView textView = findViewById(R.id.textView); textView.setText(new String(data)); } main code final Handler mHandler = new Handler(); final Runnable mToastRunnable = new Runnable() { @Override public void run() { if(manager.getConnectedDevices().size()<=0){ Toast.makeText(MainActivity.this,"No connected devices", Toast.LENGTH_LONG).show(); return; } BleDevice device = manager.getConnectedDevices().get(0); Map<String , String> reciveData = getSpecificServiceInfo(device , CHARACTERISTIC_READABLE); for (Map.Entry<String, String> e : reciveData.entrySet()){ manager.read(device, e.getKey(), e.getValue(), new BleReadCallback() { @Override public void onRead(byte[] data, BleDevice device) { newMethod(data);//call the created method here } @Override public void onFail(int failCode, String info, BleDevice device) { // Toast.makeText(MainActivity.this, "Read fail! data: " + info, Toast.LENGTH_LONG).show(); } }); } } }; private void readData(){ mToastRunnable.run(); }
doc_23530060
Unfortunately, I am unable to take screenshots in the container. This code works perfectly ok outside of the container: from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.get("http://www.python.org") driver.save_screenshot("some_file.png") driver.close() but in the container, save_screenshot returns false. I found a small hint in the github of chrome, that screensize and depth must be set, but setting them to 1920 * 1080 * 24 did not change anythign A: If you work with containers, then you should consider using fully separated browser containers. Selenoid (or its Kubernetes version, Moon) utilizes the Selenium Grid mechanism for this purpose. This means that the only thing required in your code is to specify the Selenium Hub server and the desired version of the browser. capabilities = { "browserName": "chrome", "version": "109.0" } context.driver = webdriver.Remote( command_executor="http://localhost:4444/wd/hub", desired_capabilities=capabilities) Remote driver fully supports taking screenshots from any browser and you do not need to worry about maintaining browser drivers and browsers. Official webpage: https://aerokube.com/selenoid/latest/
doc_23530061
I am adding these two lines: <script src="//platform.linkedin.com/in.js" type="text/javascript"></script> <script type="IN/CompanyProfile" data-format="inline" data-id="37093"></script> Now LinkdIn is banned so platform.linkedin.com/in.js not reachable and give error. How to handle this?
doc_23530062
The issue is scaling this approach to much bigger data frames with 100k rows and groups. How can I reach the same conclusion in a more efficient manner? If this is possible in a tidyverse structure this is preferred (while not preferred, data.table solutions will also be accepted). I want to keep the flexibility to specify the different cols to be included in the function calls, as well as add additional summary calls (e.g. summarise_at(sum of values)). data <- tibble(id = c(1,1,1,2,3,4,5,5,6,6,6), date = dmy("01/01/2020"), var1 = 1:11, var2 = 12:22, var3 = 1:11) data %>% group_by(id, date) %>% {data.frame( summarise_at(., vars(var1, var2), list(~ paste(unique(.), collapse = " AND "))), # return character string summarise_at(., vars(var3), list(~ max(., na.rm = T))),#, # return max in group summarise(., count = n(), .groups = "keep") # return count of cases in group )} %>% select(-matches("[.]1$|[.]2$|[.]3$")) %>% # remove unwanted columns as_tibble() # A tibble: 6 x 6 id date var1 var2 var3 count <dbl> <date> <chr> <chr> <int> <int> 1 1 2020-01-01 1 AND 2 AND 3 12 AND 13 AND 14 3 3 2 2 2020-01-01 4 15 4 1 3 3 2020-01-01 5 16 5 1 4 4 2020-01-01 6 17 6 1 5 5 2020-01-01 7 AND 8 18 AND 19 8 2 6 6 2020-01-01 9 AND 10 AND 11 20 AND 21 AND 22 11 3 Links to this question as well. How can I use summarise_at to apply different functions to different columns? A: Here is the tidyverse approach adapted from @MichaelDewar's answer, it's tidier but I don't think there is any real improvement in the efficiency. Besides, a dataframe with 100k rows is not that big a deal in my opinion. I think a tidyverse solution is just fine. library(dplyr) data %>% group_by(id, date) %>% summarise( across(c(var1, var2), ~paste(unique(.), collapse = " AND ")), across(var3, max, na.rm = T), count = n(), .groups = "keep" ) But if you really want to improve the efficiency, perhaps try this data.table solution library(data.table) setDT(data)[, c( lapply(c(var1 = "var1", var2 = "var2"), function(x) paste(unique(.SD[[x]]), collapse = " AND ")), list(var3 = max(var3, na.rm = T), count = .N) ), by = c("id", "date")] Benchmark set.seed(2020) data2 <- data[sample.int(nrow(data), 1e5, T), ] data22 <- data.table::copy(data2) f1 <- . %>% group_by(id, date) %>% {data.frame( summarise_at(., vars(var1, var2), list(~ paste(unique(.), collapse = " AND "))), # return character string summarise_at(., vars(var3), list(~ max(., na.rm = T))),#, # return max in group summarise(., count = n(), .groups = "keep") # return count of cases in group )} %>% select(-matches("[.]1$|[.]2$|[.]3$")) %>% # remove unwanted columns as_tibble() f2 <- . %>% group_by(id, date) %>% summarise( across(c(var1, var2), ~paste(unique(.), collapse = " AND ")), across(var3, max, na.rm = T), count = n(), .groups = "keep" ) f3 <- function(dt) { setDT(dt)[, c( lapply(c(var1 = "var1", var2 = "var2"), function(x) paste(unique(.SD[[x]]), collapse = " AND ")), list(var3 = max(var3, na.rm = T), count = .N) ), by = c("id", "date")] } microbenchmark::microbenchmark(f1(data2), f2(data2), f3(data22)) Result Unit: milliseconds expr min lq mean median uq max neval cld f1(data2) 19.6730 20.27990 20.841344 20.50850 20.85045 29.2799 100 c f2(data2) 13.5455 14.09240 14.705967 14.34585 14.64625 20.5914 100 b f3(data22) 6.9186 7.80615 8.598227 8.32035 8.68040 15.8358 100 a A: Use summarize(across()): paste_distinct <- function(list){ list %>% unique %>% sort %>% paste(collapse = " AND ") } data %>% group_by(id, date) %>% summarize(across(c(var1,var2), paste_distinct), across(var3, max, na.rm = TRUE), count = n())
doc_23530063
I want to retrieve data (start_date) from an ajax request: scheduler.attachEvent("onClick", function (id, e){ var event = scheduler.getEvent(id); var start_date = event.start_date; $.ajax({ url: Routing.generate('admin_event_edit', {id : id}), type: "POST", data: { id : 'id', start_date : 'start_date'}, dataType : "json", success: function(data) { var route = Routing.generate('admin_event_edit', {id : id}); window.location.href = route; }, error: function () { alert('Error'); } }); In my controller I'm doing: $startDate = ($request->request->get('start_date'); But my $startDate is empty. How can I access the start date? A: The problem most likely is in using single quotes instead of double when building json data, try using like this: $.ajax({ url: Routing.generate('admin_event_edit', {id : id}), type: "POST", data: { id : "id", start_date : "start_date"}, dataType : "json", success: function(data) { var route = Routing.generate('admin_event_edit', {id : id}); window.location.href = route; }, error: function () { alert('Error'); } }); But here you also trying to submit simple strings 'id' 'start_date', you probably want to send variable values data: { id : id, start_date : start_date}
doc_23530064
I read a file with level and when box2d body (#1) collides with other thing (#2) I want to destroy first body(#1). But when I will put b2d bony on another b2d body these sometimes collides (level did pixel perfect). And of course I can post some parts of my code.
doc_23530065
Example Widget inside Column: SelectableText("'Lorem Ipsum is simply dummy '",)), SizedBox(height: 20), Divider(), SelectableText("'Lorem Ipsum is simply dummy text '",)), The output: When I clicked the bottom selectable or other widget beside the selectable text it doesnt deselect the previously selected text, and also when I selected a new text on another selectable text the previous selection on the top is still highlighted which is not the behaviour I expected. Is there some change on this widget on the newest version that I didn't notice? Thanks A: You can update flutter and use Global Selection in flutter version 3.3 https://medium.com/flutter/whats-new-in-flutter-3-3-893c7b9af1ff
doc_23530066
So far it seems that Watir (watir.com) will be the best solution for the Web app (I prefer to use Ruby), while MonkeyTalk (www.gorillalogic.com/ testing-tools/monkeytalk) may be the best for our Mobile platforms (because we can write one set of tests for both platforms at the same time). We still have not been able to find a good solution for our desktop platforms. We're a startup so we don't have the budget for a proprietary solution and those are looking for open source solutions. Is there a better way to tackle the situation we're in and are there any better solutions for the various platforms we want to test. A: You could use cucumber as the main test framework for all platforms (that would allow you to have the same scenarios and tests across all platforms) and use specific tools to exercise the native applications. You could use cucumber + selenium web driver for your Web App, calabash for Android and iOS (http://github.com/calabash), frank for Mac apps (https://github.com/moredip/Frank). There is probably something for Windows as well to work with cucumber, but I personally don't know about it. All of these tools would be free.
doc_23530067
<div class="theinsideofclass" style="theinsideofstyle" ...></div> <div class="theinsideofclass" style="theinsideofstyle" ...></div> <div class="theinsideofclass" style="theinsideofstyle" ...></div> <div class="theinsideofclass" style="theinsideofstyle" ...></div> And they are dynamically changed(each time in different time) and I don't have any control of the source code. The thing is, I want simply override the theinsideofstyle, but all my attempts are failed. I tried with the !important; but it didn't go. Isn't it suppose to override the inline css? Anyway, what are my options here? Obviously simple JS won't help me here as the entire divs are changed/replaced each time with the same code. Just shoot with any idea, folks... Perhaps it will navigate for some solution. A: You could write some JS that is executed once the entire page is loaded, with all resources loaded, etc: function load() { var els = document.getElementsByClassName("theinsideofclass"); for(var i = 0; i < els.length; i++) { els[i].removeAttribute("style"); } } window.onload = load; .theinsideofclass { color: green; } <div class="theinsideofclass" style="color: red;"> My inline style is color: black </div> <div class="theinsideofclass" style="color: red;"> My inline style is color: black </div> <div class="theinsideofclass" style="color: red;"> My inline style is color: black </div> As you can see, without the JS the inline style (font color of red) would normally override the external CSS style (green). However, my JS is removing the style attribute from the elements with the class of theinsideofclass so you can style with normal CSS WITHOUT using !important (I never use !important unless all my other options are exhausted). A: Hey you could wrap the elements in a div and loop through them + add a custom class which you could then use to define style to these divs. PLEASE NOTE: I assume by your question that the css-class is also dynamic/changing and you have no control of it. HTML: <div id="outerdiv"> <div class="theinsideofclass" style="theinsideofstyle"></div> <div class="theinsideofclass" style="theinsideofstyle"></div> <div class="theinsideofclass" style="theinsideofstyle"></div> <div class="theinsideofclass" style="theinsideofstyle"></div> </div> JS: var children = document.getElementById('outerdiv').children; for (var i = 0; i < children.length; i++) { var child = children[i]; child.classList.add('myclass'); // this will add the class "myclass" to all the children divs inside the outerdiv } CSS: .myclass { background-color: red !important; // which ever style you want to overwrite } You could even go as far as removing the style attribute from the div with: child.removeAttribute('style'); This way you won't need to use the !important in your css. EDIT: Based on OP's comment. You could also try wrapping all these divs in an outer div, if you can control where they are rendered: <div id="outerdiv"> <div class="theinsideofclass" style="theinsideofstyle"></div> <div class="theinsideofclass" style="theinsideofstyle"></div> <div class="theinsideofclass" style="theinsideofstyle"></div> <div class="theinsideofclass" style="theinsideofstyle"></div> </div> Then in your css: #outerdiv > div { background-color: red !important; } A: Hi you can set style attribute to blank like below: jQuery $(document).ready(function(){ $('.theinsideofclass').attr('style',''); }); Kinda working demo here : https://jsfiddle.net/nm77md0L/ , https://jsfiddle.net/nm77md0L/1/ A: Since divs are generated on the fly and recreated when style attribute gets removed, try using setProperty on its CSSStyleDeclaration with third argument set to important. //document.getElementsByClassName("theinsideofclass")[0].setAttribute('style', 'color: purple !important'); // recreates div document.getElementsByClassName("theinsideofclass")[0].style.setProperty('color', 'blue', 'important'); // maybe won't? .theinsideofclass{color: green !important} <div class="theinsideofclass" style="color: red !important">TXT</div> I can't guarantee it will work since we can't see what causes the divs to get regenerated and how, but give it a try, maybe the code is recreated when style attribute changes directly.
doc_23530068
I tried . section_wrapper clearfix { display : none; } In Custom CSS but does not work. How do I hide this? <div class="section_wrapper clearfix"> Example Code Below: <div class="section_wrapper clearfix"> <!-- additional HTML content --> </div> A: since section_wrapper and clearfix are classes so to give them styling you have to include .(dot) before them and you have to use only one among 2 of them. for example .section_wrapper{ display:none; } If you write like this .section_wrapper .clearfix{ display:none; } It means you are giving styling to the element having class clearfix which is under the element having class section_wrapper A: You need to target them as classes in CSS (i.e. with .s in front of the class names). Also, since the classes are from the same element, you need to get rid of the space between the class names: .section_wrapper.clearfix { display: none; }
doc_23530069
basically, i have this facebook style of displaying posts. each posts has <input> box where members can leave comments. when a user hits <enter> my jquery(AJAX), will fetch the submitted comment and save it on my database. the comment should appear instantly in the specific <DIV> where the comment was made. my issue is, whenever i submit a comment on a specific POST the comment i made gets updated to ALL of my posts. it will only disappear when i hit refresh. this is my <div> that displays the TITLE and the COMMENTS <div id="content"> <?php /* GET TITLE*/ $result = displayPosts(); while ($row = $result->fetch_assoc()) { $rowId = $row['id']; ?> /* ECHO TITLE*/ <b> <?php echo $row['title'] . "<br />"; ?> </b> <?php /* GET COMMENTS PER POSTS */ $comRes = getComments($rowId); while ($comRow = $comRes->fetch_assoc()) { ?> <!--COMMENT AREA--> <div class="comments"> <!--DISPLAY COMMENTS--> <small> <?php echo $comRow['comment'] . "<br />";?> </small> </div> <?php } /* end of second while loop */ ?> <input type="text" post_id="<?php echo $row['id']; ?>" id="TextBox" name="input" value="" /> <?php } /* end of first while loop */ ?> </div> THIS IS MY JQUERY. Whenever a user hits <enter> on a particular POST it should display the comment on that specific DIV/POSTS only $(document).ready(function() { $('input#TextBox').keyup(function (z) { /* when this commentbox is entered*/ if(z.keyCode == 13) { /*keyCode 13 = enter*/ var post_id = $(this).attr('post_id'); /* get the post_id in the <input> box */ var comment = $(this).val(); /* get the value of the <input> */ $.post('../portal/comment.php', {post_id: post_id, comment: comment}); $('input#TextBox').val(''); $(this).parent('#content').children('.comments').append("<div>"+comment+"</div>"); } }); }); this line contains my post_id so whenever i hit enter in my input box, my system knows what specific post im referring to.. <input type="text" post_id="<?php echo $row['id']; ?>" id="TextBox" name="input" value="" /> A: The problem lies in the way that you are trying to distinguish your comment DIVs. Suppose you want to choose a special comment div. How can you do this in your webpage? Using this code will not give you a special comment div: $(".comments") You should give each comment DIV a special identity (which is simply an html id). This way you can select it easily, for example: $("#comments_14") and updating would become a little more complex. Instead of the following line: $(this).parent('#content').children('.comments').append("<div>"+comment+"</div>"); you should do something like this: var post_id = get post id some way; // e.g. put it in an attribute in text input $('#comments_' + post_id).append("<div>"+comment+"</div>"); A: The problem is on this line : $(this).parent('#content').children('.comments').append("<div>"+comment+"</div>"); With this you are appending the new comment text in each div with comments css class. You could perform something like : <!-- Add post id to identify corresponding comment area --> <div class="<?php echo $rowId; ?>_comments comments"> <small> <?php echo $comRow['comment'] . "<br />";?> </small> </div> Then in your js : $(function() { $('input#TextBox').keyup(function (z) { if(z.keyCode == 13) { var input = $(this); var post_id = input.attr('post_id'); var comment = input.val(); $.post('../portal/comment.php', {post_id: post_id, comment: comment}); $('input#TextBox').val(''); // Append comment to the corresponding div $('.' + post_id + '_comments').append("<div>"+comment+"</div>"); } }); });
doc_23530070
# Attempt 1 mkfs.vfat -F 32 -s 8 /dev/mmcblk0p1 # Attempt 2 mkfs.vfat -F 32 -S 4096 /dev/mmcblk0p1 The thing I don't understand and what I am looking for more information on is why the following way does appear to work. mkfs.vfat -F 32 /dev/mmcblk0p1 So, it appears there is some special requirement regarding the sector sizing of the first partition in order for MLO to boot properly. Do you know what those requirements are? I have tried searching the U-boot documentation without success and am waiting on replies on IRC. If I find anything I will update this post.
doc_23530071
A: The JIT compiler, compiles the code dynamically. * *It generates different code for different flavours of CPU. *It generates different code for different memory models, e.g. For tyhe 64-bit JVM, if the maximum heap size is < 4 GB, < 24 GB, < 32 GB or more, you will produce different code in each case. *It will re-compile code as classes are loaded and unloaded. *It will re-optimise code based on how it is used. e.g. if a flag which used to be off is not on and visa-versa. A static compiler cannot do these things. A: JIT = Just In Time. An *.exe is compiled way before of execution. </nitpick> ;) As others said, there is more to a JVM than just compiling bytecode to native machine code. However, these parts of a JVM can be put into a native library ("dll"). There is at least one project to generate native binaries out of java code: GCJ (http://en.wikipedia.org/wiki/Gcj). I don't know how good it is and whether there is a windows version available. There might also be other Java-to-native compilers out there. A: The aims of JITs and compilers are normally different, I think that is the main reason. That said, the Maxine VM contains a JIT written in Java that is used to compile the entire VM itself and the output is written to a so-called bootimage, essentially being a binary. However, even this binary needs an executable, called loader, to start. So, there is at least one example for a JIT that is used to produce a binary, but normally, the aims of a JIT do simply not include producing a binary. A: Jit is a re compiler, so for any particular system platform, it compiles the bytecode into the particular system code. So we cannot directly use the Jit to turn Java-byte code into binary executables. When the jit produces binary code, its binary format will not support another platform. The main usage of a Jit-compiler is fast compilation as a second compiler for Java. Therefore Jit can't produce binaries from Java bytecode. A: IBM Java Runtime is capable of storing the results of dynamic bytecode to native code compilation in its shared data cache and sharing it between JVMs (prooflink).
doc_23530072
Age Work Zone SomeNumber 26 1 2.61 32 4 8.42 41 2 9.71 45 2 4.14 64 3 6.04 56 1 5.28 37 4 7.93 I want to get the maximum SomeNumber for each zone at or below each age. SomeNumber increases with age, so I expect that the highest SomeNumber in Zone 2 by an under-32-y/o is by a guy who's age 31, but it could in fact be a guy age 27. To do this I've written a nested for loop: for(i in zonelist){ temp = data[data$zone==i,] for(j in 1:max(data$age)){ temp.lessequal=c(temp.lessequal,max((temp[temp$Age<=j,])$SomeNumber)) } #plot temp.lessequal or save it at this point } which of course is tremendously slow. How can I do this faster? I've looked at the order function to sort by two columns at once, but that doesn't let me take the max of each group. A: Data: df1 <- read.table(text='Age Work_Zone SomeNumber 26 1 2.61 32 4 8.42 41 2 9.71 45 2 4.14 64 3 6.04 56 1 5.28 37 4 7.93', header = TRUE) Code: df2 <- with( df1, df1[ Age <= 32, ] ) # extract rows with Age <= 32 # get maximum of someNumber by aggregating with work_zone and then merging with df1 to combine the age column merge(aggregate(SomeNumber ~ Work_Zone, data = df2, max), df2) # Work_Zone SomeNumber Age # 1 1 2.61 26 # 2 4 8.42 32 A: Using the library data.table you can select the rows which are less than required age, then output the max(somenumber) and their respective age for each Workzone ie group by workzone. library(data.table) setDT(df1)[Age<=32,.(max(SomeNumber),Age),by=Work_Zone] Work_Zone V1 Age 1: 1 2.61 26 2: 4 8.42 32 A: It seems OP is looking for max value based on <= condition on a particular column (Age). The use of sqldf comes very handy in such cases in order to explain the logic. One solution could be: # Data df <- read.table(text = "Age Work_Zone SomeNumber 26 1 2.61 32 4 8.42 41 2 9.71 45 2 4.14 64 3 6.04 56 1 5.28 37 4 7.93", header = T, stringsAsFactors = F) library(sqldf) df3 <- sqldf("select df1.Work_Zone, df1.Age, max(df2.SomeNumber) from df df1 inner join df df2 on df1.Work_Zone = df2.Work_Zone WHERE df2.Age <= df1.Age GROUP BY df1.Work_Zone, df1.Age") # Result: # Work_Zone Age max(df2.SomeNumber) # 1 1 26 2.61 # 2 1 56 5.28 # 3 2 41 9.71 # 4 2 45 9.71 # 5 3 64 6.04 # 6 4 32 8.42 # 7 4 37 8.42
doc_23530073
Or the inverse: why using ObjectId instead of Number in Person? var mongoose = require('mongoose') , Schema = mongoose.Schema var personSchema = Schema({ _id : Number, name : String, age : Number, stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }] }); var storySchema = Schema({ _creator : { type: Number, ref: 'Person' }, title : String, fans : [{ type: Number, ref: 'Person' }] }); var Story = mongoose.model('Story', storySchema); var Person = mongoose.model('Person', personSchema); A: Type of reference has to be the same as the referenced schema's _id property. In case of personSchema it's a Number. storySchema on the other hand, has the _id field assigned automatically by mongoose - it's not specified in parameters for the schema constructor. Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assiged is an ObjectId to coincide with MongoDBs default behavior
doc_23530074
This is the solution I came up with but its rather slow in my opinion: # a) create a mask of rows containing True if this column was > 0 or False otherwise mask = (X[:, i] > 0).transpose().toarray()[0] # b) now get the indices of these rows as list indices_of_row = list(np.where(mask > 0)[0]) if len(indices_of_row) == 0: return # c) use the indices of these rows to create the mean vector mean_vector = X[indices_of_row,].mean(axis=0) Any ideas how to make it more efficient or maybe more readable? Edit: I would like to avoid call toarray() on the whole matrix A: Here are three comparatively fast solutions: from scipy import sparse import numpy as np def pp(): m = np.maximum.reduceat(a.indices==i,a.indptr[:-1]) cnt = np.count_nonzero(m) m = m.repeat(np.diff(a.indptr)) return np.bincount(a.indices[m],a.data[m],a.shape[1])/cnt def qq(): idx = a.indptr.searchsorted(*(a.indices==i).nonzero(),"right")-1 return np.bincount( np.concatenate([a.indices[a.indptr[i]:a.indptr[i+1]] for i in idx]), np.concatenate([a.data[a.indptr[i]:a.indptr[i+1]] for i in idx]), a.shape[1]) / len(idx) def mm(): idx = (a@(np.arange(a.shape[1])==i))!=0 return idx/np.count_nonzero(idx)@a def OP(): # a) create a mask of rows containing True if this column was > 0 or False otherwise mask = (a[:, i] > 0).transpose().toarray()[0] # b) now get the indices of these rows as list indices_of_row = list(np.where(mask > 0)[0]) if len(indices_of_row) == 0: return # c) use the indices of these rows to create the mean vector return a[indices_of_row,].mean(axis=0) from timeit import timeit n = 1000 a = sparse.random(n,n, format="csr") i = np.random.randint(0,n) print("mask ",timeit(pp,number=1000),"ms") print("concat",timeit(qq,number=1000),"ms") print("matmul",timeit(mm,number=1000),"ms") print("OP ",timeit(OP,number=1000),"ms") assert np.allclose(pp(),OP()) assert np.allclose(qq(),OP()) assert np.allclose(mm(),OP()) Sample run: mask 0.08981675305403769 ms concat 0.04179211403243244 ms matmul 0.14177833893336356 ms OP 0.9761617160402238 ms A: I think this will suffice. Y = X.toarray() MeanVec = Y[Y[:,i] > 0].mean(axis=1) Edited X.mean(axis=1)[(X.getcol(i) > 0).toarray()]
doc_23530075
using Microsoft.Advertising.WinRT.UI; . . private InterstitialAd ad; . . Interop.RequestInterstitialEvent += Interop_RequestInterstitialEvent; Interop.ShowInterstitialEvent += Interop_ShowInterstitialEvent; . . . void Interop_RequestInterstitialEvent(object sender, EventArgs e) { //When I want to recharge ad ad = new InterstitialAd(); ad.RequestAd(AdType.Video, "d25517cb-12d4-4699-8bdc-52040c712cab", "11389925"); } void Interop_ShowInterstitialEvent(object sender, EventArgs e) { // Show your ad only if it is charging if (ad.State == InterstitialAdState.Ready) { ad.Show(); } } Displays the following error: Determine when to display the announcement shortly after the Ready the same it works: void Interop_RequestInterstitialEvent(object sender, EventArgs e) { ad = new InterstitialAd(); ad.RequestAd(AdType.Video, "d25517cb-12d4-4699-8bdc-52040c712cab", "11389925"); ad.AdReady += ad_AdReady; } void ad_AdReady(object sender, object e) { ad.Show(); } But I want to display it only when I call Interop_ShowInterstitialEvent. How do I display it in that event?
doc_23530076
$currencies = Currency ::getByActive(true) ->withCount('currencyHistories') ->with('latestCurrencyHistory') ->orderBy('ordering', 'asc') ->get(); In model app/Models/Currency.php I have : public function latestCurrencyHistory() { return $this->hasOne('App\Models\CurrencyHistory')->latest(); } But checking generated sql I see lines like : SELECT * FROM `currency_histories` WHERE `currency_histories`.`currency_id` in (8, 13, 16, 19, 27, 30) ORDER BY `created_at` desc I suppose this code is raised by latestCurrencyHistory method and wonder can I set some limit 1 condition here, as resulting data are too big. Thanks! A: Query is correct. As you eager load your relation for the collection of currencies using with method, you load currency_histories for all of your Currency models in collection. If you dump the result, you will have currencies with IDs: 8, 13, 16, 19, 27, 30 and one latestCurrencyHistory (if present) for each.
doc_23530077
var obj= { "id": "6", "name": "parent", "path": "/", "category": "folder", "fid":"6" "children": [ { //some values }, { //some other values } ] } how to iterate and push it into an new array. type declaration getEntry: Array<Object> = [] pushing into an array method get addedEntry() { let files = [] this.getEntry = files.push(this.obj) } But, i am getting type error. How to push this object into an array or make it array.? A: The push method returns a Number representing the new value of the array. That's why you are getting a TypeError (you are assigning a Number to an Array of Objects). You should do the following instead. get addedEntry() { let files = [] files.push(this.obj) this.getEntry = files } Here's the docs entry for the push method in JavaScript.
doc_23530078
Take this simple HTML for example <label class="input"> <i class="icon-prepend fa fa-user"></i> <input type="text" name="fname" placeholder="First name"> </label> What would the equivalent to this be in Razor? For whoever thought this is too broad. I basically want to register @Html.Label() then go on and set child attributes for it which will include an icon and and textbox. Is it even possible to do what I'm trying to achieve with razor? It will create something like this I tried to figure it out but failed badly. This is the best I got. <label class="input"> @Html.Bootstrap().Icon("icon-prepend fa fa-user") @Html.Bootstrap().TextBoxFor("fname", htmlattributes: new { placeholder = "First name" }) </label> I was hoping to create the label in razor too. A: You can do something like this: <label class="input"> <i class="icon-prepend fa fa-user"></i> @Html.TextBoxFor("fname", htmlattributes: new { placeholder = "First name" }) </label> A: Create a custom HTML helper. The output of the HTML helper will be what @CarlosAraujo suggests: <label class="input"> <i class="icon-prepend fa fa-user"></i> @Html.TextBoxFor("fname", htmlattributes: new { placeholder = "First name" }) </label> You call it something like this: @Html.MyCustomAwesomeTextBoxFor(...) In this way you can encapsulate and re-use this component anywhere in your code.
doc_23530079
The kotlin part is as follows. Note that Matrix4 and Vector3 are libGDX (a Java/Kotlin's game library) classes, and they are nothing more than just containers of data. The mul function multiplies the matrix with the vector, and stores the result in-place back into the vector. fun benchmark(a: Matrix4, b: List<Vector3>) { var i = 0; while (i < 100000) { b[i].mul(a); ++i; } } var a = Matrix4(floatArrayOf(1f, 2f, 3f, 4f, 3f, 2f, 1f, 2f, 3f, 4f, 3f, 2f, 1f, 2f, 3f, 4f)) var b = List<Vector3>(); for (i in 0..100000) { b.add(Vector3(3f, 2f, 1f)); } // warmup JIT for (i in 0..9) { benchmark(a, b) } var t: Double = 0.0; for (i in 0..9) { t += measureNanoTime { benchmark(a, b) }.toDouble() } println(t / 10.0 / 1000000.0) // milliseconds The Unity C# part is as follows. Note that M4 and V3 are helper classes created to match what libGDX had. private void Benchmark(M4 a, List<V3> b) { var i = 0; while (i < 100000) { b[i].mul(a); ++i; } } var a = new M4(1f, 2f, 3f, 4f, 3f, 2f, 1f, 2f, 3f, 4f, 3f, 2f, 1f, 2f, 3f, 4f); var b = new List<V3>(); for (int i = 0; i < 100000; ++i) { b.Add(new V3(3, 2, 1)); } // warmup JIT for (int i = 0; i < 10; ++i) { Benchmark(a, b); } var t = 0.0; for (int i = 0; i < 10; ++i) { var s = (double) nanoTime(); Benchmark(a, b); var e = (double) nanoTime(); t += e - s; } Debug.Log(t / 10.0 / 1000000.0); // milliseconds The implementation of mul is made to match libGDX's exact implementation (https://github.com/libgdx/libgdx/bl...x/src/com/badlogic/gdx/math/Vector3.java#L353). The device is a mid-2015 MacBook Pro. Unity version is 2020.3.0f1, building to OSX standalone with Mono backend, not a development build. The results are as follows: * *Kotlin: 0.3658762ms *Unity C#: 1.74067ms (almost 4 times slower). If I change M4 and V3 to be struct instead of class, it becomes even slower: 2.51ms (almost 6 times slower). What would be the cause of such a significant difference? A: The performance of C# could be better if it's done in a different way. First of all, Unity Engine when using MonoBehaviour, most the code under the MonoBehaviour classes are Single Threaded which means it might take ridiculous time to complete the code especially when more mathematics are involved. Then, Unity not only compile and runs code, apart from running code it also does rendering, some calculations to get the performance of the game in the editor, many process will be running in the background just to run Unity, some RAM and most CPU power will be spent to run Unity Engine and it's editor, So the Code can't get the most power from hardware. So, to get the most out from Unity and C#, Try Unity's DOTS (Data Oriented Technology Stack) which is a game changer. Burst works by compiling a subset of the C# language, known as High-Performance C# (HPC#), to make efficient use of a device’s power by deploying advanced optimizations built on top of the LLVM compiler framework. Burst is great for exploiting hidden parallelism in your applications. DOTS's primary feature is to run the game in multiple threads and utilizing the hardware using JobSystem and ComponentSystem and much more. Most of the classes gets it's new name in DOTS which is Burst Compiler Supported unlike Vector3, burst has float3, float4 which increases the performance drastically.
doc_23530080
A particularity of the SPA is that it always runs under different domains (I have enabled CORS for a given list of domains). My API will therefore always address the data according to the origin of a request eg: request origin domainId -------------- -------- https://www.client1.com -> client1.com https://client1.com -> client1.com https://www.client2.xxx -> client2.com At the present moment, I made a utility class that recover the domainId based on a given Request: public static class DomainId { public static string Get(HttpRequestMessage Request) { InMemoryDomainRepository repo = new InMemoryDomainRepository(); try { IEnumerable<string> headerValues = Request.Headers.GetValues("Origin"); var origin = headerValues.FirstOrDefault(); return repo.GetDomainId(origin); } catch { return repo.GetDomainId("http://client1.com"); } } Then, in a controller, to get for instance a specific userProfile, I will use my utility class like so: [Authorize] public IHttpActionResult GetProfile() { var domainId = DomainId.Get(Request); // uses the utility class above IClientRepository repo = new ClientRepositoryAx30(); var client = repo.GetClient(domainId, User.Identity.Name); return Ok(client); } The question: When writing test cases, there is no origin since I am not querying the API from within a browser. So how can I specify the origin of the request? As I understand so far, it is not possible to set the origin like this: Request.Headers.SetValues("Origin", "https://client1.com"); Fetching out the DomainId from the origin (Request.Headers.GetValues("Origin");) is the best way I have found so far. But maybe there is a better solution? I am currently stuck with the following test method: [TestClass] public class ClientControllerTests { [TestMethod] public void TestGetProfile() { var identity = new GenericIdentity("Bob"); Thread.CurrentPrincipal = new GenericPrincipal(identity, null); // how to set a Generic Domain? var ctrl = new ClientController(); var result = ctrl.GetProfile(); IHttpActionResult actionResult = ctrl.GetProfile(); System.Diagnostics.Debug.WriteLine(actionResult); //Assert.IsInstanceOfType(actionResult, typeof(OkResult)); } } I would like to be able to specify a "generic" domain, just like I define a "Generic Identity" Any help will be greatly appreciated. Best, Mikou
doc_23530081
I’ve successfully configure my service in symfony2 and server is working… Exemple here, when i call in JS network.onSubscribe every people who have already subscribe receive the info. class ChatTopic implements TopicHandlerInterface { /** * Announce to this topic that someone else has joined the chat room * Also, set their nickname to Guest if it doesnt exist. * * @param \Ratchet\ConnectionInterface $conn * @param $topic */ public function onSubscribe(Conn $conn, $topic) { if (!isset($conn->ChatNickname)) { $conn->ChatNickname = "Guest"; **how i have to do if i want to use "$this->getUser(); " here ?** } $msg = $conn->ChatNickname . " joined the chat room."; $topic->broadcast(array("msg" => $msg, "from" => "System")); } But now, I would like to use some other tools that I’ve already build like some Entity or Form “in my service”. For example, I would like to be able to do “$this->getUser()” in my service to return the pseudo of the user. To return for example “Pseudo has joined this channel “ to every client connected to the channel. This class is a part of my service and i would like use inside $this->getUser or $em = $this->getDoctrine()->getManager(); $em->persist($music);" . Or I would like to persist things send throw my websocket in Doctrine. (Like save every message send by any people connected to the websocket channel. Like you see i'm not very confortable with Symfony2 and websocket but i'm learning ! I hope I’m clear (sorry for my english...) and someone can help me! Thanks. A: To persist entities, you need to first inject the entity manager into your class. class ChatTopic implements TopicHandlerInterface { protected $em; public function __construct($em) { $this->em = $em; } } You'll need to inject the dependency in services.xml <services> <service id="jdare_clank.chat_topic_handler" class="JDare\ClankChatBundle\Topic\ChatTopic"> <argument>"@doctrine.orm.default_entity_manager"</argument> </service> And get your class from the service container in a controller or some other ContainerAwareInterface: $chatTopic = $this->getContainer()->get('jdare_clank.chat_topic_handler'); Getting the user is trickier, since you won't have access to the security context in that class, since it is not container aware. There are a few ways you could do it. In our case, we actually implemented a secure websocket (wss) protocol and created a login protocol within, so we could store a user id with each connection. But one quick and dirty way would be to simply add the user id to your session in another controller. $userId = $this->get('security.context')->getToken()->getUser()->getId(); $session = $this->get('session'); $session->set('user', (str) $userId); Then you can get the user from the session inside your class. public function onSubscribe(Conn $conn, $topic) { $userId = $conn->Session->get('user'); $user = $this->em->getRepository('AcmeUserBundle:User')->find((int) $userId); ... Hope this is helpful. Let me know if any of this loses you, and I'll try to help. Dependency injection is a little hard to wrap your head around, but it's a very powerfool tool in your kit!
doc_23530082
to string format 9,113267 and 59,300357 Thx john A: VascoP is right in how to convert the number to a "proper" decimal but he is wrong about how to convert those decimal values to a string. the ToString method has an overload whose signature is public string ToString(IFormatProvider provider) See: http://msdn.microsoft.com/en-us/library/3ebe5aks.aspx You can use this to create a culture specific string. The examples on the linked page show how to do it but for completeness of answer an example might be: (Latitude/1000000).ToString(CultureInfo.CreateSpecificCulture("en-GB") // Outputs with a "." decimal separator (Latitude/1000000).ToString(CultureInfo.CreateSpecificCulture("de-DE") // Outputs with a "," decimal separator I assume you have a specific culture that you want to be able to understand this so you should use the correct culture. That makes it much easier to change later if you want (eg you can pick up the culture from a global config setting) or have a user preference for the number format, etc. Also if you start using custom formats (eg to put thousand separators in) then the cultureinfo object will again do the right thing. It should also be noted at the end of all this that you may just need the .ToString if the default culture is actually the one you are using. You didn't provide that info though so I just assumed that a simple ToString wouldn't be doing the trick. A: (Latitude/1000000).ToString().Replace('.', ','); (Longitude/1000000).ToString().Replace('.', ','); EDIT: Although this works, as stated by Chris, it is not best practice. You should use his solution instead.
doc_23530083
Do you know how to set width to file without using escape characters? The following code is just a part of student-related functions- void save() { FILE* fp; fp = fopen("Student.txt", "w"); fprintf(fp,"Roll No\tName\t\t\t\tPaper 1\tPaper 2\tPaper 3\tTotal \tGrade\n"); for(int i = 0; i < time; ++i) { fprintf(fp, "%d\t%s\t \t%d\t%d\t%d\t%d\t%c\n", info[i].rollNo, info[i].name,info[i].p1, info[i].p2, info[i].p3, info[i].total, info[i].grade); } cout << "Successfully written to file!" << endl; fclose(fp); getch(); menu(); } Thank you!!1 A: If I understood your question, you might wanna take a look at the setw and setfill functions.
doc_23530084
<!DOCTYPE html> <html class="no-js" data-placeholder-focus="false"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=0" /> <meta name="mobileoptimized" content="0" /> <title>index</title> <meta name="description" content="" /> <meta name="keywords" content="" /> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css"> <link rel="stylesheet" href="css/owl.carousel.css"> <link rel="stylesheet" href="css/animate.css"> <link rel="stylesheet" href="css/custom.css"> </head> when I open website from mobile, it is not responsive at all. I have not changed my css code. Please, help me! Thank you!
doc_23530085
private void executeCommand(String command) throws IOException { Log.e(TAG, "executeCommand: " + command); Runtime.getRuntime().exec(command); } I need to capture my app log (Log.e) + some connectivity logs, so I'm filtering it like this: logcat -f /storage/emulated/0/Android/data/com.myapp.androidterminal/files/log/Terminal.log -n 1 -r 10000 -v threadtime MyAppTag:E AndroidRuntime:E AWSIotMqttManager:* System.out:* *:S When I have Developer options - USB debugging enabled, it captures the log properly. But when I run it with dev options disabled, it captures only my app log, but skipping AWSIotMqttManager and System.out. How to make it work with Developer options disabled?
doc_23530086
template<typename TypeA, typename TypeB> class MyClass { public: static TypeA StaticA; static TypeB StaticB; //...other stuff.... }; How do I initialize 'StaticA' (and StaticB)? If I do this: (in the header file, under the class's declaration but not inside it) template<> typename MyClass<TypeA, TypeB>::TypeA MyClass<TypeA, TypeB>::StaticA = TypeA(); Gives me: 'TypeA' was not declared in this scope. 'TypeB' was not declared in this scope. template argument 1 is invalid template argument 2 is invalid And this: template<typename TypeA, typename TypeB> typename MyClass<TypeA, TypeB>::TypeA MyClass<TypeA, TypeB>::StaticA = TypeA(); Gives me: conflicting declaration 'typename MyClass<TypeA, TypeB>::TypeA MyClass<TypeA, TypeB>::StaticA' 'MyClass<TypeA, TypeB>::StaticA' has a previous declaration as 'TypeA MyClass<TypeA, TypeB>::StaticA' declaration of 'TypeA MyClass<TypeA, TypeB>::StaticA' outside of class is not definition [-fpermissive] What's the proper way to initialize a templated class's static member that uses a template argument as the type? A: Ah, the correct syntax is: template<typename TypeA, typename TypeB> TypeA ResourceFactory<TypeA, TypeB>::StaticA = TypeA(); Which in my original problem is: template<typename TypeA, typename TypeB> typename MyClass<TypeA, TypeB>:: TypeA MyClass<TypeA, TypeB>::StaticA = TypeA(); ^remove^ ^-------remove--------^ I was getting confused because of all the template arguments. =) Similar to, but not entirely overlapping, this question's answer.
doc_23530087
Foreign Address - The IP address and port number of the remote computer to which the socket is connected. This is what I understood about Foreign Address. But when I ran the command what I got in Foreign Address column is that validation:port_number This is what I am getting I didn't understood what is validation ? Can someone please explain me? Or if I am wrong somewhere please show me the way.
doc_23530088
This is how I declare my activity in phone module: <activity android:name=".Main" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="com.google.android.wearable.watchface.category.COMPANION_CONFIGURATION" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND"></action> <category android:name="android.intent.category.DEFAULT"></category> <data android:mimeType="image/*"></data> </intent-filter> </activity> On the watch part, I added in: <meta-data android:name= "com.google.android.wearable.watchface.companionConfigurationAction" android:value= "virtualgs.photowatch.Main" /> <meta-data android:name= "com.google.android.wearable.watchface.wearableConfigurationAction" android:value= "virtualgs.photowatch.Main" /> And the result is the same - no gear shown on the Android Wear app. A: Try something like this: Phone Manifest: <intent-filter> <action android:name="com.virtualgs.photowatch.MAIN_CONFIG" /> <category android:name="com.google.android.wearable.watchface.category.COMPANION_CONFIGURATION" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> Watch Manifest: <meta-data android:name="com.google.android.wearable.watchface.companionConfigurationAction" android:value="com.virtualgs.photowatch.MAIN_CONFIG" /> I think the intent action in the phone manifest has to be the same as the meta-data value in the watch manifest to work. A: I think this is the correct answer about XML file config: <activity android:name=".DigitalWatchFaceWearableConfigActivity" android:label="@string/digital_config_name"> <intent-filter> <action android:name= "com.example.android.wearable.watchface.CONFIG_DIGITAL" /> <category android:name= "com.google.android.wearable.watchface.category.WEARABLE_CONFIGURATION" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> A: As well as having the activity defined in the phone module, you need to reference it in the wear module as part of the declaration of your watch face service like this: <service android:name=".MyWatchFaceService" ... /> <!-- companion configuration activity --> <meta-data android:name= "com.google.android.wearable.watchface.companionConfigurationAction" android:value= "com.my.watchface.CompanionConfigurationActivity" /> <!-- wearable configuration activity --> <meta-data android:name= "com.google.android.wearable.watchface.wearableConfigurationAction" android:value= "com.my.watchface.WearableConfigurationActivity" /> ... Replacing com.my.watchface.CompanionConfigurationActivity and com.my.watchface.WearableConfigurationActivity with the fully qualified names of the configuration activities in the wear and phone modules respectively.
doc_23530089
Here is the heart of my problem : #include <boost/spirit/home/qi.hpp> using boost::spirit::qi::ascii::space_type; using boost::spirit::qi::grammar; using boost::spirit::qi::phrase_parse; template<typename P> bool test_parser(char const* input, P const& p) { char const* f(input); char const* l(f + strlen(f)); return parse(f, l, p) && f == l; } struct my_grammar : grammar<char const*, space_type> { my_grammar() : base_type(r) { r = boost::spirit::qi::int_; } rule<char const*, space_type> r; } g; bool b = test_phrase_parser("5", g); And this is was the compiler says: error: no matching function for call to ‘test_phrase_parser(const char [6], ph_files_parsing::process_parsing::test_method()::my_grammar&)’ note: candidate is: note: template bool test_phrase_parser(const char*, const P&) It all works fine if I replace bool b = test_phrase_parser("5", g); by bool b = test_phrase_parser("5", boost::spirit::qi::int_); Many thanks in advance to anyone who can help. (Boost version is 1.48) A: Your question turns out to be frequently-asked (at the bottom). Since the grammar has a skip-parser, it must be invoked with phrase_parse() instead of just parse(). For example, return phrase_parse(f, l, p, boost::spirit::ascii::space) && f == l;
doc_23530090
The concept of the project Creating a machine that will permanently loop through a bunch of code for the rest of its existence. Basically I am making an automatic cat feeder that will dispense food at certain times during the day. THAT IS WHY THE LOOP MUST BE PERMANENT. Here is my basic code so far: DateFormat dateFormat = new SimpleDateFormat("HH:mm"); // 1. Calendar cal = Calendar.getInstance(); // 2. String CurrentTime = dateFormat.format(cal.getTime()); // 3. jTextArea2.setText(CurrentTime); String FeedTimeMorning = "06:00"; String FeedTimeSnack = "19:07"; String FeedTimeMidday = "12:30"; boolean TempFeed = false; while(TempFeed=false) { if (FeedTimeMorning.equals(CurrentTime)) { txaOne.setText("FeedCats"+" " +CurrentTime);} if (FeedTimeSnack.equals(CurrentTime)){txaOne.setText("FeedCats"+" " +CurrentTime);} if(FeedTimeMidday.equals(CurrentTime)){txaOne.setText("FeedCats"+" " +CurrentTime);} When it comes to the designated time the text "Feed Cats " does not appear. Any help would be appreciated. A: One equals (=) is assignment while two (==) is equality, this while(TempFeed=false) should be one of while(TempFeed==false) or the shorter boolean negation (omitting the = entirely) like while(!TempFeed) With one = it assigns false to TempFeed and evaluates to false (which means the loop is never entered).
doc_23530091
The error is - "An unhandled exception of type System.StackOverflowException occurred in mscorlib.dll" It is thrown in the final code block below where public DIEMEntities() is called. It occurs whenever I add a new item, I can update items ok. Any help would be appreciated. The code is - protected void OnSave(object sender, EventArgs e) { ArrayList validationErrors = new ArrayList(); ContactTypeEO contactType = new ContactTypeEO(); if (uxID.Value.Length > 0) { //Updating contactType.Id = int.Parse(uxID.Value); } contactType.Name = uxName.Text; contactType.ExpressionValidator = uxExpression.Text; contactType.Save(ref validationErrors); if (validationErrors.Count > 0) { ShowValidationMessages(validationErrors); } else { this.RefreshUI(); } } public bool Save(ref ArrayList validationErrors) { ValidateSave(ref validationErrors); if (validationErrors.Count == 0) { if (Id == 0) { ContactTypeData.Insert(Name, ExpressionValidator); } else { ContactTypeData.Update(Id, Name, ExpressionValidator); } return true; } else { return false; } } /// <summary> /// Inserts the new Contact Type. /// </summary> /// <param name="name">The name.</param> /// <param name="validator">The validator.</param> public static void Insert(string name, string validator) { using (DIEMEntities diemEntities = new DIEMEntities()) { Insert(name, validator); } } /// <summary> /// Inserts the new Contact Type. /// </summary> /// <param name="diemEntities">The DIEM Entities.</param> /// <param name="name">The name.</param> /// <param name="validator">The validator.</param> public static void Insert(DIEMEntities diemEntities, string name, string validator) { diemEntities.usp_ContactTypes_Insert(name, validator); } public partial class DIEMEntities : DbContext { public DIEMEntities() : base("name=DIEMEntities") { } ... OTHER CODE} A: You have a recursive loop here: public static void Insert(string name, string validator) { using (DIEMEntities diemEntities = new DIEMEntities()) { Insert(name, validator); } } This will execute continuously until you run out of memory. I believe you're intention is to do this: public static void Insert(string name, string validator) { using (DIEMEntities diemEntities = new DIEMEntities()) { Insert(diemEntities, name, validator); } }
doc_23530092
A: This will happen when you're running the server from inside an IDE like Eclipse. The IDE's server plugin such as Eclipse Tomcat plugin will after the startup process do a self-test by sending a GET request to /. Apparently you've on / a page associated with those view scoped beans. Ignore it. This wouldn't happen during production.
doc_23530093
along with AWS CloudWatch for message monitoring. There's currently only 5 metrics to be watched: * *NumberOfMessagesPublished *PublishSize *NumberOfNotificationsDelivered *NumberOfNotificationsFailed *SMSSuccessRate None of these seems to be like message content, recipient platforms, or delivered date/time. (contents that make more sense to marketers rather than developers) How could I query the history of all my sent messages or a specific message? A: SNS does not retain sent messages. You would have to archive the sent messages yourself as you send them. A: One idea is to let SNS itself do the message archiving for you, so that you can then query the archive for the analytics that are relevant to you. This can be done by subscribing a Kinesis Data Firehose to the SNS topic that you use for sending these mobile notifications. You can configure your Firehose stream to store the SNS notifications in S3, Redshift, Elasticsearch, Datadog, Splunk, New Relic, or MongoDB. Check this out: https://aws.amazon.com/about-aws/whats-new/2021/01/amazon-sns-adds-support-for-message-archiving-and-analytics-via-kineses-data-firehose-subscriptions/ A: SNS is a wrapper around a number of similar notification APIs. The APIs for Apple (APNS) and Google (Most Android) GCN don't offer any kind of receipt confirmation. If you need receipt confirmation you would have to build that into the application on the mobile device to inspect messages received that were for that application and there is no universal way to do that either. The other issue is that you are totally at the mercy of the user authorizing notifications. I suggest you incorporate messaging of your own inside the app and have push notifications as an optional enhancement. In order to get badges to work right you also need cooperation with the app since there is no way using SNS to react to actions taken in the app to clear the notifications or adjust the badge value.
doc_23530094
Below is the method in angular: Note: Currently i am manually adding it with headers. private heroesUrl = 'http://localhost:8080/hi'; header = new HttpHeaders().set("Cookie", "JSESSIONID=A2A75EC9A3E1172D60060C6E708549B5"); getMessage() :Observable<Message>{ return this.http.get<Message>(this.heroesUrl,{headers:this.header}); } Response which i get when i login using basic Auth A: You can't do this, cause the browser doesn't allow you to do it. Let me describe the problem here: Did you notice the Set-Cookie: JSESSIONID=......; Path=/; HttpOnly in your response headers? Well, The problem is the HttpOnly flag. Actually :) it's not a problem, it's a feature to prevent attacks that aim to steal your browser cookies: HttpOnly is a flag added to cookies that tell the browser not to display the cookie through client-side scripts (document.cookie and others). ... When you set a cookie with the HttpOnly flag, it informs the browser that this special cookie should only be accessed by the server So the browser doesn't allow any javascript code to access this variable. If you could change that value, then it's not a HttpOnly flagged cookie anymore:) If you want to send this cookie via javascript, you should send it via the Authorization header for example and write middleware in Java server so that it captures these values from the Authorization header and think of them as JSESSIONID cookie. No more options for you :) A: I also had this issue, and i just fixed it right now. I realized that is you pass option {withCredentials: true} your browser will automatically send all available cookies along with your request. That way you don't have to add the cookies manually, so it's fluent and i thinks it also safer. Change your code to this and see and check. Cookies are available when the path is same as your front end. private heroesUrl = 'http://localhost:8080/hi'; getMessage() :Observable<Message>{ return this.http.get<Message>(this.heroesUrl, {withCredentials: true}); }
doc_23530095
Custom formly idea: import { Component } from '@angular/core'; import { FieldType } from '@ngx-formly/core'; @Component({ selector: 'formly-field-input', template: ` <span class="toggleContainer"> <p [class]="to.checked ? '' : 'toggleSelected'"> {{ to.textBefore }} </p> <ion-toggle [checked]="to.checked" [disabled]="to.disabled" color="primary"> </ion-toggle> <p [class]="to.checked ? 'toggleSelected' : ''"> {{ to.textAfter }} </p> </span> `, styleUrls: ['./toggle-2-labels.component.scss'], }) export class toggle2LabelsComponent extends FieldType { } Imput added to form: { key: 'exampleName', type: 'toggle2Labels', wrappers: ['acc-wrapper'], templateOptions: { disabled: true, checked: false, textBefore: 'something', textAfter: 'something', onChange: (field, value) => console.log('onChange'), change: (field, $event) => { console.log('change'); }, }, hooks: { onInit: (field: FormlyFieldConfig) => { //Other stuff }, } }, I tried with onChange and change events without working. I think that could be a problem of not having an value itself, but I don't know how to add it to my custom toggle. Maybe any kind of method to get an attributes like to.checked change would be fine. Any idea? A: The attribute you need is called ionChange. Since this is an ionic framework element, simply using the convention defaults is not assured of working. template: ` <span class="toggleContainer"> <p [class]="to.checked ? '' : 'toggleSelected'"> {{ to.textBefore }} </p> <ion-toggle (ionChange)="() => console.log('onChange')" [checked]="to.checked" [disabled]="to.disabled" color="primary"> </ion-toggle> <p [class]="to.checked ? 'toggleSelected' : ''"> {{ to.textAfter }} </p> </span> `, A: Finally I got it, formly onChange and change events doesn't works for custom imputs (they doesn't works with the formly guide example too) so the solution for me was getting the (ionChange) event on the custom imput template with a hook on init like the example; Custom formly: import { Component } from '@angular/core'; import { FieldType } from '@ngx-formly/core'; @Component({ selector: 'formly-field-input', template: ` <span class="toggleContainer"> <p [class]="to.checked ? '' : 'toggleSelected'"> {{ to.textBefore }} </p> <ion-toggle <ion-toggle [formControl]="formControl" [formlyAttributes]="field" [value]="to.checked" [checked]="to.checked" [disabled]="to.disabled" (ionChange)="formControl.setValue(to.checked)" color="primary"> color="primary"> </ion-toggle> <p [class]="to.checked ? 'toggleSelected' : ''"> {{ to.textAfter }} </p> </span> `, styleUrls: ['./toggle-2-labels.component.scss'], }) export class toggle2LabelsComponent extends FieldType { } Custom imput { key: 'exampleName', type: 'toggle2Labels', wrappers: ['acc-wrapper'], templateOptions: { disabled: true, checked: false, textBefore: 'something', textAfter: 'something', onChange: (field, value) => console.log('onChange'), change: (field, $event) => { console.log('change'); }, }, hooks: { onInit: (field: FormlyFieldConfig) => { field.formControl.valueChanges.subscribe(() => { console.log('only works here for me'); }); }, } }, A: Html file <span class="toggleContainer"> <p [class]="to.checked ? '' : 'toggleSelected'">{{ to.textBefore }}</p> <ion-toggle (ionChange)="changeToggle($event)" [checked]="to.checked" [disabled]="to.disabled" color="primary" > </ion-toggle> <p [class]="to.checked ? 'toggleSelected' : ''">{{ to.textAfter }}</p> </span> ts File public to = { checked: false, disabled: false, textBefore: 'something', textAfter: 'something' }; changeToggle(event: any) { console.log(event.value); this.to.checked = event.value; }
doc_23530096
In this jquery on function calculateBerat => $('input[name=newBeratItem]').eq(0).val(getItemBerat); I have some troubles can you please help me to fix this problem. thanks. <script src="jquery.min.js"></script> <script> $(document).ready(function () { $(".jmlItem").keyup(function () { var idBarang = $(this).attr('id'); var jmlBarang = $(this).attr('value'); var beratBarang = $(this).attr('rel'); var jmlBarangNew = $(this).val(); calculateItem(); calculateBerat(idBarang, jmlBarangNew, beratBarang); }); function calculateBerat(idBarang, jmlBarangNew, beratBarang) { var ttlBerat = 0; var getItemBerat = jmlBarangNew * beratBarang; $('input[name=newBeratItem]').eq(0).val(getItemBerat); //in this code, the value is only charged on the first line does not correspond to the selected row keyup event. //how to ensure that value is filled in the corresponding row keyup event? $(".newBeratItem").each(function() { ttlBerat += parseFloat(this.value); }); $("#isTotalBerat").html(ttlBerat.toFixed(2)); } function calculateItem() { var jmlItem = 0; //iterate through each textboxes and add the values $(".jmlItem").each(function() { //add only if the value is number if (!isNaN(this.value) && this.value.length != 0) { jmlItem += parseFloat(this.value); $(this).css("background-color", "#FEFFB0"); } else if (this.value.length != 0){ $(this).css("background-color", "red"); } }); $("#isTotalItem").html(jmlItem.toFixed(2)); } }); </script> <table style="text-align:center;"> <tr> <td>Item</td> <td>Berat</td> <td>Harga</td> </tr> <tr> <td> <input type="text" id="IdBarang01" value="5" rel="0.3" class="jmlItem" size="1"/> </td> <td> <input type="text" id="0.3" value="0.3" class="oldBeratItem" disabled size="1" style="background-color:#A0A197;"/> <input type="text" name="newBeratItem" class="newBeratItem" size="1"/> </td> <td> <input type="text" id="5000" value="5000" class="oldHargaItem" readonly size="2" style="background-color:#A0A197;"/> </td> </tr> <tr> <td> <input type="text" id="IdBarang02" value="6" rel="0.6" class="jmlItem" size="1"/> </td> <td> <input type="text" id="0.6" value="0.6" class="oldBeratItem" disabled size="1" style="background-color:#A0A197;"/> <input type="text" name="newBeratItem" class="newBeratItem" size="1"/> </td> <td> <input type="text" id="10000" value="10000" class="oldHargaItem" readonly size="2" style="background-color:#A0A197;"/> </td> </tr> <tr> <td><div id="isTotalItem"></div></td> <td><div id="isTotalBerat"></div></td> <td><div id="isTotalHarga"></div></td> </tr> </table> A: You need to find the closest parent tr and find the required input and set the value using val() as follows, function calculateBerat(idBarang, jmlBarangNew, beratBarang) { var ttlBerat = 0; var getItemBerat = jmlBarangNew * beratBarang; $("#"+idBarang).closest("tr").find('input[name=newBeratItem]').val(getItemBerat); //in this code, the value is only charged on the first line does not correspond to the selected row keyup event. //how to ensure that value is filled in the corresponding row keyup event? $(".newBeratItem").each(function() { ttlBerat += parseFloat(this.value); }); $("#isTotalBerat").html(ttlBerat.toFixed(2)); }
doc_23530097
The webpage has references of companies in a grid view (16 rows x 5 columns) and I want to retrieve each reference's url and the title. The problem is that all 5 references in each row, are in one class named row and when I'm scraping the page, I can only see the first reference of every row, instead of all 5 of them. Here is my code so far: url = 'http://www.slimstock.com/nl/referenties/' r = requests.get(url) soup = BeautifulSoup(r.content, "lxml") info_block = soup.find_all("div", attrs={"class": "row"}) references = pd.DataFrame(columns=['Company Name', 'Web Page']) for entry in info_block: try: title = entry.find('img').get('title') url = entry.a['href'] urlcontent = BeautifulSoup(requests.get(url).content, "lxml") row = [{'Company Name': title, 'Web Page': url}] references = references.append(row, ignore_index=True) except: pass Is there a way to fix this? A: I think you should iterate over the "img" or over the "a". You can write something like this: for entry in info_block: try: for a in entry.find_all("a"): title = a.find('img').get('title') url = a.get('href') urlcontent = BeautifulSoup(requests.get(url).content, "lxml") row = [{'Company Name': title, 'Web Page': url}] references = references.append(row, ignore_index=True) except: pass A: import pandas as pd from bs4 import BeautifulSoup import requests url = 'http://www.slimstock.com/nl/referenties/' r = requests.get(url) soup = BeautifulSoup(r.content, "lxml") info_block = soup.find_all("div", attrs={"class": "row"}) references = pd.DataFrame(columns=['Company Name', 'Web Page']) for entry in info_block: anchors = entry.find_all("a") for a in anchors: try: title = a.find('img').get('title') url = a['href'] # urlcontent = BeautifulSoup(requests.get(url).content, "lxml") row = [{'Company Name': title, 'Web Page': url}] references = references.append(row, ignore_index=True) except: pass
doc_23530098
How can I do this? I've searched but it's hard to search as I'm not really too sure how to describe it without the image. A: If I understand correctly, what you want, it is called separator and the class which can be used in Swing is JSeparator
doc_23530099
void reverse(char *str) { char *end = str; char tmp; if (str) // I don't understand what is happening within this if loop and how this is carried out for `str` which is not Boolean { while (*end) // I dont know what this means either { ++end; } --end; while (str < end) { tmp = *str *str++ = *end //I am confused as to why this is not just *str = *end *end-- = tmp; //Similarly, why is this not *end = tmp } } } A: * *if (str) means Check if str a pointer to char is not NULL. Same as: if (str != NULL) *while (*end) check that the char pointed to by end is not the null-terminating character. Same as: while (*end != '\0') **str++ = *end Assign the char pointed to by end to str and then advance str pointer by 1 char. *end-- advances end backwards by 1 char. *while (str < end) Compare the addresses as numbers (and not the values the pointers point to). This only makes sense if both pointers refer to different positions in the same memory block e.g. a c string in this case or any array. If str points to the 1st element of the string and end to the 2nd, then str < end will be true. The actuals chars in the 1st and 2nd positions will are not taken into account A: *end = str; means the value of end pointer contains characters of string str if (str) means check if str pointer isn't null ,so it's always true when str point to char. while (*end) means check if end points to char , when pointer is null the condition is terminated , so when pointer reach the end of string end, while condition break and end pointer value contains the last char of string end. *str++ = *end this statement can be break down to 2 statements to understand it : first *str=*end; replace char value pointed by str with char pointed by end. second *str++; move pointer to next character in string str after replacing. *end-- = tmp; this statement can be break down to 2 statements to understand it : first *end = tmp; replace char value pointed by end with tmp char. second *end--; move pointer to previous char in string end after replacing. I hope the idea is clear for you. A: know that *end = str; end = is the pointer here They're checking the string if is not null if it is null ,if is should take the value of the char and assign to it in your case the string is temp i want you understand what char temp is doing and *end as pointer treat *end as a string meaning *end should not be null ,temp is character while (*end) ++end; it is telling that while end is not null, meaning the results should be a string ( e.g. a name like john) --end it is telling you that the null should be clear then it should go to another while while (str < end) because the string is null take char temp take to be a string *str++ = *end then allow characters to make it a string or a name or increement the character to make it a string end-- = tmp // they are assign the string to that null string to have a vlue