id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23527700
namespace Search { enum SearchConditionType { Like = 0, EqualNotString = 1, EqualString = 2 }; } Then I try to declare enum: namespace Search { public partial class Controls_SelectYesNo : System.Web.UI.UserControl { public SearchConditionType Field; ... And got an error: The type or namespace name '' could not be found (are you missing a using directive or an assembly reference?) What is wrong? A: enum SearchConditionType Your enum is not public. A: Make the enum public: public enum SearchConditionType { Like = 0, EqualNotString = 1, EqualString = 2 }; Types that do not have an access modifier default to internal in C#. If the files are in different assemblies, you need to add a reference to the assembly containingn the enum. This can be done through the References node of the project in the Solution Explorer. A: Hmm... you are attempting to expose an internal type as a public type. That's the only problem I see with your code. But it shouldn't cause the compiler error you're providing, so I'm thinking maybe the problem is elsewhere in your code. edit: Are you trying to expose the enum in another assembly? That'd cause the error you're listing. So, yeah, just make the enum public. A: Problem was in next: I made a web application from web site. In web site enums was situated in App_Code folder. When I rename this folder - problem disappears.
doc_23527701
Because of this I have been trying to figure out a workaround where I make a custom calculated field that changes which latitude/longitude information it outputs depending on an outside parameter. This is however not recognised as latitude/longitude by Quicksight and I am not allowed to add it to the geospatial field well. ifelse( ${MapDrillDownLevel} = 'Region', {region_latitude}, ${MapDrillDownLevel} = 'City', {city_latitude}, ${MapDrillDownLevel} = 'Block', {block_latitude}, 1 /*Default value shouldn't be reached*/ ) So, the questions are: * *Why doesn't Quicksight allow me to add a drill down level here? *How can I make Quicksight recognise my custom calculated field as geospatial information? *Is there a better way of doing this?
doc_23527702
I need to hide the dropdown in-case the user decides to not change the value (particular case). Problem is when the dropdown event is invoked the combobox droppeddown setting still shows as false. According to the definition of the event "dropdown": Occurs when the drop-down portion of a ComboBox is shown. So shouldn't the "droppeddown" setting be true when the event is invoked? private void comboBoxSelectEntry_DropDown(object sender, EventArgs e) { MessageBox.Show(comboBoxSelectEntry.DroppedDown.ToString()); if (isChange || isOAWinShown) if (MessageBox.Show("Warning: You will loose current session data", "Warning", MessageBoxButtons.OKCancel) == DialogResult.Cancel) { this.comboBoxSelectEntry.DroppedDown = false; return; } List<string> _data = classes.databank.Anchor.Collection.Where(node => !node.retired).Select(node => node.Name).ToList(); this.comboBoxSelectEntry.DataSource = null; this.comboBoxSelectEntry.DataSource = _data; } A: Actually you already provided your answer, it's a 'NO' for your question 'So shouldn't the "droppeddown" setting be true when the event is invoked?'. The DroppedDown property is actually set after the droppeddown list is shown. So the event is triggered, but setting the property is just set after the visualization of the contents of the combobox is shown. Therefore the naming of the event DropDown is correct, it will perform a dropdown event to fire. After fireing (and visualizing the list), the DroppedDown property is set to true and stays this way until the user selects an item. The MSDN page is actually right, so I guess you can disagree with it, but don't bother. The design back then has been that the DroppedDown property is set only after the event has been triggered. Not before. If you really need that approach, consider a redesign (like Hans Passant mentioned in his comment) of your GUI or create your own control if you have the time for it.
doc_23527703
string1 = "\xc5\x06\x92\xd0\x02k=\x91" string2 = "qwert\00\00\00" and function: def xor(str1,str2): ret = '' for i in range(8): ret += chr(ord(str1[i]) ^ ord(str2[i])) return ret The result of the above function is: in python2.7: ´�q��vk=� ; in hex: ef bf bd 71 ef bf bd ef bf bd 76 6b 3d ef bf bd in python3.6 ´q÷¢vk=‘ ; in hex: b4 71 f7 a2 76 6b 3d 91 I suppose this is connected with the fact that in python2 str type is limited to ascii, but how to get the same value in both versions ? A: It is the same value in both versions. You're just printing it on a locale that doesn't support some of the characters, and it's using the Unicode replacement character to display it (the ef bf bd sequences in your output are where a character it didn't recognize became the replacement character; whatever you used to convert to bytes seamlessly replaced the Unicode replacement character with its UTF-8 encoding). When the locale is correct and you have terminal/font support that handles the result, it works identically on Python 2 and Python 3. The only real difference is that Python 3 has somewhat saner behaviors under some locales (e.g. Windows console using UTF-8 automatically in 3.6, legacy C locale coercion in 3.7), but you got the same string, it's just outputting and displaying it that produces the wrong result while trying to avoid unencodable characters. To be clear, Python 2 str is not limited to ASCII. In terms of what it can hold, it's equivalent to Python 3 bytes; both can hold arbitrary values in the range [0, 256). The literals differ (Py2 allows non-ASCII characters in a literal without escapes, though without a file encoding declaration, it's not portable), but Py2 str can hold '\xff' just like Py3 bytes's b'\xff'. Note that your code often won't work identically when the str contains characters outside the ASCII range that aren't inserted using escapes (it's dependent on the encoding declaration for the file what non-ASCII literal characters in a string literal mean for Python 2), and definitely won't work the same for stuff that's not in latin-1 (because it will have ordinals larger than 256 in Py3, and who knows what in Py2) unless the inputs are of unicode type in Python 2 (e.g. for literals, prefixed with u).
doc_23527704
Here is the code I write, but it will only print out the first 3 lines numbers. Why? I am very new to use Python. with open('OpenDR Data.txt', 'r') as f: for poseNum in range(0, 4): Data = f.readlines()[7+10*poseNum:10+10*poseNum] for line in Data: matAll = line.split() MatList = map(float, matAll) MatArray1D = np.array(MatList) print MatArray1D A: with open('OpenDR Data.txt') as f: lines = f.readlines() for poseNum in range(0, 4): Data = lines[7+10*poseNum:10+10*poseNum] A: This simplifies the math a little to choose the relevant lines. You don't need to use readlines(). with open('OpenDR Data.txt', 'r') as fp: for idx, line in enumerate(fp, 1): if idx % 10 in [7,8,9,0]: matAll = line.split() MatList = map(float, matAll) MatArray1D = np.array(MatList) print MatArray1D A: You should only call readlines() once, so you should do it outside the loop: with open('OpenDR Data.txt', 'r') as f: lines = f.readlines() for poseNum in range(0, 4): Data = lines[7+10*poseNum:10+10*poseNum] for line in Data: matAll = line.split() MatList = map(float, matAll) MatArray1D = np.array(MatList) print MatArray1D A: You can use a combination list slicing and comprehension. start = 7 end = 10 interval = 10 groups = 3 with open('data.txt') as f: lines = f.readlines() mult_lines = [lines[start-1 + interval*i:end + interval*i] for i in range(groups)] This will return a list of lists containing each group of lines (i.e. 7 thru 10, 17 thru 20).
doc_23527705
The former, grep -ri --include *.sh backup returns results. The latter, :grep -ri --include *.sh backup does not. Any thoughts? Edit 1: :set grepprg returns grepprg=grep -n $* /dev/null Edit 2: My only grep alias is alias grep='grep --color=auto' A: Changing my grepprg value fixed my issue In my ~/.vimrc " Grep settings set grepprg=grep\ -n\ $* The default value of grepprg=grep -n $* /dev/null was using /dev/null as the directory.
doc_23527706
Everything works but there is an unwanted loop. The second video (videohome.mp4)loops -as expected- but the paragraph and the heading duplicates in the screen over an over as the video loops. I have removed the videoPlayer.play=loop; from code and it does not affect the unwanted loop. This is original HTML <div class="container"> <div class="row viewport"> <div class="col-lg-6 align-middle animated fadeIn" id="animationtxt"> </div> </div> </div> JAVASCRIPT document.getElementById("background").onended = function() {myFunction();run()}; function myFunction() { var h = document.createElement("H1"); var t = document.createTextNode("Hello World"); h.appendChild(t); document.getElementById("animationtxt").appendChild(h); var para = document.createElement("p"); var txt = document.createTextNode("This is a paragraph."); para.setAttribute("class","custom-epost-txt"); para.appendChild(txt); document.getElementById("animationtxt").appendChild(para); return; } videoPlayer = document.getElementById("background"); function run(){ var nextVideo = "videos/videohome.mp4"; videoPlayer.src = nextVideo; videoPlayer.play=autoplay; videoPlayer.play=loop; }
doc_23527707
My approach is to import my project and the project of the facebook-ios-sdk into one workspace, but my project can't find the header files of the facebook sdk. I thought that the files in one workspace will be shared isn't it? How can I import the facebook-ios-sdk to my project without copying the files directly into my project? thanks A: I hope to understand what you want. I'm using facebook-ios-sdk, and I added all files in directoctory src (.m and .h) in my project with right click, "add files to…" A: Try step 3 of this answer: “lexical or preprocessor issue file not found ” in Xcode 4 3 - Create a group call "Indexing headers" in your project and drag the headers to this group, DO NOT add to any targets when prompted.
doc_23527708
The problem is that sometimes I have in my text the sequence '...' (3 dots). I want this sequence to be referred as 3 separated dots, but, sometimes my c# code 'understands' them as 3 separated dots ('.' * 3) and sometimes - as a one '...' sequence (Unicode 8230 - '...'). why it is not consistency? and how I can always identify them as 3 dots? //part of the code: foreach (char c in line) //line is "שלום ... . . . ..." { if (c == letter) //letter is '.' counter++; } A: It sounds like you just have a lot of inconsistently-spelled ellipses (plural of ellipsis) in your file … * *..., three ordinary ASCII characters *…, one Unicode character
doc_23527709
Can you please suggest how to add touch based events using javascript/jquery. Thanks, Srinivas A: You can use this function swiperight or another direction // jquery mobile $("#id").swiperight(function() { //do some with $.mobile.changePage function }); $("#id").swipeleft(function() { //do some $.mobile.changePage function }); // javascript document.ontouchmove = function(e) { var target = e.currentTarget; while(target) { if(checkIfElementShouldScroll(target)) return; target = target.parentNode; } e.preventDefault(); }; A: This jQuery plugin works well. http://www.netcu.de/jquery-touchwipe-iphone-ipad-library Easy to use. Ex: $('.slideshow').touchwipe({ wipeLeft: function() {$('.slideshow').cycle('next');}, wipeRight: function() { $('.slideshow').cycle('prev');}, min_move_x: 60 });
doc_23527710
A while loop isn´t the solution, since it is blocking the ui-thread. How can this be achieved? In Java (Android) I would do this with a asynctask connected to a ScheduldExecutorService. Is something similar available for qt? This is where I start my processes: void mywidget::startprocesses(QString &text) { QProcess *process = new QProcess(this); this->myprocess.append(process); process->start(text); int state = process->state(); addlabelstatus(state); } And here the method is called: while(!stream->atEnd()) //check stream until empty and assign line as a caption to a new QLabel { this->fileread = stream->readLine(); if(!this->fileread.isEmpty()) { central->addlabel(this->fileread); central->startprocesses(this->fileread); } } void mywidget::addlabelstatus(QProcess::ProcessState newstate) { QString sstring; if(newstate == 0) { QString sstring = "Wird nicht ausgeführt"; QLabel *label = new QLabel(sstring); this->processstatus.append(label); this->vrarea->addWidget(label); } else if (newstate == 1) { QString sstring = "Wird gestartet!"; QLabel *label = new QLabel(sstring); this->processstatus.append(label); this->vrarea->addWidget(label); } else if (newstate == 2) { QString sstring = "Wird ausgeführt!"; QLabel *label = new QLabel(sstring); this->processstatus.append(label); this->vrarea->addWidget(label); } else { QString sstring = "kein Status vorhanden!"; QLabel *label = new QLabel(sstring); this->processstatus.append(label); this->vrarea->addWidget(label); } } A: Each QProcess has finished(int exitCode, QProcess::ExitStatus exitStatus) and stateChanged(QProcess::ProcessState newState) signals, that emits when some process has been terminated or changed (by type of). So your code can be: .H side: public slots: void processFinished(int exitCode, QProcess::ExitStatus exitStatus); void addlabelstatus(QProcess::ProcessState newState); .CPP side: void mywidget::processFinished(int exitCode, QProcess::ExitStatus exitStatus) { <...> } void mywidget::addlabelstatus(QProcess::ProcessState newState) { switch(newState) { <...> }; } // Your code change QProcess *process = new QProcess(this); this->myprocess.append(process); connect(process, &QProcess::finished, this, &mywidget::processFinished); connect(process, &QProcess::stateChanged, this, &mywidget::addlabelstatus); process->start(text); UPDATE FOR COMMENT QUESTION You can try this way: .H side public slots: void processFinished(QLabel *label, int exitCode, QProcess::ExitStatus exitStatus); void addlabelstatus(QLabel *label, QProcess::ProcessState newState); .CPP side void mywidget::processFinished(QLabel *label, int exitCode, QProcess::ExitStatus exitStatus) { <...> } void mywidget::addlabelstatus(QLabel *label, QProcess::ProcessState newState) { switch(newState) { <...> }; } while(!stream->atEnd()) { this->fileread = stream->readLine(); if(!this->fileread.isEmpty()) { QLabel *label = new QLabel(this->fileread); QProcess *process = new QProcess(this); this->myprocess.append(process); connect(process, &QProcess::finished, [=] (int exitCode, QProcess::ExitStatus exitStatus) { processFinished(label, exitCode, exitStatus); }); connect(process, &QProcess::stateChanged, [=] (QProcess::ProcessState newState) { addlabelstatus(label, newState); }); process->start(text); } } A: A while loop isn´t the solution, since it is blocking the ui-thread. Correct. However, since Qt is an event-driven framework, you could use a timer:- // Assuming we have a list of processes QList<QProcess*> called timerList QTimer* pTimer = new QTimer; connect(pTimer, &QTimer::timeout, [=](){ foreach(QProcess* proc, timerList) { // get state int state = process->state(); // update UI addlabelstatus(state); } }); pTimer->start(1000); // every second Or alternatively, as @someoneinthebox answered, connect to each QProcess's stateChanged signal to notify you when it occurs and react to that.
doc_23527711
index.js:1 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. in div (at CustomLayout.js:28) in main (created by Basic) in Basic (created by Context.Consumer) in Content (at CustomLayout.js:22) in section (created by BasicLayout) in BasicLayout (created by Context.Consumer) in Layout (at CustomLayout.js:8) in CustomLayout (at App.js:10) in div (at App.js:9) in App (at src/index.js:7) Below are the project files. Article.js is a component and ArticleListView and CustomLayout are containers to it. I am trying to access the child elements in CustomLayout.js by {props.children} App.js import React from 'react'; import './App.css'; import 'antd/dist/antd.css'; import CustomLayout from './containers/CustomLayout' import ArticleListView from './containers/ArticleListView'; function App() { return ( <div className="App"> <CustomLayout> {ArticleListView} </CustomLayout> </div> ); } export default App ArticleListView.js import React from 'react' import Article from '../components/Article' class ArticleListView extends React.Component{ render(){ return( <Article/> ); } } export default ArticleListView Article.js import React from 'react' import { List, Avatar, Icon } from 'antd'; const listData = []; for (let i = 0; i < 23; i++) { listData.push({ href: 'http://ant.design', title: `ant design part ${i}`, avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png', description: 'Ant Design, a design language for background applications, is refined by Ant UED Team.', content: 'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.', }); } const IconText = ({ type, text }) => ( <span> <Icon type={type} style={{ marginRight: 8 }} /> {text} </span> ); function Article(props){ return( <List itemLayout="vertical" size="large" pagination={{ onChange: page => { console.log(page); }, pageSize: 3, }} dataSource={listData} footer={ <div> <b>ant design</b> footer part </div> } renderItem={item => ( <List.Item key={item.title} actions={[ <IconText type="star-o" text="156" key="list-vertical-star-o" />, <IconText type="like-o" text="156" key="list-vertical-like-o" />, <IconText type="message" text="2" key="list-vertical-message" />, ]} extra={ <img width={272} alt="logo" src="https://gw.alipayobjects.com/zos/rmsportal/mqaQswcyDLcXyDKnZfES.png" /> } > <List.Item.Meta avatar={<Avatar src={item.avatar} />} title={<a href={item.href}>{item.title}</a>} description={item.description} /> {item.content} </List.Item> )} /> ); } export default <Article/> CustomLayout.js import React from 'react' import { Layout, Menu, Breadcrumb } from 'antd'; const { Header, Content, Footer } = Layout; function CustomLayout(props){ return( <Layout className="layout"> <Header> <div className="logo" /> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['2']} style={{ lineHeight: '64px' }} > <Menu.Item key="1">nav 1</Menu.Item> <Menu.Item key="2">nav 2</Menu.Item> <Menu.Item key="3">nav 3</Menu.Item> </Menu> </Header> <Content style={{ padding: '0 50px' }}> <Breadcrumb style={{ margin: '16px 0' }}> <Breadcrumb.Item>Home</Breadcrumb.Item> <Breadcrumb.Item>List</Breadcrumb.Item> <Breadcrumb.Item>App</Breadcrumb.Item> </Breadcrumb> <div style={{ background: '#fff', padding: 24, minHeight: 280 }}>{props.children}</div> </Content> <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer> </Layout> ); } export default CustomLayout A: If you are using any javascript expression then only use curly braces like - {a+b}. but form html tags or react component you need to import as per react standard. Use like this <CustomLayout> <ArticleListView /> </CustomLayout> and change your export default <Article/> to export default Article A: It should be <ArticleListView/>, not {ArticleListView} A: Try <CustomLayout> <ArticleListView /> </CustomLayout> rather than <CustomLayout> {ArticleListView} </CustomLayout> A: in javascript we work like isConditionTrue ? screenOne :screenTwo but in typescript we have to change isConditionTrue ? :
doc_23527712
on appdelegate.m, didFinishLaunchingWithOptions, calling [FIRApp configure] returns the following error:   <FIRAnalytics/ERROR> Event origin is too long. The maximum supported length is 32: <ACPEventParam 0x18012br0>: { name: "_o" string_value: "auto" } What is Event origin? What modifications do I do? Thanks.
doc_23527713
I get a code signing error when I build and distribute my app for binary. (Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain) i have created my first binary yesterday but today this error occurs...in simulator it is perfect but not in device and ditribution A: You should create the developer certificate in distribute tab after you create. Provisioning also you should create distribute tab, please check these things you follow. A: You have to import the admin distribution certificate onto your mac .If you don't have distribution certificate you create other then that you can not do anything . For create you have togo on to this apple developer forum thought the admin a/c.Over there you will get this distribution certificate import in your mac and then try it to distribute this .On the apple developer forum you will get guide line for this how to create the certificate .If this work then select my answer .
doc_23527714
I would like that when the user swiping on a table view cell, to expose buttons (The default is the delete button in iOS 7 and early). In the Mail app for iOS 8 you can swipe and expose 3 buttons “More” "Flag" "Archive". I want to display other buttons with different color and title. Is Apple provides API in UITableView for this ? Thanks
doc_23527715
* *VC1 --Opens--> VC2: vc2 is a viewcontroller that is showing a Form. On correct filling the user is taken to another VC. call it vC3 *VC2 --Opens--> VC3: vc3 is a view controller that takes swipe card information and if the information provided is correct it takes to VC4 *VC3 --Opens--> VC4:. VC4 is the viewcontroller that loads up all user contacts and send information/data to that selected contact. SO far it is fine. now there is 2 conditions, if the data that I send is correctly sent then I have to go back to VC1 directly, and if the data is not sent then I have to go back to vc2 directly to take up information again. so what are the best thing to handle this situation. Please suggest. UPDATE: I am using Tab bar controller, in that controller under one of that View , I am opening other VIew controller from this in series. Like from this Opening VC2 that opens VC3 and so on... This is how I am showing my ViewController 2 let myVC2 = self.storyboard?.instantiateViewController(withIdentifier: "idMyVC2") as MyVC2 myVC2.modalPresentationStyle = .fullScreen self.present(myVC2,animated : true) A: Plug this into a playground and mess around with it: import UIKit protocol DismissDelegate: AnyObject { func dismissVC(_ presenting: Int) } class VC1: UIViewController, DismissDelegate { func dismissVC(_ presenting: Int) { guard presenting == 1 else { return } print("dismiss 2, 3, 4, 5") } } class VC2: UIViewController, DismissDelegate { weak var vc2Delegate: DismissDelegate? func dismissVC(_ presenting: Int) { guard presenting == 2 else { return vc2Delegate!.dismissVC(presenting) } print("dismiss 3, 4, 5") } } class VC3: UIViewController, DismissDelegate { weak var vc3Delegate: DismissDelegate? func dismissVC(_ presenting: Int) { guard presenting == 3 else { return vc3Delegate!.dismissVC(presenting) } print("dismiss 4, 5") } } class VC4: UIViewController, DismissDelegate { weak var vc4Delegate: DismissDelegate? func dismissVC(_ presenting: Int) { guard presenting == 4 else { return vc4Delegate!.dismissVC(presenting) } print("dismiss 5") } } class VC5: UIViewController { weak var vc5Delegate: DismissDelegate? func dismissStack(at presenting: Int) { vc5Delegate?.dismissVC(presenting) } } let vc1 = VC1() let vc2 = VC2() vc2.vc2Delegate = vc1 let vc3 = VC3() vc3.vc3Delegate = vc2 let vc4 = VC4() vc4.vc4Delegate = vc3 let vc5 = VC5() vc5.vc5Delegate = vc4 vc5.dismissStack(at: 1) // prints: dismiss 2, 3, 4, 5 vc5.dimissStack(at: 2) // prints: dismiss 3, 4, 5 The setup is very basic, each view controller is chained through a delegate. Because there is more than one view controller, we created a protocol. That protocol is just a method that takes an integer argument which is the view controller that should perform the dismiss (the presenting view controller). Then when you want to perform a dismiss, call the delegate (doesn't have to be from the 5th view controller), specify the presenting view controller, and the delegate will go down the chain and check if it's the presenting view controller (if it is, it will dismiss everything above it) or not (if it isn't, it will step down one view controller and repeat the process). VC5 has a method called dismissStack(at:) which lets you put in an integer of the view controller you want to dismiss at. Therefore, if you dismiss at 2, then view controllers 3, 4, 5 will be dismissed. You can, obviously, place this method into the other view controllers as well. A: You can do in various way, one them is like below:- Hierarchy of view controllers be like :- NavigationController -> VC1 -> VC2 -> VC3 -> VC4(using push).Now use below code to change your controller If pop to root use :- for controller in self.navigationController!.viewControllers as Array { if controller.isKind(of: VC1) { self.navigationController!.popToViewController(controller, animated: true) break } } if for pop go to at VC3 simply pop to root. I hope it will help you, Thanks A: Here is a way i used for controller in self.navigationController!.viewControllers { if let vc = controller as? LoginViewController { self.navigationController!.popToViewController(vc, animated: true) break } } A: way that i used most is for controller in self.navigationController.controllers { if let desiredVC = controller as? DesiredViewControllerName { self.navigationController!.popToViewController(desiredVC, animated: true) } }
doc_23527716
But when i type gulp test in cmd, what i get is Using gulpfile C:\xampp\htdocs\CodeKatas\gulpfile.js Starting 'test'... Finished 'test' after 27ms event.js 160 throw er; // Unhandled 'error' event How can this happen when the location of the .php file is exactly inside the src directory?
doc_23527717
<html> <head> <script src="../lib/jquery-1.7.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ $('#test').hide(); } </script> </head> <body> <div id="test">Hi</div> I'm here </body> </html> I added the ready function but it still doesn't work. What I'm missing? A: You are missing a ); at the end, it's that simple. Should read: <script type="text/javascript"> $(document).ready(function(){ $('#test').hide(); }); </script> A: You're missing a bracket and a semicolon at the end of your jquery code. See the code below: $(document).ready(function(){ $('#test').hide(); }); A: change $(document).ready(function(){ $('#test').hide(); } to $(document).ready(function(){ $('#test').hide(); }); you are missing ); A: You've missed out a closing ")" at the end of the function. A: Your missing a ); after your document ready call A: <html> <head> <script src="../lib/jquery-1.7.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ $('#test').hide(); }); //<----------------------------Right here! </script> </head> <body> <div id="test">Hi</div> I'm here </body> </html> You have to close the ready. added an extra parenthesis. A: Missing ); Correct: $(document).ready(function(){ $('#test').hide(); });
doc_23527718
Those two tables have a relationship with many-to-many, so the table is StudentGrade. By using the .SelectMany query, I can retrieve all records which have a relation. For example, var myResult = myDb.Student.SelectMany(x => x.Grade).ToList(); But let say I add a new record just to the Student table, which has no relation with Grade, this new record cannot be retrieved by using the query above. How can I retrieve all data including this new one? Student Id Name Age 1 AAA 4 2 BBB 5 3 CCC 6 4 DDD 7 Grade Id Name 1 G1 2 G2 3 G3 4 G4 StudentGrade Student Grade 2 1 2 2 2 3 3 3 Require result: Id Name Age Grade 1 AAA 4 2 BBB 5 G1 2 BBB 5 G2 2 BBB 5 G3 3 CCC 6 G3 4 DDD 7 I found full outer join would help but will it work in a many-to-many relationship? How can I overcome this issue ? A: var result = (from s in myDb.Student from g in myDb.Grades where !g.Select(x => x.Student).Contains(s) || g.Student == null || g.Student == s).ToList(); As long as I understand your question this should give you * *all Students that have grades, *all Grades with no students, *and all Students with no grades. I have not seen your models but this should help A: var myResult = myDb.Student.SelectMany(x => x.Grade).ToList(); This query "means" retrieve all the Grades that have a Student. If you want the Students, select Student and Include the Grades if you want. var myResult = myDb.Students.Include(x => x.Grades).ToList();
doc_23527719
using namespace std; int main() { // Declare variable ifstream inFile; // Declare constant const int MAX = 600; // Declare an array of strings named name that holds up to MAX string array [name] = MAX; // Declare an array of whole numbers named grade that holds up to MAX double array [grade] = MAX; // Declare variables quantity, x, avg, and sum (initialized to zero) that hold whole numbers int sum = 0, avg, x, quantity; // Open input file inFile.open("indata3.txt"); // Check if the file was opened if (!inFile) { cout << "File was not found!" << endl; return 1; } // Set x to 0 x = 0; // Read name and grade from the file and assign them to name[x] and grade[x] respectively cin >> name[x]; cin >> grade[x]; // While (not-end-of-file) while(inFile) { //Increment x x++; // Read a name and a grade from the file and assign them to name[x] and grade[x] respectively cin >> name[x]; cin >> grade[x]; } // Print message cout << "Enter quantity of grades to be processed (0-" << x << "): " << endl; // Read a value from the keyboard and assign it to quantity cin >> quantity; // For (x = 0 to quantity-1) for (x = 0; x <= quantity-1) { //16. Accumulate grade[x] in sum } // Assign to avg the value returned by average (sum, quantity) avg = sum/quantity; // Print "Average grade: ", avg cout << "Average grade: " << avg << endl; // Print "Name", "Grade", " Comment" cout << "Name" << "," << "Grade" << "," << " Comment" << endl; // For (x = 0 to quantity-1) for (x = 0; x <= quantity-1) { // Print name[x], grade[x] cout << name[x] << ", " << grade[x] << endl; // If (grade[x] < avg) if (grade[x] < avg) { // Print " below average" cout << " below average" << endl; } // Else if (grade[x] > avg) else if (grade[x] > avg) { // Print " above average" cout << " above average" << endl; } // Else else() { // Print " average" cout << " average" << endl; } } // Close the file. inFile.close(); return 0; } Here are some of the errors our of the 20. Most repeat the undeclared identifier. Also not sure where I would need to add more curly brackets to make it syntactically correct. One more thing..how do I accumulate grade[x] into sum? Any help would greatly be appreciated thank you. error C2065: 'name' : undeclared identifier error C2075: 'array' : array initialization needs curly braces error C2065: 'grade' : undeclared identifier error C2371: 'array' : redefinition; different basic types error C2440: 'initializing' : cannot convert from 'const int' to 'double [1]' error C2228: left of '.open' must have class/struct/union1> type is 'int' error C2143: syntax error : missing ';' before ')' error C2059: syntax error : ')' error C2143: syntax error : missing ';' before '{' error C2228: left of '.close' must have class/struct/union1> type is 'int' A: Hopefully this helps a little... (And recommend getting a C++ book and references) Many of your variables are not declared before use. Such as 'name' needs to be: string name[]; Lets take a look at this statement: string array [name] = MAX; It looks like you're not entirely familiar with C++. "String" is the datatype. "array" is the actual name of your array. "name" is an undeclared variable, and must be an integer to work. "MAX" is a constant.(You're good there.) From the way you've written it, I'm guessing you're trying to have parallel arrays of strings and double called "name" and "grade" with 600 elements. In C++, that would be written: string name[MAX]; // this creates an empty string array of 600 elements and grade would be: double grade[MAX]; // this creates an empty double array of 600 elements This section below from your code won't work for several reasons: // Open input file inFile.open("indata3.txt"); // Check if the file was opened if (!inFile) { cout << "File was not found!" << endl; return 1; } // Set x to 0 x = 0; // Read name and grade from the file and assign them to name[x] and grade[x] respectively cin >> name[x]; cin >> grade[x]; // While (not-end-of-file) while(inFile) { //Increment x x++; // Read a name and a grade from the file and assign them to name[x] and grade[x] respectively cin >> name[x]; cin >> grade[x]; } A couple of the reasons are: * *while(not-end-of-file) is not real code, you want: while(!inFile.eof()) *cin >> name[x]; never accesses the file, and would never assign a value to an element Good luck! Google is your friend! Let people know you're a newbie so they don't tear you apart in the stackoverflow wilds! Get a good IDE like dev++ or CLion. A: array is not a keyword in c++. If you want to declare array of string that can hold maximum value = MAX then you should try this string name[MAX]; where "name" is the name of array of a string and MAX is a total number of strings that array can store. Same for the whole number you should use double grade[MAX]; where grade is a name of whole number array.
doc_23527720
<select id="codeLeft" class="form-control"> {% for code in code %} <option id="{{ code['try'] - 1}}">#{{ code['try'] }} --- {{ code['date'] }}</option> {% endfor %} </select> Now I've got two buttons which I want to use to iterate this list (left button prev item and right button next item). I've the last item is reached I want to start at the bottom again. $('#button_left').click(function () { var idCode = $('#codeLeft').children(':selected').attr('id'); var idNext = parseInt(idCode) - 1; if(idNext < 0){ idNext = codeArray.length - 1; } $('#codeLeft option[id=' + idNext + ']').attr("selected", "selected"); }); $('#button_right').click(function () { var idCode = $('#codeLeft').children(':selected').attr('id'); var idNext = parseInt(idCode) + 1; if(idNext === codeArray.length){ idNext = 0; } $('#codeLeft option[id=' + idNext + ']').attr("selected", "selected"); }); My problem is that this only works n times (n is the length of code). Does anybody knows why? A: First of all, you are assigning integers as ids and this is improper. Dropdownlist shows the first attribute that has the attribute selected. Therefore, when you run it "n" times, all options would have the attribute selected as true and the browser wouldn't work no longer because it sees the current option as selected. Don't set attribute to selected. Instead, use prop: $('#codeLeft option[id=' + idNext + ']').prop('selected', true);
doc_23527721
<input type="button" id="btn1" onclick="return test();"> I want to separate javascript code from the UI by placing it in a separate file or inside the script tag. Including javascript event attachment. For example instead of the above I'd have: <input type="button" id="btn1"> and in the script section I'd us: <script type="text/javascript> btn1.onclick = function() { test(); } </script> or <script type="text/javascript> if (btn1.addEventListener){ btn1.addEventListener('click', test, false); }else if (btn1.attachEvent){ btn1.attachEvent('onclick', test ); } </script> Why do I want to do that? I like separating my UI from the business logic and database, that's my general approach. Also it is better from performance standpoint, as external javascript can be easier cached by browsers. Another reason - it is more secure. My question is whether this is worth the hassle of changing the application, removing all the inline javascript? I'd appreciate if someone gave me some pointers, some links to articles - I have been searching the web and found some conflicting information. Would appreciate to hear some opinions A: From the maintenance point of view is much easier to have at least two separate files: html and js. After that you can have a separation between UI, business logic and data. You can check this question for more information on design patterns. A: I'm fully in favor of separating JS code from markup, mostly for maintenance reasons and clarity of intent. As you pointed out, it's also better from a caching perspective. I would go one step further and suggest that you would also benefit from a framework (pick your poison, there are plenty of good options, but jQuery is a good place to start as it's very well documented and handles a lot of the boilerplate stuff like your example has (browser differences, etc). All that said, one part of your question made me curious. In what way do you think having javascript in a separate file will make your pages more secure?
doc_23527722
The website with the most tests runs has about 100 tests, and the smallest website is about 5. The issue can occur with the website with 5 or 100. These are SpecFlow tests. The results are then exported to an xml file. According to the xml file it does look like it has ran all the tests, as it shows the ones that succeeded and failed. It doesn't seem like this issue always occurs. Although it happens if I leave it on the nightly build. It won't always occur if I trigger a manual build on Octopus. The version of NUnit is 3.1.1 Here is so far an example line of what I am passing in powershell for the NUnit console. param( [string]$configurationDescription = $OctopusParameters['environment.Transform'] + " Env Test Run", [string]$site, [string]$environmentName, [string]$environmentSiteTag, [string]$testDllName, [string]$testDllFolder ) $folderPath = $OctopusParameters['tests.rootFolder'] Set-Location $folderPath $configurationDescription = $configurationDescription.Replace(" ", "-") $testResultsFolderName = "testResults" $testResultsPath = "$folderPath\$testResultsFolderName\$site" $currentTimeFormatted = Get-Date -Format "dd-MM-yyyy_hh_mm_ss" if(!(Test-Path -Path $testResultsPath)) { New-Item -Path $testResultsPath -ItemType Directory } $testDllPath = $folderPath + "\tests\$testDllFolder\$testDllName" $environmentWipTag = $OctopusParameters["tests.environment.wipname"] #Change the location of "bin\XXX" So it will pick up the respective dll file and use the respective App.XXX.config $testResultsXmlPath = "$testResultsPath\TestResult_$currentTimeFormatted.xml" $args = "$testDllPath --where `"cat != $environmentWipTag && (cat == $environmentName && cat == $environmentSiteTag)`" --result=$testResultsXmlPath --framework=net-4.0 --timeout=20000" # SECTION: Update Chrome driver # Update Chrome Driver for testing to match the machine. #1. Get the version of Chrome driver installed. $chromeDriverOutputPath = $folderPath + "\tests\$testDllFolder" # Store original preference to revert back later $OriginalProgressPreference = $ProgressPreference; # Increases the performance of downloading the ChromeDriver. $ProgressPreference = 'SilentlyContinue'; try { $chromeVersion = (Get-Item (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe').'(Default)').VersionInfo.FileVersion $chromeVersion = $chromeVersion.Substring(0, $chromeVersion.LastIndexOf(".")); } catch { "Could not find Google Chrome in the registry." } #2. Get the latest version of chrome driver available. $chromeDriverVersion = (Invoke-WebRequest "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_$chromeVersion" -UseBasicParsing).Content; Write-Host "Latest matching version of Chrome Driver is $chromeDriverVersion"; #3.Create a temp folder to store the chrome driver to be downloaded. $tempFilePath = [System.IO.Path]::GetTempFileName(); $tempZipFilePath = $tempFilePath.Replace(".tmp", ".zip"); Rename-Item -Path $tempFilePath -NewName $tempZipFilePath; $tempFileUnzipPath = $tempFilePath.Replace(".tmp", ""); # 4. Download correct chrome drive, unzip the archive and move the chromedriver to the correct location. Invoke-WebRequest "https://chromedriver.storage.googleapis.com/$chromeDriverVersion/chromedriver_win32.zip" -OutFile $tempZipFilePath -UseBasicParsing; Expand-Archive $tempZipFilePath -DestinationPath $tempFileUnzipPath; Move-Item "$tempFileUnzipPath/chromedriver.exe" -Destination $chromeDriverOutputPath -Force; # 5. Clean up files. Remove-Item $tempZipFilePath; Remove-Item $tempFileUnzipPath -Recurse; # Set back to default ProgressPreference. $ProgressPreference = $OriginalProgressPreference #END SECTION: Update Chrome driver Write-Host "Chrome Driver now matches the version installed on the machine. Beginning Test run." #Begin Test Run. $nunitRunnerResult = (Start-Process -FilePath "$folderPath\runner\nunit3-console.exe" -ArgumentList $args -PassThru -Wait).ExitCode if(!(Test-Path -Path $testResultsXmlPath)) { Write-Host "Args:$args FilePath:$folderPath\runner\nunit3-console.exe" Write-Error "Unable to find $testResultsXmlPath" return; } $testsTestResultHtmlPagePath = "$testResultsPath\$configurationDescription-$currentTimeFormatted\ExtentReport" $args = "-i $testResultsXmlPath -o $testsTestResultHtmlPagePath -r html" Start-Process -FilePath "$folderPath\extentreport\extent.exe" -ArgumentList $args -Wait $extentReportPath = $testsTestResultHtmlPagePath + "\index.html" $extentSummaryPath = $testsTestResultHtmlPagePath + "\dashboard.html" $testsTestResultPath = "$testResultsFolderName\testsTestResult-$currentTimeFormatted.xml" $args = [string]::Format("-f=Features/ -o=$testResultsFolderName/{0}-{1}/PicklesReport -trfmt=nunit3 -df=dhtml -lr={2}", $configurationDescription, $currentTimeFormatted, $testsTestResultPath) Exit 0 The C# ran after each test. using BoDi; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using System; using System.Configuration; using TechTalk.SpecFlow; namespace MyTestFramework.Helpers { [Binding] public sealed class Hooks { private readonly IObjectContainer _container; private IWebDriver _webDriver = default; public Hooks(IObjectContainer objectContainer) { _container = objectContainer; } [BeforeScenario] public void BeforeTestRun() { InstantiateDriver(); } [AfterScenario] public void AfterScenario() { if (!(_webDriver is null)) { //Close any additional tabs open and then delete all cookies when one tab is open var tabs = _webDriver.WindowHandles; int numberOfTabs = _webDriver.WindowHandles.Count; while (numberOfTabs > 1) { _webDriver.SwitchTo().Window(tabs[numberOfTabs - 1]); _webDriver.Close(); numberOfTabs = _webDriver.WindowHandles.Count; _webDriver.SwitchTo().Window(tabs[numberOfTabs - 1]); } _webDriver.Manage().Cookies.DeleteAllCookies(); _webDriver.Close(); _webDriver.Quit(); _webDriver.Dispose(); } } [AfterTestRun] public static void After() { } private void InstantiateDriver() { var selectedDriver = ConfigurationManager.AppSettings.Get("selectedWebDriver"); if (string.IsNullOrEmpty(selectedDriver)) { throw new ArgumentException(Constants.ExceptionMessages.SelectedWebdriverCouldNotBeFound, selectedDriver); } switch (selectedDriver) { case "Chrome": _webDriver = new ChromeDriver(); break; case "Chrome Headless": var chromeOption = new ChromeOptions(); chromeOption.AddArguments("headless"); chromeOption.AddArguments("--window-size=1680,1050"); _webDriver = new ChromeDriver(chromeOption); break; default: throw new ArgumentException("Webdriver could not be found", selectedDriver); } _webDriver.Manage().Window.Maximize(); _container.RegisterInstanceAs<IWebDriver>(_webDriver); } } } If I close the chrome driver it must close everything as the Octopus step then seems to fail. Worth noting as well this does not happen if directly using visual studio. A: Changing -Wait to - WaitProcess worked and has fixed the issue. $testResults = (Start-Process -FilePath "$folderPath\runner\nunit3-console.exe" -ArgumentList $args -PassThru) Wait-Process -Id $testResults.Id $testExitCode = $testResults.ExitCode @Greg Burghardt, you were right about the zombie processes, so I eventually for some reason had a look at the -Wait argument. I noticed there was another PowerShell argument called -WaitProcess. It seems there is a difference in this case. Unlike Start-Process -Wait, Wait-Process only waits for the processes identified. Start-Process -Wait waits for the process tree (the process and all its descendants) to exit before returning control. Source: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/wait-process?view=powershell-7.2 I suspect that as these chrome processes were not actually ending sometimes, even though the main process had ended it was waiting for all these other ones to exit. It would explain why I manually had shut down all the processes via Task Manager for it to continue beforehand as it was waiting for the child processes to end.
doc_23527723
However, if the property is derived with a function, wouldn't it conserve more memory to define the property on the object's prototype? I've been unable to find an example like that. The code example below seems to work, but is doing it this way acceptable? Is it more memory conservative than defining the property on the object? var Person=function(first,last) { this.firstName=first this.lastName=last } Object.defineProperty(Person.prototype, "fullName", { get: function() { return `${this.firstName} ${this.lastName}`} }) var a =new Person("Jane","Doe") console.log(a.fullName) //"Jane Doe" A: Is doing it this way acceptable? Yes, totally. Using ES6 class syntax made defining accessor properties on prototype objects even easier, it's quite common. class Person { constructor(first, last) { this.firstName = first; this.lastName = last; } get fullName() { return `${this.firstName} ${this.lastName}`; } } var a = new Person("Jane", "Doe"); console.log(a.fullName) //"Jane Doe" Is it more memory conservative than defining the property on the object? Yes, definitely.
doc_23527724
Failed to execute script My code: from tkinter import * import tkinter.messagebox as tmsg import string import random root = Tk() def helpf(): tmsg.showinfo("How it works", "Enter the length of the password required\nThen select the strength of password\nClick the generate button to receive the password.\nClick on File->Save to Save the genrated Password") def savefile(): f=open('/Passwords.txt', 'a') f.write(pwd +'\n') f.close() def password(): global pwd pwd="" #pwd=str() #pwd="" value = str() if (Lengthvalue.get()>16) or (Lengthvalue.get()==""): Label(text="Please enter a correct password strength").grid(row=6,column=1) if Weakvalue.get()==1: value = string.ascii_letters elif Moderatevalue.get()==1: value = string.ascii_letters + string.digits elif Strongvalue.get()==1: value = string.ascii_letters + string.digits + '!?@#' else: Label(text="Please select Password Strength").grid(row=6,column=1) if value!=str(): Label(text=" ").grid(row=6,column=1) for x in range(0,Lengthvalue.get()): pwd = pwd + random.choice(value) Label(text=pwd,font=("Goodtimes",10, "bold")).grid(row=6, column=1) #def password(): #print(Weakvalue, Moderatevalue, Strongvalue) root.geometry("500x400") root.minsize(500,400) root.maxsize(500,400) root.title("Random Password Generator") #Heading Label(text="Random Password Generator", bg="red", font=("Forte",15, "bold"),borderwidth=5, relief=RIDGE).grid(row=0, column=1) #CheckBox Lengthvalue=IntVar() Weakvalue=IntVar() Moderatevalue=IntVar() Strongvalue=IntVar() Label(text="Enter the length of\nPassword Required:\n(Between 8-16) ").grid(row=1, column=0) Label(text="Select the Strength of\nPassword Required: ").grid(row=3, column=0) Length=Entry(root, textvariable=Lengthvalue) Weak=Checkbutton(text="Weak Password", variable=Weakvalue) Moderate=Checkbutton(text="Moderate Password", variable=Moderatevalue) Strong=Checkbutton(text="Strong Password", variable=Strongvalue) Length.grid(row=1, column=1) Weak.grid(row=3, column=1) Moderate.grid(row=4, column=1) Strong.grid(row=5, column=1) #Generate Password Button fr=Frame(root, borderwidth=3, bg="grey", relief=SUNKEN) fr.grid(row=8, column=1) b1=Button(fr, bg="white", text="Generate", command=password) b1.grid(row=8, column=1) #Adding Menus mainmenu=Menu(root) filemenu=Menu(mainmenu, tearoff=0) filemenu.add_command(label="Save", command=savefile) filemenu.add_separator() filemenu.add_command(label="Exit", command=quit) mainmenu.add_cascade(label="File", menu=filemenu) root.config(menu=mainmenu) helpmenu=Menu(mainmenu, tearoff=0) helpmenu.add_command(label="How it works", command=helpf) mainmenu.add_cascade(label="Help", menu=helpmenu) root.config(menu=mainmenu) root.mainloop() It is a random password generator, and it creates and saves its answer in .txt file in the same directory. Python version 3.60 (Downgraded it for pyinstaller to work) A: Surprisingly! this thing works for me you need to use this code pyinstaller password_generator.py --add-data passwords.txt
doc_23527725
<ul> <li>Apple</li> <li>Monkey</li> <li>Sun</li> <li>Moon</li> <li>Movies</li> </ul> And a scale in animation: ul li { animation : scale-in 1s; } @keyframes scale-in { 0% { opacity : 0; -webkit-transform : scale(0.5); } 20% { opacity : 0; -webkit-transform : scale(0.5); } 100% { opacity : 1; -webkit-transform : scale(1.0); } } Now I like the delay of each element to be 1 second apart from each other. So first item appears immediately, second 1sec delay, third 2sec delay, etc. Is there a neat way to do this, perhaps using the nth selector? or do I actually have to write it out like ul li:nth-child(1) { delay : 1s; } ul li:nth-child(2) { delay : 2s; } A: There is not a way to do this with CSS3 other than the way you suggested. Since there is no real way to do math, or to loop through things, it's not really possible other than writing it out by hand. I would have to second NightCracker's JS suggestion. You don't have to necessarily write the animation itself with JS, but you could fire it using JS. Something as simple as using a While loop with a incremental counter should do the trick. In the end though, you're just saving a few lines of code versus just writing it out in CSS. Functionality wise it would still be the same, especially if cross browser compatibility is not a concern.
doc_23527726
var myItems = [myClass]() class myClass: NSObject { var a: String? var b: String? var c: String? var d: String? } What I want is to save the array called myItems into my database, and have every class inside of a personal section inside the database. Basically, I want every class to look like the one called "Eko" in this image: To clarify, after "Eko" all the rest of the classes which is inside of the array myItems should be displayed. To achieve what the picture is demonstrating, I used this code: let data = self.myItems[0] let currU = FIRAuth.auth()?.currentUser?.uid let userRef = self.ref.child("users").child(currU!).child(data.a!) userRef.updateChildValues(["a": data.a!, "b": data.b!, "c": data.c!, "d": data.d!]) Obviously, this will only save the class at index 0 from the array myItems into the Firebase Database, which is displayed in the image above. My question is thus, how do I save the entire array into the database? With my code I can only save 1 class from the array, and I would like to save all of the items into the database, so that they end up looking the same way that the one class does in the image. You could compare this to populating a tableView, where you need the "indexPath.row" to populate it with all the items instead of only one. I hope that I was clear enough! A: You can't save a class into Firebase. But.. A class has a similar structure to a dictionary (properties and values, like key: value pairs etc). Arrays in Firebase should generally be avoided - they have limited functionality and the individual elements cannot be accessed and for any changes you have to re-write the entire array. Using a structure where the parent key names are created with childByAutoId is usually preferred. The easiest solution is to simply add intelligence to the class so it would craft a dictionary and then save itself. Craft a user class UserClass var name = String() var food = String() func saveToFirebase() { let usersRef = myFirebase.child(users) let dict = ["name": self.myName, "food", self.myFood] let thisUserRef = usersRef.childByAutoId() thisUserRef.setValue(dict) } } and and array to store them var usersArray = [Users]() populate the array var aUser = UserClass() aUser.name = "Leroy" aUser.food = "Pizza" usersArray.append(aUser) var bUser = UserClass() bUser.name = "Billy" bUser.food = "Tacos" usersArray.append(bUser) and then iterate over the array saving each user for user in usersArray { user.saveToFirebase() } this will result in users -Ykasokokkpoad name: Leroy food: Pizza -YJlaok9sk0sd name: Billy food: Tacos which is very similar to the structure you want. There are many other ways of creating this structure. For example, you could craft the entire dictionary in code and write it all out at one time. Pardon typo's, I wrote this on the fly. A: Firebase has no native support for arrays. If you store an array, it really gets stored as an "object" with integers as the key names. // we send this ['hello', 'world'] // Firebase stores this {0: 'hello', 1: 'world'} Read this post for better understanding.
doc_23527727
set.seed(100) df <- data.frame(Name=letters[1:5], Apples=sample(1:10, 5), Oranges=sample(1:10, 5), Bananas=sample(1:10, 5), Dates=sample(1:10, 5)) And you want to apply the following weights to the dataframe: Weights <- c(Apples = "3", Oranges = "2", Bananas = "1") To produce a new aggregate score column. So for example the first row (row 'a') would have the following score: (3*4 + 2*5 + 1*7) = 29 And row b: (3*3 + 2*8 + 1*8) = 33 What code I write to do this automatically? Note that the weights may not be in the same order as the columns in the dataframe, nor will there necessarily be a weight for every numeric column in the dataframe (hence why in this example there is no weight for 'dates'). A: We can use rowSums after multiplying the subset of columns in 'df' by the corresponding elements in 'Weights' (by replicating the 'Weights') rowSums(df[names(Weights)]*as.numeric(Weights)[col(df[names(Weights)])]) #[1] 29 33 24 20 36
doc_23527728
my task that I am working on is this: You are given the data of weekly Covid-19 cases in your region and want to report some basic information given the data. In particular, you are interested in calculating the number of peaks, which is defined as a week where there are strictly more cases than in the week immediately preceding and in the week immediately after. The first and last week cannot be a peak. Write a function named “calc_peaks” and with a single input of a list covid_cases that does the following: * *Prints out the average cases per week as an integer, rounded down. *Prints out the maximum number of cases that ever occurred in a week. *Returns a list of the indices of the input list that correspond to peaks *(Bonus) Prints out the average number of cases during a week that is a peak. For example, if you call the function as calc_peaks([100, 300, 200, 100, 600, 300]), it should print 266 as the average number of cases and 600 as the maximum. Then, it should [1, 4] as the list of peaks. For the bonus task, it should print 450 as the average number of cases in a week that is a peak. Here is my code: for i in range(0,len(covid_cases)): if (covid_cases[i]>=covid_cases[i-1] and covid_cases[i]>=covid_cases[i+1]): return i print(calc_peaks([100,300,200,100,600,300])) When I print this it returns 1 for the peaks. How do I make it so it returns 1 and 4? Help gladly appreciated :) A: When your function returns something, it stops. In your case when the function processes the first value, it returns the value and stops further execution. You need to use yield which gives you a generator and a more pythonic way of solving this problem. A: "i" here is a variable that stores a single value. To achieve the required result you need: * *a Data Structure that can store multiple values Once you are done storing all values, you need to return the same. Please refer tweaked code below to solve your problem: peaks=[] def calc_peaks(covid_cases): for i in range(0,len(covid_cases)): if (covid_cases[i]>=covid_cases[i-1] and covid_cases[i]>=covid_cases[i+1]): peaks.append(i) return peaks print(calc_peaks([100,300,200,100,600,300]))
doc_23527729
var full_dialog = { width: "200px", height: "300px", position: [0,100] } $('<div></div>').dialog({ title: 'Claim# '+ref_num, full_dialog }); I've used $.extend to concatenate objects, I just wondered if there was a better way. A: Just use $.extend, it's simple and clear. A: If you want to dynamically merge two objects' properties, have a look at this thread's accepted answer: How can I merge properties of two JavaScript objects dynamically? Then you can do: var full_dialog = { width: "200px", height: "300px", position: [0,100] } $('<div></div>').dialog(merge_options({ title: 'Claim# '+ref_num },full_dialog));
doc_23527730
I'm using this wrapper: https://github.com/commonsguy/cwac-presentation Unfortunately I cannot force the second screen layout to be in fullscreen mode: although its width fully matches the screen, its height is always restricted to a stripe in the center of screen, approximately 1/4 of screen height Correspondingly, all its content is displayed within this narrow boundary, while the remaining parts of the screen keep staying black and useless For those who don't have an idea about this API, android.app.Presentation is a special type of Dialog which is shown on secondary screen of device, The wrapper I've mentioned above, is based on PresentationFragment which extends DialogFragment. User creates a class extending PresentationFragment, and in its overridden onCreateView() he creates the layout he wishes to be displayed on second screen. Example: public class CustomPresentationFragment extends PresentationFragment { public static CustomPresentationFragment newInstance(Context ctxt, Display display) { CustomPresentationFragment frag=new CustomPresentationFragment(); frag.setDisplay(ctxt, display); //we may prepare bundle to pass, if necessary //Bundle b=new Bundle(); //b.putString("key1", value1); //b.putString("key2", value2); //frag.setArguments(b); return(frag); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View myView = new View(getContext()); //here we create layout that we want to be displayed on second screen, and return it return(myView); } } This is the implementation of PresentationFragment. As we see, it contains Presentation variable: package com.commonsware.cwac.preso; import android.app.Dialog; import android.app.DialogFragment; import android.app.Presentation; import android.content.Context; import android.os.Bundle; import android.view.Display; public abstract class PresentationFragment extends DialogFragment { private Display display = null; private Presentation preso = null; public Dialog onCreateDialog(Bundle savedInstanceState) { if (this.preso == null) { return super.onCreateDialog(savedInstanceState); //instead of simply returning super value, I have tried the following here, //with no success: // //Dialog dlg = super.onCreateDialog(savedInstanceState); //dlg.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); //dlg.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //dlg.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); //return dlg; } return this.preso; } public void setDisplay(Context ctxt, Display display) { if (display == null) { this.preso = null; } else { this.preso = new Presentation(ctxt, display, getTheme()); //since Presentation is Dialog, I have tried the same here as well, //no success: //this.preso.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); //this.preso.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //this.preso.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } this.display = display; } public Display getDisplay() { return this.display; } protected Context getContext() { if (this.preso != null) { return this.preso.getContext(); } return getActivity(); } } EDIT. This is onCreateView() from one of my PresentationFragments: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String uri = "somefilepath"; File imgFile = new File(uri); Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); ImageView view = new ImageView(getContext()); view.setImageBitmap(myBitmap); view.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); RelativeLayout pRelative = new RelativeLayout(getContext()); pRelative.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); pRelative.setGravity(Gravity.CENTER); pRelative.addView(view); return pRelative; } A: First, the parent of your RelativeLayout is probably not another RelativeLayout, and therefore you should not be trying to set the RelativeLayout's LayoutParams to be an instance of RelativeLayout.LayoutParams. Second, rewrite this as an XML layout and inflate it. Your RelativeLayout has a better chance of working then, as it will know its parent at inflation time. RelativeLayout is a finicky beast. Another option would be to switch away from RelativeLayout to something else that can do your centering, such as a FrameLayout.
doc_23527731
I would also like to calculate the overlapping area when ellipses overlap each other. Data input description: x,y : geocoordinates that I have already transformed from lat/long into the appropriate projection system, the ellipse would be centered around this point z: area, in square feet, of the ellipse Orientation: The orientation of the ellipse (i.e. 70 degrees from north) Ratio: Aspect ratio of the ellipse (i.e. 3:1 Length:Width would mean length is 3X the width) Trying to do this in R, TERR, and spotfire, to plot the ellipses on a map. Thanks for any and all help!
doc_23527732
Condition is that parent may have child or may not have child. There is 100s of attribute that needs to map so would be great if I can map every attribute without defining individual attribute names (if feasible). It would be great if this problem could be solved by only using .dwl Original payload: [ { "id": "1", "parentAttribute1": "parent1-1", "parentAttribute2": "parent1-2", "parentAttribute3": "parent1-3", "child": [ { "childAttribute1": "inner1-1-1", "childAttribute2": "inner1-1-2" }, { "childAttribute1": "inner1-2-1", "childAttribute2": "inner1-2-2" }, { "childAttribute1": "inner1-3-1", "childAttribute2": "inner1-3-2" } ] }, { "id": "2", "parentAttribute1": "parent2-1", "parentAttribute2": "parent2-2", "parentAttribute3": "parent2-3", "child": [ { "childAttribute1": "inner2-1-1", "childAttribute2": "inner2-1-2" } ] }, { "id": "3", "parentAttribute1": "parent3-1", "parentAttribute2": "parent3-2", "parentAttribute3": "parent3-3" } ] Expected payload after translation - Scenario 1 - All attributes [ { "id": "1", "parentAttribute1": "parent1-1", "parentAttribute2": "parent1-2", "parentAttribute3": "parent1-3", "childAttribute1": "inner1-1-1", "childAttribute2": "inner1-1-2" }, { "id": "1", "parentAttribute1": "parent1-1", "parentAttribute2": "parent1-2", "parentAttribute3": "parent1-3", "childAttribute1": "inner1-2-1", "childAttribute2": "inner1-2-2" }, { "id": "1", "parentAttribute1": "parent1-1", "parentAttribute2": "parent1-2", "parentAttribute3": "parent1-3", "childAttribute1": "inner1-3-1", "childAttribute2": "inner1-3-2" }, { "id": "2", "parentAttribute1": "parent2-1", "parentAttribute2": "parent2-2", "parentAttribute3": "parent2-3", "childAttribute1": "inner2-1-1", "childAttribute2": "inner2-1-2" }, { "id": "3", "parentAttribute1": "parent3-1", "parentAttribute2": "parent3-2", "parentAttribute3": "parent3-3" } ] Expected payload after translation - Scenario 2 - Some attributes only [ { "id": "1", "parentAttribute1": "parent1-1", "childAttribute1": "inner1-1-1" }, { "id": "1", "parentAttribute1": "parent1-1", "childAttribute1": "inner1-2-1" }, { "id": "1", "parentAttribute1": "parent1-1", "childAttribute1": "inner1-3-1" }, { "id": "2", "parentAttribute1": "parent2-1", "childAttribute1": "inner2-1-1" }, { "id": "3", "parentAttribute1": "parent3-1", } ] Tried to use reduce, group functions but was unable to merge them. n/a n/a A: The key is to use the flatten plus a nested map. This way you can access both levels so you can operate with them. %dw 2.0 output application/json --- flatten(payload map ((parent, index) -> if (parent.child?) parent.child map ((child, index) -> (parent - "child") ++ child) else [parent] ) ) For dw 1 this is the solution %dw 1.0 %output application/json --- flatten (payload map ((parent, index) -> parent.child map ((child, index) -> (parent - "child") ++ child) when (parent.child?) otherwise [parent] ) )
doc_23527733
I would like to change the metadata values to values that I have chosen. In particular, I would like to replace one dictionary with another dictionary that I have written. but I got an error: AssertionError: Attribute 'stuff_dataset_id_to_contiguous_id' in the metadata of 'coco_2017_train_panoptic_separated' cannot be set to a different value! Here are the metadata I would like to change: MetadataCatalog.get(cfg.DATASETS.TRAIN[0]) --> --> out: Metadata(evaluator_type='coco_panoptic_seg', image_root='datasets/coco/train2017', json_file='datasets/coco/annotations/instances_train2017.json', name='coco_2017_train_panoptic_separated', panoptic_json='datasets/coco/annotations/panoptic_train2017.json' [...] stuff_dataset_id_to_contiguous_id={92: 1, 93: 2, 95: 3, 100: 4, 107: 5, 109: 6, 112: 7, 118: 8, 119: 9, 122: 10, 125: 11, 128: 12, 130: 13, 133: 14, 138: 15, 141: 16, [... etc etc] I would like to change stuff_dataset_id_to_contiguous_id to another dictionary. What can I do? Thank you so much. A: You could try to remove the metadata you've registered before like this: MetadataCatalog.remove("coco_2017_train_panoptic_separated") You can then print all the registered metadata to check that you removed what you wanted: detectron2.data.MetadataCatalog And after that register new changed metadata as usual using register_coco_instances(). By the way, you can use the same syntax for DatasetCatalog as well: DatasetCatalog.remove("coco_2017_train_panoptic_separated") detectron2.data.DatasetCatalog
doc_23527734
<ul> {data.characters.items.length &gt; 0 ? data.characters.items.map(character =&gt; ( <li>{character.name}</li>)) : "No characters available"} </ul> Here is the relevant code from Home: let { heroLinkName } = useParams(); const [heroName, setHeroName] = useState(""); const [heroes, setHeroes] = useState([]); const [hero, setHero] = useState([]); const [show, setShow] = useState(false); const handleClose = () => setShow(false); const buttonNameRef = useRef(); useEffect(() => { localStorage.setItem('heroName', heroLinkName); const heroName = localStorage.getItem('heroName'); setHeroName(heroName); handleClick(heroName); }, []); The hero name (as a string) is supposed to pass from HeroComics to Home and go into local storage as 'heroName' and then pulled from local storage as 'const heroName' and then set to the input value and clicked, but the search input is showing undefined. How can I fix this issue and get the input to display the actual value that is being passed? Is this happening because the value is a string and not a number because it was working fine on other pages when I'm using numbers. A: I think you should change your let { heroLinkName } = useParams(); to let { name } = useParams();
doc_23527735
I am using usersTableAdapter.Insert() for adding a new record, but it requires all 3 parameters including Id which is Identity column and auto-incremented and cannot be added manually. Here is the code: this.usersTableAdapter.Insert("Haroon", "Pakistan"); This is not working. Is there any way to use the above command without providing an Id value? A: Yes; you've set your tableadapter up incorrectly.. Examine this screenshot of a tableadapter conencted to a sql server table that has an autoincrement ID column. You can see the table design from SSMS in the to right (blue border). You can see highlighted that the table adapter was created with select * from autoinctable and the wizard has ONLY chosen to reference the Text column for INSERT (also highlighted) In code, the Insert command only asks for the Text column: This TA was created with "refresh the dataset" turned on; you can see in the commands (like insert) that the database calculated value is retrieved (select ... scope_identity)
doc_23527736
vehicle->mopServer->accept((PipelineID)MOBILE_PIPELINE_ID, UNRELIABLE, mobile_Pipeline) In the console appear this: [1185439.581]STATUS/1 @ accept, L50: /*! 0.Find whether the pipeline object is existed or not */ [1185439.581]STATUS/1 @ accept, L56: /*! 1.Create handler for binding */ [1185439.581]STATUS/1 @ accept, L64: /*! 2.Do binding */ [1185441.581]STATUS/1 @ accept, L77: /*! 3.Do accepting */ [1185441.581]STATUS/1 @ accept, L78: Do accepting blocking for channel [49154] But never ends, the program stay like "sleeping". I waited for many minutes and nothing. Please, can anyone help me? Thanks.
doc_23527737
The application is using Tomcat 7. It works fine with plaintext password (in the database) My problem is : i want to store the hashed passwords (with a salt if possible), and not in plaintext. But if i understood well, HTTP Digest requires the password to be in plaintext. Is there a way to change this in Spring Security ? A: i want to store the hashed passwords (with a salt if possible), and not in plaintext. But if i understood well, HTTP Digest requires the password to be in plaintext. Is there a way to change this in Spring Security ? No, this is not changeable, atleast at the time of writing this. The Spring Security documentation on Digest Authentication states the following, where is it quite evident that the passwords have to be in clear text. The configured UserDetailsService is needed because DigestProcessingFilter must have direct access to the clear text password of a user. Digest Authentication will NOT work if you are using encoded passwords in your DAO.
doc_23527738
* *the class will have an alignment of its widest member *the end of the class can be padded with regards of its alignment in case it is in an array *structure members are aligned according to the structure alignment So for instance: struct Nested { // Due to the long long element it is 8 aligned short int ShortNestedElement; //6 bytes of padding here long long int LongNestedElement; }; struct Example { short int ExampleMember_1; // 6 bytes of padding here Nested ExampleMember_2; char ExampleMember_2; // 7 bytes of padding here }; My confusion comes in case of inheritance: struct Base1 { short unsigned int Base_1Member_1; long unsigned int Base_1Member_2; }; struct Base2 { unsigned int Base_2Member_1; }; struct Base4 { unsigned int Base_4Member_1; }; struct Base3 : Base4 { long unsigned int Base_3Member_1; }; struct Final: Base1, Base2, Base3 { }; According to clang the layout of the class Final is: *** Dumping AST Record Layout 0 | struct Final 0 | struct Base1 (base) 0 | unsigned short Base_1Member_1 8 | unsigned long Base_1Member_2 16 | struct Base2 (base) 16 | unsigned int Base_2Member_1 24 | struct Base3 (base) --------> ? 24 | struct Base4 (base) 24 | unsigned int Base_4Member_1 32 | unsigned long Base_3Member_1 | [sizeof=40, dsize=40, align=8, | nvsize=40, nvalign=8] I don't understand why, when we consider Base3 even if it inherits from Base4 (so the members of Base4 comes before Base3) we consider the alignment of Base3(8) instead of Base4(4). But if I change the contents of these two classes so that Base3 is aligned to 4 and Base4 is aligned to 8 it takes the alignment of Base4. Is it takes the widest class in the inheritance hierarchy? A: This is largely implementation-dependent. In your code: struct Nested { // Due to the long long element it is 8 aligned short int ShortNestedElement; //6 bytes of padding here long long int LongNestedElement; }; struct Example { short int ExampleMember_1; // 6 bytes of padding here Nested ExampleMember_2; char ExampleMember_2; // 7 bytes of padding here }; long long doesn't have to be 8 bytes, short doesn't have to be 2 bytes, and char doesn't have to be 1 byte. If they are, then long long doesn't have to be 8-byte aligned, short doesn't have to be 2-byte aligned, and char doesn't have to be 1-byte aligned. It isn't guaranteed either that the paddings are inserted as your comments indicate. These are all implementation-defined. Now let's see your question: struct Base1 { short unsigned int Base_1Member_1; long unsigned int Base_1Member_2; }; struct Base2 { unsigned int Base_2Member_1; }; struct Base4 { unsigned int Base_4Member_1; }; struct Base3 : Base4 { long unsigned int Base_3Member_1; }; struct Final: Base1, Base2, Base3 { }; I don't understand why, when we consider Base3 even if it inherits from Base4 (so the members of Base4 comes before Base3) we consider the alignment of Base3(8) instead of Base4(4). But if I change the contents of these two classes so that Base3 is aligned to 4 and Base4 is aligned to 8 it takes the alignment of Base4. If Base3 inherits from Base4, then the Base4 is a subobject of Base3, so the alignment requirement of Base4 is effectively propagated to Base3. Therefore, alignof(Base3) becomes the bigger of alignof(Base4) and the alignment requirement of its member. So, effectively, it's taking the "widest in the hierarchy." That's how real-world alignment works, at least. Again, the standard doesn't specify this kind of things. There is no guarantee that alignof(Base3) == std::max(alignof(Base4), alignof(unsigned long)). In the future, when you are discussing alignment, please use alignas instead of relying on the alignment of builtin types.
doc_23527739
Is there any other configuration I am missing here ? I am able to RDP to the machine . I have tried with source as * and destination as * also . But still no luck. I am not able to telnet also with the VM public IP and the given ports. A: Did you allow 8080/TCP from anywhere, for all profiles in Windows Firewall? Is you daemon listening on 0.0.0.0 or just 127.0.0.1? netstat -ban should give you the answer there. e.g. [spoolsv.exe] TCP 0.0.0.0:1540 0.0.0.0:0 LISTENING [lsass.exe] TCP 0.0.0.0:2179 0.0.0.0:0 LISTENING [vmms.exe] TCP 0.0.0.0:5357 0.0.0.0:0 LISTENING If you're only listening on localhost (127.0.0.1) you need to address the configuration of your daemon and then restart it. A: Connect to your Virtual Machine, Open the Firewall Advanced Settings and add an exception for the port 8080 as the EndPoint Configuration doesn't do that for you
doc_23527740
<div class="dropdown "> <button class="btn btn-default dropdown-toggle btn-block" type="button"> <!-- react-text: 346 --> Select door <!-- /react-text --> <span class="glyphicon glyphicon-chevron-down"/> </button> <div class="dropdown-menu"> </div> A: This XPath, //button[normalize-space() = 'Select door'] will select the shown button element based on its Select door label. This XPath, //button[normalize-space()='Select door']/following-sibling::div[@class='dropdown-menu'][1] will select the immediately following dropdown-menu div.
doc_23527741
I want to avoid using redirect_back to prevent being sent back to the top of the screen after reload so I'm adding a JS click listener to the link_to tag with a code like this: # in my view <h5 class='my-link'><%= link_to 'vote', vote_path' %></h5> # at the bottom of my application layout <script> $('.my-link').click(function (event) { window.location.reload(true); }); </script> The JS code listener works OK in that if I click on any section of the h5 element the page will reload. However, when I click in the link the application will go to the relevant controller#action but the page wont reload. I'm assuming I'm missing a way to execute first the link action and then force the refresh. So at click the app records a vote and then JS force a reload. Can you see any way I can achieve this? Thanks. UPDATE I some what solved this issue by adding a timer to the JS event so it gives time for the link to reach the controller and do the action and do the reload after it. <script> $(document).ready(function() { $('.puke-icon, .clean-link, .comment-send').click(function() { setTimeout(function(){ window.location.reload(true); }, 50); }); }); </script> This is probably too hacky so hopefully you can provide more elegant approaches thanks! A: In your vote controller action, use location.reload() in respond_to do format. respond_to do |format| format.js {render inline: "location.reload();" } end View: <h5 class='my-link'><%= link_to 'vote', vote_path' %></h5> Controller: class VotesController < ApplicationController def vote ---------------------- // your code goes here ---------------------- respond_to do |format| format.js {render inline: "location.reload();" } end end end This will reload the page after the database action is completed. A: $('.product').click(function () { location.reload(); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <div class="container"> <div class="row" id="footerRow"> <div class="col-xs-12 product"> <h2>Product</h2> <div> </div> </div>
doc_23527742
Digging up some info on this has revealed that the Voice app can't be set as default because Android requires the carrier SMS/MMS handlers to be present in the app in order to have that option. No support for carrier, no option for default. I'm wondering- is it crazy to write a small app that would include the requisite handlers that sort of routes intent requests to different apps? For example, allow new message requests to open in an app of your choosing, Hangouts or Google Voice, etc. Heck, even Whatsapp if you so wish. But, if this forwarding app doesn't also actually DO anything with carrier messages, what will happen when/if a carrier SMS/MMS comes in? Will the message get stuck in limbo trying to be delivered somewhere? I'm not clear on how the OS handles that. I see that whatever app is set to default for messaging is the one in charge of receiving and storing messages. So, if I don't include some sort of actual carrier message handling, how might that effect the operation of the phone? Or, is it possible to forward along incoming carrier messages to another app (such as the standard Messenger) from this forwarding app? I can't seem to figure out how this should work, open to suggestions!
doc_23527743
I did put my website through the facebook debugger this was the result. Facebook Debugger The IP adress is also not right, how do i change that? A: That’s an IPv6 address shown there. Facebook prefers IPv6 over v4 when available. This sometimes causes problems like this, when the DNS settings for the domain are wrong. Most users still use IPv4, so the problem doesn’t become visible until such a client that perfers v6 comes along. Check the DNS settings for the domain (or ask your server admin to do it), looks like the AAAA record for the IPv6 address is wrong.
doc_23527744
Here is my image after detect minutiae : it is my original picture(gray) Can anybody help me to write matlab code for it?
doc_23527745
I have the below Scenario: Then I follow "Use theme" Then the page background should be blue And the step definition as: Then /^the page background should be blue$/ do page.evaluate_script("%Q[jQuery('body').css('background-color');]").should == 'rgb(1, 31, 69)' end But htis is throwing a javascript error Can someone please tell me where im going wrong? (PS: Im not very good at jQuery) Error: Then the page background should be blue syntax error (Selenium::WebDriver::Error::JavascriptError) A: The problem is the "%Q[ ]" part. It looks like you are accidentally trying to define a Ruby string in a Ruby string. You either want to wrap the string in "" or %Q[] but not both. Either of the following would work: # Using %Q[] puts page.evaluate_script(%Q[jQuery('body').css('background-color');]) # Using "" puts page.evaluate_script("jQuery('body').css('background-color');") # Using $ instead of jQuery puts page.evaluate_script('$("body").css("background-color")')
doc_23527746
Here's the fiddle code: Service: myApp.factory('myService', function($q, $timeout) { var checkStartTime = false; var checkTimeout = 30000; function checkForContent() { var deferred = $q.defer(); // simulating an $http request here $timeout(function () { console.log("Checking..."); if (!checkStartTime) checkStartTime = new Date(); // this would normally be 'if (data)' if ((new Date()) - checkStartTime > 3000) { deferred.resolve("Finished check"); checkStartTime = false; // reset the timeout start time } else { // if we didn't find data, wait a bit and check again $timeout(function () { checkForContent(); }, 400); } }, 5); // then is called in here when we find data deferred.promise.then(function(message) { console.log("Resolved inside checkForContent"); }); return deferred.promise; } return { runCheck: function() { return checkForContent() } } }); Controller: myApp.controller('MyCtrl', function ($scope, myService) { $scope.name = 'Superhero'; // then is never called myService.runCheck() .then(function (message) { console.log("Resolved outside checkForContent"); }); }); A: Check out this fiddle. The outter $timeout function is named so it can be called from within itself. $timeout(function inner() { // ... Then it is called recursively like this: $timeout(function () { inner(); }, 400);
doc_23527747
A: I think what you're asking is how to store data in a model object for use by your view controller. If this is not your meaning, then please forgive me. You are right that a model object should inherit from NSObject. Optionally, you could also extend another model object to add property values. Model objects are a great way to separate the view objects from your data. Let's say you have a CustomerViewController with some customer fields. You need to populate those customer fields, and potentially perform some processing on that data. The model object supports these relationships, by allowing you to separate your views from any processing logic related to your data and business rules. Using the relationships below as a guide, you should be on your way to building effective view controllers, that separate your views from your data! CustomModel Interface @interface CustomerModel : NSObject @property (strong, nonatomic) NSString *firstName, *lastName; @property (strong, nonatomic) NSString *phoneNumber; - (BOOL) isValidPhoneNumber:(NSString *)phoneNumber; @end CustomerModel Implementation #import "CustomerModel.h" @implementation CustomerModel - (BOOL) isValidPhoneNumber:(NSString *)phoneNumber { //Check that phone number can be parsed and is valid } @end CustomerViewController Implementation #import "CustomerViewController.h" #import "CustomerModel.h" @interface CustomerViewController () <UITextFieldDelegate> @property (strong, nonatomic) CustomerModel *customerModel; ... @property (weak, nonatomic) IBOutlet UITextField *firstNameField ... @end @implementation CustomerViewController - (void) viewDidLoad { //Optionally instantiate the customer model with stored data, // to pre-populate the view controller. self.customerModel = [CustomerModel new]; self.firstNameField.delegate = self; } - (void) textFieldDidEndEditing:(UITextField *)textField { //Validate the phone number NSString *phoneNumber = textField.text; if ([self.customerModel isValidPhoneNumber:phoneNumber]) { self.customerModel.phoneNumber = phoneNumber; } else { //Alert the user that the data is invalid } } - (BOOL) textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } @end Possible improvements * *It might be a little annoying to the User, to see alerts while filling out information. So, it might be better to defer the validation to when a save button is pressed. *Model objects can be populated from a data store, to be used to pre-populate a form.
doc_23527748
The structure of the project looks like this RootProject -buildSrc -DirectoryA -SubProjectA1 -SubProjectA2 -SubProjectA3 -DirectoryB -SubProjectB1 -SubProjectB2 -DirectoryC -SubProjectC1 -SubProjectC2 etc.. Directories are there just to conveniently separate projects. RootProject and all SubProject have build.gradle files. In the RootProject build.gradle file there are around 25 tasks. These tasks are configured on both root project and subprojects. They make build.gradle rather long and complicated. So I thought of moving them into separate Tasks.gradle file located under buildSrc directory. And then pulling them in with "apply from" Is this a good practice or is there a better way? If I pull them in, there is another issue. Some tasks are configured for SubProjects, and other are configured for RootProject. So I can't really just put them into single Tasks.gradle file. Should I then put them into something like RootProjectTasks.gradle and SubProjectsTasks.gradle? It all feels a little wrong... A: If you use Jenkins for build, then you should make build.gradle for every sub-project and also for Root Project. In Jenkins, you can Invoke Gradle script multiple times. So, you can invoke every build.gradle file one by one. There is another way to invoke every build.gradle of sub-projects by invoking only Root projects build.gradle. For that you must add following line in settings.gradle include ":sub-project1-name", ":sub-project2-name", ":sub-project3-name", Feel free for more information A: Do not put *.gradle file into the buildSrc folder. The buildSrc folder is a nested project folder that should be organized like a project and contain only *.java or *.groovy files in buildSrc/src/main/groovy. You can extract tasks into separate gradle files and include them via apply from. Tasks that apply to all projects can go here: allprojects { apply plugin: 'idea' } Tasks that apply only to all subprojects can go here: subprojects { apply plugin: 'java' } You can either also include them directly from the submodules that need them. Or apply to only some subprojects like so: def clientProjects() { return subprojects.findAll { // some predicate that is true only for client projects } } configure(clientProjects()) { apply plugin: ... }
doc_23527749
A: Add the interaction: let interaction = UIContextMenuInteraction(delegate: self) menuView.addInteraction(interaction) Add UIContextMenuInteractionDelegate to your controller: extension YourViewController: UIContextMenuInteractionDelegate { func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? { return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in // Create an action for sharing let share = UIAction(title: "Share", image: UIImage(systemName: "square.and.arrow.up")) { action in // Show system share sheet } // Create an action for renaming let rename = UIAction(title: "Rename", image: UIImage(systemName: "square.and.pencil")) { action in // Perform renaming } // Here we specify the "destructive" attribute to show that it’s destructive in nature let delete = UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { action in // Perform delete } // Create and return a UIMenu with all of the actions as children return UIMenu(title: "", children: [share, rename, delete]) } } } Now, long-press on the view and see your menu :) More here: https://kylebashour.com/posts/context-menu-guide
doc_23527750
Any help would be nice. I've tried a for loop of: x = list("ABCDEFGHIJ...") for i in range(0,55): for j in range(0,55): y = (j+55) - (i+55) list[i][j] = x[y] so yeah, thanks for any help. A: You might be looking for the functionality in a deque >>> from collections import deque >>> d = deque('ABC') >>> d deque(['A', 'B', 'C']) >>> d.rotate(-1) >>> d deque(['B', 'C', 'A']) A: If you are just trying to append a rotated list, here is how to that: >>> x=[] >>> x.append(list('ABC')) >>> x [['A', 'B', 'C']] >>> x.append(x[-1][1:]+x[-1][:1]) >>> x [['A', 'B', 'C'], ['B', 'C', 'A']] Which you can continue: >>> x.append(x[-1][1:]+x[-1][:1]) >>> x [['A', 'B', 'C'], ['B', 'C', 'A'], ['C', 'A', 'B']] And when you say 'continue until done' you may mean something like this?: x=[list('ABCD')] def rotate(l,n): return l[n:] + l[:n] while True: rl=rotate(x[-1], 1) if len(x)>1 and x[0]==rl: break else: x.append(rl) print x # [['A', 'B', 'C', 'D'], ['B', 'C', 'D', 'A'], ['C', 'D', 'A', 'B'], ['D', 'A', 'B', 'C']]
doc_23527751
I implemented a carousel, nearly the same as here (http://v4-alpha.getbootstrap.com/examples/carousel/). Well, in Bootstrap V3.X.X you could change the transition easily, but now I can't figure out how to change the transition to "fade". I tried adapting this example: (http://codepen.io/zlobae/pen/xwVqGy/) but I had no luck. This part .carousel-fade { .carousel-item { display: block; position: absolute; opacity: 0; transition: opacity .75s ease-in-out; &.active { opacity: 1; } } } doesn't seem to work properly. Does anyone know how to achieve a fading transition? EDIT: HTML is at the moment for reasons of reproducibility the same as in the Codepen Page: <div data-ride="carousel" class="carousel carousel-fade" id="carousel-example-captions"> <ol class="carousel-indicators"> <li class="active" data-slide-to="0" data-target="#carousel-example-captions"></li> <li data-slide-to="1" data-target="#carousel-example-captions" class=""></li> <li data-slide-to="2" data-target="#carousel-example-captions" class=""></li> </ol> <div role="listbox" class="carousel-inner"> <div class="carousel-item active"> <div class="carousel-caption"> <h3>First slide label</h3> <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p> </div> </div> <div class="carousel-item"> <div class="carousel-caption"> <h3>Second slide label</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </div> </div> <div class="carousel-item"> <div class="carousel-caption"> <h3>Third slide label</h3> <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p> </div> </div> </div> <a data-slide="prev" role="button" href="#carousel-example-captions" class="left carousel-control"> <span aria-hidden="true" class="icon-prev"></span> <span class="sr-only">Previous</span> </a> <a data-slide="next" role="button" href="#carousel-example-captions" class="right carousel-control"> <span aria-hidden="true" class="icon-next"></span> <span class="sr-only">Next</span> </a> </div> The Carousel shows up properly but it does not show the fade property. Seems to be a compatibility issue between v4.0.0 and v4.0.3 A: I got it working using the following CSS // Carousel fade transition .carousel-fade { .carousel-item { display: block !important; position: absolute; transform: none; perspective: none; opacity: 0; transition: opacity .75s ease-in-out; &.active { opacity: 1; } } }
doc_23527752
I created a storyboard project with a Navigation controller and a Table view controller in it. I added a UISearchDisplayController to the table view and all works well until I try to access the searchDisplayController as seen below in the code snippet. I am using a section index and added UITableViewIndexSearch (or @"{search}") to the top of the section titles so that the magnifying glass shows at the beginning of the A - Z index. When I click on the section index the following function is called: - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index { if ([title isEqualToString:UITableViewIndexSearch]) { [self.searchDisplayController setActive:TRUE animated:TRUE]; // Either of these two lines [self.searchDisplayController.searchBar becomeFirstResponder]; // will cause the search bar cancel button to not work return 0; } return index - 1; } If I comment out both of the lines that access searchDisplayController then the search bar cancel button works as expected. If either of the two lines is not commented out in the code then the cancel button on the search bar acts as if it were not even there. Removing the becomeFirstResponder line means that I must click/touch in the search bar field to transfer focus to it, so in this case when I click on the cancel button the search bar gets focus. It's as if the cancel button is seen transparently through the search bar but can't be clicked/touched. Take those two lines of code out and the cancel button works again. What the heck is going on?
doc_23527753
Is there a way for the contents of the file to be passed in to the java program as a command line argument? What I have so far: #!/usr/bin/bash javac -O Main.java uandf.java node.java java -cp Main "$1" I am running the script with ./shell_script.sh < filename The main method in the java program: public static void main(String args[]) { String[] array = args[0].split("\n"); ... } A: It's a strange and non-canonical thing to do, but yes: #!/usr/bin/bash javac -O Main.java uandf.java node.java java -cp . Main "$(cat)" Normally you would instead have your Java program read from System.in (as if from the keyboard), and just used: #!/usr/bin/bash javac -O Main.java uandf.java node.java java -cp . Main When running ./shell_script.sh < filename, reading from System.in via Scanner or BufferedReader would then return data from filename.
doc_23527754
<!DOCTYPE html> <html> <body> <script> var test= "<script>dsfdsf</script>"; alert(test); </script> </body> </html> can we show script in alert ??
doc_23527755
* *Volatile keyword to read/write from the main memory *Synchronized around the method and block *Static method to get the instance *Double checking if instance is available or not *Private constructor Below is the code - /** * */ package com.test.singleton; /** * @author * */ public class SingletonInstance implements Cloneable{ private String name; private static volatile SingletonInstance instance; private SingletonInstance(){ System.out.println("constructor called"); } public String getName() { return name; } public void setName(String name) { this.name = name; } static synchronized SingletonInstance getInstance(){ if(instance == null){ synchronized(SingletonInstance.class){ instance = new SingletonInstance(); } } return instance; } /* (non-Javadoc) * @see java.lang.Object#clone() */ @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return super.clone(); } } Please suggest if it's possible to break the singleton contract in any way? A: There are several situations your Singleton Class may have multiple instances. As of now, I have 2 points in my mind. * *Invoking private constructor trough reflection. *Through Serialization and Deserialization. Here is the way to stop creating an object through private constructor invocation. private SingletonInstance(){ if(instance != null){ throw new OperationNotSupportedException("You can't create object of singletone class using this operation"); } } Also, you can stop creating multiple objects of singleton class through serialization and deserialization by adding readObject and readResolve method like below. private void readObject(ObjectInputStream inputStream) throws ClassNotFoundException, IOException { inputStream.defaultReadObject(); instance = this; } private Object readResolve() { return instance; } Also, your clone method should through an exception. protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("Clone not supported for this class"); } A: The constructor, although private, can be invoked using reflection: Class<SingletonInstance> klass = SingletonInstance.class; Constructor<SingletonInstance> defaultConstructor = klass.getConstructor(); defaultConstructor.setAccessible(true); SingletonInstance newInstance = defaultConstructor.newInstance(); With that, multiple instances can be created. To prevent that, it should contain its own check, as suggested in effective java: private SingletonInstance(){ if(instance != null) throw new IllegalStateException(); //or some other exception System.out.println("constructor called"); }
doc_23527756
Method m = cls.getMethod("main", String[].class); System.out.println(m.getParameterTypes().length); System.out.println(Arrays.toString(m.getParameterTypes())); System.out.println(m.getName()); m.invoke(null, new String[]{}); This prints: 1 [class [Ljava.lang.String;] main But then it then it throws: IllegalArgumentException: wrong number of arguments What am I overlooking here? A: You will have to use m.invoke(null, (Object)new String[]{}); The invoke(Object, Object...) method accepts a Object.... (Correction) The String[] array passed is used as that Object[] and is empty, so it has no elements to pass to your method invocation. By casting it to Object, you are saying this is the only element in the wrapping Object[]. This is because of array covariance. You can do public static void method(Object[] a) {} ... method(new String[] {}); Because a String[] is a Object[]. System.out.println(new String[]{} instanceof Object[]); // returns true Alternatively, you can wrap your String[] in an Object[] m.invoke(null, new Object[]{new String[]{}}); The method will then use the elements in the Object[] as arguments for your method invocation. Careful with the StackOverflowError of calling main(..). A: And you can do this: Method m = cls.getMethod("main", String[].class); System.out.println(m.getParameterTypes().length); System.out.println(Arrays.toString(m.getParameterTypes())); System.out.println(m.getName()); String[] a = new String[1]; m.invoke(null, a);
doc_23527757
Windows->Preferences->Ant->Runtime->Properties in Eclipse, I can see global properties for Ant. Do I have some sort of "local" properties, like workspace directory or project directory? How to see or set them? I have created new empty build.xml in some project and want to add some automation into it. A: Right click on build.xml -> Run As -> Ant Build... Click on the Properties tab, you should be able to opt to use project specific properties here. A: See this question and answer for an example of using a 'local' eclipse property like i.e. ${project_loc} in ant. There's also Ant Addon Ant4Eclipse, which aims to make Eclipse settings available for ant.
doc_23527758
The errors I'm getting: * *https://codeshare.io/GLXByl java.lang.NoClassDefFoundError: org/apache/maven/doxia/siterenderer/DocumentContent I know I'm missing some plugins. I've tried all the solutions in previous posts and many version last and older ones but still missing them and I don't know what I'm missing in my pom.xml: * *https://codeshare.io/5MO1Xe A: Apparently you miss certain plugins in your <build/>. Add these: <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.10.0</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.2.1</version> </plugin> </plugins> </build> and see if it helps. A: This needs to be added to your pom.xml: <dependency> <groupId>org.apache.maven.doxia</groupId> <artifactId>doxia-site-renderer</artifactId> <version>1.9.2</version> </dependency>
doc_23527759
I understand that a Delegate is a pointer to a function and is multicast. I have read that am Event Handler "is a" delegate. I notice that it has this signature: Public Delegate Sub EventHandler ( _ sender As Object, _ e As EventArgs _ ) However, it does not inherit from Delegate. I do make use of the Handles keyword in VB.NET e.g. Handles Button1.Click. What is the point of an Event Handler? Is it simply a delegate with two arguements i.e. Object and EventArgs? Why does the EventHandler class not inherit from Delegate? A: A Delegate is not a class. And as such it can not be inherited. EventHandler as you observed is just a delegate with a well known signature, and thus defines a uniform way of event firing and handling. A: An event handler is the routine that is going to execute when an event occurs. A delegate is a reference to a routine. If you have no handler the delegate can't reference anything. Delegates are the easy way for VB to handle function pointers. EventHandler does not need to inherit from delegate because it is a function, not a pointer.
doc_23527760
--Project.sln ----ProjectA.csproj ------Database ------Dockerfile ----ProjectB.csproj --docker-compose.yml --Dockerfile Where ProjectA depends on and references ProjectB. docker-compose.yml: version: "3.7" services: dotnet-backend: container_name: dotnet-backend build: ./ env_file: .env links: - mssql-db ports: - "8000:80" mssql-db: container_name: mssql-db build: ./ProjectA/Database volumes: - ./Database/:/scripts/ ports: - "1433:1433" Dockerfile: FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env WORKDIR /app # Copy csproj and restore as distinct layers COPY *.sln ./ COPY ./ProjectA/*.csproj ./ProjectA/ COPY ./ProjectB/*.csproj ./ProjectB/ RUN dotnet restore # Copy everything else and build COPY . ./ RUN dotnet publish -c Release -o out # Build runtime image FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 WORKDIR /app COPY --from=build-env /app/out . EXPOSE 80 ENTRYPOINT ["dotnet", "ProjectA.dll"] Now when I run docker-compose up --build I get this error: Building dotnet-backend Step 1/14 : FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env ---> cfc38403c6bc Step 2/14 : WORKDIR /app ---> Using cache ---> 6f88c69630ff Step 3/14 : COPY *.sln ./ ---> Using cache ---> a2076128c94c Step 4/14 : COPY ./ProjectA/*.csproj ./ProjectA/ ---> Using cache ---> 41fdd541e0a8 Step 5/14 : COPY ./ProjectB/*.csproj ./ProjectB/ ERROR: Service 'dotnet-backend' failed to build: COPY failed: no source files were specified How come COPY works for ProjectA, but not for ProjectB? Never mind that it says using cache in step 4, I get the same error when building for the first time as well. A: For anyone running into a similar problem, I was able to solve it after including context and dockerfile in docker-compose.yml file. Previously Docker Compose was not able to find the files for the COPY command. Here is the fix: services: webservice: build: context: ../ # your path to context dockerfile: ./Dockerfile # path relative to context
doc_23527761
It's already minified. When I smash it together with the rest of my minified javascript, I get an Uncaught TypeError in my console. I think it might be somehow conflicting with other scripts I have (Angular, among others) So I was thinking it might be smart to somehow get an unminified version so it wouldn't conflict with the other code. Any pointers here on what might be going on and how to fix it? A: I am aware that this is an old question pertaining to an old version of foundation. Just in case this will be usefull to someone else: I was debugging an old site and the error in line 26 can be resolved if jQuery or Zepto is loaded before foundation.js oder foundation.min.js. Simply put the link tags in your HTML in the appropriate order.
doc_23527762
problem is the render cards function begins to execute before the data have been saved for some reason, and when i try to render i get undefined since the cards are undefined. when it did work it also returned the data stringified and not parsed for some reason onInit happens on body load. <body onload="onInit()"> function onInit() { FetchCards(); renderCards(); } function FetchCards(){ var cards =loadFromStorage(KEY) if(!cards){ fetch('http://www.filltext.com/?rows=10&fname=%7bfirstName%7d&lname=%7blastName%7d&tel=%7bphone|format%7d&address=%7bstreetAddress%7d&city=%7bcity%7d&state=%7busState|abbr%7d&zip=%7bzip%7d&pretty=true') .then(res => { if(res.ok) res.json() .then(data=>{ console.log(data); saveToStorage(KEY,JSON.stringify(data)) }) }) } } function renderCards() { var cards = getCardsForDisplay().... function getCardsForDisplay(){ var cards =loadFromStorage(KEY) return cards } function saveToStorage(key, val) { localStorage.setItem(key, JSON.stringify(val)) } function loadFromStorage(key) { var val = localStorage.getItem(key) if(!val || val==='undefined') return undefined; return JSON.parse(val) } A: You'll have to use async/await keywords. function onInit() { FetchCards().then(data => { // your previous logic. }).catch(err => console.log(err)).finally(() => { renderCards(); }) } async function FetchCards() { // The result is a promise const result = await fetch("https://example.com"); return result; } A: a solution if a newcomer like myself encounters this problem: what i needed to do is wait for a response from the fetch, await the object to convert to json , and only then save it, in the onInit function i simply await for it to fetch the cards, async function onInit() { await FetchCards() renderCards(); } async function FetchCards(){ var cards = loadFromStorage(KEY) if(!cards){ const response = await fetch('url'); const data= await response.json() saveToStorage(KEY,data) return data } return cards }
doc_23527763
A: You could try something like this: $(document).bind('scroll',function(event) { var scrollTop = $(window).scrollTop(); if (scrollTop <= 170) { $('#sidebar').css('top','170px'); } else { $('#sidebar').css('top',scrollTop+'px'); } }); Here's a working jsfiddle
doc_23527764
int result = JOptionPane.showConfirmDialog(null, myPanel, "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION); This works fine, but I want to remove the nasty ? at the left top corner. A: Use the PLAIN_MESSAGE message type JOptionPane.showConfirmDialog(null, "Help", "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); A: There is an overridden method showConfirmDialog() as follows /** * Brings up a dialog where the number of choices is determined * by the <code>optionType</code> parameter, where the * <code>messageType</code> * parameter determines the icon to display. * The <code>messageType</code> parameter is primarily used to supply * a default icon from the Look and Feel. * * @param parentComponent determines the <code>Frame</code> in * which the dialog is displayed; if <code>null</code>, * or if the <code>parentComponent</code> has no * <code>Frame</code>, a * default <code>Frame</code> is used. * @param message the <code>Object</code> to display * @param title the title string for the dialog * @param optionType an integer designating the options available * on the dialog: <code>YES_NO_OPTION</code>, * <code>YES_NO_CANCEL_OPTION</code>, * or <code>OK_CANCEL_OPTION</code> * @param messageType an integer designating the kind of message this is; * primarily used to determine the icon from the pluggable * Look and Feel: <code>ERROR_MESSAGE</code>, * <code>INFORMATION_MESSAGE</code>, * <code>WARNING_MESSAGE</code>, * <code>QUESTION_MESSAGE</code>, * or <code>PLAIN_MESSAGE</code> * @return an integer indicating the option selected by the user * @exception HeadlessException if * <code>GraphicsEnvironment.isHeadless</code> returns * <code>true</code> * @see java.awt.GraphicsEnvironment#isHeadless */ public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType) throws HeadlessException { return showConfirmDialog(parentComponent, message, title, optionType, messageType, null); } As you can see the 5th parameter is the int messageType which you can set. There are various message types like * *ERROR_MESSAGE *INFORMATION_MESSAGE *WARNING_MESSAGE *QUESTION_MESSAGE *PLAIN_MESSAGE You can select the one that meets your requirement.
doc_23527765
public class ListLavorationCodeClient { public string LavorationsCode { get; set; } } In my code I've written: var listLavorationsCode = new ListLavorationCodeClient() { LavorationsCode = codiceLavorazioneXx }; and the result is the following: { "LavorationsCode": "30410040136042700157" } { "LavorationsCode": "30440040136042700157" } Instead I want a result like this: { "LavorationCode": { "30410040136042700157", "30440040136042700157" } } How can I fix? A: You need to change the variable itself: public string[] LavorationsCode { get; set; }
doc_23527766
I've searched around but nothing was found about this sadly! A: I edit my composer.json and manipulate the class mappings. In this example, I wanted to override some cache classes. "autoload": { "psr-4": { "App\\": "app/", "Database\\Factories\\": "database/factories/", "Database\\Seeders\\": "database/seeders/", "Nuwave\\Lighthouse\\Cache\\": "lighthouseV6/cache/" }, "exclude-from-classmap": [ "vendor/nuwave/lighthouse/src/Cache/CacheKeyAndTags.php", "vendor/nuwave/lighthouse/src/Cache/CacheKeyAndTagsGenerator.php", "vendor/nuwave/lighthouse/src/Cache/CacheDirective.php" ] }, Then create a folder "lighthouseV6/cache" in the root of the project and copy the classes I wanted to override from "vendor/nuwave/lighthouse/src/Cache" inside it. A: I found the solution. according to https://lighthouse-php.com/5/custom-directives/getting-started.html#register-directives When Lighthouse encounters a directive within the schema, it starts looking for a matching class in the following order: 1. User-defined namespaces as configured in config/lighthouse.php, defaults to App\GraphQL\Directives 2. The RegisterDirectiveNamespaces event is dispatched to gather namespaces defined by plugins, extensions or other listeners 3. Lighthouse's built-in directive namespace. So it did seem like override could be possible, and it was. I haven't tried first method (App\GraphQL\Directive...) but that probably would work too, I went with the second method the RegisterDirectiveNamespaces event, since I was writing a package. Make all your directives in the same folder under one namespace eg: namespace SteveMoretz\Something\GraphQL\Directives; Now in a service provider (Can be your package's service provider or AppServiceProvider or any service provider you get the idea.) register that namespace your directives are under. use Illuminate\Contracts\Events\Dispatcher; use Nuwave\Lighthouse\Events\RegisterDirectiveNamespaces; class ScoutGraphQLServiceProvider { public function register(Dispatcher $dispatcher) { $dispatcher->listen( RegisterDirectiveNamespaces::class, static function (): string { return "SteveMoretz\Something\GraphQL\Directives"; } ); } } That's it so for an example I have overridden the @where directive, first I created a file named as original WhereDirective.php then put these contents in it: <?php namespace SteveMoretz\Something\GraphQL\Directives; use Nuwave\Lighthouse\Scout\ScoutBuilderDirective; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; use Nuwave\Lighthouse\Schema\Directives\BaseDirective; use Nuwave\Lighthouse\Schema\Directives\WhereDirective as WhereDirectiveOriginal; use Nuwave\Lighthouse\Support\Contracts\FieldResolver; class WhereDirective extends WhereDirectiveOriginal { public function handleBuilder($builder, $value): object { $clause = $this->directiveArgValue('clause', 'where'); // do some other stuff too... my custom logic return $builder->{$clause}( $this->directiveArgValue('key', $this->nodeName()), $this->directiveArgValue('operator', '='), $value ); } } Now whenever we use @where my custom directive runs instead of the original one, but be careful what you do in this directive don't alter the whole directive try to extend the original and add more options to it, otherwise you would end up confusing yourself later!
doc_23527767
I am creating this path (trA - which works just fine) and what I need is, is either remove a path trA after clicking on span #clean, or remove it after second click on span #tA. I don't mind which one will it be, but I just need to remove the path after the click. The second version would be of course better. HTML: <span class="trasa red" id="tA">TRASA A</span> <span class="trasa" id="clean">CLEAN</span> .js document.getElementById('tA').addEventListener('click', function() { var trA = rsr.path("M 34,33 L55,43 L222,78 L214,152 L144,150 L152,156 L205,255"); trA.attr({'stroke': 'red', 'stroke-width': '2'}); }, false); document.getElementById('clean').addEventListener('click', function() { trA.remove(); }, false); THX for any help! A: Your trA variable isn't in scope for the 2nd function, as it was defined in function scope of your first handler. Try this.. var trA; document.getElementById('tA').addEventListener('click', function() { trA = rsr.path("M 34,33 L55,43 L222,78 L214,152 L144,150 L152,156 L205,255"); trA.attr({'stroke': 'red', 'stroke-width': '2'}); }, false); document.getElementById('clean').addEventListener('click', function() { trA.remove(); }, false);
doc_23527768
Here is the code: Controller: @RequestMapping(value="/user/create",method=RequestMethod.GET) public String showCreatePage(Model model,Principal principal){ //model.addAttribute(new UserEntity()); model.addAttribute("body", "user/user-create-temp"); model.addAttribute("userInit", userService.getGeneralInfo(principal)); return "layouts/default"; } @RequestMapping(value = "/user/create", method = RequestMethod.POST) public String showCreateUser(Model model, @Valid GeneralDto userEntity,BindingResult result) { userService.saveUser(userEntity.getUserEntity()); return "redirect:/user/list"; } GeneralDto: public class GeneralDto { private List<BranchEntity> branchEntities = new ArrayList<BranchEntity>(); private UserEntity userEntity=new UserEntity(); public UserEntity getUserEntity() { return userEntity; } public void setUserEntity(UserEntity userEntity) { this.userEntity = userEntity; } public List<BranchEntity> getBranchEntities() { return branchEntities; } public void setBranchEntities(List<BranchEntity> branchEntities) { this.branchEntities = branchEntities; } } ThemeLeaf Form: <form class="form-horizontal" th:action="@{/user/create}" method="post" th:object="${userInit}" onsubmit="return validatePassword()"> <div class="box-body"> <div class="form-group form-group-code"> <label for="code" class="col-sm-2 control-label">User Name</label> <div class="col-sm-10"> <input type="hidden" th:field="*{userEntity.userId}"></input> <input type="text" th:field="*{userEntity.username}" class="form-control" placeholder="Username"></input> <div th:if="${#fields.hasErrors('userEntity.username')}"> <label th:errors="*{userEntity.username}" style="color: red"></label> </div> </div> </div> <div class="form-group"> <label for="fullName" class="col-sm-2 control-label">Full name</label> <div class="col-sm-10"> <input type="text" th:field="*{userEntity.fullName}" class="form-control" placeholder="Fullname"></input> <div th:if="${#fields.hasErrors('userEntity.fullName')}"> <label th:errors="*{userEntity.fullName}"></label> </div> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input type="email" th:field="*{userEntity.email}" class="form-control" placeholder="Email"></input> <div th:if="${#fields.hasErrors('userEntity.email')}"> <label th:errors="*{userEntity.email}"></label> </div> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Password</label> <div class="col-sm-10"> <input type="password" th:field="*{userEntity.password}" th:id="password" class="form-control" placeholder="Password"></input> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Confirm Password</label> <div class="col-sm-10"> <input type="password" class="form-control" placeholder="Confirm Password" id="confirm_password"></input> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">Branch </label> <div class="col-sm-4"> <select class="form-control" th:field="*{branchEntities}"> <option selected="selected" value="">Select Branch</option> <option th:each="branch : *{branchEntities}" th:value="${branch.branchId}" th:text="${branch.branchName}"></option> </select> </div> </div> <!-- <div class="form-group"> <label class="col-sm-2 control-label">Status</label> <div class="col-sm-10"> <label>Active <input type="radio" th:field="*{enabled}" value="" name="enabled" class="flat-red" checked="checked"></input> </label> <label>Inactive <input type="radio" th:field="*{enabled}" th:value="${userEntity.userId}" name="enabled" class="flat-red"></input> </label> </div> </div> --> <div></div> </div> <!-- /.box-body --> <div class="box-footer"> <button th:if="${userInit.userEntity.userId == null}" type="submit" class="btn btn-info pull-left">Submit</button> <button th:if="${userInit.userEntity.userId != null}" type="submit" class="btn btn-info pull-left">Update</button> <a th:href="@{/users}" type="submit" class="btn btn-danger pull-right">Cancel</a> </div> <!-- /.box-footer --> </form> A: in best practice when you add @Valid annotation beside any class always handle the errors.likeif(result.hasErrors()){ //do someething}. the problem is in your private List<BranchEntity> branchEntities = new ArrayList<BranchEntity>(); here, you are adding a list but user can't be in many branches. see the mapping of your branch and user table. A: The way it looks. I think it would be better for you to use branchId in your GeneralDto instead of branchEntities send the branchEntities via model.addAttribute("userInit",branchEntities); and show it to your drop down. And receive your branchId in your GeneralDto.
doc_23527769
i got 2 spiders = spider a and b spider a fetches some data and write it to a file. spider b reads that data. the problem is that spider b gets an empty file. I can see that the file is filled after spider a finishes hes job. I spent few hour to figure this out. code snippet: spider a f = open('file.txt', 'a+') f.write("str") f.write("\n") f.close() spider b f = open('file.txt') for line in f: print line f.close() Nothing comes out, what is wrong with this? EDIT:I got it to work. I open a file with 'a' write a line and then close the file. this goes for all lines. the code snippet was revised. A: (1) You want f.close() instead of f.close in "spider b". The way it is now, you are not properly closing the file, so its buffers aren't getting flushed. Also, regarding your use of f.flush() in "spider a" be sure you are aware of this note from the documentation: Note flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior. In fact, unless you have a good reason, it might be better to just close() the file. If you do have/want to flush it, be sure you also use os.sfsync(). (2) Also, instead of for line in f: print f try this: for line in f: print line As a final note, take a look at using with to manage open files. For instance with open('file.txt') as f: # put file related actions here for line in f: print line will automatically close the file at the end of the block for you or if an exception is encountered. A: Your example doesn't show any problems, except of two typos you've made with f.close() and print line. My guess is in your real code you try to iterate through file in b, then wait for a to add more data, and then b tries to continue interation. You can't do it. If iterator hit the end, it can't resume. Easiest way to get around this is to rewrite your code using f.readline(): while True: line = f.readline() if not line: break print line
doc_23527770
The problem is that I want to print them from the first (head) to the last (tail). Everything that I have tried has either resulted in a segmentation fault or prints only the first client. Note that the program is about a bank. I have a queue of customers that I want to print in order. Thank you in advance! void printAll(clientData* tail) { clientData *current; current = tail; if (current == NULL) { printf("There is no client in queue\n"); return ; } while (current != NULL) { printf("%s %s %d/%d/%d %s %s %s %s\n", current->firstname, current->lastname, current->birthday.day, current->birthday.month, current->birthday.year, current->bankaccount, current->telephone, current->email, current->bankcommand); current = current->next; } return; } A: What you need is a stack. Your system provides one automatically for you when you call a function recursively: void printAll(clientData* current) { if (current->next != NULL) { printAll(current->next); } printf("%s %s %d/%d/%d %s %s %s %s\n", current->firstname,current->lastname,current->birthday.day,current->birthday.month,current->birthday.year,current->bankaccount,current->telephone,current->email,current->bankcommand); }
doc_23527771
<Layout> <Route exact path='/' component={ Home } /> <Route path='/counter' component={ Counter } /> <Route path='/fetchdata/:startDateIndex?' component={ FetchData } /> </Layout>; type LayoutProps = LayoutState.LayoutState & typeof LayoutState.actionCreators; class Layout extends React.Component<LayoutProps, {}> { componentWillMount() { this.props.requestNavigationLinks(); } public render() { return <Grid fluid> <Row> <Col sm={3}> <NavMenu links={this.props.links}/> </Col> <Col sm={9}> {this.props.children} </Col> </Row> </Grid>; } } export default connect( (state: ApplicationState) => state.layout, LayoutState.actionCreators )(Layout) as typeof Layout; export interface LayoutState { isLoading: boolean; links: string[]; } The issue that I am having is that the typescript is complaining that the tag is missing properties being assigned to its props. Does the connect statement not automatically handle this? I am sure this is something easy I am missing and your help is appreciated. A: It has to do with the export line. I took it from the aspnet-spa example: export default connect( (state: ApplicationState) => state.layout, LayoutState.actionCreators )(Layout) as typeof Layout; Because of the as typeof Layout; verbiage, the component is expecting me to pass in all of those variables explicitly. Removing it solved my problem. A: I don't think requestNavigationLinks is a defined property in the LayoutState. You could try to add it to the interface. For example: export interface LayoutState { isLoading: boolean; links: string[]; requestNavigationLinks: func; }
doc_23527772
ExampleApp |- InterfaceFramework |-SDK |- InterfaceFramework I am unclear on how to set this up so that SDK is a pod that can be built by itself (to produce the framework to be used by external clients). It needs to know where the InterfaceFramework is or I get No such module errors. But this InterfaceFramework is generated by ExampleApp's Podfile...? What is the right way to go about configuring this?? Bonus karma for SPM instructions as well! (Though if I can sus cocoapods then hopefully that will follow) A: Ok the first (of many) things that perhaps Cocoapods.org doesn't make so clear is that if a Pod you are making has dependencies, then it's correct for it to have it's own Podfile. In other words, a cocoapod can use cocoapods... Perhaps I'm being daft but that wasn't immediately intuitive to me. That Podfile is just to get your pod code to build (compile/link) locally which is a requirement of pushing the podspec (whether it be to a private podspec repo or the CP public one). Note, when your pod code is pulled in by a client project, it just pulls your code. It doesn't do anything with pod's podfile and it doesn't package up those dependencies. The client app using your pod will need to take care of them (in their podfile, manually framework import, etc) Sanity check: If your pod doesn't have any dependencies then it doesn't need representation in the podfile (as a target). BUT...if you have a Demo Project in your pod repo there will still be a podfile for that (to pull your pod code). Note to newbies/absent minded: A single podfile covers all the targets in your workspace - in this case your pod's code and the demo app. These "targets" are independent (unless you nest them or something). NEXT: Podspec's don't tell you where to get the dependencies, just that your pod has them. BUT...the pod lib lint or pod repo push validations WILL look for the dependency in whatever podspec repos you specify (defaulting to just the public CP one). Fine for public depedencies but for local unhosted development ones it won't be able to find them. It's a bit lame IMO that your podfile can say a depedency is local (ie "development pod") but the podspec validator can't be told that. This is perhaps because CP was built initially for open source projects... So...you'll need to push your local dependencies' podspecs to your private podspec repo as well. This means the dependencies repos need to be accessible by whoever is using your pod. If you really (really) want them local-only on your machine (if not skip this paragraph...trust me), then you'll have to set up another private podspec repo locally, in a folder, just for the dependencies. The reason you need another private podspec repo is because you surely still want your pod's podspec available remotely (ie non-locally) or else no one would be able to pull your pod, defeating the point of having one... Sanity check: So...ignoring the above paragraph... your private podspec repo will have several entries: the podspec for your pod, and one for each of your private dependencies. NEXT...you're almost there!...When you want to lint/push your pod's podspec, you need to specify the list of podspec repos via --sources:repo1,repo2,.... It's not smart enough to just use your system registered ones. Boo. Also you may want to use a medley of vaguely defined seemingly overlaping and counter-intuitive flags to reign back the validation beast because, after all, you don't really care what CP thinks of your private pod code as long as It Just Works™. Here's an example from mine... pod repo push MyPrivatePodSpecRepo MyShinyNewPod.podspec --skip-tests --private --allow-warnings --skip-import-validation --sources=git@github.com:SnazzyCo/MyPrivatePodSpecRepo.git,https://cdn.cocoapods.org/ A few more notes... --skip-import-validation — This doesn't apply to the depedencies, just the pod itself. You'd think --include-podspecs=MyLocalUnHostedPods/**/* would save you all this trouble but it doesn't. I think --private is actually only for pod lib lint (pod repo push has a --no-private flag) but I'm too scared to remove it... pod repo push basically does a pod lib lint so save yourself the trouble of the later. Except you can run pod lib lint --quick to just check syntax (I think) FINALLY: * *Don't forget to have the client apps using your private pod to add a source 'urlToMyPrivatePodspecRepo' up top of their podfile. *I can't remember why but in order for the DemoApp in my pod repo to use the pod correctly I had to replace the pod MyShinyNewPod to podspec :path => 'MyShinyNewPod.podspec'
doc_23527773
The result is always false. I'm probably getting fetching the modulus and exponent incorrectly. Any ideas? Java applet code: protected MainApplet() { try { // CREATE RSA KEYS AND PAIR m_keyPair = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_1024); // STARTS ON-CARD KEY GENERATION PROCESS m_keyPair.genKeyPair(); // OBTAIN KEY REFERENCES m_publicKey = (RSAPublicKey) m_keyPair.getPublic(); m_privateKey = (RSAPrivateCrtKey) m_keyPair.getPrivate(); } catch (CryptoException c) { //this line will give you the reason of problem short reason = c.getReason(); ISOException.throwIt(reason); // for check } } ....... switch (INS) { case 0x00: getPublicKeyExp(apdu); break; case 0x10: getPublicKeyMod(apdu); break; case 0x21: signMessage(apdu); break; default: ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED); } } private void getExponent(APDU apdu) { byte[] buffer = apdu.getBuffer(); short length = m_publicKey.getExponent(buffer, ISO7816.OFFSET_CDATA); apdu.setOutgoingAndSend((short) 0, length); } private void getModulus(APDU apdu) { byte[] buffer = apdu.getBuffer(); short length = m_publicKey.getModulus(buffer, ISO7816.OFFSET_CDATA); apdu.setOutgoingAndSend((short) 0, length); } Java host code: /*************** EXECUTE COMMAND *************/ byte[] get_exponent = { (byte) 0x80, // CLA Class 0x00, // INS Instruction 0x00, // P1 Parameter 1 0x00, // P2 Parameter 2 0x00 // LE maximal number of bytes expected in result }; byte[] get_modulus = { (byte) 0x80, // CLA Class 0x10, // INS Instruction 0x00, // P1 Parameter 1 0x00, // P2 Parameter 2 0x00 // LE maximal number of bytes expected in result }; ResponseAPDU resp_modulus = channel.transmit(new CommandAPDU(get_modulus)); System.out.println(resp_modulus.toString()); ResponseAPDU resp_exponent = channel.transmit(new CommandAPDU(get_exponent)); System.out.println(resp_exponent.toString()); byte[] modulus = resp_modulus.getData(); byte[] exponent = resp_exponent.getData(); Code to create public key: RSAPublicKeySpec keySpec = new RSAPublicKeySpec(new BigInteger(1, modulus), new BigInteger(1, exponent)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); publicKey = keyFactory.generatePublic(keySpec); Code to verify message: byte[] get_signed_message = { (byte) 0x80, // CLA Class 0x21, // INS Instruction 0x00, // P1 Parameter 1 0x00, // P2 Parameter 2 0x00 // LE maximal number of bytes expected in result }; ResponseAPDU resp = channel.transmit(new CommandAPDU(get_signed_message)); System.out.println(resp.toString()); byte[] sigToVerify = resp.getData(); Signature sig = Signature.getInstance("SHA1withRSA"); sig.initVerify(publicKey); sig.update(sigToVerify); boolean verifies = sig.verify(sigToVerify); UPDATE: Java applet signature method byte[] testSig = new byte[256]; byte[] test = {0x01, 0x02, 0x04, 0x05, 0x06, 0x07}; // CREATE SIGNATURE OBJECT Signature m_sign = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false); // INIT WITH PRIVATE KEY m_sign.init(m_privateKey, Signature.MODE_SIGN); short len = m_sign.sign(test, (short) 0, (short) test.length, testSig, (short) 0); apdu.setOutgoing(); apdu.setOutgoingLength(len); apdu.sendBytesLong(testSig, (short) 0, len); A: The problem is in these two methods getExponent() and getModulus(). You are storing exponent and modulus into buffer's index ISO7816.OFFSET_CDATA (index 5) but sent it outside from buffer's index 0. Compare the correct approachs with the wrong approach: Wrong: private void getExponent(APDU apdu) { byte[] buffer = apdu.getBuffer(); short length = m_publicKey.getExponent(buffer, ISO7816.OFFSET_CDATA); apdu.setOutgoingAndSend((short) 0, length); // not the valid public exp } private void getModulus(APDU apdu) { byte[] buffer = apdu.getBuffer(); short length = m_publicKey.getModulus(buffer, ISO7816.OFFSET_CDATA); apdu.setOutgoingAndSend((short) 0, length); // not the valid mod } Correct 1 (appreciated): private void getExponent(APDU apdu) { byte[] buffer = apdu.getBuffer(); short length = m_publicKey.getExponent(buffer, (short) 0); apdu.setOutgoingAndSend((short) 0, length); } private void getModulus(APDU apdu) { byte[] buffer = apdu.getBuffer(); short length = m_publicKey.getModulus(buffer, (short) 0); apdu.setOutgoingAndSend((short) 0, length); } Correct 2: private void getExponent(APDU apdu) { byte[] buffer = apdu.getBuffer(); short length = m_publicKey.getExponent(buffer, ISO7816.OFFSET_CDATA); apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, length); } private void getModulus(APDU apdu) { byte[] buffer = apdu.getBuffer(); short length = m_publicKey.getModulus(buffer, ISO7816.OFFSET_CDATA); apdu.setOutgoingAndSend(ISO7816.OFFSET_CDATA, length); } EDIT: In your host application, you need the followings: byte[] test = {0x01, 0x02, 0x04, 0x05, 0x06, 0x07}; sig.update(test); boolean verifies = sig.verify(sigToVerify); To verify a Signature, you need * *a Public Key *a verification mechanism (say SHA1withRSA) *Plain Text (from which the signature was generated) *Signature
doc_23527774
div { padding-left: 20px; padding-right: 20px; text-align: center; float: left; border: solid 1px #f1f1f1; border-top: solid 1px #ccc; border-tottom: none; color: #ccc; margin: 8px; } span { padding: 10px; min-height: 30px; background: #3f47f2; color: orange; } p { clear=both; } <div> |<br /> <span>Cap</span> <p>&nbsp;</p> <div> |<br /> <span>CT-1</span> <p>&nbsp;</p> <div> |<br /> <span>CT-1-A</span> </div> <div> |<br /> <span>CT-1-B</span> </div> </div> <div> |<br /> <span>CT-2</span> <p>&nbsp;</p> <div> |<br /> <span>CT-2-A</span> </div> <div> |<br /> <span>CT-2-B</span> </div> <div> |<br /> <span>CT-2-C</span> </div> </div> <div> |<br /> <span>CT-3</span> <p>&nbsp;</p> <div> |<br /> <span>CT-3-A</span> </div> </div> </div> If you run the snippet it shows what I do NOT want. What I want is it to be on 3 rows as per this crude example: CAP CT1 CT2 CT3 CT1-A CT1-B CT2-A CT2-B CT2-C CT3-A I don't know how to achieve this. Nor do I know why it doesn't do this. Even if I try to give it a width of 1000% it still wraps! A: Added white-space: nowrap; display: inline-block; to div Removed float rule declared and invalid (typo) rule "border-tottom: none;" div { padding-left: 20px; padding-right: 20px; text-align: center; border: solid 1px #f1f1f1; border-top: solid 1px #ccc; color: #ccc; margin: 8px; white-space: nowrap; display: inline-block; } span { padding: 10px; min-height: 30px; background: #3f47f2; color: orange; } p { clear=both; } <div> |<br /> <span>Cap</span> <p>&nbsp;</p> <div> |<br /> <span>CT-1</span> <p>&nbsp;</p> <div> |<br /> <span>CT-1-A</span> </div> <div> |<br /> <span>CT-1-B</span> </div> </div> <div> |<br /> <span>CT-2</span> <p>&nbsp;</p> <div> |<br /> <span>CT-2-A</span> </div> <div> |<br /> <span>CT-2-B</span> </div> <div> |<br /> <span>CT-2-C</span> </div> </div> <div> |<br /> <span>CT-3</span> <p>&nbsp;</p> <div> |<br /> <span>CT-3-A</span> </div> </div> </div> A: You have to add min-width to container div. So here it is min-width:1024px;overflow:auto; https://jsfiddle.net/t4vmy2vj/1/
doc_23527775
"Angular Lifecycle Hooks": { "prefix": "nglifecycle", "body": [ "ngOnChanges() {", "\t// called before any bindings are made and before ngOnInit()", "\t// Here you can access the change detection results, and make any updates you want.", "\tconsole.log('ngOnChanges');", "}", "", "ngOnInit() {", "\t// called once after the first ngOnChanges()", "\tconsole.log('ngOnInit');", "}", "" ], "description": "Angular Lifecycle Hooks Snippet" } Is there a way to do so? Example for what I'm trying to achieve: The snippet generate the text in the body tag, let's say use it in line number 15. And I have this line, near the top of the file import {Component} from '@angular/core' I'm looking for a way that the snippet will update that line to import {Component, OnInit, OnChange} from '@angular/core' You see it is adding OnInit and OnChange which were added in the snippet body as ngOnChnages() and ngOnInit(). A: You cannot do that solely with built-in functionality, but it is pretty easy with an extension. For example, Find and Transform (disclaimer: I wrote it), allows you to insert the snippet AND do a find and replace elsewhere in the document. Using this keybinding (in your keybindings.json): { "key": "alt+d", // whatever keybinding you want "command": "findInCurrentFile", "args": { "preCommands": { "command": "editor.action.insertSnippet", "args": { "name": "Angular Lifecycle Hooks" } }, "find": "(?<=^import\\s*\\{)(\\s*[^}]*?)(?=\\s*\\}\\s*from\\s*'@angular\/core'$)", "replace": "$1, OnInit, OnChange", "isRegex": true, "postCommands": "cancelSelection" }, "when": "editorTextFocus && !editorReadonly && editorLangId == javascript" }, Your Angular Lifecycle Hooks snippet is still located in some snippets file. The keybinding first inserts the snippet at the cursor and then does a find/replace for your import {Component} from '@angular/core' text. Note: if your langID is not javascript swap that part with your file's language identifier - click on the language in the lower right-hand corner of the window and see the language ID, in parentheses like (javascript) - just use the part in the parentheses. The regex find works if there are leading or trailing spaces in the {}, and Component does not need to be there already. The additions onInit and onChange will simply be added to whatever is already there. If need be, the regex could be modified to handle other cases. * *Also, this uses a keybinding to trigger essentially a macro extension. I doubt there is any way to accomplish what you want solely with a snippet prefix (unless you write a custom extension) and have that snippet prefix trigger both a snippet insertion and an edit elsewhere in the document. A: Snippet is an elementary functionality to add some text with modification of selected part of document and some other smple things. It doesn't know anything about rest part of your document. But since you added vscode-extensions tag, maybe you can write your own simple extension doing the things you want :) With its help you can modify document after snippet was inserted
doc_23527776
They authors of the paper created this data set for the estimations. R> set.seed( 123 ) R> cesData <- data.frame(x1 = rchisq(200, 10), x2 = rchisq(200, 10), x3 = rchisq(200, 10), x4 = rchisq(200, 10) ) R> cesData$y2 <- cesCalc( xNames = c( "x1", "x2" ), data = cesData, + coef = c( gamma = 1, delta = 0.6, rho = 0.5, nu = 1.1 ) ) R> cesData$y2 <- cesData$y2 + 2.5 * rnorm( 200 ) R> cesData$y3 <- cesCalc(xNames = c("x1", "x2", "x3"), data = cesData, coef = c( gamma = 1, delta_1 = 0.7, delta = 0.6, rho_1 = 0.3, rho = 0.5, + nu = 1.1), nested = TRUE ) R> cesData$y3 <- cesData$y3 + 1.5 * rnorm(200) R> cesData$y4 <- cesCalc(xNames = c("x1", "x2", "x3", "x4"), data = cesData, coef = c(gamma = 1, delta_1 = 0.7, delta_2 = 0.6, delta = 0.5, rho_1 = 0.3, rho_2 = 0.4, rho = 0.5, nu = 1.1), nested = TRUE ) R> cesData$y4 <- cesData$y4 + 1.5 * rnorm(200) The first line sets the“seed”for the random number generator so that these examples can be replicated with exactly the same data set. The second line creates a data set with four input variables (called x1, x2, x3, and x4) that each have 200 observations and are generated from random χ2 distributions with 10 degrees of freedom. The third, fifth, and seventh commands use the function cesCalc, which is included in the micEconCES package, to calculate the deterministic output variables for the CES functions with two, three, and four inputs (called y2, y3, and y4, respectively) given a CES production function. Now in my paper I'm trying to estimate the CES function for the U.S. at the Aggregate Level for the two input case with capital and labor. So what I did is I gathered data from the World Bank Data Base from 1990-2015, where I used Gross Fixed Capital Formation for capital and total Labor Force for Labor. The authors did f.e. a non linear estimation the following way R> cesNls <- nls( y2 ~ gamma * ( delta * x1^(-rho) + (1 - delta) * x2^(-rho) )^(-phi / rho), + data = cesData, start = c( gamma = 0.5, delta = 0.5, rho = 0.25, phi = 1 ) ) R> print( cesNls ) Now I want the exact same thing for my own data Set which is called Data_Extract_From_World_Development_Indicators. So what I did is firstly ceslan <- cesCalc( xNames = c( "GrossFixedCapitalFormation", "LaborForce" ), data = Data_Extract_From_World_Development_Indicators, coef = c( gamma = 1, delta = 0.6, rho = 0.5, nu = 1.1 ) ) So i replicated R> cesData$y2 <- cesCalc( xNames = c( "x1", "x2" ), data = cesData, coef = c( gamma = 1, delta = 0.6, rho = 0.5, nu = 1.1 ) ) All I did was changing the name of the Dataset and replaced x1 and x2 with my two variables for capital and Labor. Afterwards I tried to do the non linear estimation cesulan <- nls(y2 ~ gamma * (delta * GrossFixedCapitalFormation^(-rho) + (1-delta)*LaborForce^(-rho))^(-phi / rho), data = Data_Extract_From_World_Development_Indicators, start = c(gamma = 0.5, delta = 0.5, rho = 0.25, phi = 1) ) Now this is where my Problem is: I dont know what variable is meant to be y2 in my dataset. I can see in the formula that y2 ~ gamma *... so ist plotted against the rest of the term, but I dont know what Kind of value I need to plug in there. Does anyone have any advice? Thanks in advance A: In Hennigsen &Hennisgen (2011), the variable y2 is created with the function cesCalc. It is perturbed in order to theoretically test the introduced function cesEst. This variable is supposed to be your function's Output (usually Gross Domestic Product, but not exclusively). this must be a series (a R column of a dataframe) of numerical non-negative values, of size equal to your other explanatory variables x1 and x2.
doc_23527777
import tensorflow as tf is responded by: ImportError: cannot import name 'saveable_objects_from_trackable' from 'tensorflow.python.training.saving.saveable_object_util' (C:\Users\Lior\AppData\Roaming\Python\Python39\site-packages\tensorflow\python\training\saving\saveable_object_util.py) I had a working tf so how did I accidently came here? I tried to fix the problem of Tensorflow 2.0 list_physical_devices doesn't detect my GPU one of the things I did was rm -rf anaconda_folder Becose I thought that how you need to remove your tf before install it again with GPU detection. Sagnificant remark about my tf version: Name: tensorflow Version: 2.8.0 Summary: TensorFlow is an open source machine learning framework for everyone. Home-page: https://www.tensorflow.org/ Author: Google Inc. Author-email: packages@tensorflow.org License: Apache 2.0 Location: c:\users\lior\appdata\roaming\python\python39\site-packages Requires: absl-py, astunparse, flatbuffers, gast, google-pasta, grpcio, h5py, keras, keras-preprocessing, libclang, numpy, opt-einsum, protobuf, setuptools, six, tensorboard, tensorflow-io-gcs-filesystem, termcolor, tf-estimator-nightly, typing-extensions, wrapt Required-by:
doc_23527778
Now, if I am only querying on both a and b (never on either field by itself), which of the following two indexes is better and why: * *{a: 1, b : 1} *{b: 1, a : 1} Explain seems to return almost identical results, but I read somewhere that you should put higher selectivity fields first. I don't know why that would make sense though. A: After some extensive work to improve queries on a 150 000 000 records database I have found out the following: not necessarily higher selectivity fields, but actually fields that are "faster" to match, being moved to the first position can increase performance drastically I had an index composed of the following fields: zip, address, city, first name, last name Address is matched by an array, not string = string so it takes most time to execute and is the slowest to match. My first index that I created was: address_zip_city_last_name_first_name and the execution time for matching 1000 records against the whole DB would go for hours. Address field actually probably has the highest selectivity on these, but since it is not being matched by a simple string equality, it takes the most time. It actually goes something like this { address: {$all : ["1233", "main", "avenue] }} By changing this index to having the "faster" fields in the beginning, for example: zip_city_first_name_last_name_address the performance was much better. The same 1000 records would match in just one second instead for going for hours. Hope this helps someone cheers A: After doing some further analysis the two indexes are in fact pretty much identical from a performance point of view. Really if you are in a similar situation, the real consideration should be whether in the future you might be more likely to query on a alone or b alone, and put that field first in the index. A: I believe the optimiser will choose the index best to use, although you can provide hints e.g. db.collection.find({user:u, foo:d}).hint({user:1}); see http://www.mongodb.org/display/DOCS/Optimization
doc_23527779
My current workflow: grep --include=*.php -R -l "tribe_events_event_classes" . Which outputs: ./plugins/events-calendar-pro/views/day/loop.php ./plugins/events-calendar-pro/views/map/loop.php ./plugins/events-calendar-pro/views/photo/loop.php ./plugins/events-calendar-pro/views/widgets/mini-calendar/list.php ./plugins/the-events-calendar/lib/tribe-template-factory.class.php ./plugins/the-events-calendar/public/template-tags/general.php ./plugins/the-events-calendar/views/list/loop.php ./plugins/the-events-calendar/views/month/single-event.php ./themes/roots/tribe-events/day/loop.php Then I usually copy and paste the files one by one with: subl ./plugins/events-calendar-pro/views/day/loop.php subl ./plugins/events-calendar-pro/views/map/loop.php etc... I know here has to be a more efficient way to do this. A: The easiest way to do this would be: subl `grep --include=*.php -R -l "tribe_events_event_classes" .` (note the backticks). Or: for file in `grep --include=*.php -R -l "tribe_events_event_classes" .`; do subl $file done EDIT Since backticks don't nest well, using command substitution is better: subl $(grep --include=*.php -R -l "tribe_events_event_classes" .) A: A bash script could solve this nicely. Here is an untested concept (may require some tweaking): #!/bin/bash files=() while grep --include=*.php -R -l "tribe_events_event_classes" .; do files += ("$REPLY") done for file in "${files[@]}"; do subl $file done
doc_23527780
Map.js import Script from 'next/script'; export default Map() { const createMap = () => { // set access token mapboxgl.accessToken = 'xxxxxxxxxxxxxxx...'; // create map const map = new mapboxgl.Map({...}); } return ( <> <Script onLoad={() => { createMap(); }} src="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js" /> <div id="map"></div> </> ); } 1 - If I have multiple instances of <Map /> on a page, will Next.js load this script multiple times? Is there a better way to load this script once, globally and synchronously? It doesn't seem to work if I load it in my _document.js page. Or is this not an issue? 2 - I also have to load the CSS file. Right now I have it loaded on the page that has the map on it. pages/contact.js import Head from 'next/head'; export default function PageContact() { return ( <Head> <link href="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css" rel="stylesheet" /> </Head> ); } If I add maps to other pages, I'd have to include this CSS file on all those other pages, resulting in a lot of duplication. Should I abstract this <Head> to its own component and include that on each page? Or should I be moving this <Head> component into the <Map> component? It makes sense to centralize this style in one place, but at that point, just like the <Script>, I'm guessing Next.js would load the CSS file each time the component is instantiated, so if a page had more than one map on it, the CSS would be loaded multiple times. What is the best way to load Mapbox in a Next.js project?
doc_23527781
head(df, 9) Day variable value 1 2015-10-18 Number_Flows.minimum 401.0000 2 2015-10-18 Number_Flows.maximum 2068.0000 3 2015-10-18 Number_Flows.average 1578.9474 4 2015-10-18 Number_srcaddr.minimum 95.0000 5 2015-10-18 Number_srcaddr.maximum 292.0000 6 2015-10-18 Number_srcaddr.average 222.6316 7 2015-10-18 Number_dstaddr.minimum 65.0000 8 2015-10-18 Number_dstaddr.maximum 411.0000 9 2015-10-18 Number_dstaddr.average 202.5789 What I want to do is plot minimum, maximum, average for each Number_Flows, Number_srcaddr, etc. I 'd rather have bars displaying the value but I am open for other methods as well, as long as I get (e.g. for reproducible example posted below) a total of 22 charts (11 for each day). I tried various things but no luck. library(dplyr) library(ggplot2) ggplot(df %>% mutate(group = paste(Day, gsub('\\..*', '', variable), sep = '-')), aes(x = Day, y = value))+geom_bar(stat = 'identity')+facet_wrap(~group) ggplot(df %>% mutate(group = paste(Day, gsub('\\..*', '', variable), sep = '-')), aes(x = Day, y = value))+geom_bar(stat = 'identity')+facet_wrap(~group) ggplot(df %>% mutate(group = paste(Day, gsub('\\..*', '', variable), sep = '-')), aes(x = Day, y = value))+geom_line()+facet_wrap(~group) DATA dput(df) structure(list(Day = structure(c(1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445115600, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000, 1445202000), class = c("POSIXct", "POSIXt" ), tzone = ""), variable = c("Number_Flows.minimum", "Number_Flows.maximum", "Number_Flows.average", "Number_srcaddr.minimum", "Number_srcaddr.maximum", "Number_srcaddr.average", "Number_dstaddr.minimum", "Number_dstaddr.maximum", "Number_dstaddr.average", "Sum_packets.minimum", "Sum_packets.maximum", "Sum_packets.average", "Sum_duration_nannosecs.minimum", "Sum_duration_nannosecs.maximum", "Sum_duration_nannosecs.average", "Average_Duration.minimum", "Average_Duration.maximum", "Average_Duration.average", "Average_Bytes.minimum", "Average_Bytes.maximum", "Average_Bytes.average", "Bytes_per_packet.minimum", "Bytes_per_packet.maximum", "Bytes_per_packet.average", "Sum_of_Bytes.minimum", "Sum_of_Bytes.maximum", "Sum_of_Bytes.average", "Actual_Batch_Duration_secs.minimum", "Actual_Batch_Duration_secs.maximum", "Actual_Batch_Duration_secs.average", "packets_per_second.minimum", "packets_per_second.maximum", "packets_per_second.average", "Number_Flows.minimum", "Number_Flows.maximum", "Number_Flows.average", "Number_srcaddr.minimum", "Number_srcaddr.maximum", "Number_srcaddr.average", "Number_dstaddr.minimum", "Number_dstaddr.maximum", "Number_dstaddr.average", "Sum_packets.minimum", "Sum_packets.maximum", "Sum_packets.average", "Sum_duration_nannosecs.minimum", "Sum_duration_nannosecs.maximum", "Sum_duration_nannosecs.average", "Average_Duration.minimum", "Average_Duration.maximum", "Average_Duration.average", "Average_Bytes.minimum", "Average_Bytes.maximum", "Average_Bytes.average", "Bytes_per_packet.minimum", "Bytes_per_packet.maximum", "Bytes_per_packet.average", "Sum_of_Bytes.minimum", "Sum_of_Bytes.maximum", "Sum_of_Bytes.average", "Actual_Batch_Duration_secs.minimum", "Actual_Batch_Duration_secs.maximum", "Actual_Batch_Duration_secs.average", "packets_per_second.minimum", "packets_per_second.maximum", "packets_per_second.average" ), value = c(401, 2068, 1578.94736842105, 95, 292, 222.631578947368, 65, 411, 202.578947368421, 4181, 130567, 33860.2631578947, 2647278, 10876533, 5438303.63157895, 1543.937984, 20335.58603, 4202.062837, 692.4193548, 77207.90476, 14689.4305788105, 231.6654261, 943.7592654, 465.315475931579, 1244970, 123223816, 19865244, 9, 30, 27.1578947368421, 179, 4352, 1265.94736842105, 609, 2352, 1578.94736842105, 89, 299, 219.105263157895, 92, 402, 193.578947368421, 1124, 60473, 19022.6842105263, 944317, 20088618, 5254959.84210526, 1550.602627, 9749.356239, 3236.99523905263, 258.9441708, 17451.96293, 5789.86937011053, 140.2998221, 717.4807734, 424.926870810526, 157697, 33505216, 9510806.21052632, 5, 30, 24.9473684210526, 114, 2179, 772.947368421053 )), .Names = c("Day", "variable", "value"), row.names = c(NA, 66L), class = "data.frame") A: I like to use lines for trends over times, and ribbons to show ranges of values. Similar to @docendo I would separate first, but I would then spread after: library(tidyverse) df %>% separate(variable, c("type", "var"), sep = "\\.") %>% spread(var, value) %>% ggplot(aes(Day)) + geom_line(aes(y = average), size = 1) + geom_ribbon(aes(ymin = minimum, ymax = maximum), alpha = 0.2) + facet_wrap(~type, scales = 'free_y') + theme(axis.text.x=element_text(angle = 90, vjust = 0.5)) This will look better if you have more days. A: I would start by separating the "variable" column before plotting: library(dplyr) library(ggplot2) library(tidyr) df %>% separate(variable, c("type", "var"), sep = "\\.") %>% ggplot(aes(x = Day, y = value, color = var)) + geom_point() + facet_wrap(~type) + theme(axis.text.x=element_text(angle = -90, hjust = 0)) You can easlily make this more informative by using free y-scales, bars instead of points etc. A: A base R solution (or almost: it uses reshape2): First you create the variables "type" and "stat", then you split your data.frame by day, then reshape your data.frame to have the needed shape and finally plot it with barplot (I let you customise the barplot). You can keep the days (and use it later as main title) by modifying a bit the lapply call, using the names of the list. df$type <- sub("([^.]+)\\..+", "\\1", df$variable) df$stat <- sub("[^.]+\\.(.+)", "\\1", df$variable) l_df <- split(df, df$Day) library(reshape2) par(mfrow=c(2, 1)) lapply(l_df, function(df_day){ df_resh <- dcast(type~stat, value.var="value", data=df_day) row.names(df_resh) <- df_resh$type barplot(t(df_resh[, -1]), beside=TRUE, legend=TRUE, col=c("green", "blue", "red"))}) A: You can try library(stringr) df$var1 <- unlist(lapply(str_split(df$variable, "[.]"), "[", 1)) df$var2 <- unlist(lapply(str_split(df$variable, "[.]"), "[", 2)) ggplot(df, aes( x=var2, y= value)) + geom_bar(stat = 'identity') + facet_wrap(var1 ~ Day, scales = "free_y")
doc_23527782
CREATE ALIAS IF NOT EXISTS PKG_DATA_INGESTION.F_GET_CONFIGURATION_COMPONENTS FOR "com.db.aminet.cucumbertests.Orchestrator.H2databaseProc.selectComponentsConfig"; The java class for the given package : public class H2databaseProc { public static ResultSet selectComponentsConfig(final String componentConfig, final Date executionDate) throws SQLException { String h2Pwd=EncrypterFactory.getEncrypter().decrypt("ENC(bZO5WqcDhckxAFZhcZD5+6g3vbMMOZuwTHmtNKuIhBe4+oFdaDwintZvbNqDQYGj)"); Connection conn = DriverManager.getConnection("jdbc:h2:mem:test", "sa", h2Pwd); PreparedStatement controlComponent = conn.prepareStatement("select PROPERTY_KEY, PROPERTY_VALUE from component_config where COMPONENT_ID = ? and INIT_DATE <= TO_DATE(?, 'YYYY-MM-DD') and (END_DATE is NULL OR END_DATE >= TO_DATE(?, 'YYYY-MM-DD')) and IS_LIST = 0; "); controlComponent.setString(1, componentConfig); controlComponent.setDate(2, executionDate); ResultSet rs = controlComponent.executeQuery(); return rs; } } calling the package in java : conn = DriverManager.getConnection(this.jdbcUrlDB, this.usernameDB, this.passwordDB); cstmt = conn.prepareCall("{? = call PKG_DATA_INGESTION.F_GET_CONFIGURATION_COMPONENTS(?, ?)}"); cstmt.registerOutParameter(1, -10); cstmt.setString(2, this.componentID); cstmt.setDate(3, new java.sql.Date(this.date.getTime())); cstmt.execute(); Error I am getting : org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement " ? = CALL PKG_DATA_INGESTION.F_GET_CONFIGURATION_COMPONENTS([*]?, ?) "; SQL statement: ? = call PKG_DATA_INGESTION.F_GET_CONFIGURATION_COMPONENTS(?, ?) [42000-176] at org.h2.message.DbException.getJdbcSQLException(DbException.java:344)
doc_23527783
<DOCUMENT> <IDS>53850_WP</IDS> <FULL_NAME>Maybank</FULL_NAME> <AD_WEIGHT>60</AD_WEIGHT> <MAP>200:37.3321363,-122.0278287</MAP> <PHONE>00-2222 3466</PHONE> <CLASS_DESC>Banks</CLASS_DESC> </DOCUMENT> <DOCUMENT> <IDS>53850_WP</IDS> <FULL_NAME>Maybank</FULL_NAME> <AD_WEIGHT>60</AD_WEIGHT> <MAP>200:37.3321363,-122.0278287</MAP> <PHONE>00-2222 3466</PHONE> <CLASS_DESC>Banks</CLASS_DESC> </DOCUMENT> <DOCUMENT> <IDS>53850_WP</IDS> <FULL_NAME>Maybank</FULL_NAME> <AD_WEIGHT>60</AD_WEIGHT> <MAP>200:37.3321363,-122.0278287</MAP> <PHONE>00-2222 3466</PHONE> <CLASS_DESC>Banks</CLASS_DESC> </DOCUMENT> How do I split the <MAP> value to lat and long? The <MAP> node is a coordinate. And, how to mark those locations in Google Maps? I'm using JSP. I don't know how to add multiple markers to the map. A: To learn more about parsing XML in JavaScript, you can look at this answer on stackoverflow: https://stackoverflow.com/a/8412989/1314132. To learn more about placing a google.maps.Markerapi-doc on the map, take a look at the Markers section of the Developer's Guide.
doc_23527784
Is there a way the code can pull the sheet name from a cell. That way I can type the sheet name into a cell and the code will reference that. So instead of typing in the sheet name "Hello" for example, it would just reference the cell "F20" to get that cell value. A: Should be ActiveSheet.Cells(20, 6).Value A: Yes you can, ActiveSheet.Name = Range("F20") A: You can pass the cell value containing Sheet name to a variable and then use that Variable to select the sheet. For multiple sheets you can use the loop to select and take action. Sub test() shtName = Range("A1") Sheets(shtName).Select End Sub
doc_23527785
Can someone please suggest a fix, Attaching the code in snippets body { background: grey; } a.button { display: inline-block; -webkit-appearance: button; -moz-appearance: button; appearance: button; text-decoration: none; background-color: black; border: 1px solid white; color: white; padding: 15px 32px; text-align: center; text-decoration: none; font-size: 16px; } <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>CSS BUTTON</title> </head> <body> <a href="#test" class="button">Click Me</a> </body> </html> A: Use -webkit-appearance: none; to turn off iOS default button styling, not "button". A great article here. And I've attached code for your button to work: body { background: blue; } a.button { display: inline-block; /*-webkit-appearance: button; -moz-appearance: button; appearance: button;*/ -webkit-appearance: none; text-decoration: none; background-color: black; border: 1px solid white; color: white; padding: 15px 32px; text-align: center; text-decoration: none; font-size: 16px; } <a href="#test" class="button">Click Me</a> A: When you remove the property -webkit-appearance: button; or set to 'none' the button takes the effect. I think that appearance properties do not take border effects A: When using the -webkit-appearance property it's purpose is to provide the browser a way to display an element using platform-native styling based on the operating system's theme. This leads to the operating system's styling interfering with your custom css. To apply custom styling you want to set -webkit-appearance to none in addition to your custom css. Here's how you can use custom styling: input { -webkit-appearance: none; -moz-appearance: none; -ms-appearance: none; appearance: none; display: inline-block; vertical-align: middle; } input[type="checkbox"] { border: 2px solid #555; width: 20px; height: 20px; outline: none; padding: 4px; } input[type="checkbox"]:checked { background: #555; background-clip: content-box; } input[type="radio"] { border: 2px solid #555; border-radius: 10px; width: 20px; height: 20px; outline: none; padding: 4px; } input[type="radio"]:checked { background: #555; background-clip: content-box; } p, h3 { color: #333; font-family: helvetica, arial; } label { display: inline-block; vertical-align: middle; margin: 0 0 -2px 8px; } <h3>Check:</h3> <p><input type="checkbox"></input><label>Include Options</label></p> <h3><br/>Select one:</h3> <p><input type="radio" name="radio"></input><label>Option A</label></p> <p><input type="radio" name="radio"></input><label>Option B</label></p> A: You are making button to -webkit-appearance-button so that makes border not visible. a.button { display: inline-block; text-decoration: none; background-color: black; border: 5px solid red; color: white; padding: 15px 32px; text-align: center; text-decoration: none; font-size: 16px; } <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>CSS BUTTON</title> </head> <body> <a href="#test" class="button">Click Me</a> </body> </html>
doc_23527786
Thanks! Update: I created a node and specified the position of it, by writing this way; let node = SKSpriteNode() node.position = CGPoint(x:self.frame.size.width/2, y:self.frame.size.height/2) node.size = CGSize(width: 100, height: 100) node.color = SKColor.red self.addChild(node) Why is it somewhere else like different place from the specified location? I firstly thought there was a change in Swift3 and the depresciation of CGPointMake caused this problem, but it does not seem like it is the cause. In this case, is the use of CGRect better? It is very helpful if you could write code that fixs this position issue. Again, thank you for your help. A: C global functions like CGRectGetMidX/Y, CGPointMake, etc. shouldn't be used in Swift (they're deprecated in Swift 2.2, removed in Swift 3). Swift imports CGRect and CGPoint as native types, with initializers, instance methods, etc. They're much more natural to use, and they don't pollute the global name space as the C functions once did. let point = CGPoint(x: 0, y: 0) //replacement of CGPointMake let rect = CGRect(x: 0, y: 0, width: 5, height: 5) //replacement of CGRectMake let midX = rect.midX //replacement of CGRectGetMidX let midY = rect.midY //replacement of CGRectGetMidY Their respect API reference is linked above. You might also find the CoreGraphics API reference handy too. A: In Swift you shouldn't use those old style notations. Just use the constructors and properties: let point = CGPoint(x: 1, y: 2) let rect = CGRect(x: 1, y: 2, width: 3, height: 4) let mx = rect.midX A: Have too many center calculations in your code. Use this. extension CGRect { var center : CGPoint { get { return CGPoint(x:self.midX, y: self.midY) } } }
doc_23527787
getSelect(); But I can get query from only the model collections, not worked in others or May be I dont know how to use it. Here I want to know what query is running behind this, $productModel = Mage::getModel('catalog/product')->getCollection(); $attr = $productModel->getResource()->getAttribute("color"); if ($attr->usesSource()) { echo $color_label = $attr->getSource()->getOptionText("28"); } If I use this, echo $productModel->getSelect(); exit; I'm just get the one part the query only, like, SELECT `e`.* FROM `catalog_product_entity` AS `e` Update: This is my full code, <?php require_once('app/Mage.php'); //Path to Magento umask(0); Mage::app(); $productModel = Mage::getModel('catalog/product')->getCollection(); $attr = $productModel->getResource()->getAttribute("color"); if ($attr->usesSource()) { $color_label = $attr->getSource()->getOptionText("28"); } $productModel->printlogquery(true);exit; Please help me guys, A: Your order condition is not visible in the query. The reason your order isn't showing is because the orders are added to the query during the load() method. See Varien_Data_Collection_Db::load() Try calling load(true) to see the complete SQL containing the order by clause. $productModel->load(true); $productModel->printLogQuery(true); Hope it helps. A: If you want to see what is the exact query, then you can get this by using: $productModel->printlogquery(true);exit; Use this code after you have loaded your model's object and applied all conditions. I hope this will help you. A: Magento collecting data with lot of internal queries - models and lot of checks, and may be more than 1 table. So it is not possible to get the query like what I'm looking for.
doc_23527788
I have some sales data which looks like this: data have; input order_id item $; cards; 1 A 1 B 2 A 2 C 3 B 4 A 4 B ; run; What I'm trying to find out is what are the most popular combinations of items ordered. For example in the above case, there were 2 orders that contained items A&B, 1 order of A&C, and 1 order of B. What would be the best way to output the different combinations along with the numbers of orders placed? A: It seems there is no permutation issue, you could try this: proc sort data=have; by order_id item; run; data temp; set have; by order_id; retain comb; length comb $4; comb=cats(comb,item); if last.order_id then do; output; call missing(comb); end; run; proc freq data=temp; table comb/norow nopercent nocol nocum; run; A: There are many possible approaches to this problem, and I would not presume to say which is the best. Here's a fairly simple method you could use: * *Transpose your data so that you only have 1 row for each order, with an indicator variable for each product. *Feed the transposed dataset into proc corr to produce a correlation matrix for the indicator variables, and look for the strongest correlations.
doc_23527789
This code works perfectly, it make an animation of a spinning bar step = 0 for x in range (0,50): animation = {0: '|', 1: '/', 2: '-', 3: '\\' }[step] tqdm.write(animation, end='\r') step = (step+1) % 4 time.sleep(0.1) But if I create progress bar just before : bar = tqdm(total=100) # Here step = 0 for x in range (0,50): animation = {0: '|', 1: '/', 2: '-', 3: '\\' }[step] tqdm.write(animation, end='\r') step = (step+1) % 4 time.sleep(0.1) I have just a display of the progress bar. Any ideas ? A: This was reported as an issue in the official tqdm github. https://github.com/tqdm/tqdm/issues/520 The author suggested a correction by using a prefix instead of end from time import sleep from tqdm import tqdm, trange from tqdm._utils import _term_move_up prefix = _term_move_up() + '\r' print('') for x in trange(50): tqdm.write(prefix + "|/-\\"[x % 4]) sleep(0.1)
doc_23527790
<meta name="" content=""> and <meta property="" content=""> what is the difference between meta name and meta property? A: The name attribute is the "usual" way for specifying metadata in HTML. It’s defined in the HTML5 spec. The property attribute comes from RDFa. RDFa 1.1 extends HTML5 so that it’s valid to use meta and link elements in the body, as long as they contain a property attribute. You can use both ways, HTML5’s name and RDFa’s property, together on the same meta element. Note that you might also see meta elements with an itemprop attribute. That would be from Microdata.
doc_23527791
{ NSString *myxmlstr = [NSString stringWithFormat:@"http://apitest.retailigence.com/v1.2/products?apikey=rMMzX5IDYVmTjQ3A7D9sZXukjKiZVmdD&barcode=%@&latitude=37.439097&longitude=-122.175806",brcode]; NSLog(@"my myxmlsstr is %@",myxmlstr); dataselected = NO; NSURL * xmlURL = [NSURL fileURLWithPath:myxmlstr]; myParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL]; myParser.delegate = self; BOOL success = [myParser parse]; if(success){ NSLog(@"Properly done "); } else{ NSLog(@"not done"); } } Thanks in advance. A: It was an error in code and I have to just replace this code NSURL * xmlURL = [NSURL fileURLWithPath:myxmlstr]; with this code NSURL * xmlURL = [NSURL URLWithString:myxmlstr]; This will work. A: more information about parsing you get if you call -parserError or use method from protocol - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError to obtain error informations
doc_23527792
I'm trying to replace the string ">=" by "<" with the code below and the result did not work. String descricao = ">= 0"; if (descricao.contains(">=") ){ descricao = descricao.replace(">=","<"); listaElementosFiltro.get(i).setDescricao(descricao)}; The result I get is: descricao = "><> 0" and not "< 0" as expected... A: That's strange, i checked it, and the result is what you want, anyway, * *try clean and build first, then run it In case it still not working try one of this: String descricao = ">= 0"; if (descricao.contains(">=")) { descricao = descricao.replace(">=", "<"); System.out.println(descricao); //listaElementosFiltro.get(i).setDescricao(descricao); } // option 2 if(descricao.startsWith(">=")){ descricao= descricao.replace(">=","<"); System.out.println(descricao); } // option 3 if(descricao.indexOf(">=") >= 0){ descricao= descricao.replace(">=","<"); System.out.println(descricao); } I don't know what listaElementosFiltro.get(i).setDescricao(descricao); is, so, i just avoid it. A: This is an interesting questions, since it's unexpected that special characters would interfere with replace. This would fix the issue (though I didn't test it). String greaterOrEqual = TextUtils.htmlEncode(">="); String smaller = TextUtils.htmlEncode("<"); String descricao = TextUtils.htmlEncode(">= 0"); if (descricao.contains(greaterOrEqual) ){ descricao = descricao.replace(greaterOrEqual,smaller); listaElementosFiltro.get(i).setDescricao(Html.fromHtml(descricao))};
doc_23527793
$str = '17:30 Football 18:30 Meal 20:00 Quiet'; $chars = preg_split('/^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/', $str, -1, PREG_SPLIT_OFFSET_CAPTURE); print_r ($chars); ?> returned: Array ( [0] => Array ( [0] => 17:30 Football 18:30 Meal 20:00 Quiet [1] => 0 ) ) while I was hoping for: Array ( [0] => Array ( [0] => Football [1] => 7 ) [1] => Array ( [0] => Meal [1] => 22 ) etc. What can I do? A: You need to drop the anchors ^ and $ around your regex - with them in place the regex can never match as they require the splitting string to begin at the start of the string and to end at the end of the string - this can never be true unless your input is 17:30 only. You might also want to include space characters in your regex, like $chars = preg_split('/\s*([0-1][0-9]|2[0-3]):([0-5][0-9])\s*/', $str, -1, PREG_SPLIT_OFFSET_CAPTURE); A: In regular expressions the ^ and $ symbols are anchors to the beginning and end, respectively, of the line of text you are scanning. Try removing them from your pattern. Maybe try something like: <?php $str = '17:30 Football 18:30 Meal 20:00 Quiet'; $chars = preg_split('/(?:[01]\d|2[0-3]):(?:[0-5]\d)/', $str, -1, PREG_SPLIT_OFFSET_CAPTURE); print_r ($chars); ?> Don't forget that : is a special character in regular expressions so it will need to be escaped. By default all bracketed groups are remembered, but you can stop this with the ?: syntax. I'm not entirely sure if that will cause an issue in PHP because I tested the expression with Python, but it should prevent the matches from being returned in the array. You may also want to extend the expression slightly to automatically strip out the whitespace around your words: $chars = preg_split('/\s*(?:[01]\d|2[0-3]):(?:[0-5]\d)\s*/', $str, -1, PREG_SPLIT_OFFSET_CAPTURE); Hope this helps! A: Or: $chars = preg_split('/\b[0-9:\s]{6,7}\b/', $str,-1,PREG_SPLIT_OFFSET_CAPTURE); This removes the leading space.
doc_23527794
The get started say to run the following commands to start off with git clone https://github.com/ucb-bar/project-template.git cd project-template git submodule update --init --recursive so when i run git clone https://github.com/ucb-bar/project-template.git i get talmadage@talmadage-Inspiron-5567:~/test$ git clone https://github.com/ucb-bar/project-template.git Cloning into 'project-template'... remote: Enumerating objects: 81, done. remote: Counting objects: 100% (81/81), done. remote: Compressing objects: 100% (59/59), done. remote: Total 17234 (delta 22), reused 50 (delta 11), pack-reused 17153 Receiving objects: 100% (17234/17234), 6.54 MiB | 5.59 MiB/s, done. Resolving deltas: 100% (9476/9476), done. When i run git submodule update --init --recursivein it. It ends up showing talmadage@talmadage-Inspiron-5567:~/test/project-template$ git submodule update --init --recursive Submodule 'fpga/fpga-shells' (https://github.com/sifive/fpga-shells.git) registered for path 'fpga/fpga-shells' Submodule 'generators/boom' (https://github.com/riscv-boom/riscv-boom.git) registered for path 'generators/boom' Submodule 'generators/cva6' (https://github.com/ucb-bar/cva6-wrapper.git) registered for path 'generators/cva6' Submodule 'generators/gemmini' (https://github.com/ucb-bar/gemmini) registered for path 'generators/gemmini' Submodule 'generators/hwacha' (https://github.com/ucb-bar/hwacha.git) registered for path 'generators/hwacha' Submodule 'generators/icenet' (https://github.com/firesim/icenet.git) registered for path 'generators/icenet' Submodule 'generators/nvdla' (https://github.com/ucb-bar/nvdla-wrapper.git) registered for path 'generators/nvdla' Submodule 'generators/riscv-sodor' (https://github.com/ucb-bar/riscv-sodor.git) registered for path 'generators/riscv-sodor' Submodule 'rocket-chip' (https://github.com/ucb-bar/rocket-chip.git) registered for path 'generators/rocket-chip' Submodule 'generators/sha3' (https://github.com/ucb-bar/sha3.git) registered for path 'generators/sha3' Submodule 'generators/sifive-blocks' (https://github.com/sifive/sifive-blocks.git) registered for path 'generators/sifive-blocks' Submodule 'generators/block-inclusivecache-sifive' (https://github.com/sifive/block-inclusivecache-sifive.git) registered for path 'generators/sifive-cache' Submodule 'testchipip' (https://github.com/ucb-bar/testchipip.git) registered for path 'generators/testchipip' Submodule 'sims/firesim' (https://github.com/firesim/firesim.git) registered for path 'sims/firesim' Submodule 'software/coremark' (https://github.com/ucb-bar/coremark-workload.git) registered for path 'software/coremark' Submodule 'software/firemarshal' (https://github.com/firesim/FireMarshal.git) registered for path 'software/firemarshal' Submodule 'software/nvdla-workload' (https://github.com/ucb-bar/nvdla-workload.git) registered for path 'software/nvdla-workload' Submodule 'software/spec2017' (https://github.com/ucb-bar/spec2017-workload.git) registered for path 'software/spec2017' Submodule 'toolchains/esp-tools/riscv-gnu-toolchain' (https://github.com/ucb-bar/esp-gnu-toolchain.git) registered for path 'toolchains/esp-tools/riscv-gnu-toolchain' Submodule 'toolchains/esp-tools/riscv-isa-sim' (https://github.com/ucb-bar/esp-isa-sim.git) registered for path 'toolchains/esp-tools/riscv-isa-sim' Submodule 'toolchains/esp-tools/riscv-pk' (https://github.com/riscv/riscv-pk.git) registered for path 'toolchains/esp-tools/riscv-pk' Submodule 'toolchains/esp-tools/riscv-tests' (https://github.com/ucb-bar/esp-tests.git) registered for path 'toolchains/esp-tools/riscv-tests' Submodule 'toolchains/libgloss' (https://github.com/ucb-bar/libgloss-htif.git) registered for path 'toolchains/libgloss' Submodule 'toolchains/qemu' (https://github.com/qemu/qemu.git) registered for path 'toolchains/qemu' Submodule 'toolchains/riscv-tools/riscv-gnu-toolchain' (https://github.com/riscv/riscv-gnu-toolchain.git) registered for path 'toolchains/riscv-tools/riscv-gnu-toolchain' Submodule 'toolchains/riscv-tools/riscv-gnu-toolchain-prebuilt' (https://github.com/ucb-bar/chipyard-toolchain-prebuilt.git) registered for path 'toolchains/riscv-tools/riscv-gnu-toolchain-prebuilt' Submodule 'toolchains/riscv-tools/riscv-isa-sim' (https://github.com/riscv/riscv-isa-sim.git) registered for path 'toolchains/riscv-tools/riscv-isa-sim' Submodule 'toolchains/riscv-tools/riscv-openocd' (https://github.com/riscv/riscv-openocd.git) registered for path 'toolchains/riscv-tools/riscv-openocd' Submodule 'toolchains/riscv-tools/riscv-pk' (https://github.com/riscv/riscv-pk.git) registered for path 'toolchains/riscv-tools/riscv-pk' Submodule 'toolchains/riscv-tools/riscv-tests' (https://github.com/riscv/riscv-tests.git) registered for path 'toolchains/riscv-tools/riscv-tests' Submodule 'tools/DRAMSim2' (https://github.com/firesim/DRAMSim2.git) registered for path 'tools/DRAMSim2' Submodule 'tools/axe' (https://github.com/CTSRD-CHERI/axe.git) registered for path 'tools/axe' Submodule 'barstools' (https://github.com/ucb-bar/barstools.git) registered for path 'tools/barstools' Submodule 'tools/chisel-testers' (https://github.com/freechipsproject/chisel-testers.git) registered for path 'tools/chisel-testers' Submodule 'tools/chisel3' (https://github.com/freechipsproject/chisel3.git) registered for path 'tools/chisel3' Submodule 'tools/dromajo/dromajo-src' (https://github.com/riscv-boom/dromajo.git) registered for path 'tools/dromajo/dromajo-src' Submodule 'tools/dsptools' (https://github.com/ucb-bar/dsptools.git) registered for path 'tools/dsptools' Submodule 'tools/firrtl' (https://github.com/freechipsproject/firrtl) registered for path 'tools/firrtl' Submodule 'tools/firrtl-interpreter' (https://github.com/freechipsproject/firrtl-interpreter.git) registered for path 'tools/firrtl-interpreter' Submodule 'tools/torture' (https://github.com/ucb-bar/riscv-torture.git) registered for path 'tools/torture' Submodule 'tools/treadle' (https://github.com/freechipsproject/treadle.git) registered for path 'tools/treadle' Submodule 'vlsi/hammer' (https://github.com/ucb-bar/hammer.git) registered for path 'vlsi/hammer' Submodule 'vlsi/hammer-cadence-plugins' (https://github.com/ucb-bar/hammer-cadence-plugins.git) registered for path 'vlsi/hammer-cadence-plugins' Submodule 'vlsi/hammer-mentor-plugins' (https://github.com/ucb-bar/hammer-mentor-plugins.git) registered for path 'vlsi/hammer-mentor-plugins' Submodule 'vlsi/hammer-synopsys-plugins' (https://github.com/ucb-bar/hammer-synopsys-plugins.git) registered for path 'vlsi/hammer-synopsys-plugins' Cloning into '/home/talmadage/test/project-template/fpga/fpga-shells'... Cloning into '/home/talmadage/test/project-template/generators/boom'... Cloning into '/home/talmadage/test/project-template/generators/cva6'... Cloning into '/home/talmadage/test/project-template/generators/gemmini'... Cloning into '/home/talmadage/test/project-template/generators/hwacha'... Cloning into '/home/talmadage/test/project-template/generators/icenet'... Cloning into '/home/talmadage/test/project-template/generators/nvdla'... Cloning into '/home/talmadage/test/project-template/generators/riscv-sodor'... Cloning into '/home/talmadage/test/project-template/generators/rocket-chip'... Cloning into '/home/talmadage/test/project-template/generators/sha3'... Cloning into '/home/talmadage/test/project-template/generators/sifive-blocks'... Cloning into '/home/talmadage/test/project-template/generators/sifive-cache'... Cloning into '/home/talmadage/test/project-template/generators/testchipip'... Cloning into '/home/talmadage/test/project-template/sims/firesim'... Cloning into '/home/talmadage/test/project-template/software/coremark'... Cloning into '/home/talmadage/test/project-template/software/firemarshal'... Cloning into '/home/talmadage/test/project-template/software/nvdla-workload'... Cloning into '/home/talmadage/test/project-template/software/spec2017'... Cloning into '/home/talmadage/test/project-template/toolchains/esp-tools/riscv-gnu-toolchain'... Cloning into '/home/talmadage/test/project-template/toolchains/esp-tools/riscv-isa-sim'... Cloning into '/home/talmadage/test/project-template/toolchains/esp-tools/riscv-pk'... Cloning into '/home/talmadage/test/project-template/toolchains/esp-tools/riscv-tests'... Cloning into '/home/talmadage/test/project-template/toolchains/libgloss'... Cloning into '/home/talmadage/test/project-template/toolchains/qemu'... Cloning into '/home/talmadage/test/project-template/toolchains/riscv-tools/riscv-gnu-toolchain'... Cloning into '/home/talmadage/test/project-template/toolchains/riscv-tools/riscv-gnu-toolchain-prebuilt'... Cloning into '/home/talmadage/test/project-template/toolchains/riscv-tools/riscv-isa-sim'... Cloning into '/home/talmadage/test/project-template/toolchains/riscv-tools/riscv-openocd'... Cloning into '/home/talmadage/test/project-template/toolchains/riscv-tools/riscv-pk'... Cloning into '/home/talmadage/test/project-template/toolchains/riscv-tools/riscv-tests'... Cloning into '/home/talmadage/test/project-template/tools/DRAMSim2'... Cloning into '/home/talmadage/test/project-template/tools/axe'... Cloning into '/home/talmadage/test/project-template/tools/barstools'... Cloning into '/home/talmadage/test/project-template/tools/chisel-testers'... Cloning into '/home/talmadage/test/project-template/tools/chisel3'... Cloning into '/home/talmadage/test/project-template/tools/dromajo/dromajo-src'... Cloning into '/home/talmadage/test/project-template/tools/dsptools'... Cloning into '/home/talmadage/test/project-template/tools/firrtl'... Cloning into '/home/talmadage/test/project-template/tools/firrtl-interpreter'... Cloning into '/home/talmadage/test/project-template/tools/torture'... Cloning into '/home/talmadage/test/project-template/tools/treadle'... Cloning into '/home/talmadage/test/project-template/vlsi/hammer'... But it all the submodule folders after the operation is done are empty talmadage@talmadage-Inspiron-5567:~/test/project-template$ ls build.sbt CHANGELOG.md common.mk CONTRIBUTING.md docs fpga generators LICENSE LICENSE.SiFive project README.md scripts sims software tests toolchains tools variables.mk vcs.mk vlsi talmadage@talmadage-Inspiron-5567:~/test/project-template$ cd generators talmadage@talmadage-Inspiron-5567:~/test/project-template/generators$ ls boom chipyard cva6 firechip gemmini hwacha icenet nvdla riscv-sodor rocket-chip sha3 sifive-blocks sifive-cache testchipip tracegen utilities talmadage@talmadage-Inspiron-5567:~/test/project-template/generators$ cd boom talmadage@talmadage-Inspiron-5567:~/test/project-template/generators/boom$ ls talmadage@talmadage-Inspiron-5567:~/test/project-template/generators/boom$ This issue happens on windows 10 as well as ubuntu 20.04 and deepin 15.11
doc_23527795
However I get this error message: sh: pig: command not found How can this be solved? A: Can you run pig normally, from the command line? If so, run whereis pig to get the full path and use that in the crontab entry. If not, install it (using whatever method/package manager is normal on your OS. A: Looks like your first issue is not able to find the pig path in the crontab since the error is "sh: pig: command not found". You might have a PATH variable in your local environment which is no longer present in your cron environment, try with absolute path to the pig script in your cron.
doc_23527796
When inline images are used in the body of the source Doc, the text is copied but the UI shows a "reconnecting" message. A greyed out image placeholder area is being displayed as loading. After closing the document and re-opening a Google Drive error is displayed. Oddly enough if I place the image in the source Doc in the header, everything is appended correctly. var targetBody = targetDoc.getBody(); for( var j = 0; j < totalElementsBody; ++j ) { var element = templateBody.getChild(j).copy(); var type = element.getType(); if (type == DocumentApp.ElementType.PARAGRAPH) { targetBody.appendParagraph(element); } else if( type == DocumentApp.ElementType.TABLE){ targetBody.appendTable(element); } else if( type == DocumentApp.ElementType.LIST_ITEM){ targetBody.appendListItem(element); } else if( type == DocumentApp.ElementType.INLINE_IMAGE) { var image = element.asInlineImage().getBlob(); targetBody.appendImage(image); } else if( type == DocumentApp.ElementType.HORIZONTAL_RULE) { targetBody.appendHorizontalRule(); } else if( type == DocumentApp.ElementType.PAGE_BREAK) { targetBody.appendPageBreak(); } } I have tried this Unable to get DocumentBodySection.appendImage(InlineImage) to function properly? but the paragraph with the inline image has no children, so the if-statement is never executed. I also noticed that copying/appending does not always use the font-family of the source document elements... sometimes it does, sometimes not. A: I believe this should take care of adding the image inline properly: if (type == DocumentApp.ElementType.PARAGRAPH) { if (element.asParagraph().getNumChildren() != 0 && element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE) { var blob = element.asParagraph().getChild(0).asInlineImage().getBlob(); doc.appendImage(blob); } else doc.appendParagraph(element.asParagraph()); } hence, when it doesn't have children, the else statement should take care of it. For copying/appending, you can write an onEdit() function that would take care of all the formatting using the setAttributes method. Below is a sample: function onEdit() { var doc = DocumentApp.getActiveDocument(); var style = {}; style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri'; style[DocumentApp.Attribute.FONT_SIZE] = 18; doc.getBody().setAttributes(style); } Hope this helps.
doc_23527797
activity_post.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:focusable="true" android:focusableInTouchMode="true" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="15dp" tools:context=".PostActivity"> <ImageButton android:id="@+id/post_image_button" android:layout_width="match_parent" android:layout_height="300dp" android:layout_centerHorizontal="true" /> </RelativeLayout> Part of PostActivity.java related to ImageButton public class PostActivity extends AppCompatActivity { private ImageButton selectCardImage; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_post); selectCardImage = findViewById(R.id.post_image_button); selectCardImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { OpenGallery(); } }); private void OpenGallery() { Intent galleryIntent = new Intent(); galleryIntent.setType("image/*"); galleryIntent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(galleryIntent, 1); } }
doc_23527798
I have a complex Array of objects, each object has it's own tag Array. I also have just an object which should match one of the objects in the tag Array, and if so remove that tag. Got some help here, however my example there was too simple, so far no luck with this below. Basically I have the object tag and I need to remove it from the tags Array inside of tagsArray. var tagsArray = [{ name: "group1", tags: [ { name: "1", tag_id: "1234" }, { name: "2", tag_id: "5678" }, { name: "3", tag_id: "9012" } ] }, { name: "group2", tags: [] } ]; console.log(tagsArray[0]); // Need to find this inside of tags inside of tagsArray and remove it: var tag = { name: "3", tag_id: "9012" } var temp_array = []; temp_array.push(tag); var map = {}; tagsArray.forEach(function(obj, index) { map[obj.tag_id] = index; }); console.log(map); temp_array.forEach(function(obj) { if ( obj.tag_id ) { tagsArray.splice(tagsArray[map[obj.tag_id]]); console.log(tagsArray); } }); A: You can loop through each item in tagsArray and then filter our matching elements in the inner tags property. var tagsArray = [{ name: "group1", tags: [{ name: "1", tag_id: "1234" }, { name: "2", tag_id: "5678" }, { name: "3", tag_id: "9012" }] }, { name: "group2", tags: [] }]; // Need to find this inside of tags inside of tagsArray and remove it: var removeTag = { name: "3", tag_id: "9012" } var message = 'Before:<br>' + JSON.stringify(tagsArray) + '<br><br>'; tagsArray.forEach(function(element) { element.tags = element.tags.filter(function(tag) { return tag.name != removeTag.name && tag.tag_id != removeTag.tag_id; }) }); message += 'After:<br>' + JSON.stringify(tagsArray); document.body.innerHTML = message A: The solution of Daniel Imms is totally fine, but this one also can solve your problem, and it is a bit faster. var tagsArray = [{ name: "group1", tags: [{ name: "1", tag_id: "1234" }, { name: "2", tag_id: "5678" }, { name: "3", tag_id: "9012" }] }, { name: "group2", tags: [{ name: "4", tag_id: "1012" }] }]; var removedTag = { name: "4", tag_id: "1012" }; var message = 'Before:</br>' + JSON.stringify(tagsArray) + '</br></br>'; tagsArray.forEach(function(obj, i) { obj.tags.forEach(function(tag, j) { if (tag.tag_id === removedTag.tag_id && tag.name === removedTag.name) { obj.tags.splice(j, 1); return; } }); }); message += 'After:</br>' + JSON.stringify(tagsArray); document.body.innerHTML = message I tested with jsPerf and here is the link and here is the result.
doc_23527799
!pip install sqlalchemy==1.3.9;!pip install ibm_db;!pip install ipython;!pip install ibm_db_sa;!pip install ibm-db;!pip install install ibm-db-sa;import ibm_db %load_ext sql # Remember the connection string is of the format: # %sql ibm_db_sa://my-username:my-password@my-hostname:my-port/my-db- name?security=SSL # Enter the connection string for your Db2 on cloud database instance below %sql ibm_db_sa://.............cloud:3131/Buludb?security=SSL) Then after running the connection I get error either: '%sql'is not found or username is not recognized and other error from creating connecting string. I'm using Jupyter Notebook in Watson Studio Lite Plan instance and try to connect to Db2 on Cloud.