date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/21
979
3,880
<issue_start>username_0: I need to consume the given API definition, But I am not able to find a function call that takes both headers and request body at [documentation](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html). Please suggest which function of RestTemplate to use here. ``` @RequestMapping(value = "/createObject", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity createObject( @RequestBody CreateObjectInput req) { CreateObjectOutput out = new CreateObjectOutput(); ///// Some Code return new ResponseEntity(out, HttpStatus.OK); } ```<issue_comment>username_1: ``` RestTemplate template = new RestTemplate(); CreateObjectInput payload = new CreateObjectInput(); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity requestEntity = new HttpEntity<>(payload, headers); CreateObjectOutput response = template.exchange("url", HttpMethod.POST, requestEntity, CreateObjectOutput.class); ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: ``` //Inject you rest template @Autowired RestTemplate restTmplt; ``` Then use it inside your method. ``` HttpHeaders header = new HttpHeaders(); //You can use more methods of HttpHeaders to set additional information header.setContentType(MediaType.APPLICATION_JSON); Map bodyParamMap = new HashMap(); //Set your request body params bodyParamMap.put("key1", "value1"); bodyParamMap.put("key2", "value2"); bodyParamMap.put("key3", "value3"); ``` You can convert your request body to JSON formatted string using writeValueAsString() method of ObjectMapper. ``` String reqBodyData = new ObjectMapper().writeValueAsString(bodyParamMap); HttpEntity requestEnty = new HttpEntity<>(reqBodyData, header); ``` postForEntity() for POST method getForEntity() for GET method ``` ResponseEntity result = restTmplt.postForEntity(reqUrl, requestEnty, Object.class); return result; ``` ObjectMapper is Jackson dependency com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper() In place of ResponseEntity Object class it can be your own class too based on response you are expecting. For example: ``` ResponseEntity result = restTmplt.postForEntity(reqUrl, requestEnty, Demo.class); ``` Upvotes: 3 <issue_comment>username_3: \*\***Api header and body parameter added for a post req:** \*\* > > You have to provide apiKey and apiUrl value to use this POST req. Thanks in advance > > > ``` public JSONObject sendRequestToPorichoyUsingRest(String nid,String dob){ JSONObject jsonObject=null; try { // create headers HttpHeaders headers = new HttpHeaders(); // set `content-type` header headers.setContentType(MediaType.APPLICATION_JSON); // set `accept` header headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.set("x-api-key",apiKey); // request body parameters Map map = new HashMap<>(); map.put("national\_id",nid); map.put("dob",dob); // build the request HttpEntity> entity = new HttpEntity<>(map, headers); // send POST request ResponseEntity response = restTemplate.postForEntity(apiUrl, entity, String.class); // check response if (response.getStatusCode() == HttpStatus.OK) { System.out.println("Request Successful"); System.out.println(response.getBody()); JSONParser parser=new JSONParser(); jsonObject=(JSONObject) parser.parse(response.getBody()); } else { System.out.println("Request Failed"); System.out.println(response.getStatusCode()); } }catch (Exception e){ LOGGER.error("Something went wrong when getting data from porichoy "+e); } return jsonObject; } ``` Upvotes: 1
2018/03/21
679
2,413
<issue_start>username_0: I recently upgraded my Visual Studio 2017 Community Edition from version 15.6.2 to 15.6.3 and since then I have not been able to successfully deploy my .NET Core 2.0 web application to my Azure App Services using an existing Publishing Profile. The error messages is 'C:\Program Files\dotnet\sdk\2.1.102\Sdks\Microsoft.NET.Sdk\build\Microsoft.PackageDependencyResolution.targets(167,5): Error : Assets file '\project.assets.json' doesn't have a target for '.NETCoreApp,Version=v2.0'. Ensure that restore has run and that you have included 'netcoreapp2.0' in the TargetFrameworks for your project.' I have tried: * Re-downloaded new Package Profiles and then rebuilding and publishing. * Deleting the project.assets.json file from \obj\ folder, rebuilding the publishing. * Changing the Target Framework in Project Properties from .NET Core 2.0 to another framework and back again, rebuilding and publishing. None of the above resulted in a successful deployment and I kept getting the same error message. I also examined the project.assets.json file and the target is ".NETCoreApp,Version=v2.0". I ran 'dotnet restore', 'dotnet build' and 'dotnet deploy', all of which succeeded.<issue_comment>username_1: I had the same problem with the publishing and a local build. The developer community has a discussion about this <https://developercommunity.visualstudio.com/content/problem/218674/assets-file-cxxxxxxobjprojectassetsjson-doesnt-hav.html> Resharper and MS people found the problem and promised to fix it soon... For now, deletion of the sdk\2.1.102 and the restart solved my problems Upvotes: 3 [selected_answer]<issue_comment>username_2: I fixed the issue by deleting the sdk\2.1.102 folder as suggested by @username_1 and @Jerry Liu. I also found that the issue was fixed by upgrading to Visual Studio 2017 verion 15.6.4, as a new sdk was installed. The new sdk version was 2.1.103. Upvotes: 2 <issue_comment>username_3: The problem is fixed in ReSharper 2017.3.5, everything works with all combinations of Visual Studio and .NET Core SDK. You can find more technical details in the official blog post: <https://blog.jetbrains.com/dotnet/2018/03/23/build-failures-visual-studio-15-6-3-resharper-ultimate-2017-3-5-rescue/> Upvotes: 2 <issue_comment>username_4: I resolved a similar issue by creating a new Publish Profile. It worked for me. Please give a try. Upvotes: 3
2018/03/21
538
1,625
<issue_start>username_0: There are some test credit card numbers, e.g. Visa's `4111 1111 1111 1111`, and when you test with these cards, it is always a successful transaction. How do I test a declined transaction? E.g. if the card is valid but doesn't have enough money for the transaction?<issue_comment>username_1: You can use the card number `4000 0000 0000 0002` or token "tok\_chargeDeclined" to get a declined test charge: <https://stripe.com/docs/testing#cards> Upvotes: 5 [selected_answer]<issue_comment>username_2: As @Muistooshort and @phlip mention in the comments, the [Stripe documentation](https://stripe.com/docs/testing#cards) give a list of test cards that will return various error messages. Common errors would be: `4000 0000 0000 0002` Card declined (e.g. insufficient funds) `4000 0000 0000 0069` Card expired `4000 0000 0000 0127` Incorrect CVC Card dates can be anything in the future (for valid dates) or in the past to test invalid dates. Upvotes: 3 <issue_comment>username_3: You have two scenarios when a charge can fail: * Charge directly a customer. * Attach a card to a customer and then try to charge that customer. [Stripe's documentation](https://stripe.com/docs/testing#cards) provides two test cards for those situations: * `4000 0000 0000 0002` "Charge is declined with a card\_declined code." * `4000 0000 0000 0341` "Attaching this card to a Customer object succeeds, but attempts to charge the customer fail." Upvotes: 5 <issue_comment>username_4: `4000000000009995` this card number return insufficient funds when I attach it to a customer. I hope it help someone. Upvotes: 1
2018/03/21
1,065
3,305
<issue_start>username_0: I am going through a PDF tutorial for C++ and currently doing a drill for a simple letter program. The program takes my input but when it comes to the 2nd input, it just shuts down. I'm quite new in C++ so excuse my ignorance. This is my code: ``` #include #include using namespace std; int main() { string first\_name, last\_name, dest\_firstName, friend\_Name; char friend\_sex = '0'; int dest\_age = 0; cout << "Enter your first and Last Names" << endl; cin >> first\_name; cin >> last\_name; cout << "Hello " << first\_name << " " << last\_name << ". Enter the name of the person you want to write to. " << endl; cin >> dest\_firstName; cout << "Enter their age" << endl; cin >> dest\_age; cout << "Enter the name of another friend." << endl; cin >> friend\_Name; cout << "Enter the gender of the friend." << endl; cin >> friend\_sex; cout << "Dear " << dest\_firstName << ", " <= 110) { cout << "Also, I've heard that not long ago was your birthday and you are " << dest\_age << " years old. NO WAY" << endl; } else if (dest\_age < 12) { cout << "Also, I've heard that not long ago was your birthday and you are " << dest\_age << ". Next year you will be " << dest\_age + 1 << " years old." << endl; } else if (dest\_age == 17) { cout << "Also, I've heard that not long ago was your birthday and you are " << dest\_age << ". Next year you will be able to vote. " << endl; } else if (dest\_age == 70) { cout << "Also, I've heard that not long ago was your birthday and you are " << dest\_age << ". I hope you're enjoying retirement." << endl; } cout << "Yours Truly" << endl; cout << first\_name << " " << last\_name << endl; return 0; } ``` And this is the output: `Dear John, How are you? It has been a long time since we spoke. Have you seen lately? Also, I've heard that not long ago was your birthday and you are 0. Next year you will be 1 years old.` `Yours Truly` `<NAME>`<issue_comment>username_1: You can use the card number `4000 0000 0000 0002` or token "tok\_chargeDeclined" to get a declined test charge: <https://stripe.com/docs/testing#cards> Upvotes: 5 [selected_answer]<issue_comment>username_2: As @Muistooshort and @phlip mention in the comments, the [Stripe documentation](https://stripe.com/docs/testing#cards) give a list of test cards that will return various error messages. Common errors would be: `4000 0000 0000 0002` Card declined (e.g. insufficient funds) `4000 0000 0000 0069` Card expired `4000 0000 0000 0127` Incorrect CVC Card dates can be anything in the future (for valid dates) or in the past to test invalid dates. Upvotes: 3 <issue_comment>username_3: You have two scenarios when a charge can fail: * Charge directly a customer. * Attach a card to a customer and then try to charge that customer. [Stripe's documentation](https://stripe.com/docs/testing#cards) provides two test cards for those situations: * `4000 0000 0000 0002` "Charge is declined with a card\_declined code." * `4000 0000 0000 0341` "Attaching this card to a Customer object succeeds, but attempts to charge the customer fail." Upvotes: 5 <issue_comment>username_4: `4000000000009995` this card number return insufficient funds when I attach it to a customer. I hope it help someone. Upvotes: 1
2018/03/21
710
2,463
<issue_start>username_0: I have ~150 files that I need to remove the jQuery import from, as we have Webpack importing it automatically. How can I achieve this with find and replace in vscode? I would like to remove a single line from each file and have the rest of the code shift up a line. I have the below regex, however, I'm not sure what I need to put in the replace field to remove the line. [![enter image description here](https://i.stack.imgur.com/kUNkB.png)](https://i.stack.imgur.com/kUNkB.png)<issue_comment>username_1: In the 'replace' input, just add a blank space. This will remove the selected lines and replace it with blank space. You can then remove that blank space by a code formatter such as Prettier and run that on all your files. [![enter image description here](https://i.stack.imgur.com/YOKHb.png)](https://i.stack.imgur.com/YOKHb.png) Upvotes: 0 <issue_comment>username_2: Try add `\n` to your search regex and replace with empty string. In your case: `^import \$ from 'jquery';$\n` --- Update: [November 2018 (version 1.30)](https://code.visualstudio.com/updates/v1_30#_multiline-search-input) > > Multiline search input > > > Last month, we added support for multiline search. This month we improved the search UX to make it easier to use. Now, you can search with multiline text without having to write a regular expression. Type Shift+Enter in the search box to insert a newline, and the search box will grow to show your full multiline query. You can also copy and paste a multiline selection from the editor into the search box. > > > Upvotes: 7 [selected_answer]<issue_comment>username_3: As an update, let's say I need to delete `deployStage: 3` from the next block of code and also be sure I don't let the blank space: ``` score: deployStage: 3 ports: - container: 1000 portName: tcp imagePullPolicy: IfNotPresent ``` I need this regex: `^.*deployStage.*[0-9]\n` as this: [![enter image description here](https://i.stack.imgur.com/c25Jt.png)](https://i.stack.imgur.com/c25Jt.png) The result is this: ``` score: ports: - container: 1000 portName: tcp imagePullPolicy: IfNotPresent ``` Upvotes: 4 <issue_comment>username_4: In my case clicking to `replace all` without entering anything in it worked. It worked like a find and delete all [![enter image description here](https://i.stack.imgur.com/M7Dru.png)](https://i.stack.imgur.com/M7Dru.png) Upvotes: 1
2018/03/21
1,750
5,908
<issue_start>username_0: How can I create a single line view separator in `UITableView` like the NavigationDrawer of Android: [![enter image description here](https://i.stack.imgur.com/4u3Kr.png)](https://i.stack.imgur.com/4u3Kr.png) I know that in Android it's easy, but I can't find a reference of that for iOS, how is it call on iOS, I just want a single line separator in my menu view, all the videos and tutorials that I can find for iOS shows how to add an expandable menu, which is not what I want, I want just one single line separating two groups of an array of strings. Is that possible on iOS, where can I found a tutorial teaching that? my code so far: ``` import UIKit class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { //Outlets @IBOutlet weak var tableView: UITableView! var menuNameArr = [String]() var iconImage = [UIImage]() override func viewDidLoad() { super.viewDidLoad() tableView.alwaysBounceVertical = false; tableView.separatorStyle = .none menuNameArr = ["Meu Perfil", "Meus Cupons", "Extrato de pontos", "Configurações", "Termos de uso", "Entre em Contato", "Avaliar aplicativo", "Sair"] iconImage = [UIImage(named: "user")!,UIImage(named: "cupons")!, UIImage(named: "extrato")!, UIImage(named: "config")!, UIImage(named: "termos")!, UIImage(named: "contato")!, UIImage(named: "avaliar")!, UIImage(named: "sair")!] self.revealViewController().rearViewRevealWidth = self.view.frame.size.width - 60 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuNameArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MenuTableViewCell") as! MenuTableViewCell cell.imgIcon.image = iconImage[indexPath.row] cell.lblMenuName.text! = menuNameArr[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } } ``` From "Configurações" to "Sair" I want that part of the array to be the second part of the menu<issue_comment>username_1: Put Condition for particular `indexPath` where you have show it else hide it. simple Custom separator line, put this code in a custom cell that's a subclass of UITableViewCell(or in CellForRow or WillDisplay TableViewDelegates for non custom cell): ``` let separatorLine = UIImageView.init(frame: CGRect(x: 8, y: 64, width: cell.frame.width - 16, height: 2)) separatorLine.backgroundColor = .blue addSubview(separatorLine) ``` Upvotes: 1 <issue_comment>username_2: try this ``` if indexPath.row == 3{ let separator = UILabel(frame: CGRect(x: 15, y: cell.frame.size.height - 1, width: cell.frame.size.width, height: 1)) separator.backgroundColor = UIColor.red cell.contentView.addSubview(separator) } ``` Upvotes: 2 <issue_comment>username_3: There are 3 type of doing this, You can choose any one of them based on your requirement and simplest seems to you: > > 1. Create a custom separator view at bottom of cell for indexpath.row = 3 > > > ``` cell.imgIcon.image = iconImage[indexPath.row] cell.lblMenuName.text! = menuNameArr[indexPath.row] if indexPath.row == 3 { let separatorView = UIView.init(frame: CGRect(x: 15, y: cell.frame.size.height - 1, width: cell.frame.size.width - 15, height: 1)) separatorView.backgroundColor = .lightGray cell.contentView.addSubview(separatorView) } return cell ``` > > 2. Can take a UIView of height "1px" at the bottom of cell at storyboard with clear colour, and assign colour for indexpath.row = 3 in code. But creating a extra view in table cell is not a good idea. > > > ``` cell.imgIcon.image = iconImage[indexPath.row] cell.lblMenuName.text! = menuNameArr[indexPath.row] if indexPath.row == 3 { cell.sepatatorView.backgroundColor = .lightGray } else { cell.sepatatorView.backgroundColor = .clear } return cell ``` > > 3. You can divide your name and icon array into 2 subarrays, You can work with 2 sections, with section height of "1px" and lightGray colour. > > > Note: With this approach you can even customize your separator, rather than just gray line, you can add a custom view/title there > > > ``` let menuNameArr = [ ["Meu Perfil", "Meus Cupons", "Extrato de pontos"], ["Configurações", "Termos de uso", "Entre em Contato", "Avaliar aplicativo", "Sair"] ] let iconImage = [ [UIImage(named: "user")!,UIImage(named: "cupons")!, UIImage(named: "extrato")!], [ UIImage(named: "config")!, UIImage(named: "termos")!, UIImage(named: "contato")!, UIImage(named: "avaliar")!, UIImage(named: "sair")!] ] ``` Update the table view's method accordingly. ``` func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 1.0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let separatorView = UIView.init(frame: CGRect(x: 15, y: 0, width: tableView.frame.size.width - 15, height: 1)) separatorView.backgroundColor = .lightGray return separatorView } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuNameArr[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MenuTableViewCell") as! MenuTableViewCell cell.imgIcon.image = iconImage[indexPath.section][indexPath.row] cell.lblMenuName.text! = menuNameArr[indexPath.section][indexPath.row] return cell } ``` Upvotes: 3 [selected_answer]
2018/03/21
1,268
4,190
<issue_start>username_0: I have vue.js project with element-ui. All installed via npm. Now I want to change something in element-ui just to test if it works so I go in it's folder in node\_modules, change code in component, run 'npm run dev' and change is not visible. Is it in some kind of cache? Sorry for dumb question but I am node.js noob. How can I update existing code in node\_modules? I know when I run update it will go away but I just want quick test. Do I really have to fork for that?<issue_comment>username_1: Put Condition for particular `indexPath` where you have show it else hide it. simple Custom separator line, put this code in a custom cell that's a subclass of UITableViewCell(or in CellForRow or WillDisplay TableViewDelegates for non custom cell): ``` let separatorLine = UIImageView.init(frame: CGRect(x: 8, y: 64, width: cell.frame.width - 16, height: 2)) separatorLine.backgroundColor = .blue addSubview(separatorLine) ``` Upvotes: 1 <issue_comment>username_2: try this ``` if indexPath.row == 3{ let separator = UILabel(frame: CGRect(x: 15, y: cell.frame.size.height - 1, width: cell.frame.size.width, height: 1)) separator.backgroundColor = UIColor.red cell.contentView.addSubview(separator) } ``` Upvotes: 2 <issue_comment>username_3: There are 3 type of doing this, You can choose any one of them based on your requirement and simplest seems to you: > > 1. Create a custom separator view at bottom of cell for indexpath.row = 3 > > > ``` cell.imgIcon.image = iconImage[indexPath.row] cell.lblMenuName.text! = menuNameArr[indexPath.row] if indexPath.row == 3 { let separatorView = UIView.init(frame: CGRect(x: 15, y: cell.frame.size.height - 1, width: cell.frame.size.width - 15, height: 1)) separatorView.backgroundColor = .lightGray cell.contentView.addSubview(separatorView) } return cell ``` > > 2. Can take a UIView of height "1px" at the bottom of cell at storyboard with clear colour, and assign colour for indexpath.row = 3 in code. But creating a extra view in table cell is not a good idea. > > > ``` cell.imgIcon.image = iconImage[indexPath.row] cell.lblMenuName.text! = menuNameArr[indexPath.row] if indexPath.row == 3 { cell.sepatatorView.backgroundColor = .lightGray } else { cell.sepatatorView.backgroundColor = .clear } return cell ``` > > 3. You can divide your name and icon array into 2 subarrays, You can work with 2 sections, with section height of "1px" and lightGray colour. > > > Note: With this approach you can even customize your separator, rather than just gray line, you can add a custom view/title there > > > ``` let menuNameArr = [ ["Meu Perfil", "Meus Cupons", "Extrato de pontos"], ["Configurações", "Termos de uso", "Entre em Contato", "Avaliar aplicativo", "Sair"] ] let iconImage = [ [UIImage(named: "user")!,UIImage(named: "cupons")!, UIImage(named: "extrato")!], [ UIImage(named: "config")!, UIImage(named: "termos")!, UIImage(named: "contato")!, UIImage(named: "avaliar")!, UIImage(named: "sair")!] ] ``` Update the table view's method accordingly. ``` func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 1.0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let separatorView = UIView.init(frame: CGRect(x: 15, y: 0, width: tableView.frame.size.width - 15, height: 1)) separatorView.backgroundColor = .lightGray return separatorView } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuNameArr[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MenuTableViewCell") as! MenuTableViewCell cell.imgIcon.image = iconImage[indexPath.section][indexPath.row] cell.lblMenuName.text! = menuNameArr[indexPath.section][indexPath.row] return cell } ``` Upvotes: 3 [selected_answer]
2018/03/21
1,379
4,566
<issue_start>username_0: I try following code to stop multiple jquery scripts loading onto product category page. This broke a lot of plugins. ``` add_filter('wp_enqueue_scripts', 'change_default_jquery', PHP_INT_MAX); if (is_product_category() || is_shop()) { // product category page or shop function change_default_jquery() { if (!is_admin() { wp_deregister_script('jquery'); wp_register_script('jquery', false); } } } ``` I tried to go back and reverse this and used the following code, ``` function getbacke_scripts() { wp_enqueue_script('jquery'); } add_action('wp_enqueue_scripts', 'getbacke_scripts'); ``` This did not work. How do I get Wordpress to go back to using it's core Jquery site and fix my plugin issue. Every solution I find says to use `wp_enqueue_script('jquery');` but this has not worked for me. Please help.<issue_comment>username_1: Put Condition for particular `indexPath` where you have show it else hide it. simple Custom separator line, put this code in a custom cell that's a subclass of UITableViewCell(or in CellForRow or WillDisplay TableViewDelegates for non custom cell): ``` let separatorLine = UIImageView.init(frame: CGRect(x: 8, y: 64, width: cell.frame.width - 16, height: 2)) separatorLine.backgroundColor = .blue addSubview(separatorLine) ``` Upvotes: 1 <issue_comment>username_2: try this ``` if indexPath.row == 3{ let separator = UILabel(frame: CGRect(x: 15, y: cell.frame.size.height - 1, width: cell.frame.size.width, height: 1)) separator.backgroundColor = UIColor.red cell.contentView.addSubview(separator) } ``` Upvotes: 2 <issue_comment>username_3: There are 3 type of doing this, You can choose any one of them based on your requirement and simplest seems to you: > > 1. Create a custom separator view at bottom of cell for indexpath.row = 3 > > > ``` cell.imgIcon.image = iconImage[indexPath.row] cell.lblMenuName.text! = menuNameArr[indexPath.row] if indexPath.row == 3 { let separatorView = UIView.init(frame: CGRect(x: 15, y: cell.frame.size.height - 1, width: cell.frame.size.width - 15, height: 1)) separatorView.backgroundColor = .lightGray cell.contentView.addSubview(separatorView) } return cell ``` > > 2. Can take a UIView of height "1px" at the bottom of cell at storyboard with clear colour, and assign colour for indexpath.row = 3 in code. But creating a extra view in table cell is not a good idea. > > > ``` cell.imgIcon.image = iconImage[indexPath.row] cell.lblMenuName.text! = menuNameArr[indexPath.row] if indexPath.row == 3 { cell.sepatatorView.backgroundColor = .lightGray } else { cell.sepatatorView.backgroundColor = .clear } return cell ``` > > 3. You can divide your name and icon array into 2 subarrays, You can work with 2 sections, with section height of "1px" and lightGray colour. > > > Note: With this approach you can even customize your separator, rather than just gray line, you can add a custom view/title there > > > ``` let menuNameArr = [ ["Meu Perfil", "Meus Cupons", "Extrato de pontos"], ["Configurações", "Termos de uso", "Entre em Contato", "Avaliar aplicativo", "Sair"] ] let iconImage = [ [UIImage(named: "user")!,UIImage(named: "cupons")!, UIImage(named: "extrato")!], [ UIImage(named: "config")!, UIImage(named: "termos")!, UIImage(named: "contato")!, UIImage(named: "avaliar")!, UIImage(named: "sair")!] ] ``` Update the table view's method accordingly. ``` func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 1.0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let separatorView = UIView.init(frame: CGRect(x: 15, y: 0, width: tableView.frame.size.width - 15, height: 1)) separatorView.backgroundColor = .lightGray return separatorView } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuNameArr[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MenuTableViewCell") as! MenuTableViewCell cell.imgIcon.image = iconImage[indexPath.section][indexPath.row] cell.lblMenuName.text! = menuNameArr[indexPath.section][indexPath.row] return cell } ``` Upvotes: 3 [selected_answer]
2018/03/21
545
1,564
<issue_start>username_0: I’m trying to compile Linux, but I keep getting the following error: ```none sudo make install sh ./arch/x86/boot/install.sh 4.14.28-2018840814 arch/x86/boot/bzImage \ System.map "boot/" *** Missing file: arch/x86/boot/bzImage *** you need to run "make before "make install". ``` I followed this direction, but I got stuck on *make install*: ```none make mrproper make menuconfig make -j4 sudo make modules_install sudo cp .config /boot/config-`make kernelrelease` sudo make install sudo reboot ```<issue_comment>username_1: In my case I was compiling the Linux 5.3.11 kernel from source in a Mint 19.2 system and ran into the same issue. The creation of bzImage is missing in your script. Before modules\_install you should type: ``` # make bzImage ``` In my case the files are located in: ``` ./arch/x86_64/boot/bzImage ./arch/x86/boot/bzImage ``` Then, the rest of the steps. Upvotes: 1 <issue_comment>username_2: I have Linux 5.19.9 kernel from source in a ubuntu 20.04.5. my issue when I run $make -j4 $sudo make modules\_install -j4 $sudo make install -j4 INSTALL/boot \*\*\* Missing file: arch/x86/boot/bzImage \*\*\* you need to run "make before "make install". solution: $make bzImage [another error](https://i.stack.imgur.com/iKOzu.jpg) reason was zstd not available then i run $sudo apt-get install zstd $make -j4 $sudo make modules\_install -j4 $sudo make install -j4 $sudo update-grub $sudo reboot check if kernel compile or not my running command $uname -r it work fine for me :) Upvotes: 2
2018/03/21
436
1,790
<issue_start>username_0: I am facing trouble with android Oreo. My MainActivity has 4 fragments, which replace each other whenever the user presses tabs. Now the problem is, I am saving a value in a singleton instance in onPause. Whenever the user presses the next tab, onResume of that fragment is called before onPause, so I am not able to retrieve the value from the singleton correctly.<issue_comment>username_1: **onResume should called before onPause.** If you want to save something before starting fragment do it in onStart. If you want to save something before leaving fragment do it in onStop. [More info on Fragment lifecycle](https://developer.android.com/guide/components/fragments.html) Upvotes: 0 <issue_comment>username_2: There is some problem with Fragment in oreo version.I created a separate app to check what lifecycle functions are called when we replace one fragment with other..Here is the log: ``` MainActivity onCreate -> FragmentA oncreate -> FragmentA oncreateView -> MainActivity onStart -> FragmentA onStart -> MainActivity onResume -> FragmentA onResume -> Button Pressed;that replace fragment A with Fragment B FragmentB onCreate -> FragmentB onCreateView -> FragmentB onStart -> FragmentB onResume -> FragmentA onPause -> FragmentA onStop -> FragmentA onDestroy -> ``` I was importing import android.app.Fragment.It worked when I replaced it with android.support.v4.app.Fragment . Upvotes: 2 [selected_answer]<issue_comment>username_3: Please use setReorderingAllowed as false to get the normal fragment lifecycle. ``` if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { fragmentTransaction.setReorderingAllowed(false); } ``` <https://developer.android.com/reference/android/app/FragmentTransaction.html#setReorderingAllowed(boolean)> Upvotes: 3
2018/03/21
656
2,867
<issue_start>username_0: I am relatively new to Kafka. We process messages from kafka and persist them to database.if there is a failure when persisting them to database, the message will not be committed. My questions are: **we are wondering how we can re-consume the uncommitted messages?** **I have tried a few approaches.** 1. Restart the consumer. It works, but relying on restarting. 2. Catch the application exception and skip the kafka commit. Store the message into RAM and then retry. **Whats the best practice approach in this kind of situation?** Thanks in advance.<issue_comment>username_1: If you use spring-Kafka project you can use [ContainerStoppingErrorHandler](https://docs.spring.io/spring-kafka/api/org/springframework/kafka/listener/ContainerStoppingErrorHandler.html) Which will stop the container in error. Below is sample KafkaListener method which will retry on DataAccessException and after retires exhausted pass error to error handler defined in Config class below ``` @KafkaListener(topics = ("${spring.kafka.consumer.topic}"), containerFactory = "kafkaManualAckListenerContainerFactory") @Retryable(include = DataAccessException.class, backoff = @Backoff(delay = 20000, multiplier = 3)) public void onMessage(List> recordList, Acknowledgment acknowledgment, Consumer, ? consumer) throws DataAccessException { try { kafkaSinkController.saveToDb(recordList); acknowledgment.acknowledge(); LOGGER.info("Message Saved DB"); } catch (Exception e) { LOGGER.error("Other than db exception ", e) } } ``` Config bean ``` @Bean KafkaListenerContainerFactory> kafkaManualAckListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(new DefaultKafkaConsumerFactory(consumerConfig)); factory.setConcurrency(concurrentConsumerCount); factory.getContainerProperties().setAckMode(AckMode.MANUAL\_IMMEDIATE); factory.getContainerProperties().setBatchErrorHandler(new ContainerStoppingBatchErrorHandler()); //It will stop container and thus consumer will stop listening factory.setBatchListener(true); return factory; } ``` When you want to start re-consuming messages you can start container using KafkaListenerEndpointRegistry, sample method below for refrence which can be invoked programmatically once database is up for by exposing as endpoint for this method. ``` @Autowired KafkaListenerEndpointRegistry registry; public void startContainer() { try { registry.start(); } catch (Exception ex) { //Todo } } ``` Above sample relies on all spring components, But same might be achieved without spring-kafka project. Upvotes: 2 <issue_comment>username_2: Catch an exception and post the message to a different Kafka retry-topic, which is processed separately by another Consumer. Upvotes: 0
2018/03/21
1,256
5,016
<issue_start>username_0: I'm trying to call menu function in the main function and let it prompt until the user decides to quit, but seems like it's not giving me response.. I'm new at this website coding, let me know if there's anything eg. post format I can improve! clearkeyboard function: ``` void clearKeyboard(void) { int c; while ((c = getchar()) != '\n' && c != EOF); } ``` The function to call menu: ``` void ContactManagerSystem(void) { int contactchoice; int done = 1; char yesno, c; do { clearKeyboard(); contactchoice = menu(); switch (contactchoice) { case 1: printf("<<< Feature 1 is unavailable >>>\n"); break; case 2: printf("<<< Feature 2 is unavailable >>>\n"); break; case 3: printf("<<< Feature 3 is unavailable >>>\n"); break; case 4: printf("<<< Feature 4 is unavailable >>>\n"); break; case 5: printf("<<< Feature 5 is unavailable >>>\n"); break; case 6: printf("<<< Feature 6 is unavailable >>>\n"); break; case 0: printf("Exit the program? (Y)es/(N)o: "); scanf("%c%c", &yesno, &c); if (yesno == 'Y' || yesno == 'y' && c == '\n') { done = 0; break; } else if (yesno == 'N' || yesno == 'n') break; default: break; } } while (done == 1); } ``` Menu function: ``` int menu(void) { int done = 1; int choice; char c; do { printf("Contact Management System\n"); printf("-------------------------\n"); printf("1. Display contacts\n"); printf("2. Add a contact\n"); printf("3. Update a contact\n"); printf("4. Delete a contact\n"); printf("5. Search contacts by cell phone number\n"); printf("6. Sort contacts by cell phone numbe\n"); printf("0. Exit\n\n"); printf("Select an option:> "); int rtn = scanf("%d%c", &choice, &c); if (rtn == EOF || rtn == 0 || c != '\n') clearKeyboard(); else if (choice >= 0 && choice <= 6 && c == '\n') done = 0; else { clearKeyboard(); printf("*** OUT OF RANGE *** : "); scanf("%d", &choice); } } while (done == 1); return choice; } ``` Attached image below is where goes wrong, the correct version should do case 1 instead of keep prompt menu again. **Incorrect Part** [![enter image description here](https://i.stack.imgur.com/QIuGy.png)](https://i.stack.imgur.com/QIuGy.png) Thanks in advance!!!<issue_comment>username_1: If you use spring-Kafka project you can use [ContainerStoppingErrorHandler](https://docs.spring.io/spring-kafka/api/org/springframework/kafka/listener/ContainerStoppingErrorHandler.html) Which will stop the container in error. Below is sample KafkaListener method which will retry on DataAccessException and after retires exhausted pass error to error handler defined in Config class below ``` @KafkaListener(topics = ("${spring.kafka.consumer.topic}"), containerFactory = "kafkaManualAckListenerContainerFactory") @Retryable(include = DataAccessException.class, backoff = @Backoff(delay = 20000, multiplier = 3)) public void onMessage(List> recordList, Acknowledgment acknowledgment, Consumer, ? consumer) throws DataAccessException { try { kafkaSinkController.saveToDb(recordList); acknowledgment.acknowledge(); LOGGER.info("Message Saved DB"); } catch (Exception e) { LOGGER.error("Other than db exception ", e) } } ``` Config bean ``` @Bean KafkaListenerContainerFactory> kafkaManualAckListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(new DefaultKafkaConsumerFactory(consumerConfig)); factory.setConcurrency(concurrentConsumerCount); factory.getContainerProperties().setAckMode(AckMode.MANUAL\_IMMEDIATE); factory.getContainerProperties().setBatchErrorHandler(new ContainerStoppingBatchErrorHandler()); //It will stop container and thus consumer will stop listening factory.setBatchListener(true); return factory; } ``` When you want to start re-consuming messages you can start container using KafkaListenerEndpointRegistry, sample method below for refrence which can be invoked programmatically once database is up for by exposing as endpoint for this method. ``` @Autowired KafkaListenerEndpointRegistry registry; public void startContainer() { try { registry.start(); } catch (Exception ex) { //Todo } } ``` Above sample relies on all spring components, But same might be achieved without spring-kafka project. Upvotes: 2 <issue_comment>username_2: Catch an exception and post the message to a different Kafka retry-topic, which is processed separately by another Consumer. Upvotes: 0
2018/03/21
705
1,960
<issue_start>username_0: I have a table as shown here below. [![enter image description here](https://i.stack.imgur.com/8EzBW.png)](https://i.stack.imgur.com/8EzBW.png) I want to select the `id_start_odon` with a particular `id_pasien` and the last date of that particular `id_pasien`. I want to get 15 as the result. I've tried this but it doesn't render what I want. ``` public function get_latest($id_pasien){ $query = "SELECT s1.id_start_odon FROM start_odon s1 WHERE s1.id_pasien=$id_pasien AND s1.created_at=(SELECT s2* FROM start_odon s2 WHERE s2.id_pasien=$id_pasien AND s2.created_at=MAX(s2.created_at))"; $res = $this->db->query($query); return $query; } ``` Any suggestions are appreciated.<issue_comment>username_1: This query will work ``` SELECT id_start_odon FROM start_odon s1 WHERE id_pasien=id_pasien=$id_pasien AND id_start_odon=(select MAX(id_start_odon) from start_odon) ``` since your created\_date seems to be in order. Upvotes: 0 <issue_comment>username_2: Try something like below ``` SELECT id_Start_odon FROM t INNER JOIN ( SELECT MAX(created_at) AS dt FROM t WHERE t.id_pasien = 193 ) AS a ON a.dt=t.created_at ``` This query will also work if there multiple records withe same date for given id\_pasien. Change **193** with your **$id\_pasien** I hope this will solve your problem, Upvotes: 0 <issue_comment>username_3: Following code will be helpful to you, ``` $query = "SELECT id_start_odon FROM start_odon s1 WHERE s1.id_pasien = $id_pasien AND s1.created_at = (SELECT MAX(s2.created_at) FROM start_odon s2 WHERE s2.id_pasien = s1.id_pasien)"; ``` Upvotes: 0 <issue_comment>username_4: `ORDER BY`created\_at`DESC` gets you the latest date. `limit 1` returns oanly one row. `WHERE id_pasien` `=` `$id_pasien` so it looks for specific `id_pasien`. ``` SELECT `id_start_odon` FROM `start_odon`WHERE `id_pasien` = `$id_pasien` order by `created_at` DESC limit 1 ``` Upvotes: 2 [selected_answer]
2018/03/21
1,100
3,431
<issue_start>username_0: I've got the following html setup: ``` Movies Music Books ``` Here is my fiddle: <https://jsfiddle.net/z7aymz5a/20/> I am targeting each checkbox by its value, because the classes the the same for all. What I would like to achieve is to put a colored circle behind each of the checkboxes, just before the label as on the picture here below [![enter image description here](https://i.stack.imgur.com/t2NzE.png)](https://i.stack.imgur.com/t2NzE.png) I got as far as putting the circle in, but I just can't figure out how to correctly style it, so it sits after the checkbox, but before the label. Anyone could pls help me crack this?<issue_comment>username_1: You can try this: ``` input { width: 32px; } input::after { font-size: 19px; line-height: 12px; content: "\25CF"; margin-left: 24px; } input[value="movie"]::after { color: red; } input[value="music"]::after { color: blue; } input[value="books"]::after { color: green; } ``` Upvotes: 1 <issue_comment>username_2: You are almost there, the issue is that input elements don't support pseudo elements. This answer has some more details on the why: <https://stackoverflow.com/a/4660434/5269101> So, a solution to your problem would be: 1- wrap the text "music", "movies" and "books" in span elements 2- replace those `::after` in your css with `::before` and instead of targeting the input elements, target the span elements with a sibling selector. your css would look like this: ``` input[value="movie"] ~ span::before { color: red; content: "\25CF"; font-size: 2.5em; } input[value="music"] ~ span::before { color: blue; content: "\25CF"; font-size: 2.5em; } input[value="books"] ~span::before { color: green; content: "\25CF"; font-size: 2.5em; } ``` and your html would be: ``` Movies Music Books ``` Upvotes: 0 <issue_comment>username_3: You can achieve this in a more simple way. Just adding a tag like before your text in the label and formatting it as you want. ``` .checkbox { position: relative; } .circle { border-radius: 50%; width: 12px; height: 12px; display: inline-block; margin-right: 5px; } .movie { background-color: red; } .music { background-color: blue; } .books { background-color: green; } ``` Your html: ``` Movies Music Books ``` Fiddle: <https://jsfiddle.net/kjcqqh44/13/> **UPDATE** For dynamically HTML provided by a plugin, you can use this code you can add the circle with javascript ``` var checkCircle = document.body.querySelectorAll('input[value][type="checkbox"]'); var checkbox = document.body.querySelectorAll('.checkbox'); for (i=0; i < checkbox.length; i++) { var inp = checkbox[i].querySelectorAll('input[value][type="checkbox"]')[0] var span = document.createElement('i'); span.className = 'circle ' + inp.value; inp.parentNode.insertBefore(span, inp.nextSibling); } ``` <https://jsfiddle.net/kjcqqh44/32/> Upvotes: 0 <issue_comment>username_4: without touching html and properly positioned ``` input { margin-right: 20px; } input::after { content: "\25CF"; font-size: 30px; position: relative; top: -12px; right: -16px; } input[value="movie"]::after { color: red; } input[value="music"]::after { color: blue; } input[value="books"]::after { color: green; } ``` Upvotes: 2 [selected_answer]
2018/03/21
371
1,578
<issue_start>username_0: Is there any valid reason that we should use interfaces over polymorphism? Every video, resource and everything else I searched just talks on how it's good to have interfaces to follow rules (contracts) or to just follow polymorphic behaviour. Can anyone expand? It seems nobody else can... I'm specifically looking at why interfaces are used for decoupling and how they can help with that.<issue_comment>username_1: 1. You can’t substitute a test stub 2. A class can’t have multiple base classes but can have multiple interfaces 3. Classes can’t have generic variance, only interfaces and delegate types can. 4. Sometimes you want to declare an interface without an implementation, e.g. so two different apps can agree on a contract defined in code. Upvotes: 0 <issue_comment>username_2: **Interfaces *Formalise* polymorphism** Interfaces allow us to define polymorphism in a declarative way, unrelated to implementation. Two elements are polymorphic with respect to a set of behaviours if they realise the same interfaces. **In regards to decoupling** Classes can share the same Footprint / Interface and live in totally different places in the world and need not know about each other, hence decoupled. [Coupling (computer programming)](https://en.wikipedia.org/wiki/Coupling_(computer_programming)) > > In software engineering, coupling is the degree of interdependence > between software modules; a measure of how closely connected two > routines or modules are;[ the strength of the relationships between > modules. > > > Upvotes: 1
2018/03/21
399
1,551
<issue_start>username_0: ``` var readline = require('readline'); var {google} = require('googleapis'); var OAuth2 = google.auth.OAuth2; var SCOPES = ['https://www.googleapis.com/auth/youtube.upload']; ``` Getting the error: ``` {google} = require('googleapis') SyntaxError: Unexpected token { ``` I am using [YouTube API](https://developers.google.com/youtube/v3/quickstart/nodejs).<issue_comment>username_1: 1. You can’t substitute a test stub 2. A class can’t have multiple base classes but can have multiple interfaces 3. Classes can’t have generic variance, only interfaces and delegate types can. 4. Sometimes you want to declare an interface without an implementation, e.g. so two different apps can agree on a contract defined in code. Upvotes: 0 <issue_comment>username_2: **Interfaces *Formalise* polymorphism** Interfaces allow us to define polymorphism in a declarative way, unrelated to implementation. Two elements are polymorphic with respect to a set of behaviours if they realise the same interfaces. **In regards to decoupling** Classes can share the same Footprint / Interface and live in totally different places in the world and need not know about each other, hence decoupled. [Coupling (computer programming)](https://en.wikipedia.org/wiki/Coupling_(computer_programming)) > > In software engineering, coupling is the degree of interdependence > between software modules; a measure of how closely connected two > routines or modules are;[ the strength of the relationships between > modules. > > > Upvotes: 1
2018/03/21
1,393
5,042
<issue_start>username_0: I've written this function to return the new array with the values that are same in both the arrays. It works fine but I'm using two loops which gives the runtime of O(n^2). Any suggestions to improve the runtime of this function. ``` var dynamicConfig = ["Test1","Test22","Test3","Test14"]; var staticConfig = [{label: 'Test 1',value: 'Test1'}, {label: 'Test 2',value: 'Test2'}, {label: 'Test 3',value: 'Test3'} ]; function configObj(dynamicConfig, staticConfig) { var templateArray = []; for (var i = 0; i < dynamicConfig.length; i++) { for (var j = 0; j < staticConfig.length; j++) { if (dynamicConfig[i] === staticConfig[j].value) { templateArray.push(staticConfig[j]); break; } } } console.log(templateArray); return templateArray; } configObj(dynamicConfig, staticConfig); ``` There's a working [jsfiddle](http://jsfiddle.net/zubairm/yvv2mdkr/18/) of the same.<issue_comment>username_1: This below code has the time complexity of O(n). Your can also compare the time taken to execute for loops by calculating the start and end time. ```js var dynamicConfig = ["Test1","Test22","Test3","Test14"]; var staticConfig = [{label: 'Test 1',value: 'Test1'}, {label: 'Test 2',value: 'Test2'}, {label: 'Test 3',value: 'Test3'} ]; function configObj(dynamicConfig, staticConfig) { var templateArray = []; for (var j = 0; j < staticConfig.length; j++) { if (dynamicConfig.includes(staticConfig[j].value)) { templateArray.push(staticConfig[j]); } } console.log(templateArray); return templateArray; } configObj(dynamicConfig, staticConfig); ``` Upvotes: -1 <issue_comment>username_2: One solution could be to have or convert the second 'staticConfig' array to javascript object. Javascript uses hashmap internally to implement any object. You can then get the object using map['Test 1'] which has complexity O(1). But you will have to convert the list in a separate loop for converting in an object. Overall complexity will come to O(n). Since you only need to compare value field of objects in 'staticConfig' you can also use javascript set object. You can try something like this: ```js var dynamicConfig = ["Test1","Test22","Test3","Test14"]; var staticConfig = [{label: 'Test 1',value: 'Test1'}, {label: 'Test 2',value: 'Test2'}, {label: 'Test 3',value: 'Test3'} ]; var map = {}; for(var i = 0; i < staticConfig.length; i++){ var obj = staticConfig[i]; map[obj.value] = obj.label; } function configObj(dynamicConfig, staticConfig) { var templateArray = []; for (var j = 0; j < dynamicConfig.length; j++) { if (map[dynamicConfig[j]] != null && map[dynamicConfig[j]] != undefined && map[dynamicConfig[j]] != 'undefined') { templateArray.push(dynamicConfig[j]); } } console.log(templateArray); return templateArray; } configObj(dynamicConfig, staticConfig); ``` Or use Set ```js var dynamicConfig = ["Test1","Test22","Test3","Test14"]; var staticConfig = [{label: 'Test 1',value: 'Test1'}, {label: 'Test 2',value: 'Test2'}, {label: 'Test 3',value: 'Test3'} ]; var setObj = new Set(); for(var i = 0; i < staticConfig.length; i++){ var obj = staticConfig[i]; setObj.add(obj.value); } function configObj(dynamicConfig, setObj) { var templateArray = []; for (var j = 0; j < dynamicConfig.length; j++) { if (setObj.has(dynamicConfig[j])) { templateArray.push(dynamicConfig[j]); } } console.log(templateArray); return templateArray; } configObj(dynamicConfig, setObj); ``` Upvotes: 0 <issue_comment>username_3: when to find the common elements in the array,it is good practice to sort both the arrays first and then it will be easy to find the common elements.. but coming to javascript you can use es6 Set function to make the task easier.. below is my code , it may appear as O(n^2) but trust me `Set.has` is faster than `array.indexOf` here is the proof -> <https://jsperf.com/array-indexof-vs-set-has> ``` let dynamicConfig1 = ["Test1","Test22","Test3","Test14"]; let staticConfig = [ { label: 'Test 1', value: 'Test1' }, { label: 'Test 2', value: 'Test2', }, { label: 'Test 3', value: 'Test3', } ]; let dynamicConfig = new Set([...dynamicConfig1.map((item)=>item)]) let commonElements = [...staticConfig].filter(x => dynamicConfig.has(x.value)); console.log(commonElements) ``` js fiddle for the same <http://jsfiddle.net/yvv2mdkr/70/> Upvotes: 2 [selected_answer]
2018/03/21
1,343
5,352
<issue_start>username_0: I already have build kendo ui and javasript function. the function return datasource value. i want to bind this datasource value inside kendo ui grid. But i dont know how to bind this together. i want to pass 'list' in function inside my kendo ui. any help ? This is my kendo ui code: ``` ` $(document).ready(function () { $("#grid").kendoGrid({ dataSource: { transport: { read: { } }, schema: { model: { fields: { ActivityID: { type: "number" }, Assigner: { type: "string" }, AssignDate: { type: "date" }, Task: { type: "string" }, Assignee: { type: "string" }, DueDate: { type: "date"}, CompletionDate: { type: "date"}, Status: { type: "string" }, } } }, ``` ` This is my javascript function: ``` ` ```<issue_comment>username_1: This below code has the time complexity of O(n). Your can also compare the time taken to execute for loops by calculating the start and end time. ```js var dynamicConfig = ["Test1","Test22","Test3","Test14"]; var staticConfig = [{label: 'Test 1',value: 'Test1'}, {label: 'Test 2',value: 'Test2'}, {label: 'Test 3',value: 'Test3'} ]; function configObj(dynamicConfig, staticConfig) { var templateArray = []; for (var j = 0; j < staticConfig.length; j++) { if (dynamicConfig.includes(staticConfig[j].value)) { templateArray.push(staticConfig[j]); } } console.log(templateArray); return templateArray; } configObj(dynamicConfig, staticConfig); ``` Upvotes: -1 <issue_comment>username_2: One solution could be to have or convert the second 'staticConfig' array to javascript object. Javascript uses hashmap internally to implement any object. You can then get the object using map['Test 1'] which has complexity O(1). But you will have to convert the list in a separate loop for converting in an object. Overall complexity will come to O(n). Since you only need to compare value field of objects in 'staticConfig' you can also use javascript set object. You can try something like this: ```js var dynamicConfig = ["Test1","Test22","Test3","Test14"]; var staticConfig = [{label: 'Test 1',value: 'Test1'}, {label: 'Test 2',value: 'Test2'}, {label: 'Test 3',value: 'Test3'} ]; var map = {}; for(var i = 0; i < staticConfig.length; i++){ var obj = staticConfig[i]; map[obj.value] = obj.label; } function configObj(dynamicConfig, staticConfig) { var templateArray = []; for (var j = 0; j < dynamicConfig.length; j++) { if (map[dynamicConfig[j]] != null && map[dynamicConfig[j]] != undefined && map[dynamicConfig[j]] != 'undefined') { templateArray.push(dynamicConfig[j]); } } console.log(templateArray); return templateArray; } configObj(dynamicConfig, staticConfig); ``` Or use Set ```js var dynamicConfig = ["Test1","Test22","Test3","Test14"]; var staticConfig = [{label: 'Test 1',value: 'Test1'}, {label: 'Test 2',value: 'Test2'}, {label: 'Test 3',value: 'Test3'} ]; var setObj = new Set(); for(var i = 0; i < staticConfig.length; i++){ var obj = staticConfig[i]; setObj.add(obj.value); } function configObj(dynamicConfig, setObj) { var templateArray = []; for (var j = 0; j < dynamicConfig.length; j++) { if (setObj.has(dynamicConfig[j])) { templateArray.push(dynamicConfig[j]); } } console.log(templateArray); return templateArray; } configObj(dynamicConfig, setObj); ``` Upvotes: 0 <issue_comment>username_3: when to find the common elements in the array,it is good practice to sort both the arrays first and then it will be easy to find the common elements.. but coming to javascript you can use es6 Set function to make the task easier.. below is my code , it may appear as O(n^2) but trust me `Set.has` is faster than `array.indexOf` here is the proof -> <https://jsperf.com/array-indexof-vs-set-has> ``` let dynamicConfig1 = ["Test1","Test22","Test3","Test14"]; let staticConfig = [ { label: 'Test 1', value: 'Test1' }, { label: 'Test 2', value: 'Test2', }, { label: 'Test 3', value: 'Test3', } ]; let dynamicConfig = new Set([...dynamicConfig1.map((item)=>item)]) let commonElements = [...staticConfig].filter(x => dynamicConfig.has(x.value)); console.log(commonElements) ``` js fiddle for the same <http://jsfiddle.net/yvv2mdkr/70/> Upvotes: 2 [selected_answer]
2018/03/21
1,256
4,472
<issue_start>username_0: I have a string content. ``` $string = "FIRST he ate some lettuces and some French beans, and then he ate some radishes AND then, feeling rather sick, he went to look for some parsley."; ``` Here I want to take a specific string ``` "then he ate some radishes" ``` How can I do it with REGEX? I want it in REGEX only ``` I want to pass just 2 parameters like 1. then 2. radishes ``` so finally I want output like `"then he ate some radishes"`<issue_comment>username_1: This below code has the time complexity of O(n). Your can also compare the time taken to execute for loops by calculating the start and end time. ```js var dynamicConfig = ["Test1","Test22","Test3","Test14"]; var staticConfig = [{label: 'Test 1',value: 'Test1'}, {label: 'Test 2',value: 'Test2'}, {label: 'Test 3',value: 'Test3'} ]; function configObj(dynamicConfig, staticConfig) { var templateArray = []; for (var j = 0; j < staticConfig.length; j++) { if (dynamicConfig.includes(staticConfig[j].value)) { templateArray.push(staticConfig[j]); } } console.log(templateArray); return templateArray; } configObj(dynamicConfig, staticConfig); ``` Upvotes: -1 <issue_comment>username_2: One solution could be to have or convert the second 'staticConfig' array to javascript object. Javascript uses hashmap internally to implement any object. You can then get the object using map['Test 1'] which has complexity O(1). But you will have to convert the list in a separate loop for converting in an object. Overall complexity will come to O(n). Since you only need to compare value field of objects in 'staticConfig' you can also use javascript set object. You can try something like this: ```js var dynamicConfig = ["Test1","Test22","Test3","Test14"]; var staticConfig = [{label: 'Test 1',value: 'Test1'}, {label: 'Test 2',value: 'Test2'}, {label: 'Test 3',value: 'Test3'} ]; var map = {}; for(var i = 0; i < staticConfig.length; i++){ var obj = staticConfig[i]; map[obj.value] = obj.label; } function configObj(dynamicConfig, staticConfig) { var templateArray = []; for (var j = 0; j < dynamicConfig.length; j++) { if (map[dynamicConfig[j]] != null && map[dynamicConfig[j]] != undefined && map[dynamicConfig[j]] != 'undefined') { templateArray.push(dynamicConfig[j]); } } console.log(templateArray); return templateArray; } configObj(dynamicConfig, staticConfig); ``` Or use Set ```js var dynamicConfig = ["Test1","Test22","Test3","Test14"]; var staticConfig = [{label: 'Test 1',value: 'Test1'}, {label: 'Test 2',value: 'Test2'}, {label: 'Test 3',value: 'Test3'} ]; var setObj = new Set(); for(var i = 0; i < staticConfig.length; i++){ var obj = staticConfig[i]; setObj.add(obj.value); } function configObj(dynamicConfig, setObj) { var templateArray = []; for (var j = 0; j < dynamicConfig.length; j++) { if (setObj.has(dynamicConfig[j])) { templateArray.push(dynamicConfig[j]); } } console.log(templateArray); return templateArray; } configObj(dynamicConfig, setObj); ``` Upvotes: 0 <issue_comment>username_3: when to find the common elements in the array,it is good practice to sort both the arrays first and then it will be easy to find the common elements.. but coming to javascript you can use es6 Set function to make the task easier.. below is my code , it may appear as O(n^2) but trust me `Set.has` is faster than `array.indexOf` here is the proof -> <https://jsperf.com/array-indexof-vs-set-has> ``` let dynamicConfig1 = ["Test1","Test22","Test3","Test14"]; let staticConfig = [ { label: 'Test 1', value: 'Test1' }, { label: 'Test 2', value: 'Test2', }, { label: 'Test 3', value: 'Test3', } ]; let dynamicConfig = new Set([...dynamicConfig1.map((item)=>item)]) let commonElements = [...staticConfig].filter(x => dynamicConfig.has(x.value)); console.log(commonElements) ``` js fiddle for the same <http://jsfiddle.net/yvv2mdkr/70/> Upvotes: 2 [selected_answer]
2018/03/21
996
2,770
<issue_start>username_0: I would like to add a string to an existing column. For example, `df['col1']` has values as `'1', '2', '3'` etc and I would like to concat string `'000'` on the left of `col1` so I can get a column (new or replace the old one doesn't matter) as `'0001', '0002', '0003'`. I thought I should use `df.withColumn('col1', '000'+df['col1'])` but of course it does not work since pyspark dataframe are immutable? This should be an easy task but i didn't find anything online. Hope someone can give me some help! Thank you!<issue_comment>username_1: ``` from pyspark.sql.functions import concat, col, lit df.select(concat(col("firstname"), lit(" "), col("lastname"))).show(5) +------------------------------+ |concat(firstname, , lastname)| +------------------------------+ | <NAME>| | <NAME>| | <NAME>| | <NAME>| | <NAME>| +------------------------------+ only showing top 5 rows ``` <http://spark.apache.org/docs/2.0.0/api/python/pyspark.sql.html#module-pyspark.sql.functions> Upvotes: 7 [selected_answer]<issue_comment>username_2: Another option here is to use [`pyspark.sql.functions.format_string()`](http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.functions.format_string) which allows you to use [C `printf` style formatting](https://docs.python.org/2/library/stdtypes.html#string-formatting). Here's an example where the values in the column are integers. ```python import pyspark.sql.functions as f df = sqlCtx.createDataFrame([(1,), (2,), (3,), (10,), (100,)], ["col1"]) df.withColumn("col2", f.format_string("%03d", "col1")).show() #+----+----+ #|col1|col2| #+----+----+ #| 1| 001| #| 2| 002| #| 3| 003| #| 10| 010| #| 100| 100| #+----+----+ ``` Here the format `"%03d"` means print an integer number left padded with up to 3 zeros. This is why the `10` gets mapped to `010` and `100` does not change at all. Or if you wanted to add exactly 3 zeros in the front: ```python df.withColumn("col2", f.format_string("000%d", "col1")).show() #+----+------+ #|col1| col2| #+----+------+ #| 1| 0001| #| 2| 0002| #| 3| 0003| #| 10| 00010| #| 100|000100| #+----+------+ ``` Upvotes: 4 <issue_comment>username_3: I did this is PySpark in Databricks (Azure). Lets assume you have a column named 'column\_source' in your data frame `df` with values `1,2,3` | column\_source | | --- | | 1 | | 2 | | 3 | Then you can use below code: ``` from pyspark.sql import functions as F df = df.withColumn('column_modified', F.concat(F.lit("000"), F.col('column_source'))) ``` output: | column\_source | column\_modified | | --- | --- | | 1 | 0001 | | 2 | 0002 | | 3 | 0003 | Upvotes: 2
2018/03/21
1,017
2,898
<issue_start>username_0: I'm trying to create a script that echoes the first 12 arguments of ls command. We are supposed to do it using the "shift" syntax build into the shell, but im having a hard time understanding how the shift command works (Yes, I looked it up, tried it, and cant figure it out). If anyone can point me in the right direction of how to use the shift command to accomplish this goal, it would be much appreciated. I posted what ive tried so far belore (Fair warning, it endlessly loops, if you try to run it yourself) ``` #!/bin/sh args=a A b c C d e E f F g h H while [ $# -lt 12 ] do echo ls -$# count=`expr $# + 1` shift done ```<issue_comment>username_1: ``` from pyspark.sql.functions import concat, col, lit df.select(concat(col("firstname"), lit(" "), col("lastname"))).show(5) +------------------------------+ |concat(firstname, , lastname)| +------------------------------+ | <NAME>| | <NAME>| | <NAME>| | <NAME>| | <NAME>| +------------------------------+ only showing top 5 rows ``` <http://spark.apache.org/docs/2.0.0/api/python/pyspark.sql.html#module-pyspark.sql.functions> Upvotes: 7 [selected_answer]<issue_comment>username_2: Another option here is to use [`pyspark.sql.functions.format_string()`](http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.functions.format_string) which allows you to use [C `printf` style formatting](https://docs.python.org/2/library/stdtypes.html#string-formatting). Here's an example where the values in the column are integers. ```python import pyspark.sql.functions as f df = sqlCtx.createDataFrame([(1,), (2,), (3,), (10,), (100,)], ["col1"]) df.withColumn("col2", f.format_string("%03d", "col1")).show() #+----+----+ #|col1|col2| #+----+----+ #| 1| 001| #| 2| 002| #| 3| 003| #| 10| 010| #| 100| 100| #+----+----+ ``` Here the format `"%03d"` means print an integer number left padded with up to 3 zeros. This is why the `10` gets mapped to `010` and `100` does not change at all. Or if you wanted to add exactly 3 zeros in the front: ```python df.withColumn("col2", f.format_string("000%d", "col1")).show() #+----+------+ #|col1| col2| #+----+------+ #| 1| 0001| #| 2| 0002| #| 3| 0003| #| 10| 00010| #| 100|000100| #+----+------+ ``` Upvotes: 4 <issue_comment>username_3: I did this is PySpark in Databricks (Azure). Lets assume you have a column named 'column\_source' in your data frame `df` with values `1,2,3` | column\_source | | --- | | 1 | | 2 | | 3 | Then you can use below code: ``` from pyspark.sql import functions as F df = df.withColumn('column_modified', F.concat(F.lit("000"), F.col('column_source'))) ``` output: | column\_source | column\_modified | | --- | --- | | 1 | 0001 | | 2 | 0002 | | 3 | 0003 | Upvotes: 2
2018/03/21
703
2,785
<issue_start>username_0: I just wanted to create query dynamically.Means I just wanted to specify in which column the sorting will occure and type sorting as `ASC or DESC` also with this query i have to limit the no of records. I am using the **PostgreSQL** here. So in the query i should specify the **limit and offset** . So that i am sending the four variable in the sense attribute to the interface. **WorkflowDetailsInterface.java** ``` @Configuration public interface WorkflowDetailsInterface extends CrudRepository { @Query(value ="SELECT workflow\_id, workflow\_name, workflow\_description, workflow\_definition, " + "camunda\_workflow\_json, camuda\_deployment\_id, camunda\_status,diagnostic\_flag, " + "active, del\_flag FROM workflow ORDER BY :orderByColoumn : orderByOrder LIMIT :recordCountLimit OFFSET :startLimit",nativeQuery = true) List listWorkflowName(@Param("startLimit") int startLimit, @Param("recordCountLimit")int recordCountLimit,@Param("orderByColoumn")String orderByColoumn, @Param("orderByOrder")String orderByOrder); } ``` Here , `@Param("startLimit") int startLimit` will be the starting point `@Param("recordCountLimit")int recordCountLimit` this is the offset `@Param("orderByColoumn")String orderByColoumn` order by column name `@Param("orderByOrder")String orderByOrder` order by type **ASC** or **DESC** How can i dynamically bind these variable to my JPA query<issue_comment>username_1: Instead of extending `CrudRepository` extend `PagingAndSortingRepository`. '[findAll](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/PagingAndSortingRepository.html#findAll-org.springframework.data.domain.Pageable-)' method serves your purpose. [PageRequest](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/PageRequest.html) is an implementation of [Pageable](https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Pageable.html). You can specify limit, offset and sort details. Check this [article](http://www.baeldung.com/spring-data-repositories) to know more about usage. You may not need native query with this approach. Upvotes: 0 <issue_comment>username_2: Why not use stored procedures inside PostgreSQL and pass the parameter mentioning which column to sort and pass Limit parameter to it. Refer to [here](https://stackoverflow.com/questions/8139618/postgresql-parameterized-order-by-limit-in-table-function) for more info. You can call the stored procedure like this: ``` String sql ="call (:parameter1)"; @SuppressWarnings("deprecation") Query query = sessionFactory.getCurrentSession().createNativeQuery(sql).addEntity(.class).setParameter("parameter1", ); ``` Hope it helps. Upvotes: 2 [selected_answer]
2018/03/21
1,931
8,958
<issue_start>username_0: I updated my office to `insider version`, and my `customFunction` is working. Then I added the `AllFormFactors` tag to my `manifest.xml` and `Visual Studio` gives me an error > > AllFormFactors is `invalid` > > > ``` ... ... ``` Thanks in advance! Here is my manifest. ```xml xml version="1.0" encoding="UTF-8"? a1225f90-b53e-4920-ae4b-2bc4a68c5176 1.0.0.0 [dddd name] en-US AppDomain1 AppDomain2 AppDomain3 ReadWriteDocument ButtonId1 MyTaskPaneID1 MyTaskPaneID2 <SourceLocation resid="functionsjs" /> ``` And here is my console: [![enter image description here](https://i.stack.imgur.com/sQvbK.png)](https://i.stack.imgur.com/sQvbK.png)<issue_comment>username_1: This is a schema validation error. You're getting this because `AllFormFactors` is still in Preview and not part of the published schema definition. This should not prevent you from sideloading your add-in in Excel however. Upvotes: 0 <issue_comment>username_2: **Issue:** This issue is caused by Visual Studio's XML schema validation. **Cause:** Microsoft have not yet updated/published the latest schema's to the Visual Studio installer. **Background:** If you look at the xmlns attributes of your office manifest(or any xml), those URL's does not point to web. Instead they are string compared and matched to a file inside your Visual Studio's installation. This issue is causing/pushing a lot of .Net developers to the NodeJS route using YeoMan generator. **Solution:** > > 1. Add your AllFormFactors tag as per the tutorials (My Schema is not perfect so the order matters). > > > ``` <SourceLocation resid="Functions.Script.Url" /> ``` > > 2. Open your Office manifest xml and at the top MenuBar and XML menu Item will appear. Click on the schema.. Look for "<http://schemas.microsoft.com/office/taskpaneappversionoverrides>". > 3. As you can see the Schema URL point to a file location on your Visual Studio installation directory. > 4. Edit that .xsd schema file(Make a backup first) with the following code: > > > ``` xml version="1.0" encoding="utf-8"? Specifies a taskpane extension URL to display when a user interface extension point is invoked by the user. Specifies a callback to execute when a user interface extension point is invoked by the user. Specifies an action to perform when a user interface extension point is invoked by the user. Specifies the super tip for this control. Specifies a user interface extension point of various kinds. The unique identifier of this control within the form factor. Specifies a user interface extension point of various kinds that contain an icon. Specifies a user interface extension point of various kinds that may or may not contain an icon. Specifies a user interface extension point that displays as a standard button. Specifies a user interface extension point that displays as an item in a menu control. Specifies a list of menu actions. Specifies a user interface extension point that displays as a menu of actions. Specifies a specific group of user interface extension points in a tab in the Office client application. The unique identifier of this group within the form factor. Specifies a tab in the Office client application where this Office add-in will customize the user interface. Specifies the identifier of the tab to which the child groups belong. If this tab is a CustomTab element, it is the identifier of the new tab. If it is an OfficeTab, it is the identifier of the preexisting Office UI tab in which to insert content. Specifies a built-in menu of the Office client application to add this Office add-in Specifies the identifier of the built-in menu to which the controls will be added Specifies an extension to a pre-existing tab in the Office client application where this Office add-in will customize the user interface. Specifies an Office add-in defined tab in the Office client application where this Office add-in will customize the user interface. Specifies an Office add-in defined tab in the Office client application where this Office add-in will customize the user interface. Specifies an Office add-in defined tab in the Office client application where this Office add-in will customize the user interface. Specifies an Office add-in defined tab in the Office client application where this Office add-in will customize the user interface. Specifies an Office add-in defined tab in the Office client application where this Office add-in will customize the user interface. Specifies the identifier of the built-in menu to which the controls will be added Specifies a location in the Office client application where the Office add-in exposes functionality. Specifies location in an Office client application's user interface where the Office add-in exposes functionality. Specifies location in an Office client application's user interface where the Office add-in exposes functionality. Specifies the ways this Office add-in exposes functionality through the primary command display of the Office client application (eg. Desktop Ribbon). Specifies the ways this Office add-in exposes functionality through the context menus of the Office client application. Specifies the Get Started information for the Office add-in. This information is used at various places on the Office User Interface after user installs an add-in. Specifies the list of settings for the Office add-in when activated for a given form factor of the Office client application. Specifies the Get Started information for the Office add-in. This information is used at various places on the Office User Interface after user installs an add-in. Specifies the source code file for the Office add-in, containing operations it exposes via its extension points, to use when loaded in this form factor. Specifies a location in an Office client application where the Office add-in registers itself to perform operations. Generic type for specifying Host node types under the Hosts element list Defines add-in command extensions for Excel, including supported form factors. Specifies the settings of the Office add-in when running in a desktop version of Excel. Specifies the settings of the Office add-in when running in a all version of Excel. Defines add-in command extensions for Word, including supported form factors. Specifies the settings of the Office add-in when running in a desktop version of Word. Defines add-in command extensions for OneNote, including supported form factors. Specifies the settings of the Office add-in when running in a desktop version of OneNote. Defines add-in command extensions for PowerPoint, including supported form factors. Specifies the settings of the Office add-in when running in a desktop version of PowerPoint. Specifies the Office client application types where an Office add-in will be activated. Specifies the Office client application where an Office add-in will be activated. Specifies the scope strings for any permissions that your application needs to external resources. Specifies the scope string for one permission that your application needs to external resources. A parent node for SSO node: Id, Resource and Scopes. Specifies the client id of your multi-tenant application as registered with Microsoft. Specifies the resource for your application’s Web API. Specifies the scope strings for any permissions that your application needs to external resources. Contains elements for the version 1.0 overrides of the Office task pane add-in manifest. Specifies a more verbose description of the Office add-in. Overrides the Description element in the parent node of this element in the manifest Specifies the minimum set of Office.js requirements that the Office add-in needs to activate. Overrides the Requirements element in the parent node of this element in the manifest. Specifies a collection of Office client application types. Overrides the Hosts element in the parent node of this element in the manifest. Specifies a collection of resources referenced by other elements of the manifest where resource references are supported. A parent node for SSO node: WebApplicationId, WebApplicationResource and WebApplicationScopes. Contains elements for use in future versions of the Office add-in platform as they release. These elements may be overrides to previously defined elements or new elements. Specifies a collection of Office client application types. Data defined in this element overrides the same data present in the parent node of this element in the manifest for Office client applications that support this extended manifest content. ``` **Tip:** I took it so far by even removing the default web project inside the solution and added a ASP.Net Core web project with authentication with my manifest pointing to that URL successfully ;) Upvotes: 1
2018/03/21
1,729
8,517
<issue_start>username_0: I have Users table, which has firstName and lastName columns. I want to add a new column userName and populate it with concatenation of firstname and lastname, i.e. <NAME> should have smth like john\_smith (j\_smith) as username<issue_comment>username_1: This is a schema validation error. You're getting this because `AllFormFactors` is still in Preview and not part of the published schema definition. This should not prevent you from sideloading your add-in in Excel however. Upvotes: 0 <issue_comment>username_2: **Issue:** This issue is caused by Visual Studio's XML schema validation. **Cause:** Microsoft have not yet updated/published the latest schema's to the Visual Studio installer. **Background:** If you look at the xmlns attributes of your office manifest(or any xml), those URL's does not point to web. Instead they are string compared and matched to a file inside your Visual Studio's installation. This issue is causing/pushing a lot of .Net developers to the NodeJS route using YeoMan generator. **Solution:** > > 1. Add your AllFormFactors tag as per the tutorials (My Schema is not perfect so the order matters). > > > ``` <SourceLocation resid="Functions.Script.Url" /> ``` > > 2. Open your Office manifest xml and at the top MenuBar and XML menu Item will appear. Click on the schema.. Look for "<http://schemas.microsoft.com/office/taskpaneappversionoverrides>". > 3. As you can see the Schema URL point to a file location on your Visual Studio installation directory. > 4. Edit that .xsd schema file(Make a backup first) with the following code: > > > ``` xml version="1.0" encoding="utf-8"? Specifies a taskpane extension URL to display when a user interface extension point is invoked by the user. Specifies a callback to execute when a user interface extension point is invoked by the user. Specifies an action to perform when a user interface extension point is invoked by the user. Specifies the super tip for this control. Specifies a user interface extension point of various kinds. The unique identifier of this control within the form factor. Specifies a user interface extension point of various kinds that contain an icon. Specifies a user interface extension point of various kinds that may or may not contain an icon. Specifies a user interface extension point that displays as a standard button. Specifies a user interface extension point that displays as an item in a menu control. Specifies a list of menu actions. Specifies a user interface extension point that displays as a menu of actions. Specifies a specific group of user interface extension points in a tab in the Office client application. The unique identifier of this group within the form factor. Specifies a tab in the Office client application where this Office add-in will customize the user interface. Specifies the identifier of the tab to which the child groups belong. If this tab is a CustomTab element, it is the identifier of the new tab. If it is an OfficeTab, it is the identifier of the preexisting Office UI tab in which to insert content. Specifies a built-in menu of the Office client application to add this Office add-in Specifies the identifier of the built-in menu to which the controls will be added Specifies an extension to a pre-existing tab in the Office client application where this Office add-in will customize the user interface. Specifies an Office add-in defined tab in the Office client application where this Office add-in will customize the user interface. Specifies an Office add-in defined tab in the Office client application where this Office add-in will customize the user interface. Specifies an Office add-in defined tab in the Office client application where this Office add-in will customize the user interface. Specifies an Office add-in defined tab in the Office client application where this Office add-in will customize the user interface. Specifies an Office add-in defined tab in the Office client application where this Office add-in will customize the user interface. Specifies the identifier of the built-in menu to which the controls will be added Specifies a location in the Office client application where the Office add-in exposes functionality. Specifies location in an Office client application's user interface where the Office add-in exposes functionality. Specifies location in an Office client application's user interface where the Office add-in exposes functionality. Specifies the ways this Office add-in exposes functionality through the primary command display of the Office client application (eg. Desktop Ribbon). Specifies the ways this Office add-in exposes functionality through the context menus of the Office client application. Specifies the Get Started information for the Office add-in. This information is used at various places on the Office User Interface after user installs an add-in. Specifies the list of settings for the Office add-in when activated for a given form factor of the Office client application. Specifies the Get Started information for the Office add-in. This information is used at various places on the Office User Interface after user installs an add-in. Specifies the source code file for the Office add-in, containing operations it exposes via its extension points, to use when loaded in this form factor. Specifies a location in an Office client application where the Office add-in registers itself to perform operations. Generic type for specifying Host node types under the Hosts element list Defines add-in command extensions for Excel, including supported form factors. Specifies the settings of the Office add-in when running in a desktop version of Excel. Specifies the settings of the Office add-in when running in a all version of Excel. Defines add-in command extensions for Word, including supported form factors. Specifies the settings of the Office add-in when running in a desktop version of Word. Defines add-in command extensions for OneNote, including supported form factors. Specifies the settings of the Office add-in when running in a desktop version of OneNote. Defines add-in command extensions for PowerPoint, including supported form factors. Specifies the settings of the Office add-in when running in a desktop version of PowerPoint. Specifies the Office client application types where an Office add-in will be activated. Specifies the Office client application where an Office add-in will be activated. Specifies the scope strings for any permissions that your application needs to external resources. Specifies the scope string for one permission that your application needs to external resources. A parent node for SSO node: Id, Resource and Scopes. Specifies the client id of your multi-tenant application as registered with Microsoft. Specifies the resource for your application’s Web API. Specifies the scope strings for any permissions that your application needs to external resources. Contains elements for the version 1.0 overrides of the Office task pane add-in manifest. Specifies a more verbose description of the Office add-in. Overrides the Description element in the parent node of this element in the manifest Specifies the minimum set of Office.js requirements that the Office add-in needs to activate. Overrides the Requirements element in the parent node of this element in the manifest. Specifies a collection of Office client application types. Overrides the Hosts element in the parent node of this element in the manifest. Specifies a collection of resources referenced by other elements of the manifest where resource references are supported. A parent node for SSO node: WebApplicationId, WebApplicationResource and WebApplicationScopes. Contains elements for use in future versions of the Office add-in platform as they release. These elements may be overrides to previously defined elements or new elements. Specifies a collection of Office client application types. Data defined in this element overrides the same data present in the parent node of this element in the manifest for Office client applications that support this extended manifest content. ``` **Tip:** I took it so far by even removing the default web project inside the solution and added a ASP.Net Core web project with authentication with my manifest pointing to that URL successfully ;) Upvotes: 1
2018/03/21
1,527
4,913
<issue_start>username_0: How do I copy a value from `WarehouseInventory` Sheet to `Scan Report` Sheet if that value exists on `dictionary items`? I'm able to compare the values on both Sheets (columns) but having trouble referencing the dictionary items offset cell address. --- *Example* ``` If List.Exists(Inv_Data(i, 1)) Then .Cells(i, 1).Offset(0, 7).Value2 = "LPN SCANNED" SCAN_REPORT.Cells(x, 1).Offset(0, 1).Value2 = Inv_Data(i, 2) Else .Cells(i, 1).Offset(0, 7).Value = "LPN NOT SCAN" End If ``` --- *`SCAN_REPORT.Cells(x, 1)` is adding the value on the last row* --- ``` Option Explicit Private Sub Example() Dim SCAN_REPORT As Worksheet Set SCAN_REPORT = ActiveWorkbook.Worksheets("Scan Report") Dim List As New Scripting.Dictionary With SCAN_REPORT Dim Scn_LRow As Long Scn_LRow = .Cells(.Rows.Count, 1).End(xlUp).Row Dim Scn_Data() As Variant Scn_Data = .Range(.Cells(1, 1), .Cells(Scn_LRow, 1)).Value2 Dim x As Long For x = LBound(Scn_Data) To UBound(Scn_Data) Step 1 DoEvents Debug.Print Scn_Data(x, 1) On Error Resume Next 'resume if dupe List.Add Scn_Data(x, 1), x On Error GoTo 0 Debug.Print Scn_Data(x, 1), x Next Dim INVENTORY_REPORT As Worksheet Set INVENTORY_REPORT = ActiveWorkbook.Worksheets("WarehouseInventory") With INVENTORY_REPORT Dim Inv_LRow As Long Inv_LRow = INVENTORY_REPORT.Cells(.Rows.Count, 1).End(xlUp).Row Dim Inv_Data() As Variant Inv_Data = .Range(.Cells(1, 1), .Cells(Inv_LRow, 7)).Value2 Dim i As Long For i = LBound(Inv_Data) To UBound(Inv_Data) Step 1 DoEvents If List.Exists(Inv_Data(i, 1)) Then .Cells(i, 1).Offset(0, 7).Value2 = "LPN SCANNED" SCAN_REPORT.Cells(x, 1).Offset(0, 1).Value2 = Inv_Data(i, 2) ' SCAN_REPORT.Cells(x, 1).Offset(0, 2).Value2 = Inv_Data(i, 3) ' SCAN_REPORT.Cells(x, 1).Offset(0, 3).Value2 = Inv_Data(i, 4) Else .Cells(i, 1).Offset(0, 7).Value = "LPN NOT SCAN" End If Next End With End With End Sub ```<issue_comment>username_1: You don't have any use for `x` in your second loop. You need to retrieve the item (which is the row number you denoted as `x` when dumping values in the dictionary) associated with your *key*. Something like this might work: ``` SCAN_REPORT.Cells(List(Inv_Data(i, 1)), 1).Offset(0, 1).Value2 = Inv_Data(i, 2) ``` However, this will only mark or update the last occurrence of data in `SCAN_REPORT` if you go with what Jeeped suggested in his comment(the shortcut in item overwriting). In your current code though, you will only update the first occurrence. Upvotes: 2 <issue_comment>username_2: I added a .CompareMode option and tightened up some code. HTHs. ``` Option Explicit Private Sub Example() Dim SCAN_REPORT As Worksheet Set SCAN_REPORT = ActiveWorkbook.Worksheets("Scan Report") Dim List As New Scripting.Dictionary List.comparemode = vbTextCompare '<~~ ADDED! With SCAN_REPORT Dim Scn_LRow As Long Scn_LRow = .Cells(.Rows.Count, 1).End(xlUp).Row Dim Scn_Data() As Variant Scn_Data = .Range(.Cells(1, 1), .Cells(Scn_LRow, 1)).Value2 Dim x As Long For x = LBound(Scn_Data) To UBound(Scn_Data) Step 1 'Debug.Print Scn_Data(x, 1) List.Item(Scn_Data(x, 1)) = x 'Debug.Print Scn_Data(x, 1), x Next Dim INVENTORY_REPORT As Worksheet Set INVENTORY_REPORT = ActiveWorkbook.Worksheets("WarehouseInventory") With INVENTORY_REPORT Dim Inv_LRow As Long Inv_LRow = .Cells(.Rows.Count, 1).End(xlUp).Row Dim Inv_Data() As Variant Inv_Data = .Range(.Cells(1, 1), .Cells(Inv_LRow, 7)).Value2 Dim i As Long For i = LBound(Inv_Data, 1) To UBound(Inv_Data, 1) 'DoEvents If List.Exists(Inv_Data(i, 1)) Then .Cells(i, 1).Offset(0, 7).Value2 = "LPN SCANNED" 'i think this next line correction should resolve things SCAN_REPORT.Cells(List.ITEM(Inv_Data(i, 1)), 1).Offset(0, 1).Value2 = Inv_Data(i, 2) 'SCAN_REPORT.Cells(List.ITEM(Inv_Data(i, 1)), 1).Offset(0, 2).Value2 = Inv_Data(i, 3) 'SCAN_REPORT.Cells(List.ITEM(Inv_Data(i, 1)), 1).Offset(0, 3).Value2 = Inv_Data(i, 4) Else .Cells(i, 1).Offset(0, 7).Value = "LPN NOT SCAN" End If Next End With End With End Sub ``` Upvotes: 2 [selected_answer]
2018/03/21
601
2,273
<issue_start>username_0: I have developed quite a big single page application using create-react-app. I am in the process of migrating everything to NextJS, mainly for SEO purposes. I'm scratching my head on one issue : what is the best way to handle responsive design? In my create-react-app legacy code, I'm always keepings components in sync with window.innerWidth, and am using it to handle most of the responsiveness (except for the grid layout that is handled by material-ui). But since we can't guess the client's width during the server render, then how can you avoid a 'flicker' of the UI? Do we need to delay any responsive UI logic until we can execute on the client?<issue_comment>username_1: The solution is : using javascript to handle responsivness is bad practice, css should be used if we don't want to browser to re-flow the content on the screen. if you are using material-ui, take a look at [this page](https://mui.com/material-ui/react-hidden/) Upvotes: 4 [selected_answer]<issue_comment>username_2: This is how I tackled the problem I defined a theme and breakpoints for my stylings. in theme.js file I use createTheme from material-ui. it gives you the option of defining breakpoints: ``` breakpoints: { values: { xs: 0, sm: 600, md: 960, lg: 1220, xl: 1920, }, } ``` I predefined sizes I want to change styles based on them. meaning that 0 to 600 is a mobile view... this is how I use breakpoints in my styles classes ``` const styles = theme => { return { classname: { //css codes for web view [theme.breakpoints.down('sm')]: { //css codes for mobile view. }, [theme.breakpoints.between('sm', 'md')]: { //css codes tablet view }, [theme.breakpoints.up('md')]: { //css codes for resizes between web to tablet size }, }, }} ``` By resizing the window or opening the page in different devices you will see the different styles. It works fine in both ssr and client side components. note: If you are not interested in predefining the sizes you can use a different size for each css class like this one. ``` [theme.breakpoints.down('600')]: { //css codes for mobile view. }, ``` Upvotes: 1
2018/03/21
714
2,880
<issue_start>username_0: So far for storing in **Room Database** I've been using type converter for each classes. Like this: ``` @SerializedName("sidebar") @Expose @TypeConverters(SidebarConverter.class) private Sidebar sidebar; @SerializedName("splash") @Expose @TypeConverters(SplashConverter.class) private Splash splash; @SerializedName("overview") @Expose @TypeConverters(OverviewConverter.class) private Overview overview; @SerializedName("home") @Expose @TypeConverters(HomeConverter.class) private Home home; @SerializedName("portfolio") @Expose @TypeConverters(PortfolioConverter.class) private Portfolio portfolio; @SerializedName("team") @Expose @TypeConverters(TeamConverter.class) private Team team; ``` I want to know if there's a more convenient way to use one `TypeConverter` single handedly in Database.<issue_comment>username_1: You can define all your converter in a Single Class like this: ``` public class DateTypeConverter { @TypeConverter public static Date toDate(Long value) { return value == null ? null : new Date(value); } @TypeConverter public static Long toLong(Date value) { return value == null ? null : value.getTime(); } } ``` And then set this converter on your Room Database with `@TypeConverter` annotation like this which work globally on any `@Entity` class.You don't need to define `@TypeConverter` Individually in Entity class ``` @Database(entities = {Product.class}, version = 1) @TypeConverters({DateTypeConverter.class}) public abstract class MyDatabase extends RoomDatabase { public abstract ProductDao productDao(); } ``` Note we’ve added a new annotation named `@TypeConverters` in our database definition in order to reference the different converters that we can have (you can separate it by commas and add others). Upvotes: 3 <issue_comment>username_2: The issue here is that Room's code generation tries to find specific type, and if you try to make a generic converter it fails to generate appropriate methods. However, if in your case it's appropriate to transfrom data to json for storage, you can reduce boilerplate like this: ``` @TypeConverter fun toSomething(value: String): Something = fromJson(value) @TypeConverter fun fromSomething(value: Something): String = toJson(value) ``` fromJson and toJson are generic, for example they can look like this. Any time you need to add types, just take two methods above and replace 'Something' with your type. If you have a lot of classes to convert, you can even code-gen TypeConverters like this pretty easily to satisfy Room's code-gen needs. ``` inline fun fromJson(value: String): T { val jsonAdapter = moshi.adapter(T::class.java) return jsonAdapter.fromJson(value) } inline fun toJson(value: T): String { val jsonAdapter = moshi.adapter(T::class.java) return jsonAdapter.toJson(value) } ``` Upvotes: 1
2018/03/21
3,946
13,206
<issue_start>username_0: When I try to run the command `ionic cordova build android` out error as title above. Then I try to remove one of the `gms`, when I build again the deleted it appears again. how to solve this?. Here is my dependencies of my `build.gradle` : ``` dependencies { compile fileTree(dir: 'libs', include: '*.jar') // SUB-PROJECT DEPENDENCIES START debugCompile(project(path: "CordovaLib", configuration: "debug")) releaseCompile(project(path: "CordovaLib", configuration: "release")) compile "com.google.android.gms:play-services-auth:+" // i remove this compile "com.google.android.gms:play-services-identity:+" compile "com.facebook.android:facebook-android-sdk:4.+" // SUB-PROJECT DEPENDENCIES END } ```<issue_comment>username_1: When you run the command **ionic cordova** you can change the version,I have the same error, and i fixed the problem by changing version my nodes modules, my plugin cordova, version off android studio. **My conf below:** ANDROID STUDIO: 3.0.0 ``` pply plugin: 'com.android.application' ``` buildscript { repositories { jcenter() maven { url "<https://maven.google.com>" } } ``` // Switch the Android Gradle plugin version requirement depending on the // installed version of Gradle. This dependency is documented at // http://tools.android.com/tech-docs/new-build-system/version-compatibility // and https://issues.apache.org/jira/browse/CB-8143 dependencies { classpath 'com.android.tools.build:gradle:2.2.3' classpath 'com.google.gms:google-services:3.1.1' // google-services plugin } ``` } // Allow plugins to declare Maven dependencies via build-extras.gradle. allprojects { repositories { jcenter() maven { url "<https://maven.google.com>" } } } task wrapper(type: Wrapper) { gradleVersion = '2.14.1' } ... ... ... ... ... apply plugin: 'com.google.gms.google-services' Gradle version : 3.3 com.google.android.gms:play-services:11.4.2 Some times node module and cordova plugin gets himself wrong, so you do delete manually in the folder. Don’t forget to remove and add cordova plugin when you update it. Try to go in android studio => files => project structure => project =>ok Normally android studio should synchonize your gradle **OR** **Error: more than one library with package name com.google.android.gms.license** In my case, the problem was because I was including: ``` compile 'com.google.android.gms:play-services-wearable:+' compile 'com.google.android.gms:play-services:4.4.52' ``` both the wearable play services, and the regular. I commented out the wearable part, and it works. Not sure if I'll need it, but it was included by default by the project wizard I hope I can help you. Keep going ! Upvotes: 2 <issue_comment>username_2: I've faced this issue quite recently and the problem for me was that for some reason the android project.properties file was generated with different versions for the com.google.android.gms, as such: ``` target=android-26 android.library.reference.1=CordovaLib cordova.system.library.1=com.android.support:support-v4:24.1.1+ cordova.system.library.2=com.google.android.gms:play-services-auth:+ cordova.system.library.3=com.google.android.gms:play-services-identity:+ cordova.system.library.4=com.google.android.gms:play-services-location:11.+ ``` This makes the library.2 and library.3 require one version while the library.4 requires a more specific version, thus causing the duplicate library reference during compiling. While I don't think this should be the final solution, adding the specific library worked for me. As such: ``` target=android-26 android.library.reference.1=CordovaLib cordova.system.library.1=com.android.support:support-v4:24.1.1+ cordova.system.library.2=com.google.android.gms:play-services-auth:11.+ cordova.system.library.3=com.google.android.gms:play-services-identity:11.+ cordova.system.library.4=com.google.android.gms:play-services-location:11.+ ``` Upvotes: 5 [selected_answer]<issue_comment>username_3: This happening because of Play services 12.0.0. I went ahead and downgraded the dependencies to 11.8.0 ( last known working version for my project). I'm using react native. I had 2 dependencies which were pulling in 12.0.0 of google play services - com.google.android:play-services...12.0.0 Hope this helps. Upvotes: 3 <issue_comment>username_4: Maybe it related to new release of Google Play services 12.0.0(released at March 20, 2018) I've resolved it fixing dependencies: Add config in `android/build.gradle` ``` allprojects { repositories { ... configurations.all { resolutionStrategy { // Add force (11.0.0 is version you want to use) force 'com.google.firebase:firebase-core:11.0.0' force 'com.google.firebase:firebase-crash:11.0.0' force 'com.google.firebase:firebase-analytics:11.0.0' force 'com.google.firebase:firebase-messaging:11.0.0' force 'com.google.android.gms:play-services-base:11.0.0' force 'com.google.android.gms:play-services-maps:11.0.0' force 'com.google.android.gms:play-services-wallet:11.0.0' } } } } ``` Set of dependencies are from your `android/app/build.gradle` Upvotes: 3 <issue_comment>username_5: in build.gradle add this ``` configurations.all { resolutionStrategy { force "com.google.android.gms:play-services-ads:11.8.0" force "com.google.android.gms:play-services-base:11.8.0" force "com.google.android.gms:play-services-gcm:11.8.0" force "com.google.android.gms:play-services-analytics:11.8.0" force "com.google.android.gms:play-services-location:11.8.0" force "com.google.android.gms:play-services-basement:11.8.0" force "com.google.android.gms:play-services-tagmanager:11.8.0" force 'com.google.firebase:firebase-core:11.8.0' force 'com.google.firebase:firebase-crash:11.8.0' force 'com.google.firebase:firebase-auth:11.8.0' force 'com.google.firebase:firebase-common:11.8.0' force 'com.google.firebase:firebase-config:11.8.0' force 'com.google.firebase:firebase-messaging:11.8.0' } } ``` if that doesn't work, search in your project the string '12.0.0' and add in the list above the missing library Upvotes: 4 <issue_comment>username_6: Things i had to do to get the build to succeed on my Ionic3 App: * Add Plugin cordova-android-play-services-gradle-release * Remove and re-add the android platform * 11.+ in platform/android/project.properties file for libraries ( Especially if you're using firebase ) * 11.+ for dependencies in platforms/android/cordova-plugin-firebase/-build.gradle * The above changes in platforms/android/build.gradle This might be the worst possible way to get things work, but kinda saved my life. Hope this helps someone! Upvotes: 3 <issue_comment>username_7: For me, it was a matter of adding version number to Google Play Services in **project.properies** file. So you need to change something like: ``` android.library.reference.1=CordovaLib cordova.system.library.2=com.google.android.gms:play-services-auth: cordova.system.library.3=com.google.android.gms:play-services-identity: ``` to: ``` android.library.reference.1=CordovaLib cordova.system.library.2=com.google.android.gms:play-services-auth:11. cordova.system.library.3=com.google.android.gms:play-services-identity:11. ``` Upvotes: 1 <issue_comment>username_8: In my case ``` npm update cordova platform remove android cordova platform add [email protected] ``` And replace in platform/android/projet.properties ``` cordova.system.library.1=com.android.support:support-v4+ ``` To ``` cordova.system.library.1=com.android.support:support-v4:26+ ``` Upvotes: 2 <issue_comment>username_9: just change platform/android/project.properties to ``` target=android-26 android.library.reference.1=CordovaLib cordova.system.library.1=com.android.support:support-v4:24.1.1+ cordova.system.library.2=com.google.android.gms:play-services-auth:11.+ cordova.system.library.3=com.google.android.gms:play-services-identity:11.+ cordova.system.library.4=com.google.android.gms:play-services-location:11.+ ``` this worked for me Upvotes: 2 <issue_comment>username_10: It works for me. ``` node_modules/react-native-camera/android/build.gradle: dependencies { compile 'com.facebook.react:react-native:+' compile 'com.google.android.gms:play-services-gcm:11.8.0' // update by me on 20180321 } ``` Upvotes: 2 <issue_comment>username_11: **UPDATE** The cause of this error has been identified as a bug in [v12.0.0 of the Google Play Services library](https://developers.google.com/android/guides/releases#march_20_2018_-_version_1200): > > **Known Issues with version 12.0.0** > -license POM dependencies cause "more than one library with package name ‘com.google.android.gms.license'" issues in Ionic Pro. > > > The bug has been fixed in [v12.0.1 of the Google Play Services library](https://developers.google.com/android/guides/releases#march_28_2018_-_version_1201): > > Restores unique package names for runtime linked -license artifacts which affected some build systems' (e.g. Ionic Pro) compatibility issues. > > > Therefore specifying v12.0.1 or above of the Play Services Library via the [cordova-android-play-services-gradle-release](https://github.com/dpa99c/cordova-android-play-services-gradle-release) plugin resolves the issue, for example: ``` cordova plugin add cordova-android-play-services-gradle-release --variable PLAY_SERVICES_VERSION=12.+ ``` Upvotes: 2 <issue_comment>username_12: Only this worked for me in `build.gradle`: ``` allprojects { repositories { ... configurations.all { resolutionStrategy.eachDependency { DependencyResolveDetails details -> def requested = details.requested if (requested.group == 'com.google.android.gms') { details.useVersion '11.8.0' } if (requested.group == 'com.google.firebase') { details.useVersion '11.8.0' } } } } } ``` <https://github.com/evollu/react-native-fcm/issues/857#issuecomment-375243825> Upvotes: 1 <issue_comment>username_13: **1.** Go to project.properties (in your platform folder) **2.** I was using just google analytics in my "project.properties" and had to add " 11.+" to the end of the version and that worked for me. Not sure if that's long term fix but it did the trick. ``` cordova.system.library.2=com.google.android.gms:play-services-analytics:11.+ ``` Upvotes: 1 <issue_comment>username_14: I was facing the same error in my ionic project, after little search I have read about to upgrade the Android platform which is required for latest Android Gradle Plugin in order to build the app. **The solution to is very easy** just follow the below mentioned step. 1. Remove your existing Anroid platform > > ionic cordova platform remove android > > > 2. Add minimum version Android SDK Build Tools 26.0.2 through Android SDK Manager to use latest Android Gradle Plugin in order to build the app 3. Add minimum version for Android platform > > ionic cordova platform add android@^6.4.0 > > > Upvotes: 1 <issue_comment>username_15: For reference, from: <https://developers.google.com/android/guides/releases> **Google APIs for Android** **March 20, 2018 - Version 12.0.0** **Known Issues with version 12.0.0** * ... * -license POM dependencies cause "more than one library with package name ‘com.google.android.gms.license'" issues in Ionic Pro. * ... We will provide an updated 12.0.1 release to address these issues soon. --- ***My Workaround*** (based on [username_5](https://stackoverflow.com/users/2246035/jeremy-castelli)'s [answer](https://stackoverflow.com/a/49408093/644634) and [keldar](https://stackoverflow.com/users/1038786/keldar)'s subsequent comment) I am using the following workaround (and I stress, this is a workaround). Add the following to the bottom of build-extras.gradle, creating the file if necessary. ``` configurations.all { resolutionStrategy { force 'com.google.firebase:firebase-core:11.8+', 'com.google.firebase:firebase-messaging:11.8+', 'com.google.firebase:firebase-crash:11.8+', 'com.google.firebase:firebase-config:11.8+', 'com.google.firebase:firebase-auth:11.8+', 'com.google.android.gms:play-services-tagmanager:11.8+', 'com.google.android.gms:play-services-location:11.8+' } } ``` It is important to include all firebase and all android.gms library references, if you miss just one from here, it will still fail to build. Grep your gradle files for all the references. In my case I had missed firebase-auth which was referenced in the firebase plugin folder's .gradle file. What [resolutionStrategy](https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html) `force` does is override the version choices made by the project/plugins and force gradle to reference a specific version. There is no need to edit project.properties or any other gradle files using this workaround. Upvotes: 2
2018/03/21
931
3,351
<issue_start>username_0: I want to disable the submit button till all the input fields are filled in the page using angularjs/bootstrap. I tried using `ng-disabled="myForm.$invalid"` but it doesn't seem to work. Any inputs? [Demo](https://plnkr.co/edit/mqIYIx4KIlOV1JOSHVJI?p=preview) **HTML Code** ``` Select Color : {{color}} Please Select the color Username : The Username is required Submit ```<issue_comment>username_1: I think you missed to add ng-model for checkbox and textbox. Can you please check below code. ```html Example - example-checkbox-input-directive-production angular.module('checkboxExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.colorNames = ['RED', 'BLUE', 'BLACK']; $scope.selectedColor = []; $scope.userSelection = function userSelection(team) { var idx = $scope.selectedColor.indexOf(team); if (idx > -1) { $scope.selectedColor.splice(idx, 1); } else { $scope.selectedColor.push(team); } }; $scope.submitForm = function(){ if ($scope.selectedColor != "" && $scope.selectedColor != undefined && $scope.user != "" && $scope.user != undefined) { alert("all fields are entered"); }else{ } } }]); Select Color : {{color}} Please Select the color Username : The Username is required Submit ``` Upvotes: 2 <issue_comment>username_2: You have written the condition wrong. Please write ng-disabled="!myForm.$invalid". Also, writing {{myForm.$invalid}} in html shows its current value which was false in your case. ``` Select Color : {{color}} Please Select the color Username : The Username is required {{myForm.$invalid}} Submit ``` Upvotes: 1 <issue_comment>username_3: add `ng-model` to your input field ``` ``` Upvotes: 1 <issue_comment>username_4: You need to do 2 additional things, 1. Use ng-required for all the inputs instead of required. and add ng-model for all the inputs. 2. for checkboxes, you need to check if atleast one of the checkboxes is selected. If one is selected you can make ng-required = false. For that you can check if the length of the selectedColor is greater than 0. PFB the modified code, ``` Example - example-checkbox-input-directive-production angular.module('checkboxExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.colorNames = ['RED', 'BLUE', 'BLACK']; $scope.selectedColor = []; $scope.userSelection = function userSelection(team) { var idx = $scope.selectedColor.indexOf(team); if (idx > -1) { $scope.selectedColor.splice(idx, 1); } else { $scope.selectedColor.push(team); } }; $scope.submitForm = function(){ if ($scope.selectedColor != "" && $scope.selectedColor != undefined && $scope.user != "" && $scope.user != undefined) { alert("all fields are entered"); }else{ } } }]); Select Color : {{color}} Please Select the color Username : The Username is required Submit ``` Upvotes: 0 <issue_comment>username_5: I did two changes: 1. add ng-model for your fields 2. in check boxes I change the model name as `ng-model="color_$index"` **$index** get the index of the array and it helps to identify each checkbox individually. ``` Select Color : {{color}} Please Select the color Username : The Username is required Submit ``` Upvotes: 0
2018/03/21
1,039
4,488
<issue_start>username_0: I'm trying to add Facebook and Twitter auth to my react-native app at the same time. According to the official instructions, I need to modify the AppDelegate.m file for handUrl the following way for twitter: ``` - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary \*)options { return [[Twitter sharedInstance] application:app openURL:url options:options]; } ``` And the following way for facebook. ``` - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary \*)options { BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey] ]; // Add any custom logic here. return handled; } ``` How can I combine the two? I tried to check the variables and decide which one to return however no success so far.<issue_comment>username_1: You can try with checking **`url.absoluteString`** **For Example:** ``` - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { //Get absolute string NSString *aStrURL = url.absoluteString; if ([aStrURL containsString:@"YOUR_FACEBOOK_APP_ID"]){ // facebook related code here return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation]; } else{ // twitter or other code here return [[Twitter sharedInstance] application:app openURL:url options:options]; } } ``` Upvotes: 1 <issue_comment>username_2: You can check for url.scheme like this :- ``` - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { //App opened with Facebook scheme if([url.scheme isEqualToString:@"YOUR_FACEBOOK_ID"]){ return [[FBSDKApplicationDelegate sharedInstance] application:app openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey]]; } //App opened with Twitter scheme else if ([url.scheme isEqualToString:@"YOUR_TWITTER_ID"]){ return [[Twitter sharedInstance] application:app openURL:url options:options]; } //App opened with different scheme else{ return YES; } } ``` Upvotes: 1 <issue_comment>username_3: I ended up solving it the following way: My AppDelegate.m ``` #import "AppDelegate.h" #import #import #import #import #import @implementation AppDelegate - (BOOL)application:(UIApplication \*)application didFinishLaunchingWithOptions:(NSDictionary \*)launchOptions { NSURL \*jsCodeLocation; jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil]; RCTRootView \*rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"mirrorapp" initialProperties:nil launchOptions:launchOptions]; rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController \*rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; return [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions]; // return YES; } - (BOOL)application:(UIApplication \*)app openURL:(NSURL \*)url options:(NSDictionary \*)options { return [[Twitter sharedInstance] application:app openURL:url options:options]; } - (BOOL)application:(UIApplication \*)application openURL:(NSURL \*)url sourceApplication:(NSString \*)sourceApplication annotation:(id)annotation { return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation]; } @end ``` Upvotes: 1 [selected_answer]
2018/03/21
526
1,860
<issue_start>username_0: I am working in an Angular4 application, where I want to handle the span (enable/disable) based on a condition. When there's no items in the cart I want to disable the span. But when there's at least 1 product in the cart. The span will be enabled. [![enter image description here](https://i.stack.imgur.com/7hM9L.png)](https://i.stack.imgur.com/7hM9L.png) ``` {{nCount}} ``` How can I handle this, from HTML or typescript side.. ``` import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { DatePipe } from '@angular/common'; import { HostListener } from '@angular/core'; import {CartdataService} from './cartdata.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit{ nCount : string; constructor(private CartdataService:CartdataService,private http: HttpClient) { } ngOnInit() { this.CartdataService.cast.subscribe(Count=> this.nCount = Count); } } ```<issue_comment>username_1: You can add an If statement \*ngIf you want to hide it. If you don't want it displayed. (I'm assuming you meant that instead of disabled). Here it will not display if the count is 0. Span doesn't act as a control, therefore it isn't possible to disable. See the following list for what elements can be disabled: <https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes> ``` {{nCount}} ``` Upvotes: 1 <issue_comment>username_2: Try this in your css: ``` .disabled { pointer-events: none; # use this if you want to block all pointer events on element display: none; # use this if you want to hide element } .notification-counter { cursor: pointer; } ``` and for your span: ``` {{nCount}} ``` Upvotes: 5 [selected_answer]
2018/03/21
337
1,212
<issue_start>username_0: I have a simple website made with PHP and framework Laravel. Now I want to just display the date not the clock time and when I am posting my article on my website it will display the time and date according to the clock on the laptop. how do I do this? any references? this is my code: ``` ###### {{ ucwords($article->user->name) }}    {{ date('d M Y', strtotime($article->created\_at)) }} *{{ count($count) }}* ```<issue_comment>username_1: You can add an If statement \*ngIf you want to hide it. If you don't want it displayed. (I'm assuming you meant that instead of disabled). Here it will not display if the count is 0. Span doesn't act as a control, therefore it isn't possible to disable. See the following list for what elements can be disabled: <https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes> ``` {{nCount}} ``` Upvotes: 1 <issue_comment>username_2: Try this in your css: ``` .disabled { pointer-events: none; # use this if you want to block all pointer events on element display: none; # use this if you want to hide element } .notification-counter { cursor: pointer; } ``` and for your span: ``` {{nCount}} ``` Upvotes: 5 [selected_answer]
2018/03/21
359
1,207
<issue_start>username_0: Can't figure out this trivial thing. Have several elements with different classes and I need to count `height` of that one which has for example class `.a`. ``` ``` I would need to get the result count in variable `count_of_a` so something like that: ``` var count_of_a = jQuery( ".a" ).each(function(){ jQuery(this).height(); }); ```<issue_comment>username_1: Here is an example : ``` $('.a').height() * $('.a').length ``` Upvotes: 0 <issue_comment>username_2: you're close :) the definition of `each` is > > Function( Integer index, Element element ) > > > so you need the second argument to access your current object try this : ``` var totalHeight = 0; jQuery('.a').each(function(index ,element ){ totalHeight += jQuery(element).height(); }); console.log(totalHeight); ``` here's a fiddle : <https://jsfiddle.net/uduauxrg/8/> <https://api.jquery.com/each/> Upvotes: 3 [selected_answer]<issue_comment>username_3: ``` $(function(){ $('div.a').each(function(){ alert($(this).height()); }); }); ``` Do you mean you want the height value total or respectively? Here's an example shows individual height of class a div. Upvotes: 0
2018/03/21
1,022
3,735
<issue_start>username_0: I'm new to Mobx but so far it's been working great and I've managed to get pretty far. I have a react-native application with mobx, and mobx-persist. I'm using axios to pull posts from a Wordpress site. The functionality that I'm trying to improve is an "add to favorites" feature. Here's my PostsStore: ``` export default class PostsStore { // Define observables and persisting elements @observable isLoading = true; @persist('list') @observable posts = []; @persist('list') @observable favorites = []; // Get posts from Wordpress REST API @action getPosts() { this.isLoading = true; axios({ url: 'SITE_URL', method: 'get' }) .then((response) => { this.posts = response.data this.isLoading = false }) .catch(error => console.log(error)) } // Add post to favorites list, ensuring that it does not previously exist @action addToFavorites(id) { if (this.favorites.indexOf(id) === -1) { this.favorites.push(id); } } // Remove post from favorites list, ensuring that it does indeed exist @action removeFromFavorites(id) { if (this.favorites.indexOf(id) !== -1) { this.favorites.remove(id); } } } ``` In my Favorites component, which is intended to render a button to add or remove from favorites, I thought that using an @computed function would've been preferred to determine if the current post being rendered has an 'id' that has been added to the observable 'favorites' array. However, it seems that an @computed function is not allowed to take arguments (a minimum parameter would be the post's 'id' to evaluate if it is in the favorites observable array. I can accomplish the test using an @action but that doesn't seem to update the rendered screen immediately which is the objective. As the code below demonstrates, I'm forced to perform the test with an 'if' statement in the component render. ``` render () { if (this.props.postsStore.favorites.includes(this.props.item.id)) { return ( this.props.postsStore.removeFromFavorites(this.props.item.id)} title="★" /> ) } ``` Does this affect my application's performance? Is there an @computed way to do what I want? Should I just not worry about this since it's kinda working?<issue_comment>username_1: Doing this worked: ``` @computed get isFavorite() { return createTransformer(id => this.favorites.includes(id)) } ``` Called in my view like so: ``` this.props.postsStore.isFavorite(this.props.item.id) ``` Upvotes: 3 <issue_comment>username_2: I'm not sure `@computed` is necessary here as it will create a new `createTransformer` when called everytime after `this.favorites` changes. This should produce the same result with only using a single `createTransformer` ```js isFavorite = id => createTransformer(id => this.favorites.includes(id)) ``` Upvotes: 2 <issue_comment>username_3: Just for the sake of completeness: [mobx-utils](https://github.com/mobxjs/mobx-utils) provides a way to use arguments in computed functions by now. You can use `computedFn` and would declare your function as follows: ``` isFavorite = computedFn(function isFavorite(id) { return this.favorites.includes(id) }) ``` Take a look at the [article](https://mobx.js.org/computeds-with-args.html#4-use-computedfn-) in the docs. Upvotes: 3 <issue_comment>username_4: You can simply wrap it: ``` @computed get isFavorite(): (id: string) => boolean { return (id: string) => { return this.favorites.includes(id); }; } ``` And see the options the official MobX docs suggests: <https://mobx.js.org/computeds-with-args.html> PS. I recomend to re-check whether you really need the `computed` here. The regular method might be good enough in your case. Upvotes: 0
2018/03/21
334
1,004
<issue_start>username_0: When I use ScrollableTabView is nested inside ScrollView, it can't show anything in Android althought I updated ScrollableTabView version 0.8.0. react-native-cli: 2.0.1 react-native: 0.44.3 My code like this: ``` render() { return ( {this.\_renderUser()} }> {this.\_renderCusProfile()} ); } ``` [Please click here to show image example](https://user-images.githubusercontent.com/24695000/30317641-45153a30-97dd-11e7-91aa-80de94a961b0.png) Any pointers to what I might need to change in your code to get this to work? Thanks<issue_comment>username_1: Not sure what styling includes in your Styles.tabView. If you use { flex: 1 } inside your style object for this might work. Upvotes: 0 <issue_comment>username_2: import Dimensions from react native : ``` import { ... Dimensions } from "react-native"; ``` then you bring height : ``` const { height } = Dimensions.get('window'); ``` And you apply hight to ScrollableTabView ``` ``` Upvotes: 1
2018/03/21
1,262
3,795
<issue_start>username_0: I recently started using the [huxtable](https://hughjonesd.github.io/huxtable/) R package for tables and I'm really impressed with it. One thing I can't seem to figure out, however, is how to get line breaks *within* a cell. Here's what I've tried ``` library(tidyverse) library(huxtable) cars <- mtcars %>% mutate(car = rownames(.), car = str_replace(car, " ", "\n")) %>% slice(1:5) %>% select(car, cyl, hp) cars # A tibble: 5 x 3 car cyl hp 1 "Mazda\nRX4" 6.00 110 2 "Mazda\nRX4 Wag" 6.00 110 3 "Datsun\n710" 4.00 93.0 4 "Hornet\n4 Drive" 6.00 110 5 "Hornet\nSportabout" 8.00 175 ht <- as\_hux(cars, add\_colnames = TRUE) escape\_contents(ht) <- TRUE ht ``` But this ends up without the line break, as in the screenshot below [![enter image description here](https://i.stack.imgur.com/PuWnz.png)](https://i.stack.imgur.com/PuWnz.png) The `escape_contents` part doesn't seem to make a difference. I'm not sure if what I want is possible, but I know it is in other packages (e.g., `DT::datatable`). I'd really like to use huxtable, if possible, however, because I like the design and flexibility of the package. Any thoughts would be great. **EDIT:** I should have specified I'm hoping to get this to work for PDF.<issue_comment>username_1: According to [Escaping HTML or LaTeX](https://hughjonesd.github.io/huxtable/huxtable.html#escaping-html-or-latex), You should use `escape_contents(ht) <- FALSE` and use tag instead of `\n` ``` library(tidyverse) library(huxtable) cars <- mtcars %>% mutate(car = rownames(.), car = str_replace(car, " ", " ")) %>% slice(1:5) %>% select(car, cyl, hp) ht <- as_hux(cars, add_colnames = TRUE) escape_contents(ht) <- FALSE ht ``` note that the output is a Rmarkdown document and thanks for the package information. it looks good. following is the output of mine [![enter image description here](https://i.stack.imgur.com/qlL5g.png)](https://i.stack.imgur.com/qlL5g.png) Upvotes: 2 <issue_comment>username_2: Okay, so combining insights from [this LaTeX StackExchange post](https://tex.stackexchange.com/questions/2441/how-to-add-a-forced-line-break-inside-a-table-cell/132661#132661) and [this classic XKCD](https://xkcd.com/1638/) got me this: ``` library(tidyverse) library(huxtable) cars <- mtcars %>% mutate(car = rownames(.), car = str_replace(car, "(\\S*)\\s(.*)", "\\\\vtop{\\\\hbox{\\\\strut \\1}\\\\hbox{\\\\strut \\2}}")) %>% slice(1:5) %>% select(car, cyl, hp) ht <- as_hux(cars, add_colnames = TRUE) %>% set_escape_contents(1:6, 1, FALSE) theme_article(ht) ``` which gives the following PDF output: [![enter image description here](https://i.stack.imgur.com/A08Rb.png)](https://i.stack.imgur.com/A08Rb.png) Of course, you won't need quite as many escapes if you're building your own cells by hand rather than using `str_replace`. Note that putting `set_escape_contents` to `FALSE` for the cells with line breaks is crucial. Upvotes: 1 <issue_comment>username_3: Try this, which minimizes the amount of backslashes: ```r library(tidyverse) library(huxtable) cars <- mtcars %>% mutate(car = rownames(.)) cars$car <- str_replace(cars$car, " ", "\\\\newline ") cars %>% as_hux(add_colnames = TRUE) %>% set_wrap(TRUE) %>% set_escape_contents(everywhere, "car", FALSE) %>% quick_pdf() ``` [![enter image description here](https://i.stack.imgur.com/piX5I.png)](https://i.stack.imgur.com/piX5I.png) The `set_wrap()` call is necessary for LaTeX tables to accept newlines, I believe. If you want to escape different parts of the cells containing newlines, you can do that manually, e.g. with `xtable::sanitize()`. Upvotes: 2
2018/03/21
1,124
3,527
<issue_start>username_0: I want to create a pie chart for the percentage of males and females in a table in my database. I've Written the following code but it is not working. Please help. ```js php $mysqli = new mysqli("localhost", "root", "", "ganesh"); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $sql1 = mysqli_query($mysqli,"SELECT SUM(CASE WHEN Gender = \'Male\' THEN 1 ELSE 0 END) FROM student"); $sql2 = mysqli_query($mysqli,"SELECT SUM(CASE WHEN Gender = \'Female\' THEN 1 ELSE 0 END) as Female_count FROM student"); echo " <script type = 'text/javascript' src="https://www.gstatic.com/charts/loader.js" google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Gender', 'Number'], ['Male', ".$sql1."], ['Female', ".$sql2."] ]); var options = { title: 'First Year' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } "; ?> chart ```<issue_comment>username_1: According to [Escaping HTML or LaTeX](https://hughjonesd.github.io/huxtable/huxtable.html#escaping-html-or-latex), You should use `escape_contents(ht) <- FALSE` and use tag instead of `\n` ``` library(tidyverse) library(huxtable) cars <- mtcars %>% mutate(car = rownames(.), car = str_replace(car, " ", " ")) %>% slice(1:5) %>% select(car, cyl, hp) ht <- as_hux(cars, add_colnames = TRUE) escape_contents(ht) <- FALSE ht ``` note that the output is a Rmarkdown document and thanks for the package information. it looks good. following is the output of mine [![enter image description here](https://i.stack.imgur.com/qlL5g.png)](https://i.stack.imgur.com/qlL5g.png) Upvotes: 2 <issue_comment>username_2: Okay, so combining insights from [this LaTeX StackExchange post](https://tex.stackexchange.com/questions/2441/how-to-add-a-forced-line-break-inside-a-table-cell/132661#132661) and [this classic XKCD](https://xkcd.com/1638/) got me this: ``` library(tidyverse) library(huxtable) cars <- mtcars %>% mutate(car = rownames(.), car = str_replace(car, "(\\S*)\\s(.*)", "\\\\vtop{\\\\hbox{\\\\strut \\1}\\\\hbox{\\\\strut \\2}}")) %>% slice(1:5) %>% select(car, cyl, hp) ht <- as_hux(cars, add_colnames = TRUE) %>% set_escape_contents(1:6, 1, FALSE) theme_article(ht) ``` which gives the following PDF output: [![enter image description here](https://i.stack.imgur.com/A08Rb.png)](https://i.stack.imgur.com/A08Rb.png) Of course, you won't need quite as many escapes if you're building your own cells by hand rather than using `str_replace`. Note that putting `set_escape_contents` to `FALSE` for the cells with line breaks is crucial. Upvotes: 1 <issue_comment>username_3: Try this, which minimizes the amount of backslashes: ```r library(tidyverse) library(huxtable) cars <- mtcars %>% mutate(car = rownames(.)) cars$car <- str_replace(cars$car, " ", "\\\\newline ") cars %>% as_hux(add_colnames = TRUE) %>% set_wrap(TRUE) %>% set_escape_contents(everywhere, "car", FALSE) %>% quick_pdf() ``` [![enter image description here](https://i.stack.imgur.com/piX5I.png)](https://i.stack.imgur.com/piX5I.png) The `set_wrap()` call is necessary for LaTeX tables to accept newlines, I believe. If you want to escape different parts of the cells containing newlines, you can do that manually, e.g. with `xtable::sanitize()`. Upvotes: 2
2018/03/21
1,069
3,467
<issue_start>username_0: This is my code. ``` var ad; FBInstant.getRewardedVideoAsync('1234_1234') .then(function(rewardedVideo) { if(typeof rewardedVideo !== 'undefined'){ if(typeof rewardedVideo.getPlacementID() === 'undefined'){ console.log('can not get placement ID') } ad = rewardedVideo; return rewardedVideo.loadAsync() } else { return Promise.reject(new Error('rewardedVideo is undefined')) } }) .then(function(){ //adv loaded console.log('adv loaded') }) .catch(function(error){ console.log(error.code, error.message); }); ``` I always get {code: "ADS\_NO\_FILL", message: 'No fill'}. The document said: "ADS\_NO\_FILL string We were not able to serve ads to the current user. This can happen if the user has opted out of interest-based ads on their device, or if we do not have ad inventory to show for that user." But my app still in development.<issue_comment>username_1: According to [Escaping HTML or LaTeX](https://hughjonesd.github.io/huxtable/huxtable.html#escaping-html-or-latex), You should use `escape_contents(ht) <- FALSE` and use tag instead of `\n` ``` library(tidyverse) library(huxtable) cars <- mtcars %>% mutate(car = rownames(.), car = str_replace(car, " ", " ")) %>% slice(1:5) %>% select(car, cyl, hp) ht <- as_hux(cars, add_colnames = TRUE) escape_contents(ht) <- FALSE ht ``` note that the output is a Rmarkdown document and thanks for the package information. it looks good. following is the output of mine [![enter image description here](https://i.stack.imgur.com/qlL5g.png)](https://i.stack.imgur.com/qlL5g.png) Upvotes: 2 <issue_comment>username_2: Okay, so combining insights from [this LaTeX StackExchange post](https://tex.stackexchange.com/questions/2441/how-to-add-a-forced-line-break-inside-a-table-cell/132661#132661) and [this classic XKCD](https://xkcd.com/1638/) got me this: ``` library(tidyverse) library(huxtable) cars <- mtcars %>% mutate(car = rownames(.), car = str_replace(car, "(\\S*)\\s(.*)", "\\\\vtop{\\\\hbox{\\\\strut \\1}\\\\hbox{\\\\strut \\2}}")) %>% slice(1:5) %>% select(car, cyl, hp) ht <- as_hux(cars, add_colnames = TRUE) %>% set_escape_contents(1:6, 1, FALSE) theme_article(ht) ``` which gives the following PDF output: [![enter image description here](https://i.stack.imgur.com/A08Rb.png)](https://i.stack.imgur.com/A08Rb.png) Of course, you won't need quite as many escapes if you're building your own cells by hand rather than using `str_replace`. Note that putting `set_escape_contents` to `FALSE` for the cells with line breaks is crucial. Upvotes: 1 <issue_comment>username_3: Try this, which minimizes the amount of backslashes: ```r library(tidyverse) library(huxtable) cars <- mtcars %>% mutate(car = rownames(.)) cars$car <- str_replace(cars$car, " ", "\\\\newline ") cars %>% as_hux(add_colnames = TRUE) %>% set_wrap(TRUE) %>% set_escape_contents(everywhere, "car", FALSE) %>% quick_pdf() ``` [![enter image description here](https://i.stack.imgur.com/piX5I.png)](https://i.stack.imgur.com/piX5I.png) The `set_wrap()` call is necessary for LaTeX tables to accept newlines, I believe. If you want to escape different parts of the cells containing newlines, you can do that manually, e.g. with `xtable::sanitize()`. Upvotes: 2
2018/03/21
1,146
3,754
<issue_start>username_0: According to w3schools: > > **Important**: When you set the width and height properties of an element with CSS, you just set the width and height of the **content area**. To calculate the full size of an element, you must also add padding, borders and margins. > > > What I'm finding in practice with an tag, however, is that whether I specify width and height via CSS, or by using the `width` and `height` attributes of the tag, is that it's not just the size of my content being affected. The entirety of the image content, the padding, and the border are being sized to match my specified width and height. To put some specific numbers on this: * I have flag icons measuring 32px \* 22px. I want to scale them down 50% to 16px \* 11px. * I want to put 1 px of padding around the flag icons, then a 1 pixel solid light gray border. * The total screen size of the result *including padding and border* should be 20px \* 15px. The CSS that works correctly is this: ``` .flag-image { width: 20px; height: 15px; position: relative; top: 3px; padding: 1px; border: lightgray 1px solid; } ``` If it were true, however, that I'm only supposed to be specifying the content size, shouldn't that be 16px and 11px for width and height instead? Why, if I use 16px and 11px, is my flag icon squashed too small? I've taken a screen shot, magnified it, and counted pixels. It's 20px and 15px that give me correct results. Is this something special about the `img` tag? Am I missing or misinterpreting the HTML or CSS specs? [![enter image description here](https://i.stack.imgur.com/Qgzp4.png)](https://i.stack.imgur.com/Qgzp4.png)<issue_comment>username_1: Your assumption is correct — `img` elements by default should be treated the same as any other element when calculating sizes taking borders and padding into account. The most likely explanation for what you're observing is that your stylesheet or that of a third-party library or framework has a `box-sizing: border-box` rule somewhere that's affecting your `img` elements. If removing that rule is not an option (e.g. because it's [a universal rule](https://stackoverflow.com/questions/23542579/purpose-of-before-after-rule-without-content-property/23542683#23542683)), you can override it by resetting `box-sizing` to `content-box` so you can set the dimensions that make the most sense: ``` .flag-image { width: 16px; height: 11px; position: relative; top: 3px; padding: 1px; border: lightgray 1px solid; box-sizing: content-box; } ``` Or you can choose to run with it and leave the width and height declarations as they are, with the disadvantage that the numbers seem counter-intuitive. Upvotes: 3 [selected_answer]<issue_comment>username_2: You will need to use `box-sizing: border-box` to the image if you want the exact `width` and `height` you have mentioned...See the below example And also if you use `width` and `height` attributes to `img` rather than from css, then the total width of your image will be `width + padding + border` if `box-sizing` is not set to `border-box` ```js console.log("img1 dimension: " + $(".img1").outerWidth() + "x" + $(".img1").outerHeight()) console.log("img2 dimension: " + $(".img2").outerWidth() + "x" + $(".img2").outerHeight()) console.log("img3 dimension: " + $(".img3").outerWidth() + "x" + $(".img3").outerHeight()) ``` ```css .img1, .img2 { width: 30px; height: 25px; position: relative; padding: 1px; border: lightgray 1px solid; } .img3 { position: relative; padding: 1px; border: lightgray 1px solid; } ``` ```html ![](http://via.placeholder.com/50x50) ![](http://via.placeholder.com/50x50) ![](http://via.placeholder.com/50x50) ``` Upvotes: 1
2018/03/21
1,231
4,753
<issue_start>username_0: We are trying our luck with robot framework for tests. Automation. I am stuck at database connection at this point. A DB connection using cx\_Oracle is displaying an error saying “ No keyword withy the name cx\_Oracle’ . If you have any idea please help . It will be helpful if you could put out an example of the Oracle dB connection sample.<issue_comment>username_1: Check **DatabaseLibrary** available with RobotFramework. [Check Here for more info !!!](http://franz-see.github.io/Robotframework-Database-Library/) [DatabaseLibrary Keyword Documentation](http://franz-see.github.io/Robotframework-Database-Library/api/1.0.1/DatabaseLibrary.html) It has two keywords for Database Connection : 1. Connect To Database 2. Connect To Database Using Custom Params Upvotes: 1 <issue_comment>username_2: "No keyword withy the name cx\_Oracle" means that you are using 'cx\_Oracle' as keyword. I do not see given library in commonly used [Robot Extended libraries](http://robotframework.org/#libraries). If the case is that you installed the library wrongly and imported it correctly into Robot script as: ``` *** Settings *** Library MyLibraryName ``` then I would expect it to fail on the import. I agree with Dinesh. Try to use the Database Library first. Or if you cannot use Database Library (the *Connect To Database Using Custom Params* has limitations), it is possible to write your own Robot Library that would reuse the cx\_Oracle python library and expose keywords to robot. It is generally [not that complicated](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#creating-test-libraries) and I did that with pyodbc. Upvotes: 0 <issue_comment>username_3: It was indeed an installation issue. We had to use Anaconda3 and had to installed the library under its site-packages . I had this one under default Python folder.The issue is now resolved . Upvotes: 0 <issue_comment>username_4: I had the same issue and This is the solution which I found Step 1: Install Oracle instant client (32 bit) ( I'm using instantclient\_18\_3, You don't have to install cx\_oracle seperately ) Step 2: Install Operating System Literary and the Database Library for Robot and import it ``` *** Settings *** Library DatabaseLibrary Library OperatingSystem ``` Then in your robot script, Add The following variable and make sure it's with the test cases (NOT in an external resource file) ``` *** Variables *** ${DB_CONNECT_STRING} 'DB_USERNAME/DB_PASSWORD@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YOUR_DB_OR_HOST)(PORT=YOUR_PORT))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=YOUR_SID)))' ``` Then you can use the following keywords to set the environment variables and to run queries ``` *** Keywords *** Connect To DB [Arguments] ${DB_CONNECT_STRING_VALUE} Set Environment Variable PATH PATH_TO_YOUR_INSTANT_CLIENT\\instantclient_18_3 Set Global Variable ${DB_CONNECT_STRING_VALUE} #Connect to DB connect to database using custom params cx_Oracle ${DB_CONNECT_STRING_VALUE} Run Query and log results [Arguments] ${QUERY_TO_EXECUTE} Set Global Variable ${QUERY_TO_EXECUTE} ${queryResults} Query ${QUERY_TO_EXECUTE} log to console ${queryResults} Disconnect From DB #Disconnect from DB disconnect from database ``` Finally, in your test case run it like this ``` *** Test Cases *** Test Connetion [Tags] DBConnect Connect To DB ${DB_CONNECT_STRING} Run Query and log results SELECT sysdate from Dual ``` This should work fine for you Upvotes: 1 <issue_comment>username_5: You can use [robotframework-oracledb-library](https://pypi.org/project/robotframework-oracledb-library/) * Install OracleDBLibrary module ``` pip install robotframework-oracledb-library ``` * After the installation, you can import OracleDBLibrary and connect to Oracle Database as follows ``` *** Settings *** Library OracleDBLibrary *** Variables *** ${HOST} localhost ${PORT} 1521 ${SID} ORCLCDB ${USER} SYS ${PASSWORD} <PASSWORD> ${MODE} SYSDBA *** Test Cases *** CONNECT TO ORACLE DATABASE WITH SID SUCCESSFULLY ${DSN} = ORACLE MAKEDSN host=${HOST} port=${PORT} sid=${SID} ORACLE CONNECT user=${USER} ... password=${<PASSWORD>} ... dsn=${DSN} ... mode=${MODE} ${CONNECTION STATUS} = ORACLE CONNECTION PING SHOULD BE EQUAL ${CONNECTION STATUS} ${NONE} ORACLE CONNECTION CLOSE ``` For more information, you can check [robotframework-oracledb-library-test](https://github.com/adeliogullari/robotframework-oracledb-library/blob/main/test/OracleDatabase.robot) Upvotes: 0
2018/03/21
1,231
4,690
<issue_start>username_0: I launched a free tier Linux instance in Singapore region. But unable to connect with ssh using pem key. Only newly launched instance have this problem. The error shows below, Permission denied (publickey,gssapi-keyex,gssapi-with-mic). Thanks in advance. Regards, <NAME><issue_comment>username_1: Check **DatabaseLibrary** available with RobotFramework. [Check Here for more info !!!](http://franz-see.github.io/Robotframework-Database-Library/) [DatabaseLibrary Keyword Documentation](http://franz-see.github.io/Robotframework-Database-Library/api/1.0.1/DatabaseLibrary.html) It has two keywords for Database Connection : 1. Connect To Database 2. Connect To Database Using Custom Params Upvotes: 1 <issue_comment>username_2: "No keyword withy the name cx\_Oracle" means that you are using 'cx\_Oracle' as keyword. I do not see given library in commonly used [Robot Extended libraries](http://robotframework.org/#libraries). If the case is that you installed the library wrongly and imported it correctly into Robot script as: ``` *** Settings *** Library MyLibraryName ``` then I would expect it to fail on the import. I agree with Dinesh. Try to use the Database Library first. Or if you cannot use Database Library (the *Connect To Database Using Custom Params* has limitations), it is possible to write your own Robot Library that would reuse the cx\_Oracle python library and expose keywords to robot. It is generally [not that complicated](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#creating-test-libraries) and I did that with pyodbc. Upvotes: 0 <issue_comment>username_3: It was indeed an installation issue. We had to use Anaconda3 and had to installed the library under its site-packages . I had this one under default Python folder.The issue is now resolved . Upvotes: 0 <issue_comment>username_4: I had the same issue and This is the solution which I found Step 1: Install Oracle instant client (32 bit) ( I'm using instantclient\_18\_3, You don't have to install cx\_oracle seperately ) Step 2: Install Operating System Literary and the Database Library for Robot and import it ``` *** Settings *** Library DatabaseLibrary Library OperatingSystem ``` Then in your robot script, Add The following variable and make sure it's with the test cases (NOT in an external resource file) ``` *** Variables *** ${DB_CONNECT_STRING} 'DB_USERNAME/DB_PASSWORD@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YOUR_DB_OR_HOST)(PORT=YOUR_PORT))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=YOUR_SID)))' ``` Then you can use the following keywords to set the environment variables and to run queries ``` *** Keywords *** Connect To DB [Arguments] ${DB_CONNECT_STRING_VALUE} Set Environment Variable PATH PATH_TO_YOUR_INSTANT_CLIENT\\instantclient_18_3 Set Global Variable ${DB_CONNECT_STRING_VALUE} #Connect to DB connect to database using custom params cx_Oracle ${DB_CONNECT_STRING_VALUE} Run Query and log results [Arguments] ${QUERY_TO_EXECUTE} Set Global Variable ${QUERY_TO_EXECUTE} ${queryResults} Query ${QUERY_TO_EXECUTE} log to console ${queryResults} Disconnect From DB #Disconnect from DB disconnect from database ``` Finally, in your test case run it like this ``` *** Test Cases *** Test Connetion [Tags] DBConnect Connect To DB ${DB_CONNECT_STRING} Run Query and log results SELECT sysdate from Dual ``` This should work fine for you Upvotes: 1 <issue_comment>username_5: You can use [robotframework-oracledb-library](https://pypi.org/project/robotframework-oracledb-library/) * Install OracleDBLibrary module ``` pip install robotframework-oracledb-library ``` * After the installation, you can import OracleDBLibrary and connect to Oracle Database as follows ``` *** Settings *** Library OracleDBLibrary *** Variables *** ${HOST} localhost ${PORT} 1521 ${SID} ORCLCDB ${USER} SYS ${PASSWORD} <PASSWORD> ${MODE} SYSDBA *** Test Cases *** CONNECT TO ORACLE DATABASE WITH SID SUCCESSFULLY ${DSN} = ORACLE MAKEDSN host=${HOST} port=${PORT} sid=${SID} ORACLE CONNECT user=${USER} ... password=${<PASSWORD>} ... dsn=${DSN} ... mode=${MODE} ${CONNECTION STATUS} = ORACLE CONNECTION PING SHOULD BE EQUAL ${CONNECTION STATUS} ${NONE} ORACLE CONNECTION CLOSE ``` For more information, you can check [robotframework-oracledb-library-test](https://github.com/adeliogullari/robotframework-oracledb-library/blob/main/test/OracleDatabase.robot) Upvotes: 0
2018/03/21
1,299
4,906
<issue_start>username_0: Hi everyone I am having some problems with my code. It is unable to be able to work when i add in the code below. ``` until result || input == "quit" ``` However when i remove the input for that line the code works perfectly okay. ``` input = gets.chomp print "you just told me #{input}" result = " " until result || input == "quit" result = gets.chomp if result == "quit" puts "Alright Goodbye" else puts "I heard #{results}" end end ``` Thank you so much for your help:)<issue_comment>username_1: Check **DatabaseLibrary** available with RobotFramework. [Check Here for more info !!!](http://franz-see.github.io/Robotframework-Database-Library/) [DatabaseLibrary Keyword Documentation](http://franz-see.github.io/Robotframework-Database-Library/api/1.0.1/DatabaseLibrary.html) It has two keywords for Database Connection : 1. Connect To Database 2. Connect To Database Using Custom Params Upvotes: 1 <issue_comment>username_2: "No keyword withy the name cx\_Oracle" means that you are using 'cx\_Oracle' as keyword. I do not see given library in commonly used [Robot Extended libraries](http://robotframework.org/#libraries). If the case is that you installed the library wrongly and imported it correctly into Robot script as: ``` *** Settings *** Library MyLibraryName ``` then I would expect it to fail on the import. I agree with Dinesh. Try to use the Database Library first. Or if you cannot use Database Library (the *Connect To Database Using Custom Params* has limitations), it is possible to write your own Robot Library that would reuse the cx\_Oracle python library and expose keywords to robot. It is generally [not that complicated](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#creating-test-libraries) and I did that with pyodbc. Upvotes: 0 <issue_comment>username_3: It was indeed an installation issue. We had to use Anaconda3 and had to installed the library under its site-packages . I had this one under default Python folder.The issue is now resolved . Upvotes: 0 <issue_comment>username_4: I had the same issue and This is the solution which I found Step 1: Install Oracle instant client (32 bit) ( I'm using instantclient\_18\_3, You don't have to install cx\_oracle seperately ) Step 2: Install Operating System Literary and the Database Library for Robot and import it ``` *** Settings *** Library DatabaseLibrary Library OperatingSystem ``` Then in your robot script, Add The following variable and make sure it's with the test cases (NOT in an external resource file) ``` *** Variables *** ${DB_CONNECT_STRING} 'DB_USERNAME/DB_PASSWORD@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YOUR_DB_OR_HOST)(PORT=YOUR_PORT))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=YOUR_SID)))' ``` Then you can use the following keywords to set the environment variables and to run queries ``` *** Keywords *** Connect To DB [Arguments] ${DB_CONNECT_STRING_VALUE} Set Environment Variable PATH PATH_TO_YOUR_INSTANT_CLIENT\\instantclient_18_3 Set Global Variable ${DB_CONNECT_STRING_VALUE} #Connect to DB connect to database using custom params cx_Oracle ${DB_CONNECT_STRING_VALUE} Run Query and log results [Arguments] ${QUERY_TO_EXECUTE} Set Global Variable ${QUERY_TO_EXECUTE} ${queryResults} Query ${QUERY_TO_EXECUTE} log to console ${queryResults} Disconnect From DB #Disconnect from DB disconnect from database ``` Finally, in your test case run it like this ``` *** Test Cases *** Test Connetion [Tags] DBConnect Connect To DB ${DB_CONNECT_STRING} Run Query and log results SELECT sysdate from Dual ``` This should work fine for you Upvotes: 1 <issue_comment>username_5: You can use [robotframework-oracledb-library](https://pypi.org/project/robotframework-oracledb-library/) * Install OracleDBLibrary module ``` pip install robotframework-oracledb-library ``` * After the installation, you can import OracleDBLibrary and connect to Oracle Database as follows ``` *** Settings *** Library OracleDBLibrary *** Variables *** ${HOST} localhost ${PORT} 1521 ${SID} ORCLCDB ${USER} SYS ${PASSWORD} <PASSWORD> ${MODE} SYSDBA *** Test Cases *** CONNECT TO ORACLE DATABASE WITH SID SUCCESSFULLY ${DSN} = ORACLE MAKEDSN host=${HOST} port=${PORT} sid=${SID} ORACLE CONNECT user=${USER} ... password=${<PASSWORD>} ... dsn=${DSN} ... mode=${MODE} ${CONNECTION STATUS} = ORACLE CONNECTION PING SHOULD BE EQUAL ${CONNECTION STATUS} ${NONE} ORACLE CONNECTION CLOSE ``` For more information, you can check [robotframework-oracledb-library-test](https://github.com/adeliogullari/robotframework-oracledb-library/blob/main/test/OracleDatabase.robot) Upvotes: 0
2018/03/21
686
2,541
<issue_start>username_0: We are in the process of migrating HA cluster to Causal Clustering. **Is there any real advantage of migrating from HA Clustering to Causal Clustering?** Currently using REST End points only. **Is it possible to have causal clustering with just two Neo4j instances?** Thanks.<issue_comment>username_1: To me, 3 CORE instances is the minimun Then 3 ReadReplicas seems a minimum. If you already have HA working, can you precise why moving to causal clustering ? Upvotes: -1 <issue_comment>username_2: Causal cluster is the new generation of Neo4j cluster, and it will continue to evolve with new releases. There are many advantages for CC comparing to HA : * no branch data (thanks to raft and consensus commit) * more stability * smart driver with bolt protocol (with LB and `read your own write` functionnality) * cluster communication encryption * ... You need at minima *3 core nodes* to create a cluster (`2n+1` in fact where `n` is the number of failure you want to support). I really recommend you to use the bolt protocol instead of the REST API, because official drivers only use bolt, and they can hide to you the complexity of a cluster. Upvotes: 2 <issue_comment>username_3: HA Clustering is deprecated in `Neo4j 3.5` and will be removed in `Neo4j 4.0`. > > The functionality described in this section (HA Clustering) has been deprecated and > will be removed in Neo4j 4.0. Causal Clustering should be used > instead. > > > Source: <https://neo4j.com/docs/operations-manual/current/ha-cluster/architecture/> > > > <https://neo4j.com/docs/operations-manual/current/clustering/> > > Neo4j (Enterprise Only) Causal Clustering provides three main > features: > > > **Safety:** Core Servers provide a fault tolerant platform for transaction processing which will remain available while a simple > majority of those Core Servers are functioning. > > > **Scale:** Read Replicas provide a massively scalable platform for graph queries that enables very large graph workloads to be executed > in a widely distributed topology. > > > **Causal consistency:** when invoked, a client application is guaranteed to read at least its own writes. Together, this allows the > end-user system to be fully functional and both read and write to the > database in the event of multiple hardware and network failures and > makes reasoning about database interactions straightforward. > > > Source: <https://neo4j.com/docs/operations-manual/current/clustering/introduction/> > > > Upvotes: 0
2018/03/21
2,312
5,750
<issue_start>username_0: As I understand, one cannot use pip to install/upgrade `pywin32`, though `pip install -U pypiwin32` is a workaround. `pywin32` is now hosted on [GitHub](https://github.com/mhammond/pywin32/releases). I know very little of `git` but know that it works with binary files. Is there a way to programmatically upgrade the `pywin32` binary? That is, say `pywin32` v221 is installed with Python v.3.6 (64bit), the program should check against the latest (v223) on GitHub and download the `pywin32-223.win-amd64-py3.6.exe` and install it. So far, I can only think of a web-scraping-like script that compares the installed version with the latest version on the web and act accordingly. I wonder whether there's a simple solution.<issue_comment>username_1: You could use [Chocolatey](https://chocolatey.org/) and its [pywin32 package](https://chocolatey.org/packages/PyWin32), but it is out of date. So a scripting solution as [one described in this article](https://gist.github.com/lukechilds/a83e1d7127b78fef38c2914c4ececc3c) (for other programs, but with a similar idea) is possible. See also [this gist](https://gist.github.com/steinwaywhw/a4cd19cda655b8249d908261a62687f8). If you uncompress the [latest Git for Windows](https://github.com/git-for-windows/git/releases/download/v2.16.2.windows.1/PortableGit-2.16.2-64-bit.7z.exe) anywhere you want, and use a **[simplified `PATH`](https://stackoverflow.com/a/49248983/6309)**, you will have access to 200+ Linux commands, including `awk`, `head`, etc. Upvotes: 1 <issue_comment>username_2: I might be missing something crucial, otherwise (almost) every statement / assumption in the question seems incorrect: 1. It **is** possible to install / upgrade [[GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions](https://github.com/mhammond/pywin32) using *PIP* 2. [GitHub](https://github.com) is used to host the **source code** (mainly). The assets there are Mark Hammond's *Win* installers (since *PyWin32* was hosted on [SourceForge](https://sourceforge.net) - long before *PIP* was born), I suppose they are only built for backward compatibility. There is a way to (build and) install directly from *GitHub* (or any other *URL*): [[SO]: pip install from git repo branch](https://stackoverflow.com/q/20101834/4788546) 3. *PIP* doesn't download the *PyWin32* binary, but *.whl* (*wheel*) packages from [[PyPI]: Links for pywin32](https://pypi.python.org/simple/pywin32) In order to demo all the above, I created a *VirtualEnv*, and based on that, a series of steps: * *Python* and *PIP* executables locations / versions * *PIP* test (list *PyWin32* version using *PIP*) - no output (no *PyWin32* installed) * *PyWin32* download and *URL* display * *PyWin32* install (an older version to test upgrade later) * *PIP* test * *PyWin32* test (list *PyWin32* version using *PyWin32*) * *PyWin32* upgrade * *PIP* test * *PyWin32* test **Output**: > > > ```bat > (py36x64_test) e:\Work\Dev\StackOverflow\q049398198> sopr.bat > ### Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ### > > [prompt]> where python pip > c:\Work\Dev\VEnvs\py36x64_test\Scripts\python.exe > c:\Work\Dev\VEnvs\py36x64_test\Scripts\pip.exe > > [prompt]> python -c "import sys;print(sys.version)" > 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] > > [prompt]> pip -V > pip 9.0.3 from c:\work\dev\venvs\py36x64_test\lib\site-packages (python 3.6) > > [prompt]> :: PIP test > > [prompt]> pip list 2>nul | findstr pywin32 > > [prompt]> pip download -vvv pywin32 2>nul | findstr /i download > Downloading pywin32-223-cp36-cp36m-win_amd64.whl (9.0MB) > Downloading from URL https://pypi.python.org/packages/9f/9d/f4b2170e8ff5d825cd4398856fee88f6c70c60bce0aa8411ed17c1e1b21f/pywin32-223-cp36-cp36m-win_amd64.whl#md5=2d211288ee000b6ec5d37436bcbe8a43 (from https://pypi.python.org/simple/pywin32/) > Successfully downloaded pywin32 > > [prompt]> pip install https://pypi.python.org/packages/be/25/0e0c568456b77ce144dd2b8799f915b046ffa1cd922771d214e4be05bca2/pywin32-222-cp36-cp36m-win_amd64.whl#md5=94a9a3782081e14973c5ae448957d530 2>nul > Collecting pywin32==222 from https://pypi.python.org/packages/be/25/0e0c568456b77ce144dd2b8799f915b046ffa1cd922771d214e4be05bca2/pywin32-222-cp36-cp36m-win_amd64.whl#md5=94a9a3782081e14973c5ae448957d530 > Downloading pywin32-222-cp36-cp36m-win_amd64.whl (9.0MB) > 100% |################################| 9.0MB 135kB/s > Installing collected packages: pywin32 > Successfully installed pywin32-222 > > [prompt]> :: PIP test > > [prompt]> pip list 2>nul | findstr pywin32 > pywin32 (222) > > [prompt]> :: PyWin32 test > > [prompt]> python -c "import win32api as wapi;print(wapi.GetFileVersionInfo(wapi.__file__, \"\\\\\")[\"FileVersionLS\"] >> 16)" > 222 > > [prompt]> pip install -U pywin32 2>nul > Collecting pywin32 > Using cached pywin32-223-cp36-cp36m-win_amd64.whl > Installing collected packages: pywin32 > Found existing installation: pywin32 222 > Uninstalling pywin32-222: > Successfully uninstalled pywin32-222 > > [prompt]> :: PIP test > > [prompt]> pip list 2>nul | findstr pywin32 > pywin32 (223) > > [prompt]> :: PyWin32 test > > [prompt]> python -c "import win32api as wapi;print(wapi.GetFileVersionInfo(wapi.__file__, \"\\\\\")[\"FileVersionLS\"] >> 16)" > 223 > > ``` > > Check: * [[SO]: How to install a package for a specific Python version on Windows 10? (@username_2's answer)](https://stackoverflow.com/a/57883242/4788546) - for more details using *PIP* * [[SO]: ImportError: No module named win32com.client (@username_2's answer)](https://stackoverflow.com/a/75310161/4788546) - for *PyWin32* details Upvotes: 3 [selected_answer]
2018/03/21
719
2,098
<issue_start>username_0: I have a pending job and I want to resize it. I tried: ``` scontrol update job NumNodes=128 ``` It does not work. Note: I can change the walltime using `scontrol`. But when I try to change number of nodes, it failed. It looks like I can change the nodes according to this page <http://www.nersc.gov/users/computational-systems/cori/running-jobs/monitoring-jobs/>.<issue_comment>username_1: You can resize jobs in Slurm provided that the job is pending or running. According to the [FAQ](https://slurm.schedmd.com/faq.html#job_size), you can resize following the next steps (with examples): Expand ------ 1. Assuming that **j1** requests 4 nodes and is submitted with: ``` $ salloc -N4 bash ``` 2. Submit a new job (**j2**) with the number of extra nodes for **j1** (in this case 10 for a total of 14 nodes) and make it dependent of **j1** (SLURM\_JOBID): ``` $ salloc -N10 --dependency=expand:$SLURM_JOBID ``` 3. Deallocate the nodes of **j2**: ``` $ scontrol update jobid=$SLURM_JOBID NumNodes=0 ``` 4. Terminate **j2**: ``` $ exit ``` 5. Assign to **j1** the previous released nodes: ``` $ scontrol update jobid=$SLURM_JOBID NumNodes=ALL ``` 6. And update the environmental variables of **j1**: ``` $ ./slurm_job_$SLURM_JOBID_resize.sh ``` Now, **j1** has 14 nodes. Shrink ------ 1. Assuming that **j1** has been submitted with: ``` $ salloc -N4 bash ``` 2. Update **j1** to the new size: ``` $ scontrol update jobid=$SLURM_JOBID NumNodes=2 $ scontrol update jobid=$SLURM_JOBID NumNodes=ALL ``` 3. And update the environmental variables of **j1** (the script is created by the previous commands): ``` $ ./slurm_job_$SLURM_JOBID_resize.sh ``` Now, **j1** has 2 nodes. Upvotes: 2 <issue_comment>username_2: Here is a solution I got from NERSC help desk (Credits to <NAME> at LBNL): `$ scontrol update jobid=jobid numnodes=new_numnodes-new_numnodes` E.g. `$ scontrol update jobid=12345 numnodes=10-10` The trick is to have numnodes in the above format. It works for both shrinking and expanding your nodes. Upvotes: 3 [selected_answer]
2018/03/21
673
2,614
<issue_start>username_0: using the Qualcomm NeturalNetwork SDK. i can run the SNPE SDK Example and change to inception\_v3 model, works fine. but snpe will block-ui thread in the execute(); i have no way to stop this. android user will get bad UX. i have tryed: low priority thread, job scheduler, etc when i execute snpe with GPU, it always block the UI. How can i config the SNPE, the Android UI is the high priority, SNPE is the lower priority, so we can get result quickly and do not block the UI thank you.<issue_comment>username_1: You should be able to use an AsyncTask to run your inference on a background thread. See 'ClassifyImageTask' in the SNPE SDK for an example of this. Upvotes: 0 <issue_comment>username_2: The bulk operation on GPU blocks the rendering of new frames. It's hard to solve this problem and it actually have nothing to do with SNPE, because we can reproduce this issue using non-SNPE implementation (in-house OpenCL-based framework). You can simply change the placement of tensor operations to mitigate this problem. For example, you can do the computation on CPU (e.g.: tensorflow mobile), and the UI can be rendered properly while being much slower and CPU-hunger. It's possible to visualize my explanation by on-device developer options. For more information, follow this link: <https://developer.android.com/studio/profile/inspect-gpu-rendering#profile_rendering>. You'll be able to see that several "Swap Buffer"[1](https://i.stack.imgur.com/u2ZAh.png) operations could take unusually long intervals. The best solution is to do computation on DSP with quantized network, but there are many limitations on the available operators and memory. It's possible that Android 8.1 could solve these issues with NN-API abstraction and OS-level scheduling of GPU-resource, but I would not expect too much from Google. BTW: I have a hypothetical scheme to mitigate this issue by fragmenting the bulk operations. In theory, if the worker-thread would sleep for 20ms between sub-50ms operations so that UI thread could render properly, the user experience should be tolerable since the FPS could be maintained above 15. We'll try this scheme because this handicapped scheme should still be much faster than schemes based on CPU. Upvotes: 2 <issue_comment>username_3: For SNPE GPU runtime, you can use **low** execution hint, which will set SNPE to lowest GPU priority. By setting **ExecutionPriorityHint\_t::Low** thru [SNPEBuilder::setExecutionPriorityHint()](https://developer.qualcomm.com/docs/snpe/group__c__plus__plus__apis.html#a84ac8bc624d067391e1ff9946db2dd66) Upvotes: 0
2018/03/21
200
740
<issue_start>username_0: If "wallSize" is in localStorage, store the result in bathroomLength variable. Otherwise, do not change bathroomLength. ``` var bathroomLength = 'initial'; ``` What is the proper way of answering this question?<issue_comment>username_1: `if (localStorage.wallSize) bathroomLength = localStorage.wallSize;` Upvotes: 2 [selected_answer]<issue_comment>username_2: First you could check: <https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage> for more detailed reference. As for your question: ``` var bathroomLength = localStorage.getItem('wallSize') || 'initial'; // if there is no wallSize in localStorage, // bathroomLength will be initialized with 'initial' automatically; ``` Upvotes: 0
2018/03/21
274
907
<issue_start>username_0: I´ve been ask to find out, what: ``` function foo(input) { var output = "intet match!"; if (input.length <= 5) { output = input; } else if (input.length < 12) { output = input + "#" + input; } else if (input == 'anders') { output = "[" + input + "]"; } return output; ``` would return, if following input were entered: * <NAME> * Rub * <NAME> * Anders<issue_comment>username_1: `if (localStorage.wallSize) bathroomLength = localStorage.wallSize;` Upvotes: 2 [selected_answer]<issue_comment>username_2: First you could check: <https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage> for more detailed reference. As for your question: ``` var bathroomLength = localStorage.getItem('wallSize') || 'initial'; // if there is no wallSize in localStorage, // bathroomLength will be initialized with 'initial' automatically; ``` Upvotes: 0
2018/03/21
1,076
3,140
<issue_start>username_0: Toy Example =========== I don't really want to concatenate (i.e., I don't want to merge strings), but if I say `JOIN` it will confuse people. I have 2 tables that I **know** are properly aligned by row. I simply want to take the 2 tables and *join* them, but not **on** anything, and I don't want to `CROSS JOIN` or anything similar. Let me explain by example: table 1: ``` name | city --------|----------- Phillip | Chicago Sarah | London ``` table 2: ``` phone | email -------------|------- 312-241-7754 | <EMAIL> +011-11-1111 | <EMAIL> ``` I **know** that these rows match. That is, the first row of each table refers to `Phillip` and the second row of each table refers to `Sarah`. But I don't have any shared thing to join ***on***. --- Question ======== I simply want to say something like: ``` INSERT INTO table3 (SELECT * FROM table1 ??CONCATENATE?? table2) ``` where that funny `??CONCATENATE??` is my magical function that simply says "align row 1 of each table together, then row 2, then row 3, etc." so that it looks like: ``` name | city | phone | email --------|----------|--------------|----------------- Phillip | Chicago | 312-241-7754 | <EMAIL> Sarah | London | +011-11-1111 | <EMAIL> ``` I'm sure there must be a function to do this, but after searching for a while still couldn't find anything.<issue_comment>username_1: select tb1.name ,tb1.city,tb2.phone,tb2.email from (select \*,row\_number() over(order by (SELECT NULL))as rno from table1)tb1 inner join (select \*,row\_number() over(order by (SELECT NULL))as rno from table2)tb2 on tb1.rno =tb2.rno Upvotes: 0 <issue_comment>username_2: You Can Achieve This by Using Row\_Number(). But I will better If you Use Primary And Foreign Key Relation Between The 2 Tables ``` BEGIN TRAN CREATE TABLE #table1(NAME NVARCHAR(50),city NVARCHAR(50)) CREATE TABLE #table2(phone NVARCHAR(50),email NVARCHAR(50)) INSERT INTO #table1 SELECT 'Phillip','Chicago' UNION ALL SELECT 'Sarah','London' INSERT INTO #table2 SELECT '312-241-7754','<EMAIL>' UNION ALL SELECT '+011-11-1111','<EMAIL>' SELECT *,ROW_NUMBER()OVER (ORDER BY NAME)Rownum INTO #T1 FROM #table1 SELECT *,ROW_NUMBER()OVER (ORDER BY email)Rownum INTO #T2 FROM #table2 SELECT NAME, City,Phone, Email FROM #T1 INNER JOIN #T2 ON #t1.Rownum= #t2.Rownum ROLLBACK TRAN ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: Hi I have modified little bit above username_2 coding ``` BEGIN TRAN CREATE TABLE #table1(ID INT IDENTITY, NAME NVARCHAR(50),city NVARCHAR(50)) CREATE TABLE #table2(ID INT IDENTITY, phone NVARCHAR(50),email NVARCHAR(50)) INSERT INTO #table1 SELECT 'Phillip','Chicago' UNION ALL SELECT 'Sarah','London' INSERT INTO #table2 SELECT '312-241-7754','<EMAIL>' UNION ALL SELECT '+011-11-1111','<EMAIL>' SELECT *,ROW_NUMBER()OVER (ORDER BY NAME)Rownum INTO #T1 FROM #table1 SELECT *,ROW_NUMBER()OVER (ORDER BY email)Rownum INTO #T2 FROM #table2 SELECT NAME, City,Phone, Email FROM #T1 INNER JOIN #T2 ON #t1.ID = #t2.ID ROLLBACK TRAN ``` Upvotes: -1
2018/03/21
541
1,796
<issue_start>username_0: How do I load pretrained model using fastai implementation over PyTorch? Like in SkLearn I can use pickle to dump a model in file then load and use later. I've use .load() method after declaring learn instance like bellow to load previously saved weights: ``` arch=resnet34 data = ImageClassifierData.from_paths(PATH, tfms=tfms_from_model(arch, sz)) learn = ConvLearner.pretrained(arch, data, precompute=False) learn.load('resnet34_test') ``` Then to predict the class of an image: ``` trn_tfms, val_tfms = tfms_from_model(arch,100) img = open_image('circle/14.png') im = val_tfms(img) preds = learn.predict_array(im[None]) print(np.argmax(preds)) ``` But It gets me the error: ``` ValueError: Expected more than 1 value per channel when training, got input size [1, 1024] ``` This code works if I use `learn.fit(0.01, 3)` instead of `learn.load()`. What I really want is to avoid the training step In my application.<issue_comment>username_1: This could be an edge case where batch size equals 1 for some batch. Make sure none of you batches = 1 (mostly the last batch) Upvotes: 2 <issue_comment>username_2: This error occurs whenever a batch of your data contains a single element. **Solution 1**: Call learn.predict() after learn.load('resnet34\_test') **Solution 2**: Remove 1 data point from your training set. [Pytorch issue](https://github.com/pytorch/pytorch/issues/4534) [Fastai forum issue description](http://forums.fast.ai/t/understanding-code-error-expected-more-than-1-value-per-channel-when-training/9257) Upvotes: 3 [selected_answer]<issue_comment>username_3: In training you will get this error if you have 1 data in training set batch. If you are using model to predict output please make sure to set ``` learner.eval() ``` Upvotes: -1
2018/03/21
1,135
4,677
<issue_start>username_0: I have 2 radio groups in MainActivity as follow: ``` public class MainActivity extends AppCompatActivity { public static RadioGroup tapRadioGroup, timeRadioGroup; ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tapRadioGroup = findViewById(R.id.finger_radio_group); timeRadioGroup = findViewById(R.id.time_radio_group); ... } } ``` and I want to refer them to 2 methods inside another activity like this: ``` public void getTapCheckedOption() { RadioGroup radioGroup = MainActivity.tapRadioGroup; ... } public void getTimeCheckedOption() { RadioGroup radioGroup = MainActivity.timeRadioGroup; ... } ``` It's all good and running, but the problem is when I declare static on the 2 radio groups, there is a warning said that practice will lead to memory leak. However if I don't declare it, I cannot call `MainActivity.tapRadioGroup` in the other activity. So how can I do it correctly without the warning message?<issue_comment>username_1: > > how to correctly refer a view from another activity? > > > Bad idea to make radio groups as static variables **(Never Declare your views as Static,)** to use it another activity also it can cause memory leak you can use [`Fragments`](https://developer.android.com/guide/components/fragments.html) > > when I declare static on the 2 radio groups, there is a warning said that practice will lead to memory leak > > > Memory leaks occur if there is any data in memory which can't be garbage collected ,Having said that, static variables can't be garbage collected as they stays live in memory throughout the Application life where as non-static variables can be garbage collected once > > So how can I do it correctly without the warning message? > > > 1. You Go with [**`Fragments`**](https://developer.android.com/guide/components/fragments.html) A `Fragment` represents a behavior or a portion of user interface in an Activity. You can combine multiple `fragments` in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities). 2. You can also use [**`Shared Preferences`**](https://developer.android.com/reference/android/content/SharedPreferences.html) to save the state of your radio button here is the example of [how to use shared Preferences to save the state of radio button](https://stackoverflow.com/a/46293188/7666442) Upvotes: 3 [selected_answer]<issue_comment>username_2: You should not refer to them at all. The current Activity should not need to refer to objects from other Activities. When starting your Activity from MainActivity, you can pass the necessary data to it using the `Intent`. In your MainActivity.java: ``` Intent intent = new Intent(this, OtherActivity.class); String someData = …; intent.putExtra("SOME_DATA", someData); startActivity(intent); ``` In your other Activity: ``` String someData = getIntent().getStringExtra("SOME_DATA"); ``` Upvotes: 0 <issue_comment>username_3: > > how to correctly refer a view from another activity? > > > Never Declare your views as ***Static***, **It's Bad idea** The reason is each view holds to **context** object. And in this case, the two static views will be holding the activity context, so when the Activity goes out of scope, *it will not be destroyed and it is still referenced by the view which is static .* > > So how can I do it correctly without the warning message? > > > **Two ways you can do these:** 1) Use **fragments** in the case where you want to show multi-panel UI on the same screen. 2) Otherwise, if you still go with Activity, save the state changes in a **Shared Preferences** when doing some operation from current activity and once your activity is shown again, read the state changes and alter the UI accordingly. Upvotes: 2 <issue_comment>username_4: Do not directly mutate the state of a view from a different UI controller (activity or fragment). Use local storage(SQL or Shared Preferences) to store the state of the view. In `onResume` of the UI, the controller read the value of state from local storage and update the UI component (in your case RadioButton). It's a best practice to load the state of UI from cache in android Upvotes: 0
2018/03/21
572
1,971
<issue_start>username_0: I am trying to add my custom jar in spark job using "spark.jars" property. Although I can read the info in logs of jar getting added but when I check the jars that are added to the classpath, I don't find it.Below are the functions that I also have tried it out. 1)spark.jars 2)spark.driver.extraLibraryPath 3)spark.executor.extraLibraryPath 4)setJars(Seq[String]) But none added the jar.I am using spark 2.2.0 in HDP and files were kept locally. Please let me know what possibly I am doing wrong. First option worked for me.Spark.jars was adding jar as it was being shown in Spark UI.<issue_comment>username_1: Check the [documentation for submitting jobs](https://spark.apache.org/docs/latest/submitting-applications.html#advanced-dependency-management), adding extra non-runtime jars is at the bottom You can either add the jars to the `spark.jars` in the [SparkConf](https://spark.apache.org/docs/latest/configuration.html) or specify them at runtime ``` ./bin/spark-submit \ --class \ --master \ --deploy-mode \ --conf = \ ... # other options \ ``` so try `spark-submit --master yarn --jars the_jar_i_need.jar my_script.py` For example, I have a pyspark script `kafak_consumer.py` that requires a jar, `spark-streaming-kafka-0-8-assembly_2.11-2.1.1.jar` To run it the command is ``` spark-submit --master yarn --jars spark-streaming-kafka-0-8-assembly_2.11-2.1.1.jar kafka_consumer.py ``` Upvotes: 0 <issue_comment>username_2: If you need an external jar available to the executors, you can try `spark.executor.extraClassPath`. According to the documentation it shouldn't be necessary, but it helped me in the past > > Extra classpath entries to prepend to the classpath of executors. This exists primarily for backwards-compatibility with older versions of Spark. Users typically should not need to set this option. > > > Documentation: <https://spark.apache.org/docs/latest/configuration.html> Upvotes: 1
2018/03/21
561
1,693
<issue_start>username_0: I'm working on the following pthread program that finds the number of substrings in string2 that are in string: ``` #include #include #include #include #define NUM\_THREADS 4 #define MAX 1024 int n1,n2,i; char \*s1,\*s2; FILE \*fp; char \*substring(char \*string, int position, int length); void occurrence(); int readf(FILE \*fp) { if((fp=fopen("strings.txt", "r"))==NULL){ printf("ERROR: can't open strings.txt!\n"); return 0; } s1=(char \*)malloc(sizeof(char)\*MAX); if(s1==NULL){ printf("ERROR: Out of memory!\n"); return -1; } s2=(char \*)malloc(sizeof(char)\*MAX); if(s1==NULL){ printf("ERROR: Out of memory\n"); return -1; } /\*read s1 s2 from the file\*/ s1=fgets(s1, MAX, fp); s2=fgets(s2, MAX, fp); n1=strlen(s1); /\*length of s1\*/ n2=strlen(s2)-1; /\*length of s2\*/ if(s1==NULL || s2==NULL || n1 ``` When I compile and run it, it runs okay but I get the following warning: ``` |44|warning: passing argument 3 of 'pthread_create' from incompatible pointer type| |314|note: expected 'void * (*)(void *)' but argument is of type 'void (*)()'| ``` I know it has to do with the parameters used for Pthread, however i'm having trouble figuring out how to fix it. Any suggestions?<issue_comment>username_1: Just make `occurence` function accept one `void*` parameter and the warning go away. Upvotes: 1 [selected_answer]<issue_comment>username_2: The thread function must follow a specific signature. Even if you don't use the argument and don't return a value, you must still have the correct signature. If you don't need the argument, just ignore it. If you don't have a specific return value, just return `NULL`. Upvotes: 2
2018/03/21
378
1,206
<issue_start>username_0: Basically I want the image to fall down the screen all the way through the right side of the window and I tried it like this (see snippet below) ```css #falling2 { position: absolute; top: 0; right: 0; z-index: -2; } ``` ```html ![](http://via.placeholder.com/50x50) ``` However, it stays glued to the left side for some reason. I tried solutions from here on stack overflow but they did not seem to solve my problem.<issue_comment>username_1: ``` #falling2 { position: absolute; top: 0; right: 0; z-index: -2; text-align: right; } ``` set text-align:right Upvotes: 1 <issue_comment>username_2: There is a css property known as text align , which is used to align inner elements (with respect to outer element border/boundary), have a look at it in below snippet ```css #falling2 { position: absolute; top: 0; text-align:right; z-index: -2; } ``` ```html ![](image.png) ``` Upvotes: 1 <issue_comment>username_3: ```css #falling2 { position: absolute; left: 0; z-index: -2; text-align: right; } ``` ```html ![](http://via.placeholder.com/50x50) ``` Upvotes: 3 [selected_answer]
2018/03/21
353
1,268
<issue_start>username_0: ``` var apikey = "someKey"; var SEid = "<KEY>"; var query = "Flower"; var returnedData; $.get("https://www.googleapis.com/customsearch/v1?key=" + apikey + "&cx=" + SEid + "&q=" + query, function(data){ console.log(data); returnedData = data; }); console.log(returnedData.items[1].formattedUrl); ``` I keep getting back the error Uncaught TypeError: Cannot read property 'items' of undefined but I can't figure out why the variable returned Data is undefined. I'm not trying to even reference it until *after* I've called the get request. Please don't flag this question as invalid, I'm really trying to figure this out and have tried for the past 2 days various methods but I just can't figure it out.<issue_comment>username_1: Using `returnedData.toJSON().items` or just `returnedData.get(items).get(0)` directly. Upvotes: 0 <issue_comment>username_2: The `$.get` is running *asynchronously* - once the script reaches that line, it simply sends out the request, it doesn't wait for the request to complete before continuing. You can't return a value that's generated asynchronously. You could, however, return a *promise* that, when resolved, resolves with the desired value. Upvotes: 1
2018/03/21
224
857
<issue_start>username_0: Code: ``` {{item.English\_name.toLowerCase()}} #### Rate {{ parseFloat(item.Rate).toFixed(2) }} #### MRP {{ parseFloat(item.MRP\_rate).toFixed(2) }} Add to cart ``` Anyone can please tell me why parseFloat is not working How can I make it workable? I am using ngFor loop so doing parseFloat and toDixed in controller is bad idea.<issue_comment>username_1: Using `returnedData.toJSON().items` or just `returnedData.get(items).get(0)` directly. Upvotes: 0 <issue_comment>username_2: The `$.get` is running *asynchronously* - once the script reaches that line, it simply sends out the request, it doesn't wait for the request to complete before continuing. You can't return a value that's generated asynchronously. You could, however, return a *promise* that, when resolved, resolves with the desired value. Upvotes: 1
2018/03/21
1,100
3,606
<issue_start>username_0: Fedora 27 with openjdk 1.8.0 and Gerrit 2.14.7. This is what I get: ``` gerrit_testsite/bin/gerrit.sh start Starting Gerrit Code Review: FAILED ``` The logs are empty. There is a `gerrit.pid` file; the corresponding process is running: ``` GerritCodeReview -jar /home/gerrit2/gerrit_testsite/bin/gerrit.war daemon -d /home/gerrit2/gerrit_testsite --run-id=1521606266.3474 ``` But nothing listens at the configured port 8080. When I add the -x option, I can see the gerrit.sh script is timing out waiting for a `gerrit.run` file to appear - which doesn't happen. I tried increasing the timeout to 600 seconds. I tried `gerrit.sh run`. This does create an error log with two warnings: ``` [main] WARN com.google.gerrit.sshd.SshDaemon : Cannot format SSHD host key [EdDSA]: invalid key type [main] WARN com.google.gerrit.server.config.GitwebCgiConfig : gitweb not installed (no /usr/lib/cgi-bin/gitweb.cgi found) ``` Again, nothing listens on 8080. I believe that I was able to run Gerrit for the very first time. I had to change the canonicalWebUrl parameter, restarted Gerrit and have had the problem ever since. I removed my gerrit\_testsite directory and reinitialized it, but starting it up keeps failing. What is the SSHD key warning about? Do I need gitweb? Where else to look? **EDIT**: I restarted from a fresh Fedora installation. Then: ``` $ java -jar gerrit.war init -d ~/review-site .... Initialized /home/gerrit2/review-site Executing /home/gerrit2/review-site/bin/gerrit.sh start Starting Gerrit Code Review: FAILED error: cannot start Gerrit: exit status 1 Waiting for server on 192.168.1.201:8080 ... OK Opening http://192.168.1.201:8080/#/admin/projects/ ...FAILED Open Gerrit with a JavaScript capable browser: http://192.168.1.201:8080/#/admin/projects/ ``` In spite of the FAILED message, I do find a `gerrit.run` file in the logs directory. `error_log` contains the same two warnings as earlier. The GerritCodeReview process listens on port 8080, and I have access via web browser. For now, life is good, but I wonder what happens when I have to restart Gerrit. **EDIT2**: Yes, as I feared, after `gerrit.sh restart`, not only do I get FAILED, but nothing listens on the web port 8080 nor on the SSH port 29418. **EDIT3**: In summary, to me it looks like I can successfully start Gerrit on an entirely new OS, but as soon as I restart it, something makes it either wait for an event that never happens, or crash before writing to the log.<issue_comment>username_1: The problem might be *lack of entropy*. Gerrit reads from /dev/random, and on a headless server the entropy might be exhausted before Gerrit has had time to start up. A fix could be to install the `haveged` package. Since you're on Fedora, the required commands would be: ``` yum install haveged chkconfig haveged on service haveged start ``` After doing this, Gerrit should start relatively quickly. Note: I've found this solution [here](https://www.digitalocean.com/community/tutorials/how-to-setup-additional-entropy-for-cloud-servers-using-haveged). Upvotes: 0 <issue_comment>username_2: I just had the same problem and the hint to the fix is right here, in your logs: ``` [main] WARN com.google.gerrit.server.config.GitwebCgiConfig : gitweb not installed (no /usr/lib/cgi-bin/gitweb.cgi found) ``` You don't have gitweb installed and you have it configured in your system. Either remove the gitweb configuration from gerrit.config: ``` [gitweb] type = gitweb cgi = /usr/lib/cgi-bin/gitweb.cgi ``` Or make sure it is properly installed. Upvotes: 1
2018/03/21
224
802
<issue_start>username_0: In my react native project when I press > > `⌘ + d debug menu won't show up` > The problem is the splashScreen won't hide is there any way to debug? > > ><issue_comment>username_1: Sometimes it happens because of your App is in release mode. Try below steps. **Make sure for debugging application your build is in release mode not in debug mode and for the release time you can set release al well** > > Path to change release to debug mode: Product(Menu) > Scheme > Edit > Scheme > Build Configuration > > > and reset (Menu > Hardware > Erase all content and settigs) your simulator then try run again and press `⌘ + d` it will work. Hope it helps you! Upvotes: 2 [selected_answer]<issue_comment>username_2: Just restart your Simulator from xcode. Upvotes: -1
2018/03/21
1,097
3,143
<issue_start>username_0: I have a string: ``` {"lat":28.67167520663993,"lng":77.23913223769534} ``` When I use: ``` $json = json_decode($json['latlng'] , true); echo " ``` ";print_r($json ); ``` ``` then output value is: Array: ``` ( [lat] => 28.67167520664 [lng] => 77.239132237695 ) ``` but result is different and truncated I need original value how can i do it?<issue_comment>username_1: It's matter of numeric precision. You can't do much about that using `json_decode()` unless you want to parse JSON file yourself and use [GMP](https://secure.php.net/manual/en/ref.gmp.php) to handle your values. See notes in docs: <https://secure.php.net/manual/en/language.types.float.php> > > **Warning** > > > Floating point precision Floating point numbers have limited > precision. Although it depends on the system, PHP typically uses the > IEEE 754 double precision format, which will give a maximum relative > error due to rounding in the order of 1.11e-16. Non elementary > arithmetic operations may give larger errors, and, of course, error > propagation must be considered when several operations are compounded. > > > Additionally, rational numbers that are exactly representable as > floating point numbers in base 10, like 0.1 or 0.7, do not have an > exact representation as floating point numbers in base 2, which is > used internally, no matter the size of the mantissa. Hence, they > cannot be converted into their internal binary counterparts without a > small loss of precision. This can lead to confusing results: for > example, floor((0.1+0.7)\*10) will usually return 7 instead of the > expected 8, since the internal representation will be something like > 7.9999999999999991118.... > > > **So never trust floating number results to the last digit, and do not > compare floating point numbers directly for equality. If higher > precision is necessary, the arbitrary precision math functions and gmp > functions are available.** > > > Upvotes: 0 <issue_comment>username_2: As much i understand below is my input: 1) The value you providing is `float` value. It's float problem not `json` problem. 2) The workaround is you can wrap your value in double quotes `"28.67167520663993"`. It will give you proper output. Code shown below ``` $a = '{"lat":"28.67167520663993","lng":"77.23913223769534"}'; print_r(json_decode($a,true)); ``` 3) Float is going to round till `3 digit precision` by default in my system. 4) Another method to prevent set `ini_set('precesion',15)`. It will not round up till 15 digits. ``` php ini_set('precision', 15); $a = '{"lat":28.67167520663993,"lng":77.23913223769534}'; print_r(json_decode($a,true)); </code ``` 5) Bugs already reported [here](https://bugs.php.net/bug.php?id=68200). Above is different way of prevention till php introduce some solution for it. Upvotes: 2 <issue_comment>username_3: Try this : ``` $json = '{"lat":28.67167520663993,"lng":77.23913223769534}'; $json = preg_replace('/:\s*(\-?\d+(\.\d+)?([e|E][\-|\+]\d+)?)/', ': "$1"', $json); $jsond = json_decode($json , true); echo " ``` ";print_r($jsond ); ``` ``` Upvotes: 1
2018/03/21
1,062
3,631
<issue_start>username_0: I am developing Tabs using TabbedPage in `xaml`. The default tabs **Icons & Text size is big** so I need to reduce the size of Icons & Text. Below is my `main.xaml` code Where I am setting icons. ``` ``` This is First page of tabs where I am giving Title of tab as `Title="Dairy"` ``` ``` See the below Screenshot where you can see icons and tab text. [![enter image description here](https://i.stack.imgur.com/tQYHx.png)](https://i.stack.imgur.com/tQYHx.png)<issue_comment>username_1: In your Android project's `Resources/values/style.xml` file, you can create a style: ``` <item name="android:textSize">8sp</item> ``` And then in your `Resources/layout/tabs.axml` file, you can use the style: ``` ``` As for the icon, try this: <https://stackoverflow.com/a/46465233/3183946> And by the way, I think "Dairy" should be "Diary" in your app Upvotes: 3 <issue_comment>username_2: After some effort i get it work for android using `TabbedPageRenderer`. Created custom layout with `ImageView` & `TetxtView` below **Custom\_tab\_layou.xaml** ``` xml version="1.0" encoding="utf-8"? ``` Created `MyTabbedPageRenderer` class ``` public class MyTabbedPageRenderer : TabbedPageRenderer { private Dictionary icons = new Dictionary(); bool setup; ViewPager pager; TabLayout layout; public MyTabbedPageRenderer(Context context) : base(context) { } protected override void SetTabIcon(TabLayout.Tab tab, FileImageSource icon) { base.SetTabIcon(tab, icon); tab.SetCustomView(Resource.Layout.Custom\_tab\_layou); var imageview = tab.CustomView.FindViewById(Resource.Id.icon); var tv = tab.CustomView.FindViewById(Resource.Id.tv); tv.SetText(tab.Text, TextView.BufferType.Normal); imageview.SetBackgroundDrawable(tab.Icon); ColorStateList colors2 = null; if ((int)Build.VERSION.SdkInt >= 23) colors2 = Resources.GetColorStateList(Resource.Color.icon\_tab, Forms.Context.Theme); else colors2 = Resources.GetColorStateList(Resource.Color.icon\_tab); tv.SetTextColor(colors2); } //this is for changing text color of select tab protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (setup) return; if (e.PropertyName == "Renderer") { pager = (ViewPager)ViewGroup.GetChildAt(0); layout = (TabLayout)ViewGroup.GetChildAt(1); setup = true; ColorStateList colors = null; if ((int)Build.VERSION.SdkInt >= 23) colors = Resources.GetColorStateList(Resource.Color.icon\_tab, Forms.Context.Theme); else colors = Resources.GetColorStateList(Resource.Color.icon\_tab); for (int i = 0; i < layout.TabCount; i++) { var tab = layout.GetTabAt(i); var icon = tab.Icon; Android.Views.View view = GetChildAt(i); if (view is TabLayout) layout = (TabLayout)view; if (icon != null) { icon = Android.Support.V4.Graphics.Drawable.DrawableCompat.Wrap(icon); Android.Support.V4.Graphics.Drawable.DrawableCompat.SetTintList(icon, colors); } } } } } ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: In my case I really wanted to skip all the custom renderers... and many of the implementations seemed much more work than should be necessary. I was also implementing Font Awesome Icons which seemed pretty straight forward, but all of the examples I found applied the icons to labels and nothing with tabbed page. After some dinking around I finally compiled this which works great and removes the need of a renderer. ``` ... ``` **To answer the question of setting FontSize:** Font Icon is a Font so it is set like any other. Example: ``` ``` Upvotes: 2
2018/03/21
1,321
5,157
<issue_start>username_0: I hosted my portfolio (which is still under development) on github pages. It's just a web app with static content. And I needed to add Google Analytics to my portfolio and get the number of visits (mainly to get familiar with the process). I found out [react-ga](https://github.com/react-ga/react-ga) module which can be used to configure Google Analytics on React Apps (which created using create-react-app). And followed [this](https://web-design-weekly.com/2016/07/08/adding-google-analytics-react-application/) tutorial and configured it and hosted. And I checked the site with **test traffic** but Google Analytics dashboard doesn't update. What maybe the case ? It should work according to the tutorial. As I'm new to *Google Analytics* it's hard for me to figure out the issue. This is my **App.js** ``` import React, { Component } from "react"; import HeaderList from "./components/Header"; import "./App.css"; import { Layout } from "antd"; import { Router, Route, Switch } from "react-router-dom"; import createHistory from "history/createBrowserHistory"; import ReactGA from 'react-ga'; import Keys from './config/keys'; import AboutMe from "./components/AboutMe"; import Skills from "./components/Skills"; import Contact from "./components/Contact"; import Projects from "./components/Projects"; const { Content } = Layout; ReactGA.initialize(Keys.GOOGLE_TRACKING_ID); //Unique Google Analytics tracking number function fireTracking() { ReactGA.pageview(window.location.hash); } class App extends Component { render() { return ( ); } } export default App; ```<issue_comment>username_1: React v16.8 or higher --------------------- The pageviews can be generated in a `useEffect` function; `withRouter` is used to inject props on route changes: ```js import React, { useEffect } from 'react'; import { Switch, Route, withRouter } from 'react-router-dom'; import ReactGA from 'react-ga'; import Keys from './config/keys'; //Unique Google Analytics tracking number ReactGA.initialize(Keys.GOOGLE_TRACKING_ID); const App = () => { useEffect( () => { // This line will trigger on a route change ReactGA.pageview(window.location.pathname + window.location.search); }); return (/* Code here */); } export default withRouter(App); ``` Prior to React v16.8 -------------------- You need to generate a pageview in componentDidMount and componentDidUpdate: ``` componentDidMount = () => ReactGA.pageview(window.location.pathname + window.location.search); componentDidUpdate = () => ReactGA.pageview(window.location.pathname + window.location.search); ``` So, final code: ``` import React, { Component } from "react"; import HeaderList from "./components/Header"; import "./App.css"; import { Layout } from "antd"; import { Router, Route, Switch } from "react-router-dom"; import createHistory from "history/createBrowserHistory"; import ReactGA from 'react-ga'; import Keys from './config/keys'; import AboutMe from "./components/AboutMe"; import Skills from "./components/Skills"; import Contact from "./components/Contact"; import Projects from "./components/Projects"; const { Content } = Layout; ReactGA.initialize(Keys.GOOGLE_TRACKING_ID); //Unique Google Analytics tracking number class App extends Component { componentDidMount = () => ReactGA.pageview(window.location.pathname + window.location.search); componentDidUpdate = () => ReactGA.pageview(window.location.pathname + window.location.search); render() { return ( ); } } export default App; ``` Upvotes: 4 <issue_comment>username_2: Unfortunately [`onUpdate` was removed in React Router v4](https://github.com/ReactTraining/react-router/issues/4278), which means your `fireTracking` function never fires. In the react-ga documentation [there's an example from <NAME>](https://github.com/react-ga/react-ga/wiki/React-Router-v4-withTracker) that has been included for exactly this scenario which involves wrapping your application in an HoC. Upvotes: 0 <issue_comment>username_3: If you’re interested in tracking page visits (and user behavior down the road), I suggest using the Segment analytics library and following our [React quickstart guide](https://github.com/segmentio/analytics-react) to track page calls using the [react-router](https://reacttraining.com/react-router/) library. You can allow the component to handle when the page renders and use `componentDidMount` to invoke `page` calls. The example below shows one way you could do this: ``` const App = () => ( ); export default App; ``` ``` export default class Home extends Component { componentDidMount() { window.analytics.page('Home'); } render() { return ( Home page. ============ ); } } ``` I’m the maintainer of <https://github.com/segmentio/analytics-react>. With Segment, you’ll be able to switch different destinations on-and-off by the flip of a switch if you are interested in trying multiple analytics tools (we support over 250+ destinations) without having to write any additional code. Upvotes: 0
2018/03/21
739
2,726
<issue_start>username_0: I'm using a DataTable. And this table I am adding data to DataTable using this code: **t.row.add ([...]). Draw (false);** Here is what I need: I want to print an alert on the screen if there is an r\_name with the same name already registered. For this I want to keep the r\_name of all the rows in a array. And I want to compare the name of the newly added row with this array.If there is a r\_name equal to each other, I want to make a warning on the screen. How can I do this? ``` var t = $('#datatables').DataTable(); //-------------------------INSERT ROOM START---------------------------- $("[name='add-room-submit']").click(function () { var r_name = document.getElementById('room-name').value; var r_plan = document.getElementById('image-path').value; t.row.add([ '' + '![...](../../assets/img/room-plan/' + r_plan + ')' + '' , r_name, '' + '' + '' + '' ]).draw(false); //var oTable = $('#datatables').dataTable(); //aData = oTable.fnGetData(); //var aReturn = []; //$(aData).each(function () { // var nextRow = new Array(); // aReturn.push(nextRow); //}); //console.log(aReturn[0]); }); //-------------------------INSERT ROOM END---------------------------- $('#add-room-submit').click(); ```<issue_comment>username_1: If I was you, I'd stay within the DataTables environment - you can just query the table itself to see if `r_name` is present. DataTables caches the table so these searches are fast - so you don't need to keep another array: ``` t.column(1).data().toArray().includes(r_name) ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Using the answer given by colino117, I solved the problem as follows: ``` var t = $('#datatables').DataTable(); //-------------------------INSERT ROOM START---------------------------- $("[name='add-room-submit']").click(function () { var r_name = document.getElementById('room-name').value; var r_plan = document.getElementById('image-path').value; t.row.add([ '' + '![...](../../assets/img/room-plan/' + r_plan + ')' + '' , r_name.toUpperCase(), '' + '' + '' + '' ]).draw(false); //addition var oTable = $('#datatables').dataTable(); aData = oTable.fnGetData(); var ndx = 0; var count = 0; $(aData).each(function () { if ( r_name.toUpperCase() == oTable.fnGetData()[ndx][1] ) { count++; } ndx++; }); if (count > 1) { alert('Warning!'); } //addition }); //-------------------------INSERT ROOM END---------------------------- $('#add-room-submit').click(); ``` Upvotes: 0
2018/03/21
759
2,712
<issue_start>username_0: I am writing some code where I need to remove an item in a circularly linked list (who's head acts as a dummy node) and return it (if removing the first node). I think I have the code just about right, but I'm not sure. Am I understanding this correctly? (starting with a dummy node) dummy -> A -> B -> C -> D -> dummy (wrap around to the dummy node) So if I want to remove the first actual piece of data(A), I would need to assign it to a temp variable. So Node first = head.next. Then I need to have the dummy head reference "b" so I would need to do head.next = first.next. Is this all that needs to be done? ``` private Node remove() { Node returnNode = head.next; head.next = returnNode.next; return returnNode; } ``` In the case of removing any node N from the list (assuming it is on the list), it is sort of the same concept? So from the example above, lets say we want to remove node B. In this case, we need to set B.next = B.previous and B.previous = B.next correct? Or do I need to do something like B.previous.next = B.next and B.next.previous = B.previous? Do I need to traverse the list to find the element to remove? ``` private void removeNode(Node n) { n.next = n.previous; // or n.previous.next = n.next n.previous = n.next; // or n.next.previous = n.previous } ```<issue_comment>username_1: If I was you, I'd stay within the DataTables environment - you can just query the table itself to see if `r_name` is present. DataTables caches the table so these searches are fast - so you don't need to keep another array: ``` t.column(1).data().toArray().includes(r_name) ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Using the answer given by colino117, I solved the problem as follows: ``` var t = $('#datatables').DataTable(); //-------------------------INSERT ROOM START---------------------------- $("[name='add-room-submit']").click(function () { var r_name = document.getElementById('room-name').value; var r_plan = document.getElementById('image-path').value; t.row.add([ '' + '![...](../../assets/img/room-plan/' + r_plan + ')' + '' , r_name.toUpperCase(), '' + '' + '' + '' ]).draw(false); //addition var oTable = $('#datatables').dataTable(); aData = oTable.fnGetData(); var ndx = 0; var count = 0; $(aData).each(function () { if ( r_name.toUpperCase() == oTable.fnGetData()[ndx][1] ) { count++; } ndx++; }); if (count > 1) { alert('Warning!'); } //addition }); //-------------------------INSERT ROOM END---------------------------- $('#add-room-submit').click(); ``` Upvotes: 0
2018/03/21
803
2,467
<issue_start>username_0: I have krogoth yocto source when i compile `bitbake core-image-sato` its showing nearly 4560 packages are compiling but after successfull compilation the rootfs size is 30 mb only. ``` Note: when I boot with this 30 mb size rootfs board is booting but lcd xwindow display not coming. ``` why all packages are not added to core-image-sato my `core-image-sato.bb` > > DESCRIPTION = "core-image-sato basic image " > > > IMAGE\_FEATURES += "splash package-management x11-base x11-sato > ssh-server-dropbear hwcodecs" > > > LICENSE = "MIT" > > > inherit core-image > > > IMAGE\_INSTALL += "packagegroup-core-x11-sato-games" > > > Did i missing anything else? Below is my `distro yogurt.conf` > > require conf/distro/poky.conf require common.inc > > > DISTRO = "yogurt" DISTRO\_NAME = "Yogurt (Phytec Example > Distribution)" DISTRO\_FEATURES += "systemd x11" > DISTRO\_FEATURES\_remove = "argp irda pcmcia zeroconf ptest multiarch > wayland" > > > VIRTUAL-RUNTIME\_dev\_manager = "udev" VIRTUAL-RUNTIME\_init\_manager = > "systemd" DISTRO\_FEATURES\_BACKFILL\_CONSIDERED += "sysvinit" > VIRTUAL-RUNTIME\_login\_manager = "busybox" VIRTUAL-RUNTIME\_syslog = "" > VIRTUAL-RUNTIME\_initscripts = "" > some default locales > > IMAGE\_LINGUAS ?= "de-de fr-fr en-us" > > > 2. Also when I see `tmp/work/cortexa8-...../` all packages are compiled but no `image dir` is creating for all packages. but i believe those are compiled. Why those all packages are not created image dir. is there any reason . Please help me to solve this. Thanks,<issue_comment>username_1: Don't use DISTRO\_FEATURES += because the default is a ?= assignment. Use DISTRO\_FEATURES\_append = " x11 systemd" Same for IMAGE\_INSTALL. The default is a += assignment, so what you're doing is creating an image that just contains the sato-games and nothing else. Upvotes: 3 [selected_answer]<issue_comment>username_2: I think also that you schould place the inherit in the beginning : ``` inherit core-image ``` If you settled it after ``` IMAGE_FEATURES ``` then it will erase your content settled before and assign the core-image content So a better image file is like ``` DESCRIPTION = "core-image-sato basic image " LICENSE = "MIT" inherit core-image IMAGE_FEATURES += "splash package-management x11-base x11-sato ssh-server-dropbear hwcodecs" IMAGE_INSTALL += "packagegroup-core-x11-sato-games" ``` BR. Upvotes: 0
2018/03/21
914
3,010
<issue_start>username_0: I'm really not a star with regular expressions, especially with Haskell and even after reading some tutos. I have a list of numbers like this: ``` let x = [1, 2, 3.5] ``` My goal is to have the string `"1.0 2.0 3.5"` from this input. My idea was to use regular expressions. But the way I use is tedious. First, I do ``` let xstr = show x ``` Then I remove the first bracket like this: ``` import Text.Regex let regex1 = mkRegex "\\[" let sub1 = subRegex regex1 xstr "" -- this gives "1.0,2.0,3.5]" ``` Then I remove the second bracket similarly: ``` let regex2 = mkRegex "\\]" let sub2 = subRegex regex2 sub1 "" ``` Finally I remove the commas and replace them with white spaces: ``` let regex3 = mkRegex "," let sub3 = subRegex regex3 sub2 " " ``` This gives `"1.0 2.0 3.5"`, as desired. Please do you have a better way ? I always have lists with 3 elements, so this approach is not irrealistic, but it is tedious and not elegant. I even don't know how to delete the two brackets in one shot.<issue_comment>username_1: `map` will take a function and apply it to each element of a list, and [`intercalate`](https://hackage.haskell.org/package/base-4.10.1.0/docs/Data-List.html#v:intercalate) will position something between every element of a list. ``` import Data.List stringify :: Show a => [a] -> String stringify = intercalate " " . map show ``` Sample use: ``` > stringify [1, 2, 3.5] "1.0 2.0 3.5" ``` The idea is to keep the data in a computer-friendly form for as long as possible. Your approach immediately stringifies the whole thing, then tries to manipulate something that should really be treated as a list of integer as a string, which leads to some messy workarounds, as you've already seen. It may also be a good exercise to do this by hand. `map` and `intercalate` are both fairly easy to implement with just recursion in Haskell, and doing so can be useful practice. Upvotes: 3 [selected_answer]<issue_comment>username_2: This did just not seem too obvious but, goodness, I finally thought to try 'show' for the floating point numbers which were very easy to generate. In fact, Haskell converts all numbers of an ostensibly mixed type list to the highest common type. In the case of let [1,2,3,4.5] produces [1.0,2.0,3.0,4.5] just by itself. I should have guessed. I found two quick ways to generate the floating point strings. ``` concat [show fl ++ " "| fl <- [1,2,3,4.5]] ``` or ``` concat $ map (\st -> show st + " ") [1,2,3,4.5] ``` These, of course, can easily be parameterized. I do love concat. It is so very versatile. There is a trailing space which is easily removed with an "init $ ' before concat. Then, of course, after a few minutes after posting this, I tried ``` tail . init $ show [1,2,3,4.5] ``` and it worked. haskell is just too cool. But, also of course, my bad. This last bit produces a string but the numbers do not have space between them. There are commas between them :( Upvotes: 0
2018/03/21
1,706
3,607
<issue_start>username_0: I have a dataframe `df1`: ``` Site cells national plan value T13630 G13630B 225 T13631 G13631A T13631 U13631A 57 T13672 G13672A 310 T13802 G13802A 150 T13802 G13802B 151 T13802 U13802A T13880 G13880A 274 T13880 U13880B T33281 U33281A ``` I want dataframe `df2` such that I want to fill the blanks in "national plan value" column based on the some conditions. The conditions are first consider the cell that has blank national plan value. if any other cell has same site name (the other cell can be above / below this cell) and if the last letter of the cell matches e.g. G13631A & U13631A, then copy the national plan value of U13631A to G13631A else write "no-cosector". Hence my resultant dataframe `df2` should have something like this: ``` Site cells national plan value T13630 G13630B 225 T13631 G13631A 57 T13631 U13631A 57 T13672 G13672A 310 T13802 G13802A 150 T13802 G13802B 151 T13802 U13802A 150 T13880 G13880A 274 T13880 U13880B no-cosector T33281 U33281A no-cosector ```<issue_comment>username_1: Create a new column that will be used to identify the rows that belong to the same class: ``` df1['ind'] = df1['Site'] + df1['cells'].str[-1] ``` Sort by that column. This way, all rows that belong to the same class are consecutive: ``` df1.sort_values(['ind', 'npv'], inplace=True) ``` Fill the rows that do not have duplicates in the same class: ``` df1.loc[~df1.duplicated(subset='ind') & df1['npv'].isnull(), 'npv'] = 'no-cosector' ``` Fill the rows that do have duplicates in the same class: ``` df1['npv'].ffill(inplace=True) ``` Remove the temporary column: ``` df1.drop('ind',axis=1) ``` Enjoy: ``` # Site cells npv #0 T13630 G13630B 225 #2 T13631 U13631A 57 #1 T13631 G13631A 57 #3 T13672 G13672A 310 #4 T13802 G13802A 150 #6 T13802 U13802A 150 #5 T13802 G13802B 151 #7 T13880 G13880A 274 #8 T13880 U13880B no-cosector #9 T33281 U33281A no-cosector ``` Upvotes: 2 <issue_comment>username_2: You can build a column with the last char of the cells col and then groupby Site and the last char column. Finally fill na accordingly. ``` df_new = ( df1.assign(cells_last=df1.cells.str.slice(-1)) .groupby(['Site','cells_last']) .apply(lambda x: x.bfill().ffill()) .fillna('no-cosector') .reindex(columns=df1.columns) ) df_new Out[104]: Site cells national_plan_value 0 T13630 G13630B 225 1 T13631 G13631A 57 2 T13631 U13631A 57 3 T13672 G13672A 310 4 T13802 G13802A 150 5 T13802 G13802B 151 6 T13802 U13802A 150 7 T13880 G13880A 274 8 T13880 U13880B no-cosector 9 T33281 U33281A no-cosector ``` Upvotes: 2 <issue_comment>username_3: Step 1, create a new column: ``` df["cellsend"] = df["cells"].str.slice(1) ``` Step 2, use `sort_values` and `groupby` to fill na: ``` df.sort_values(["Site", "cellsend", "national plan value"]).groupby(["Site", "cellsend"]).ffill().drop(["cellsend"], axis=1).fillna("no-cosector") ``` Output: ``` Site cells national plan value 0 T13630 G13630B 225 2 T13631 U13631A 57 1 T13631 G13631A 57 3 T13672 G13672A 310 4 T13802 G13802A 150 6 T13802 U13802A 150 5 T13802 G13802B 151 7 T13880 G13880A 274 8 T13880 U13880B no-cosector 9 T33281 U33281A no-cosector ``` Upvotes: 0
2018/03/21
333
1,131
<issue_start>username_0: I have 4 columns in SQL, out of which I use only three columns. I need to create a `view` which subtracts the `total_energy_generated_till` value based on the first value of a day and the last value of a day using the column TSTAMP. How do I achieve the same ? See the image for the table information. Previously it had the `timestamp` but I converted it into a `Date` data type. **SQL Table** [![enter image description here](https://i.stack.imgur.com/ih6AW.jpg)](https://i.stack.imgur.com/ih6AW.jpg) [Sample Data](https://i.stack.imgur.com/HKlaf.jpg)<issue_comment>username_1: If TimeStamp is unique you could do something like this: ``` select * from myTable a inner join ( select MinTimeStamp = min(TimeStamp), MaxTimeStamp = max(TimeStamp) from myTable ) b on a.TimeStamp = b.TimeStamp ``` If not, row\_number might work too Upvotes: 0 <issue_comment>username_2: Try this: ``` CREATE VIEW Your_View_Name AS SELECT TSTAMP,Inverter_ID ,MAX(TotalEnergyGenerated)-MIN(TotalEnergyGenerated) [total_energy_generated_till] GROUP BY TSTAMP, Inverter_ID ``` Upvotes: 1
2018/03/21
415
1,563
<issue_start>username_0: I am using spring security oauth2 client and configured the app as follow ``` spring.security.oauth2.client.registration.google.client-id=abcd spring.security.oauth2.client.registration.google.client-secret=<PASSWORD> ``` 1. As I start the application, I must login with login link which redirects user to google login page. 2. Once successfully authenticated with google, the user is redirected to the web page again 3. In this page I can check the **Principale** object successfully, which contains user data including **access token** 4. **The problem is** when I try to do ajax call to one of my controllers it always return > > (403 Unauthorized) > > > I am stuck on this for more than a week and googled it many times with luck, since the autoconfiguration for oauth2 client is new in spring boot 2. **Update** I believe **CORS** is out of the reasons because the ajax calls are executed from within the web app itself, using same domain name, not from third party (like app)<issue_comment>username_1: If TimeStamp is unique you could do something like this: ``` select * from myTable a inner join ( select MinTimeStamp = min(TimeStamp), MaxTimeStamp = max(TimeStamp) from myTable ) b on a.TimeStamp = b.TimeStamp ``` If not, row\_number might work too Upvotes: 0 <issue_comment>username_2: Try this: ``` CREATE VIEW Your_View_Name AS SELECT TSTAMP,Inverter_ID ,MAX(TotalEnergyGenerated)-MIN(TotalEnergyGenerated) [total_energy_generated_till] GROUP BY TSTAMP, Inverter_ID ``` Upvotes: 1
2018/03/21
339
1,043
<issue_start>username_0: Context: I'm working on a lighting protocol converter for architectural LED matrices and need to encode byte strings in a very specific way for the headers to be recognized by my hardware. Q: How can I convert an int into two bytes such that I can then use them separately? Example: I want to convert ``` var aDynamicValue = 511 //where value will range from 0-511 ``` to a list like: `[0x01, 0xFF]` Such that I can then ``` magicString.add(--the bytes above--) ``` Thanks<issue_comment>username_1: Use bit shifting together with logical `AND` to mask out all but first 8 bits. Pseudo code: ``` a = 511; byte1 = a & 0xff; byte2 = (a >> 8) & 0xff; ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: typed\_data and `int.toRadixString(16)` can be used to get hex from integers: ``` final list = new Uint64List.fromList([511]); final bytes = new Uint8List.view(list.buffer); final result = bytes.map((b) => '0x${b.toRadixString(16).padLeft(2, '0')}'); print('bytes: ${result}'); ``` Upvotes: 4
2018/03/21
2,383
8,093
<issue_start>username_0: I am working on a project on Spring Boot and have to process a lot of information stored in Solr. I have to compare all my stored images with the entered by the user and establish a similitude. I used LinkedList of images at the beginning, now working with Arrays and LinkedList, but is also very slow and sometimes not working. I am talking about 11 000 000 images that I have to process. Here is my code: ``` public LinkedList comparar(Imagen[] lista, Imagen imagen) throws NullPointerException { LinkedList resultado = new LinkedList<>(); for (int i = 0; i < lista.length; i++) { if (lista[i].getFacesDetectedQuantity() == imagen.getFacesDetectedQuantity()) { lista[i].setSimilitud(3); } if (herramientas.rangoHue(imagen.getPredominantColor\_hue()).equals(herramientas.rangoHue(lista[i].getPredominantColor\_hue()))) { lista[i].setSimilitud(3); } if (lista[i].isTransparency() == imagen.isTransparency()) { lista[i].setSimilitud(4); } if (analizar.compareFeature(herramientas.image64ToImage(lista[i].getLarge\_thumbnail()), herramientas.image64ToImage(imagen.getLarge\_thumbnail())) > 400) { lista[i].setSimilitud(3); } if (analizar.compare\_histogram(herramientas.image64ToImage(lista[i].getLarge\_thumbnail()), herramientas.image64ToImage(imagen.getLarge\_thumbnail())) > 90) { lista[i].setSimilitud(3); } if (lista[i].getSimilitud() > 7) { resultado.add(lista[i]); } } return ordenarLista(resultado); } public LinkedList ordenarLista(LinkedList lista) { LinkedList resultado = new LinkedList<>(); for (int y = 0; y < lista.size(); y++) { Imagen imagen = lista.get(0); int posicion = 0; for (int x = 0; x < lista.size(); x++) { if (lista.get(x).getSimilitud() > imagen.getSimilitud()) { imagen = lista.get(x); posicion = x; } } resultado.add(imagen); lista.remove(posicion); } return resultado; } ``` Any idea of what data structure could I use to make the process faster. I also was thinking on make every comparative `if` inside a thread but also not idea how to do that. A lot of googling and nothing found. Sorry for my English and Thanks!!! I solved the problem of sorting with `ordenarLista()` method just ignoring it and add this code on my `comparar()` method before returning the list. ``` Collections.sort(resultado, new Comparator() { @Override public int compare(Imagen image1, Imagen image2) { return image2.getSimilitud() - image1.getSimilitud(); } }); ``` Still working on my algorithm!<issue_comment>username_1: If you're using `get(int)` you should certainly be using `ArrayList`, not `LinkedList`. However it's not just your data structures, it's your terrible algorithms. For example, in your `ordenarLista()` method, `lista.get(0)` should be `lista.get(y)`, and `posicion = 0` should be `posicion = y`, and the inner loop should start from `y+1`. not zero. Or else you don't need the outer loop at all. Upvotes: 0 <issue_comment>username_2: In a general way, before trying to optimize any part at random, use monitoring tool as JVisualVM to detect exactly the costly invocations. You have to place efforts at the correct place. Besides, tracing the time elapsed for the first big processing (before `ordenarLista()`) and the second one (`ordenarLista()`) should be helpful too. Actually, I note some things : 1) Very probably an issue : `comparar()` does many duplication processings that can be expensive in terms of CPU. Look at these two invocations: ``` if (analizar.compareFeature(herramientas.image64ToImage(lista[i].getLarge_thumbnail()), herramientas.image64ToImage(imagen.getLarge_thumbnail())) > 400) { lista[i].setSimilitud(3); } if (analizar.compare_histogram(herramientas.image64ToImage(lista[i].getLarge_thumbnail()), herramientas.image64ToImage(imagen.getLarge_thumbnail())) > 90) { lista[i].setSimilitud(3); } ``` You invoke for example 4 times `herramientas.image64ToImage()` at each iteration. This should be executed once before the loop : ``` herramientas.image64ToImage(imagen.getLarge_thumbnail()) ``` But you execute it millions of times in the loop. Just store the result in a variable before the loop and use it in. The same thing for : ``` herramientas.rangoHue(imagen.getPredominantColor_hue() ``` All computations that depend only of the `Imagen imagen` parameter should be computed before the loop and never in to spare millions of them. 2) `ordenarLista()` seems having an issue : you hardcoded the first index here : ``` Imagen imagen = lista.get(0); ``` 3) `ordenarLista()` iterates potentially many times : ``` lista.size() + lista.size() + lista.size()-1 + lista.size() + lista.size()-2 + lista.size() + ... + 1 * lista.size() ``` Imagine with `1.000.000` of elements in : ``` 1.000.000 + 1.000.000 + 999.999 + 1.000.000 + 999.998 + 1.000.000 + ... + 1 + 1.000.000 ``` It makes many millions... Upvotes: 2 <issue_comment>username_3: Don't really understand what you did. But I think you are searching things linearly, just some if else cannot make things better. Using the BTree algorithm to sort and search may be a good idea, every database use that algorithm. As you can see, a database usually do a great job at querying records. [BTree](https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/BTree.java.html) java example. Just in case you don't understand what BTree is: [Wikipedia](https://en.wikipedia.org/wiki/B-tree) But never use a real database for storing image. [Reason](https://stackoverflow.com/questions/6472233/can-i-store-images-in-mysql) Upvotes: 0 <issue_comment>username_4: Seems like you may need a help from this: `java.util.concurrent.Future`. You can try to split the `for loop` in `public LinkedList comparar(Imagen[] lista, Imagen imagen)` using this `java.util.concurrent.Future` and see if it reduced the time it process. If the speed is reduced you can then again add the `java.util.concurrent.Future` in the for loop of `public LinkedList ordenarLista(LinkedList lista)` Upvotes: 0 <issue_comment>username_5: I suspect using a 'List' may not be a good choice for what you are doing (this answer contains quite some guess, as I'm not quite sure of the intentions of your program, I still hope it is useful). If your program tries to detect similar images, there are already a number of algorithms and library to compare image similarity, for example [here](https://stackoverflow.com/questions/843972/image-comparison-fast-algorithm). If you don't want to change you approach too much, or if it's not about image similarity, a multi-dimensional index may be something you should look at. For example, it looks like you calculate certain values for each image (hue, a number of histogram values, number of faces). You can pre-calculate all these values once for each image and then put them in a large vector/array: ``` double[] calculateVector(Image image) { //put all image characteristics into a single array double[] vector = new double[]{hue, #of faces, hist value 1, histo value 2, ...}; return vector; } ``` This may give you one vector/array per image with, say, 20 'double' value. Then you use a multi-dimensional index, such as KD-Tree or R\*Tree (there are some sample implementations in [my own project](https://github.com/tzaeschke/tinspin-indexes)). ``` KDTree allImages = new KDTree(20); for (Image image : all images) { double[] vector = calculateVector(image); kdtree.put(vector, image); } ``` Now if you have a new image and want to find the 5 most similar images you calculate the vector/array for the new image and the perform a kNN-query (k-nearest neighbor query) on the index. ``` double[] newImageVector = calculateVector(newImage); List result = kdtree.queryKNN(newImageVector, 5); //method names may vary between implementation ``` This gives you a list of the 5 most similar images. This is usually very fast, the complexity is about O(log n), and you should be able to execute it several 1000 times per second. If you want to know more about multi-dim indexing, search the web for 'kNN query'. Upvotes: 0
2018/03/21
440
1,495
<issue_start>username_0: I want to do command chaining with git. I want exactly to clone a repo then set the configurations for that working copy changing user.name, user.email. I tried this: ``` git clone https://repoUrl.git && git config user.name "Khaled" && git config user.email "<EMAIL>" ``` But I got this error: ``` error: could not lock config file .git/config: No such file or directory ```<issue_comment>username_1: You have not in gitdir folder after clone please follow . ``` 1) git clone https://repoUrl.git ``` now you need to enter in repo dir ``` 2) cd gitfolder 3) git config user.name "Khaled" && git config user.email "<EMAIL>" ``` Upvotes: 2 <issue_comment>username_2: Using @torek comment this problem was fixed. `git clone` really puts its clone into a new directory and I needed to cd into it before calling the configs so here is the fixed version: ``` git clone https://repoUrl.git customDirectory && cd customDirectory && git config user.name "Khaled" && git config user.email "<EMAIL>" ``` Upvotes: 1 [selected_answer]<issue_comment>username_3: try using this it worked for me:- ``` git clone https://github.com/rtyley/small-test-repo.git && git config --global user.name "name" && git config --global user.email "<EMAIL>" ``` Upvotes: 1 <issue_comment>username_4: ``` git clone --config key1=value1 --config key2=value2 https://git.com/repo.git ``` Please reference: <https://git-scm.com/docs/git-clone> Upvotes: 3
2018/03/21
419
1,461
<issue_start>username_0: I have three promises. I need to combine them together to create one more promise. Something like this `Promise.all('url1','url2','url3')` or if there is other possible way to achieve it. Intent is to fire all of them in parallel. I have requirement that when either two of them are resolved, then the final one will be resolved. How I can achieve it?<issue_comment>username_1: You have not in gitdir folder after clone please follow . ``` 1) git clone https://repoUrl.git ``` now you need to enter in repo dir ``` 2) cd gitfolder 3) git config user.name "Khaled" && git config user.email "<EMAIL>" ``` Upvotes: 2 <issue_comment>username_2: Using @torek comment this problem was fixed. `git clone` really puts its clone into a new directory and I needed to cd into it before calling the configs so here is the fixed version: ``` git clone https://repoUrl.git customDirectory && cd customDirectory && git config user.name "Khaled" && git config user.email "<EMAIL>" ``` Upvotes: 1 [selected_answer]<issue_comment>username_3: try using this it worked for me:- ``` git clone https://github.com/rtyley/small-test-repo.git && git config --global user.name "name" && git config --global user.email "<EMAIL>" ``` Upvotes: 1 <issue_comment>username_4: ``` git clone --config key1=value1 --config key2=value2 https://git.com/repo.git ``` Please reference: <https://git-scm.com/docs/git-clone> Upvotes: 3
2018/03/21
1,157
4,716
<issue_start>username_0: I have a custom `View` which contains a `LinearLayout` in turn containing a `TextView` and and an `EditText`. When I will try to click on my custom view if I have pressed on the `TextView` the `LinearLayout` will receive the click but if I have pressed on the `EditText` it will not. Below is a simplified version of my xml. ``` ``` So when I will press on the `EditText` I want the parent view (the `LinearLayout`) to receive the click. I have tried below code: ``` private void init(Context context, AttributeSet attrs) { LayoutInflater inflater = LayoutInflater.from(context); binding = LayoutHeadingEdittextBinding.inflate(inflater, this, true); TypedArray array = context.getTheme().obtainStyledAttributes( attrs, R.styleable.headingtext, 0, 0); if (attrs != null) { try { String hint = array.getString(R.styleable.headingtext_field_hint); String name = array.getString(R.styleable.headingtext_field_name); String text = array.getString(R.styleable.headingtext_field_text); Boolean isFocuable = array.getBoolean(R.styleable.headingtext_field_focus, true); if (!isFocuable) { binding.edtTitle.setClickable(false); binding.edtTitle.setFocusable(false); binding.edtTitle.setFocusableInTouchMode(false); binding.edtTitle.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ((View) v.getParent()).performClick(); } }); // binding.edtTitle.setEnabled(false); } else { binding.edtTitle.setClickable(true); binding.edtTitle.setFocusable(true); binding.edtTitle.setFocusableInTouchMode(true); } binding.edtTitle.setHint(hint); binding.tvTitle.setText(name); binding.edtTitle.setText(text); } finally { array.recycle(); } } } ``` And this is how i want to use it: ``` ``` But it is still not working So i think issue with databinding and click of my customview.<issue_comment>username_1: Programatically ``` //disable click action editText.setFocusable(false); editText.setEnabled(false); //enable click action editText.setFocusable(true); editText.setEnabled(true); ``` xml: ``` android:focusable="false" android:enabled="false" ``` Upvotes: 2 <issue_comment>username_2: Try this in `EditText` : ``` android:focusable="true" android:focusableInTouchMode="true" ``` Programatically : ``` editText.setFocusable(false); ``` ===============**EDIT**=============== ``` if (!isFocuable) { binding.edtTitle.setClickable(false); binding.edtTitle.setFocusable(false); binding.edtTitle.setFocusableInTouchMode(false); binding.edtTitle.setOnTouchListener(null); binding.edtTitle.setOnClickListener(null); // binding.edtTitle.setEnabled(false); } else { binding.edtTitle.setClickable(true); binding.edtTitle.setFocusable(true); binding.edtTitle.setFocusableInTouchMode(true); binding.edtTitle.setOnTouchListener(this); binding.edtTitle.setOnClickListener(this); } ``` ===============**EDIT**=============== Add in edittext ``` android:duplicateParentState="true" ``` If this not works then try with this line also ``` android:duplicateParentState="true" android:clickable="false" ``` Upvotes: 2 <issue_comment>username_3: Here is a work around. ``` // Inside HeadingEditText.kt binding.edtTitle.setOnClickListener { [email protected]() } ``` Set the `OnClickListener` at your Activity ``` edt_country.edtTitle.setOnClickListener { // foo action } ``` Upvotes: 0 <issue_comment>username_4: THIS IS **NOT** A GOOD SOLUTION JUST USABLE IN A CUSTOM-VIEW USING A `FrameLayout` on your **parent** (ViewGroup) of contained `EditText`, override `onInterceptTouchEvent` method like this: ``` override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean { return true } ``` I use `EditText` inside a `FrameLayout` and **override** the method inside my `FrameLayout` and all of them used inside a recycler list item (xml)... and Worked fine click listener of recycler root item view... Upvotes: 0
2018/03/21
560
2,389
<issue_start>username_0: So this is more of a theoretical question rather than a programming question. In my basic understanding of the Angular 4 framework a component can have `inputs, outputs and services which also interact with the store to store data`. Now all of this, in the case of a web-app is displayed on a template. I have recently been looking at testing of such an app. I plan to use `Jasmine` as the framework and `Karma` as the test runner on Chrome (for now). With that said, what should I be testing for? According to my understanding the basic tests should include some mock object handed to the component and checking if that is rendered properly on the template, mocking a service and checking what is rendered when we receive the correct response. 1. So what do I do after this? After I have tested this? 2. How is this behavior driven development? What can I do more? 3. What is a "good angular test"?<issue_comment>username_1: You should also check if your bread-crumbs are in position, bread-crumbs are used for internal routing between pages. Also use the right path of your routing component in your app-module. Upvotes: -1 <issue_comment>username_2: Since you have mensioned jasmine with karma, My perspective of answering this question will be mostly on Unit Testing. Let us go one question after another **What is a "good angular test"?** 1) Unit testing should be written by the developer not by anyone else (tester). 2) It must have both positive and negative scenarios handled. 3) All network calls should be mocked or stubbed. 4) It should pass irrespective of environment. 5) It should have be easily readable, reliable and should not test the integration. **How is this behavior driven development? What can I do more?** In a nut shell BDD: 1) Write unit test cases prior to your development 2) Let all of your unit test cases fail 3) Start with your development unit by unit. Pass the assertion. 4) BDD is a advancement of TDD. In BDD we should not test the implementation but behavior should be tested. 5) BDD increases the code quality as well since we create test case based on behavior. **So what do I do after this? After I have tested this?** Current trend as explained above, after writing the test cases start with the development. Write the assertion, even the non technical person can understand the behavior. Upvotes: 0
2018/03/21
613
1,996
<issue_start>username_0: I have an aware `datetime` object: ``` dt = datetime.datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')) ``` I'm using this to convert the object to timestamp and it currently runs fine: ``` int(time.mktime(dt.utctimetuple())) ``` But according to [time docs](https://docs.python.org/2/library/time.html), `time.mktime` requires local `timetuple`, not UTC `timetuple`. How do I get local `timetuple` from an aware `datetime`? Or is any other way to make `timestamp` instead of `time.mktime`? I have read this question and it seems that I should use `calendar.timegm(dt.utctimetuple())`. [Converting datetime to unix timestamp](https://stackoverflow.com/questions/11554365/converting-datetime-to-unix-timestamp)<issue_comment>username_1: It seems that your are confused on what do you want. Based on your comment, the answer is in python `datetime` documentation: > > There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying tzinfo=timezone.utc: > > > > ``` > timestamp = dt.replace(tzinfo=timezone.utc).timestamp() > > ``` > > or by calculating the timestamp directly: > > > timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1) > > > Upvotes: -1 <issue_comment>username_2: If you have an aware datetime you can convert it to a unix epoch timestamp by subtracting a datetime at UTC epoch like: ### Code: ``` import datetime as dt import pytz def aware_to_epoch(aware): # get a datetime that is equal to epoch in UTC utc_at_epoch = pytz.timezone('UTC').localize(dt.datetime(1970, 1, 1)) # return the number of seconds since epoch return (aware - utc_at_epoch).total_seconds() aware = dt.datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')) print(aware_to_epoch(aware)) ``` ### Results: ``` 1521612302.341014 ``` Upvotes: 2 [selected_answer]
2018/03/21
659
2,767
<issue_start>username_0: I tried to access `NotificationManagerService` class which is in `android.service.notification` package using reflection method. I tried this to clear Notifications of other apps which has `FLAG_NO_CLEAR` Here is the snippet, ``` try { Class c = Class.forName("com.android.server.notification.NotificationManagerService"); Constructor constructor = c.getDeclaredConstructor(); constructor.setAccessible(true); Object o = constructor.newInstance(); Method method = c.getDeclaredMethod("cancelAllNotificationsInt", new Class[]{String.class,int.class,int.class,boolean.class}); method.setAccessible(true); Object r = method.invoke(o,sbn.getPackageName(), Notification.FLAG_NO_CLEAR,0,true); if((boolean)r) Log.d("Working","yes"); } catch (Exception e) { e.printStackTrace(); } ``` But I am getting exception, > > java.lang.ClassNotFoundException: > com.android.server.notification.NotificationManagerService > > > The class exist and [here is the link](https://android.googlesource.com/platform/frameworks/base/+/master/services/core/java/com/android/server/notification/NotificationManagerService.java?autodive=0%2F%2F) from where I confirmed it. Help me!!! Thanks in advance<issue_comment>username_1: I am not very particular with android development but this is usually environment issue. Sometimes, the actual class is not there in the library depending on how you have included your dependencies. * If at your development / IDE, you already encounter the problem, go to your external libraries imported by your gradle (or maven). Drill down to com.android.server.notification.NotificationManagerService if it is there. Or debug it and see if `Class c` is null. * If it happened on the deployed version, open the file, go to the imported classes and drill down to the actual class if it is there or not. * If this library is provided by the environment you deploy - might be (1) overwritten by other library conflict or (2) version issue Upvotes: 0 <issue_comment>username_2: Using **Reflection** and trying to assess **Framework class** is not a good way of implementing a feature. This is a bad practice. From Android 4.3 onward, you can now cancel notifications from any apps. You just need to implement the [NotificationListenerService](https://developer.android.com/reference/android/service/notification/NotificationListenerService.html) you could cancel the notification of any app using the method `NotificationListenerService.cancelNotification(String pkg, String tag, int id)` you could refer this sample [notification-listener-service-example](https://github.com/Chagall/notification-listener-service-example) Upvotes: 1
2018/03/21
1,481
3,958
<issue_start>username_0: I am creating a scatter plot using ggplot2 and would like to size my point means proportional to the sample size used to calculate the mean. This is my code, where I used `fun.y` to calculate the mean by group `Trt`: ``` branch1 %>% ggplot() + aes(x=Branch, y=Flow_T, group=Trt, color=Trt) + stat_summary(aes(group=Trt), fun.y=mean, geom="point", size=) ``` I am relatively new to R, but my guess is to use `size` in the `aes` function to resize my points. I thought it might be a good idea to extract the sample sizes used in `fun.y=mean` and create a new class that could be inputted into `size`, however I am not sure how to do that. Any help will be greatly appreciated! Cheers. **EDIT** Here's my data for reference: ``` Plant Branch Pod_B Flow_Miss Pod_A Flow_T Trt Dmg 1 1 1.00 0 16 20 36.0 Early 1 2 1 2.00 0 1 17 18.0 Early 1 3 1 3.00 0 0 17 17.0 Early 1 4 1 4.00 0 3 14 17.0 Early 1 5 1 5.00 5 2 4 11.0 Early 1 6 1 6.00 0 3 7 10.0 Early 1 7 1 7.00 0 4 6 10.0 Early 1 8 1 8.00 0 13 6 19.0 Early 1 9 1 9.00 0 2 7 9.00 Early 1 10 1 10.0 0 2 3 5.00 Early 1 ``` EDIT 2: Here is a graph of what I'm trying to achieve with proportional sizing by sample size n per `Trt` (treatment), where the mean is calculated per `Trt` and `Branch` number. I'm wondering if I should make `Branch` a categorical variable. [Plot without Proportional Sizing](https://i.stack.imgur.com/lZeHx.jpg)<issue_comment>username_1: If I understood you correctly you would like to scale the size of points based on the number of points per `Trt` group. How about something like this? Note that I appended your sample data, because `Trt` contains only `Early` entries. ``` df %>% group_by(Trt) %>% mutate(ssize = n()) %>% ggplot(aes(x = Branch, y = Flow_T, colour = Trt, size = ssize)) + geom_point(); ``` [![enter image description here](https://i.stack.imgur.com/By7p4.png)](https://i.stack.imgur.com/By7p4.png) Explanation: We group by `Trt`, then calculate the number of samples per group `ssize`, and plot with argument `aes(...., size = ssize)` to ensure that the size of points scale with `sscale`. You don't need the `group` aesthetic here. --- Update ------ To scale points according to the mean of `Flow_T` per `Trt` we can do: ``` df %>% group_by(Trt) %>% mutate( ssize = n(), mean.Flow_T = mean(Flow_T)) %>% ggplot(aes(x = Branch, y = Flow_T, colour = Trt, size = mean.Flow_T)) + geom_point(); ``` [![enter image description here](https://i.stack.imgur.com/Hwa9r.png)](https://i.stack.imgur.com/Hwa9r.png) --- Sample data ----------- ``` # Sample data df <- read.table(text = "Plant Branch Pod_B Flow_Miss Pod_A Flow_T Trt Dmg 1 1 1.00 0 16 20 36.0 Early 1 2 1 2.00 0 1 17 18.0 Early 1 3 1 3.00 0 0 17 17.0 Early 1 4 1 4.00 0 3 14 17.0 Early 1 5 1 5.00 5 2 4 11.0 Early 1 6 1 6.00 0 3 7 10.0 Early 1 7 1 7.00 0 4 6 10.0 Early 1 8 1 8.00 0 13 6 19.0 Early 1 9 1 9.00 0 2 7 9.00 Early 1 10 1 10.0 0 2 3 5.00 Early 1 11 1 10.0 0 2 3 20.00 Late 1", header = T) ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Using [@username_1](https://stackoverflow.com/users/6530970/maurits-evers)'s help, I created my desired graph by making `Branch` a factor. The following is my code as well as my intended graph: ``` branch1$Branch <- as.factor(branch1$Branch) branch1$Flow_T <- as.numeric(branch1$Flow_T) branch1 %>% group_by(Trt, Branch) %>% mutate(ssize = n()) %>% ggplot(aes(x = Branch, y = Flow_T, colour = Trt)) + stat_summary(aes(size=ssize), fun.y=mean, geom="point") ``` [Final Plot](https://i.stack.imgur.com/PruG7.jpg) Upvotes: 0
2018/03/21
709
2,288
<issue_start>username_0: I have a html element: ``` Top Ten Miler ``` I would like to remove string "Top Ten" from: ``` Top Ten Miler ``` So out should be straight: ``` Miler ``` How can I do it using JavaScript or jQuery on windows load?<issue_comment>username_1: Use `String.replace` method ```js var x = 'Top Ten Miler'; var newString = x.replace('Top Ten', ''); console.log(newString.trim()) //trim to replace any white space ``` Upvotes: 0 <issue_comment>username_2: Find `p` text and replace. ```js $('p').text($('p').text().replace('Top Ten','')); ``` ```html Top Ten Miler ``` Or if your is inside any div and div have any `class or id` you can use that `class or id`.In below snippet I use `class`: ```js $('.yourclass > p').text($('.yourclass > p').text().replace('Top Ten','')); ``` ```html Top Ten Miler ``` Upvotes: 1 [selected_answer]<issue_comment>username_3: ```js var str = "Top Ten Miler"; var res = str.substring(7, 13); console.log(res) ``` Upvotes: -1 <issue_comment>username_4: You can use `String.split()`, like this: ``` let cutVal = "Top Ten Miler"; // Or Top Ten whatever let arryVal = cutVal.split(" "); // Split string into three parts console.log(arryVal[2]); // Grab the third part // output is Miler ``` Upvotes: -1 <issue_comment>username_5: lets say you want to remove `xxx` by `yyy` on every node of `span` or `p` or `div`. This is generic code you can try. ```js $(document).ready(function(){ $('span[data-replace][data-replace-by]') .each(function(i, el) { var html = $(el).html(); var oldValue = $(el).data('replace'); var newValue = $(el).data('replace-by'); html = html.replace(oldValue, newValue); $(el).html(html); }); }); ``` ```html this is deepak sharma this is deepak sharma this is deepak sharma This will not change, as no replace-by specified. ``` Upvotes: 0 <issue_comment>username_6: You can loop through each instance and replace the text you want ```js $('#top-tens p').each(function(index, element){ let text = $(element).text().replace('Top Ten ', ''); $(element).text(text); }); ``` ```html Top Ten Miler Top Ten Thriller Top Ten Dealer ``` Upvotes: 0
2018/03/21
494
1,280
<issue_start>username_0: I have a big list that basically looks like: ``` _list = [('123.45','678.90'), ('098.76', '543.21'),('135.79','246.80')] ``` The parentheses come from another function, so I am unsure if it is part of the output, or if it is placed there as a reference of some sorts. And I need to split the left values into a left column, with the corresponding right values in another column, where I will have both in a new dataframe: ``` col1 = ['123.45', '098.76','135.79'] col2 = ['678.90', '543.21', '246.80'] new_df = pd.concat([col1, col2]) ``` I tried the .split() function, but realized i had multiple commas, so that would include incorrect values : ")" or "(". Is there something else I can try?<issue_comment>username_1: Your `_list` (**not** `list`, because `list` is a list constructor!) is a list of tuples. The simplest solution is the direct conversion of the list to a DataFrame: ``` pd.DataFrame(_list) 0 1 #0 123.45 678.90 #1 098.76 543.21 #2 135.79 246.80 ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: ``` _list = [('123.45','678.90'), ('098.76', '543.21'),('135.79','246.80')] col1= [] col2 = [] col1.extend([i[0] for i in _list]) col2.extend([i[1] for i in _list]) ``` Hope this helps. Upvotes: 0
2018/03/21
745
2,485
<issue_start>username_0: I have this segment of code ... ``` string rand = RandomString(16); byte[] bytes = Encoding.ASCII.GetBytes(rand); BitArray b = new BitArray(bytes); ``` The code converts string to Bitarray properly. Now I need to convert the BitArray to zeros and ones. I need to manipulate with zeros and ones variables (i. e. not for representation perposes [without left zeros padding] ). Can anyone help me please ?<issue_comment>username_1: If you want to perform **bitwise operations** on `Byte[]`,you can use `BigInteger` class. 1. Use `BigInteger` class constructor `public BigInteger(byte[] value)` to convert it into 0 and 1. 2. Perform bitwise operations on it. ``` string rand = "ssrpcgg4b3c"; string rand1 = "uqb1idvly03"; byte[] bytes = Encoding.ASCII.GetBytes(rand); byte[] bytes1 = Encoding.ASCII.GetBytes(rand1); BigInteger b = new BigInteger(bytes); BigInteger b1 = new BigInteger(bytes1); BigInteger result = b & b1; ``` BigInteger class supports BitWiseAnd and BitWiseOr Helpful link: [BigInteger class](https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx) [Operators in BigInteger class](https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx#Anchor_4) Upvotes: 0 <issue_comment>username_2: `BitArray` class is the ideal class to use in your case for bitwise operations. You probably do not want to convert `BitArray` to `bool[]` or any other type if you want to do boolean operations. It stores `bool` values efficiently (1 bit for each) and provides you the necessary methods to do bitwise operations. `BitArray.And(BitArray other)`, `BitArray.Or(BitArray other)`, `BitArray.Xor(BitArray other)` are for boolean operations and `BitArray.Set(int index, bool value)`, `BitArray.Get(int index)` to work with individual values. **EDIT** You can manipulate values individually using any bitwise operations: ``` bool xorValue = bool1 ^ bool2; bitArray.Set(index, xorValue); ``` You can have a collection of `BitArray`'s of course: ``` BitArray[] arrays = new BitArray[2]; ... arrays[0].And(arrays[1]); // And'ing two BitArray's ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: You can get 0 and 1 `integer` array from `BitArray`. ``` string rand = "yiyiuyiyuiyi"; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(rand); BitArray b = new BitArray(bytes); int[] numbers = new int [b.Count]; for(int i = 0; i ``` [FIDDLE](http://rextester.com/EKBZM39316) Upvotes: 0
2018/03/21
496
1,694
<issue_start>username_0: Can you create a programming language with just one symbol like brainfuck.<issue_comment>username_1: Yes, it has been done before - see [Unary](https://esolangs.org/wiki/Unary). Basically it's a strange encoding of brainfuck. Treat each BF command as a number. The whole program is then also a number, created by concatenating the commands together (with an extra 1 at front, for unambiguous decoding). Convert the number to unary numeric system (aka the number of digits is your number) and you're done. Note however the programs in this tend to be very large - a `cat` implemented in Unary is (according to the information on page) 56623 characters long. [MGIFOS](https://esolangs.org/wiki/MGIFOS), [Lenguage](https://esolangs.org/wiki/Lenguage) and [Ellipsis](https://esolangs.org/wiki/Ellipsis) follow the same principle. Note that e.g. a hello world in MGIFOS > > has more characters than particles in the observable universe > > > Then [Len(language,encoding)](https://esolangs.org/wiki/Len(language,encoding)) extends this principle to any language. Upvotes: 3 <issue_comment>username_2: They are called [OISC](https://en.wikipedia.org/wiki/One_instruction_set_computer) One Instruction Set Compiler. The first one know of is [Melzak's Arithmetic Machine (1961)](https://cms.math.ca/10.4153/CMB-1961-031-9), with the instruction: ``` z = x-y or jump if y>x ``` You also have Zero Instruction Set Computer, which are more like neural nets. Not forgetting the amazing [FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN) of Conway & Guy (1996), with no instruction but interprets a series of fractions (the program) in a Tuning complete way. Upvotes: 1
2018/03/21
1,774
6,625
<issue_start>username_0: I'm trying to figure out the problem I have when I try to use the segment to change the name of the text in each scrolling. I'm glad if anyone has a good idea for it and can help me. **FirstViewController.swift** ``` class FirstViewController: UIViewController ,ScrollUISegmentControllerDelegate{ @IBOutlet weak var Label1: UILabel! @IBOutlet weak var Label2: UILabel! @IBOutlet weak var Label3: UILabel! @IBOutlet weak var segment: ScrollUISegmentController! override func viewDidLoad() { super.viewDidLoad() segment.segmentDelegate = self segment.tag = 1 segment.segmentItems = ["1","2","3","4","5","6","7","8","9","10"] } func selectItemAt(index: Int, onScrollUISegmentController scrollUISegmentController: ScrollUISegmentController) { print("select Item At\(index) in scrollUISegmentController with tag \(scrollUISegmentController.tag) ") } @IBAction func SegeValueChange(_ sender: Any) { if segment.selectedSegmentIndex == 1 { Label1.text = " 100 " Label2.text = " 40 " Label3.text = " 400 " } if segment.selectedSegmentIndex == 2 { Label1.text = " 100 " Label2.text = " 50 " Label3.text = " 400 " } if segment.selectedSegmentIndex == 3 { Label1.text = " 100 " Label2.text = " 60 " Label3.text = " 600 " } } } ``` **ScrollUISegmentController.swift** ``` // // ScrollUISegmentController.swift // ScrollUISegmentController // // Created by <NAME> on 8/3/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit protocol ScrollUISegmentControllerDelegate: class { func selectItemAt(index :Int, onScrollUISegmentController scrollUISegmentController:ScrollUISegmentController) } @IBDesignable class ScrollUISegmentController: UIScrollView { private var segmentedControl: UISegmentedControl = UISegmentedControl() weak var segmentDelegate: ScrollUISegmentControllerDelegate? @IBInspectable public var segmentTintColor: UIColor = .black { didSet { self.segmentedControl.tintColor = self.segmentTintColor } } @IBInspectable public var itemWidth: CGFloat = 100 { didSet { } } public var segmentFont: UIFont = UIFont.systemFont(ofSize: 13) { didSet { self.segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font: self.segmentFont],for: UIControlState()) } } public var itemsCount: Int = 3 public var segmentheight : CGFloat = 29.0 public var segmentItems: Array = ["1","2","3"] { didSet { self.itemsCount = segmentItems.count self.createSegment() } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! createSegment() } override init(frame: CGRect) { super.init(frame: frame) createSegment() } init(frame: CGRect , andItems items:[String]) { super.init(frame: frame) self.segmentItems = items self.itemsCount = segmentItems.count self.createSegment() } func createSegment() { self.segmentedControl.removeFromSuperview() segmentheight = self.frame.height var width = CGFloat(self.itemWidth * CGFloat(self.itemsCount)) if width < self.frame.width { itemWidth = CGFloat(self.frame.width) / CGFloat(itemsCount) width = CGFloat(self.itemWidth * CGFloat(self.itemsCount)) } self.segmentedControl = UISegmentedControl(frame: CGRect(x: 0 , y: 0, width: width , height: segmentheight)) self.addSubview(self.segmentedControl) self.backgroundColor = .clear showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false NSLayoutConstraint(item: self.segmentedControl, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: self.segmentedControl, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true let contentHeight = self.frame.height self.contentSize = CGSize (width: width, height: contentHeight) self.segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font: self.segmentFont],for: UIControlState()) self.segmentedControl.tintColor = self.segmentTintColor self.segmentedControl.selectedSegmentIndex = 0; insertItems() self.segmentedControl.addTarget(self, action: #selector(self.segmentChangeSelectedIndex(_:)), for: .valueChanged) } func insertItems(){ for item in segmentItems { self.segmentedControl.insertSegment(withTitle: item, at: (segmentItems.index(of: item))!, animated: true) } } @objc func segmentChangeSelectedIndex(_ sender: AnyObject) { segmentDelegate?.selectItemAt(index: self.segmentedControl.selectedSegmentIndex, onScrollUISegmentController: self) print("\(self.segmentedControl.selectedSegmentIndex)") } } ``` I have this error: > > Value of type 'ScrollUISegmentController' has no member 'selectedSegmentIndex' > > ><issue_comment>username_1: Please find your `ScrollUISegmentController`, there is private variable of `UISegmentedControl` named `segmentedControl`, please remove `private` from there. Now you can access `selectedSegmentIndex` using `segment.segmentedControl.selectedSegmentIndex`. Hope it works. **UPDATE** or you can create this property in `ScrollUISegmentController` like this, ``` var selectedIndex: Int { return self.segmentedControl.selectedSegmentIndex } ``` then you can access it like `segment.selectedIndex` It works pretty. Take a look. Upvotes: 0 <issue_comment>username_2: I think you are using third party ScrollUISegmentController. You have to implement the delegate method to get selected index ``` func selectItemAt(index: Int, onScrollUISegmentController scrollUISegmentController: ScrollUISegmentController) { if index== 1 { Label1.text = " 100 " Label2.text = " 40 " Label3.text = " 400 " } if index == 2 { Label1.text = " 100 " Label2.text = " 50 " Label3.text = " 400 " } if index == 3 { Label1.text = " 100 " Label2.text = " 60 " Label3.text = " 600 " } } ``` Upvotes: 3 [selected_answer]
2018/03/21
782
1,864
<issue_start>username_0: How can I sort a Python list (with sublists)? For example, I have the following list: ``` list1 = [[0, 4, 1, 5], [3, 1, 5], [4, 0, 1, 5]] ``` After sorting I am expecting: ``` list1 = [[3, 1, 5], [0, 4, 1, 5], [4, 0, 1, 5]] ``` Another example. I have the following list: ``` list2 = [[4, 5, 2], [2, 5, 4], [2, 4, 5]] ``` After sorting I am expecting: ``` list2 = [[2, 4, 5], [2, 5, 4], [4, 5, 2]] ``` At first I want to sort by length, and then by itemwise in each sublist. **I do not want to sort any sublist.** I have tried the following code, which helped me to sort by length only: ``` list1.sort(key=len) ```<issue_comment>username_1: You need a key like: ``` lambda l: (len(l), l) ``` ### How: This uses a [`lambda`](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions) to create a [`tuple`](https://docs.python.org/3/library/functions.html#sorted) which can the be used by [`sorted`](https://docs.python.org/3/library/functions.html#sorted) to sort in the desired fashion. This works because tuples sort element by element. ### Test Code: ``` list1 = [[0, 4, 1, 5], [3, 1, 5], [4, 0, 1, 5]] print(sorted(list1, key=lambda l: (len(l), l))) list2 = [[4, 5, 2], [2, 5, 4], [2, 4, 5]] print(sorted(list2, key=lambda l: (len(l), l))) ``` ### Results: ``` [[3, 1, 5], [0, 4, 1, 5], [4, 0, 1, 5]] [[2, 4, 5], [2, 5, 4], [4, 5, 2]] ``` Upvotes: 6 [selected_answer]<issue_comment>username_2: Python's list.sort() method is "stable", i. e. the relative order of items that compare equal does not change. Therefore you can also achieve the desired order by calling sort() twice: ``` >>> list1 = [[3, 1, 5], [0, 4, 1, 5], [4, 0, 1, 5]] >>> list1.sort() # sort by sublist contents >>> list1.sort(key=len) # sort by sublist length >>> list1 [[3, 1, 5], [0, 4, 1, 5], [4, 0, 1, 5]] ``` Upvotes: 0
2018/03/21
322
1,151
<issue_start>username_0: I am trying to use the PHP API, and same example as given in the code <https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_search_operations.html#_scrolling> ``` $client = ClientBuilder::create()->build(); $params = [ "scroll" => "30s", // how long between scroll requests. should be small! "size" => 50, // how many results *per shard* you want back "index" => "my_index", "body" => [ "query" => [ "match_all" => new \stdClass() ] ] ]; // Execute the search // The response will contain the first batch of documents // and a scroll_id $response = $client->search($params); ``` But getting error like this Unknown key for a VALUE\_STRING in [scroll]. Currently using Elasticsearch version 6.2.2 Any ideas?<issue_comment>username_1: You may have accidentaly put scroll attribute inside body. Upvotes: 0 <issue_comment>username_2: The problem is that you put scroll parameter in json body, but it should be instead in the URL. e.g ``` index-name/_search?scroll=30s ``` Don't forget to remove it from `$params` as well Upvotes: 1
2018/03/21
1,183
4,445
<issue_start>username_0: Under .NET's older `packages.config` system for NuGet, [I could constrain the possible versions of a package](https://learn.microsoft.com/en-us/nuget/consume-packages/reinstalling-and-updating-packages#constraining-upgrade-versions) that are considered when packages are updated by using the [`allowedVersions`](https://learn.microsoft.com/en-us/nuget/reference/package-versioning#version-ranges-and-wildcards) attribute on the Package element ``` ``` When [`update-package`](https://learn.microsoft.com/en-us/nuget/tools/ps-ref-update-package) is run within Visual studio for a project including the above, no update will occur for `Newtonsoft.Json` because I've pinned to 10.0.3 using the `allowedVersions` attribute. How can I achieve this under [`PackageReference`](https://learn.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files)? Applying [semver](https://learn.microsoft.com/en-us/nuget/reference/package-versioning#version-ranges-and-wildcards) syntax to the Version attribute only affects the version *restored* - it doesn't constrain updates. So if I specify the below `PackageReference` and run `update-package`, I will for example be upgraded to 11.0.1 if 11.0.1 is in my NuGet repository. ``` ``` Background ---------- We rely on command line tooling to update packages because we have both fast moving internal packages (updated multiple times a day) and more stable low moving packages (eg: ASP.NET). On large codebases updating each dependency by hand in `.csproj` files is simply not scalable for us (and error prone). Under `packages.config` we can 'pin' the third party packages which we don't want upgraded and also update to the latest fast moving dependencies.<issue_comment>username_1: From [this answer](https://stackoverflow.com/a/44530102): > > At the moment, this is not possible. See [this GitHub issue](https://github.com/NuGet/Home/issues/4358) for tracking. > > > The cli commands for adding references however support updating single packages in a project by re-running `dotnet add package The.Package.Id`. > > > From [GitHub Issue 4358](https://github.com/NuGet/Home/issues/4358#issuecomment-274361787): > > There is no `PackageReference` replacement for `update` yet, the command to modify references is only in `dotnet`. > > > You might want to weigh in on the open feature request [GitHub issue 4103](https://github.com/NuGet/Home/issues/4103) about this (4358 was closed as a duplicate). Microsoft hasn't put a high priority on this feature (it was originally opened in October, 2016). Possible Workarounds ==================== Option 1 -------- It is possible to "update" a dependency by removing and adding the reference. According to [this post](https://github.com/NuGet/Home/issues/6382#issuecomment-366961987), specifying the version explicitly with the command will install the *exact version*, not the latest version. I have also confirmed you can add version constraints with the command: ``` dotnet remove NewCsproj.csproj package Newtonsoft.Json dotnet add NewCsproj.csproj package Newtonsoft.Json -v [10.0.3] ``` What you could do with these commands: 1. Keep version numbers of packages around in a text file (perhaps just keep it named `packages.config`). 2. Use a script to create your own "update" command that reads the text file and processes each dependency in a loop using the above 2 commands. The script could be setup to be passed a `.sln` file to process each of the projects within it. Option 2 -------- Use MSBuild to "import" dependencies from a common MSBuild file, where you can update the versions in one place. You can define your own element to include specific dependencies to each project. ### `SomeProject.csproj` ``` Newtonsoft.Json;FastMoving ... ``` ### `Dependencies.proj` ``` ``` Upvotes: 2 <issue_comment>username_2: This has now been implemented as of <https://github.com/NuGet/NuGet.Client/pull/2201>. If you are using any version of NuGet 5, `PackageReference` semver constraints should now work as expected. Upvotes: 2 [selected_answer]<issue_comment>username_3: Pinning - Yet another workaround ================================ This doesn't prevent the update but triggers a build error if one did and update. It won't help much with the use case of automated updates but it may help others that do manual updates and need some way of pinning. ``` ``` Upvotes: 0
2018/03/21
679
2,115
<issue_start>username_0: While creating new tests, I got this error: ``` Determining test suites to run...Error: ENOENT: no such file or directory, stat '/home/andrew/Documents/wise-fox/The-App/src/tests/components/AlertsComponent/AlertsPages/PromoPage3.test.js' at Object.fs.statSync (fs.js:948:11) at Object.statSync (/home/andrew/Documents/wise-fox/The-App/node_modules/graceful-fs/polyfills.js:297:22) at fileSize (/home/andrew/Documents/wise-fox/The-App/node_modules/jest/node_modules/jest-cli/build/test_sequencer.js:71:73) at tests.sort (/home/andrew/Documents/wise-fox/The-App/node_modules/jest/node_modules/jest-cli/build/test_sequencer.js:91:34) at Array.sort (native) at TestSequencer.sort (/home/andrew/Documents/wise-fox/The-App/node_modules/jest/node_modules/jest-cli/build/test_sequencer.js:77:18) at /home/andrew/Documents/wise-fox/The-App/node_modules/jest/node_modules/jest-cli/build/run_jest.js:148:26 at Generator.next () at step (/home/andrew/Documents/wise-fox/The-App/node\_modules/jest/node\_modules/jest-cli/build/run\_jest.js:27:377) at /home/andrew/Documents/wise-fox/The-App/node\_modules/jest/node\_modules/jest-cli/build/run\_jest.js:27:537 ``` The error is trying to look for a test file that no longer exists. I had copied a number of tests and then adapted the names of the files as well as the tests inside to fit the new files. Previously, jest just realized that certain test files had disappeared (because of renaming), but in this case jest thinks these files still exist. I'm not sure why, and I'm not sure how to fix it. Framework: React 16 OS: Linux Elementary OS<issue_comment>username_1: Ah, it had something to do with the obsolete snapshot files. I deleted them manually and the tests ran just fine Upvotes: 4 [selected_answer]<issue_comment>username_2: Just, delete the generated directory **snapshots** it will be generated where you have written YOUR\_FILE\_NAME.test.js. Upvotes: 2 <issue_comment>username_3: For me it was not a snapshot issue, but a cache issue. Run ``` jest --clearCache ``` to get rid of it. Upvotes: 4
2018/03/21
508
1,685
<issue_start>username_0: can anyone show me how to upload and store video using laravel ? whenever i try to upload a video it gives me post too large exception. I also changed values in php.ini file like post\_max\_size etc but did not worked<issue_comment>username_1: You should check if the php.ini options are getting loaded correctly. There are a lot of ways to overwrite this configuration file. A quick Google search gave me this page: <http://php.net/manual/en/configuration.changes.php> Upvotes: 0 <issue_comment>username_2: As others said, you have to set "post\_max\_size" parameter on php.ini file. If you are using php under the ubuntu, you could find the php.ini file on the path like: "/etc/php/7.2/fpm/php.ini". The path may differ according to your php version or installation method. ``` sudo nano /etc/php/7.2/fpm/php.ini ``` and also for Command-line version: ``` sudo nano /etc/php/7.2/cli/php.ini ``` Now, search for "post\_max\_size" using CTRL+w functional keys. The default value is ``` post_max_size = 8M ``` I changed the value to ``` post_max_size = 500M ``` press CTRL+O and then enter the "y" to confirm changes. do this flow for "upload\_max\_filesize" parameter; we changed it from: ``` upload_max_filesize = 2M ``` to ``` upload_max_filesize = 500M ``` now confirm the changes with CTRL+O and then exit with CTRL+X . It could be useful to change some other parameters like "memory\_limit", so on (check this article from [DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-change-your-php-settings-on-ubuntu-14-04)). Don't forget to reload new configurations: ``` sudo service php7.2-fpm restart ``` Upvotes: 1
2018/03/21
751
2,673
<issue_start>username_0: How can I disable certain alert on the page and allow others? I tried With this code: ``` window.alert = function ( text ) { console.log(text); if(!text.includes("rambo")) alert("rambo"); }; ``` This won't work because it calls alert again and not the alert. I need to use javascript alert( not any other libraries)<issue_comment>username_1: Save a reference to the old `window.alert` first. ``` const oldAlert = window.alert; window.alert = function ( text ) { console.log(text); if(!text.includes("rambo")) oldAlert(text); return true; }; window.alert('ram'); window.alert('rambo'); ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: You can store old alter in variable ``` var ar = alert; window.alert = function(text) { console.log(text); if (!text.includes("rambo")) ar("rambo"); return true; }; alert('dfs'); ``` Upvotes: 2 <issue_comment>username_3: The other two answers are mostly correct, but they pollute the global namespace by creating a new reference to `window.alert`. So I would suggest wrapping this in an IIFE: ```js (function() { var nativeAlert = window.alert; window.alert = function(message) { if (message.includes("test")) { nativeAlert(message); } }; }()); alert("Hello"); // Doesn't show up. alert("Hello test"); // Works. nativeAlert("test"); // Throws an error. ``` You could go a step further an create an alert function generator that creates an alert object using a predicate: ```js function alertGenerator(predicate) { if (typeof predicate === "function") { return function(message) { if (predicate(message) === true) { window.alert(message); } } } else { return undefined; } } // Create an alert generator that requires the word "test" in it: var testAlert = alertGenerator(t => t.includes("test")); testAlert("Hello"); // Doesn't show up. testAlert("Hello test"); // Works. // Create an alert generator that requires the word "Hello" in it: var helloAlert = alertGenerator(t => t.includes("Hello")); helloAlert("Hello"); // Works. helloAlert("Hello test"); // Works. helloAlert("Test"); // Doesn't work. ``` Upvotes: 2 <issue_comment>username_4: If you **don't wan't** to pollute *global namespace* or use an *IIFE*, why don't you simply wrap `window.alert` in another function like this: ```js function myCustomAlert(message) { return message.includes('rambo') ? window.alert(message) : false; } myCustomAlert("This message won't be shown!"); myCustomAlert("This message will be shown because it contains rambo"); ``` Upvotes: 1
2018/03/21
1,762
6,198
<issue_start>username_0: I got this from a tutorial and made some changes but I'm unable to figure out why it's pointing to a null object. Here are the codes: **HomeActivity.java** ``` final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference(Common.token_table).child(Common.user_workers_table).child(stringWorkerType); dbRef.orderByKey().equalTo(workerId).addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot ds: dataSnapshot.getChildren()) { Token token = ds.getValue(Token.class); //Make raw payload - convert LatLng to json String json_lat_lng = new Gson().toJson(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude())); String workerToken = FirebaseInstanceId.getInstance().getToken(); Notification notification = new Notification(workerToken, json_lat_lng); Sender content = new Sender(token.getToken(), notification); //IFCMService mService; mService.sendMessage(content).enqueue(new Callback() { @Override public void onResponse(Call call, Response response) { if(response.body().success == 1) { Log.d("LOG/I", "Request sent."); } else { Toast.makeText(HomeActivity.this, "Request not sent.", Toast.LENGTH\_SHORT).show(); } } ``` **IFCMService.java** ``` public interface IFCMService { @Headers({ "Content-Type:application/json", "Authorization:key=<KEY> <KEY>" }) @POST("fcm/send") Call sendMessage(@Body Sender body); } ``` **FCMResponse.java** ``` public class FCMResponse { public long multicast_id; public int success; public int failure; public int canonical_ids; public List results; public FCMResponse() { } public FCMResponse(long multicast\_id, int success, int failure, int canonical\_ids, List results) { this.multicast\_id = multicast\_id; this.success = success; this.failure = failure; this.canonical\_ids = canonical\_ids; this.results = results; } public long getMulticast\_id() { return multicast\_id; } public void setMulticast\_id(long multicast\_id) { this.multicast\_id = multicast\_id; } public int getSuccess() { return success; } public void setSuccess(int success) { this.success = success; } public int getFailure() { return failure; } public void setFailure(int failure) { this.failure = failure; } public int getCanonical\_ids() { return canonical\_ids; } public void setCanonical\_ids(int canonical\_ids) { this.canonical\_ids = canonical\_ids; } public List getResults() { return results; } public void setResults(List results) { this.results = results; } } ``` **Sender.class** ``` public class Sender { public String to; public Notification notification; public Sender() { } public Sender(String to, Notification notification) { this.to = to; this.notification = notification; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public Notification getNotification() { return notification; } public void setNotification(Notification notification) { this.notification = notification; } } ``` It's an app like uber, what this codes supposed to be doing is when the driver/client app request and a driver/worker is available, it will give a notification to the driver/worker. But it does nothing and I'm getting an error at ``` java.lang.NullPointerException at com.fixitph.client.HomeActivity$22$1.onResponse(HomeActivity.java:1129) ``` 1129 is the ***if(response.body().success == 1) {*** line Let me know if you need more information on this. Thank you in advance :)<issue_comment>username_1: Save a reference to the old `window.alert` first. ``` const oldAlert = window.alert; window.alert = function ( text ) { console.log(text); if(!text.includes("rambo")) oldAlert(text); return true; }; window.alert('ram'); window.alert('rambo'); ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: You can store old alter in variable ``` var ar = alert; window.alert = function(text) { console.log(text); if (!text.includes("rambo")) ar("rambo"); return true; }; alert('dfs'); ``` Upvotes: 2 <issue_comment>username_3: The other two answers are mostly correct, but they pollute the global namespace by creating a new reference to `window.alert`. So I would suggest wrapping this in an IIFE: ```js (function() { var nativeAlert = window.alert; window.alert = function(message) { if (message.includes("test")) { nativeAlert(message); } }; }()); alert("Hello"); // Doesn't show up. alert("Hello test"); // Works. nativeAlert("test"); // Throws an error. ``` You could go a step further an create an alert function generator that creates an alert object using a predicate: ```js function alertGenerator(predicate) { if (typeof predicate === "function") { return function(message) { if (predicate(message) === true) { window.alert(message); } } } else { return undefined; } } // Create an alert generator that requires the word "test" in it: var testAlert = alertGenerator(t => t.includes("test")); testAlert("Hello"); // Doesn't show up. testAlert("Hello test"); // Works. // Create an alert generator that requires the word "Hello" in it: var helloAlert = alertGenerator(t => t.includes("Hello")); helloAlert("Hello"); // Works. helloAlert("Hello test"); // Works. helloAlert("Test"); // Doesn't work. ``` Upvotes: 2 <issue_comment>username_4: If you **don't wan't** to pollute *global namespace* or use an *IIFE*, why don't you simply wrap `window.alert` in another function like this: ```js function myCustomAlert(message) { return message.includes('rambo') ? window.alert(message) : false; } myCustomAlert("This message won't be shown!"); myCustomAlert("This message will be shown because it contains rambo"); ``` Upvotes: 1
2018/03/21
778
2,747
<issue_start>username_0: As an example, I'm trying to define quot in a single function. I'm struggling to see how to do so without appending an extra parameter (in this case, a counter). ``` quot x y n | x < y = n | otherwise = quot (x-y) y (n+1) quot0 x y = x y 0 ``` I've run into this problem multiple times and continue to use this ad hoc solution, while I know there must be an easy way to incorporate the n implicitly.<issue_comment>username_1: Save a reference to the old `window.alert` first. ``` const oldAlert = window.alert; window.alert = function ( text ) { console.log(text); if(!text.includes("rambo")) oldAlert(text); return true; }; window.alert('ram'); window.alert('rambo'); ``` Upvotes: 5 [selected_answer]<issue_comment>username_2: You can store old alter in variable ``` var ar = alert; window.alert = function(text) { console.log(text); if (!text.includes("rambo")) ar("rambo"); return true; }; alert('dfs'); ``` Upvotes: 2 <issue_comment>username_3: The other two answers are mostly correct, but they pollute the global namespace by creating a new reference to `window.alert`. So I would suggest wrapping this in an IIFE: ```js (function() { var nativeAlert = window.alert; window.alert = function(message) { if (message.includes("test")) { nativeAlert(message); } }; }()); alert("Hello"); // Doesn't show up. alert("Hello test"); // Works. nativeAlert("test"); // Throws an error. ``` You could go a step further an create an alert function generator that creates an alert object using a predicate: ```js function alertGenerator(predicate) { if (typeof predicate === "function") { return function(message) { if (predicate(message) === true) { window.alert(message); } } } else { return undefined; } } // Create an alert generator that requires the word "test" in it: var testAlert = alertGenerator(t => t.includes("test")); testAlert("Hello"); // Doesn't show up. testAlert("Hello test"); // Works. // Create an alert generator that requires the word "Hello" in it: var helloAlert = alertGenerator(t => t.includes("Hello")); helloAlert("Hello"); // Works. helloAlert("Hello test"); // Works. helloAlert("Test"); // Doesn't work. ``` Upvotes: 2 <issue_comment>username_4: If you **don't wan't** to pollute *global namespace* or use an *IIFE*, why don't you simply wrap `window.alert` in another function like this: ```js function myCustomAlert(message) { return message.includes('rambo') ? window.alert(message) : false; } myCustomAlert("This message won't be shown!"); myCustomAlert("This message will be shown because it contains rambo"); ``` Upvotes: 1
2018/03/21
605
1,980
<issue_start>username_0: I would like to clarify that this is a basic *page* and there will be no scrolling whatsoever and minimal text. I have been trying to use Bootstrap 4 to align text to the direct middle of the page, then also having a footer at the bottom of the page, also centered. I currently have the following ``` Test Anything here adds a scrollbar ``` I have tried to change the h-100 and split the classes up into different divs to see if that would make a difference, but it does not. I have also tried things like (with this, it works, besides a scrollbar being added to the page and to see the footer I need to scroll down): ``` Hi! === Footer ```<issue_comment>username_1: **Try this:** Change `to and add **justify-content-center** class to` ``` Hi! === Footer ``` Upvotes: 0 <issue_comment>username_2: The *vertical center* aspect of this question is duplicate: [Vertical Align Center in Bootstrap 4](https://stackoverflow.com/questions/42252443/vertical-align-center-in-bootstrap-4) The *page height and no scrolling* aspect of the question, "no scrolling whatsoever... direct middle of the page, then also having a footer at the bottom of the page" requires **flexbox to fill the height**. `h-100` won't work since it pushes the footer over height:100% and thus requires scrolling to see the footer (or hides the footer). ``` .cover-container { height: 100vh; } .flex-fill { flex: 1 1 auto; } ``` HTML ``` Hi! === Footer ``` <https://www.codeply.com/go/CIMvZxkT4O> Note: The `flex-fill` class will be [included in Bootstrap 4.1](https://github.com/twbs/bootstrap/commit/2137d61eacbd962ea41e16a492da8b1d1597d3d9) so the extra `flex-fill` CSS will no longer be needed when 4.1 is released. --- Related question: [Bootstrap 4 expanded navbar and content fill height flexbox](https://stackoverflow.com/questions/49191957/bootstrap-4-expanded-navbar-and-content-fill-height-flexbox) Upvotes: 3 [selected_answer]
2018/03/21
535
2,001
<issue_start>username_0: Before the actual test execution, I want to call some HTTP APIs and parse the response out of it before handling it to my SSH Command sampler. What's the best way to do it in Jmeter? Like there is a pre-processor for JDBC request, then why not a pre-processor for HTTP request?<issue_comment>username_1: Simply put the HTTP calls before the SSH Command Sampler in the ThreadGroup. Pre-processors are mostly used to perform some modifications on the request before executing the sampler. Upvotes: 0 <issue_comment>username_2: There is [JSR223 PreProcessor](https://jmeter.apache.org/usermanual/component_reference.html#JSR223_PreProcessor) you can use to make an arbitrary HTTP Request using underlying [Apache HttpComponent](https://hc.apache.org/) libraries. 1. Add JSR223 PreProcessor as a child of your SSH Command sampler 2. Put the following code into "Script" area: ``` import org.apache.http.client.methods.HttpGet import org.apache.http.impl.client.HttpClientBuilder import org.apache.http.util.EntityUtils def httpClient = HttpClientBuilder.create().build() def httpGet = new HttpGet("http://example.com") def httpResponse = httpClient.execute(httpGet) def responseData = EntityUtils.toString(httpResponse.getEntity()) log.info('----- Response -----') log.info(responseData) vars.put('response', responseData) ``` 3. The above code executes simple [HTTP GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request to <http://example.com> website, prints the response to *jmeter.log* and additionally stores it into `${response}` JMeter Variable which you can reuse later on where required. Demo: [![JMeter Groovy Execute HTTP Request](https://i.stack.imgur.com/6Agso.png)](https://i.stack.imgur.com/6Agso.png) References: * [HttpClient Quick Start](https://hc.apache.org/httpcomponents-client-ga/quickstart.html) * [Apache Groovy - Why and How You Should Use It](https://www.blazemeter.com/blog/groovy-new-black) Upvotes: 4 [selected_answer]
2018/03/21
570
1,654
<issue_start>username_0: I am trying to place an icon inside a circle and that circle will be placed at the start of an input field like below: [![enter image description here](https://i.stack.imgur.com/eR0tE.png)](https://i.stack.imgur.com/eR0tE.png) I am trying to achieve this using below code in `ionic`: // in .html ``` ``` // in .scss ``` ion-item { border-radius: 23px; padding-left: 0; } ion-label { border-radius: 23px; border: 2px solid red; width: 12%; height: 100%; } ``` But i could achieve only below: [![enter image description here](https://i.stack.imgur.com/4Jg1Q.png)](https://i.stack.imgur.com/4Jg1Q.png) Can anyone help me on that?<issue_comment>username_1: You will need to use `position:absolute` for the `label` icon...And use `display:flex` to the label to align the icon inside to center *Note: I have used font-awesome here just for icon visual...* ```css ion-item { position: relative; } ion-label { border-radius: 50%; border: 2px solid red; position: absolute; top: 0; left: 0; width: 46px; height: 46px; z-index: 9; box-sizing: border-box; display: flex; align-items: center; justify-content: center; } input { border: 1px solid; height: 46px; width: 100%; display: block; border-radius: 23px; box-sizing: border-box; padding-left: 50px; outline: none; } ``` ```html ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: very simple, just give margin to ion-icon class ``` .ion-icon{ margin: 8px 0 0 8px; display: block; } ``` Adjust the margin according to the correct position of icon. Upvotes: -1
2018/03/21
232
843
<issue_start>username_0: Can anybody know how to split an STL into surfaces in VTK? Or how to do it in Paraview?<issue_comment>username_1: In ParaView : * Open ParaView * File -> Open -> Select your STL file, Apply * You obtain a single vtkPolyData object, you can then use ParaView for any splliting you may want to do. In VTK : ``` vtkNew reader; reader->SetFileName("/path/to/your/file.stl"); reader->Update() ``` You can the use reader output and show it or split it to your needs using VTK filters. Upvotes: 1 <issue_comment>username_2: Depends on how you want to split it. If you want to split it into grouped surfaces, use vtkPolyDataNormals with SplittingOn, and use SetFeatureAngle to decide what angle to split at. Then, you can use vtkPolyDataConnectivityFilter to get each split piece in a loop. Upvotes: 3 [selected_answer]
2018/03/21
5,741
20,426
<issue_start>username_0: I'm using `android studio 3.0`. Whenever I try to create a new project, I get this error: ``` Gradle 'MyActivity' project refresh failed, Error:Cause: malformed input around byte 13 ``` I'm unable to fix this because it is related to `gradle`. I've followed certain steps to fix it which are given below. I've added a screen shot. [![SS](https://i.stack.imgur.com/30wEZ.png)](https://i.stack.imgur.com/30wEZ.png) Log is as given below: ``` 2018-03-21 10:41:48,786 [thread 206] INFO - #com.jetbrains.cidr.lang - Clearing symbols finished in 0 s. 2018-03-21 10:41:48,786 [thread 206] INFO - #com.jetbrains.cidr.lang - Loading symbols finished in 0 s. 2018-03-21 10:41:48,786 [thread 206] INFO - #com.jetbrains.cidr.lang - Building symbols finished in 0 s. 2018-03-21 10:41:48,786 [thread 206] INFO - #com.jetbrains.cidr.lang - Saving symbols finished in 0 s. 2018-03-21 10:41:49,952 [se-915-b01] INFO - e.project.sync.GradleSyncState - Started sync with Gradle for project 'MyActivity'. 2018-03-21 10:41:49,980 [thread 206] INFO - s.plugins.gradle.GradleManager - Instructing gradle to use java from C:/Program Files/Android/Android Studio/jre 2018-03-21 10:41:49,987 [thread 206] INFO - s.plugins.gradle.GradleManager - Instructing gradle to use java from C:/Program Files/Android/Android Studio/jre 2018-03-21 10:41:50,019 [thread 206] INFO - oject.common.GradleInitScripts - init script file sync.local.repo contents "allprojects {\n buildscript {\n repositories {\n maven { url 'C:\\\\Program Files\\\\Android\\\\Android Studio\\\\gradle\\\\m2repository'}\n }\n }\n repositories {\n maven { url 'C:\\\\Program Files\\\\Android\\\\Android Studio\\\\gradle\\\\m2repository'}\n }\n}\n" 2018-03-21 10:41:50,019 [thread 206] INFO - xecution.GradleExecutionHelper - Passing command-line args to Gradle Tooling API: -Didea.version=3.0 -Djava.awt.headless=true -Pandroid.injected.build.model.only=true -Pandroid.injected.build.model.only.advanced=true -Pandroid.injected.invoked.from.ide=true -Pandroid.injected.build.model.only.versioned=3 -Pandroid.injected.studio.version=3.0.0.18 --init-script C:\Users\kulkaa\AppData\Local\Temp\sync.local.repo1148.gradle --init-script C:\Users\kulkaa\AppData\Local\Temp\ijinit13.gradle 2018-03-21 10:41:50,051 [thread 206] INFO - .project.GradleProjectResolver - Gradle project resolve error org.gradle.tooling.GradleConnectionException: Could not run build action using Gradle distribution 'https://services.gradle.org/distributions/gradle-4.1-all.zip'. at org.gradle.tooling.internal.consumer.ExceptionTransformer.transform(ExceptionTransformer.java:55) at org.gradle.tooling.internal.consumer.ExceptionTransformer.transform(ExceptionTransformer.java:29) at org.gradle.tooling.internal.consumer.ResultHandlerAdapter.onFailure(ResultHandlerAdapter.java:41) at org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:57) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63) at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) at org.gradle.tooling.internal.consumer.BlockingResultHandler.getResult(BlockingResultHandler.java:46) at org.gradle.tooling.internal.consumer.DefaultBuildActionExecuter.run(DefaultBuildActionExecuter.java:60) at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.doResolveProjectInfo(GradleProjectResolver.java:258) at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.access$200(GradleProjectResolver.java:79) at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:902) at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:886) at org.jetbrains.plugins.gradle.service.execution.GradleExecutionHelper.execute(GradleExecutionHelper.java:218) at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:139) at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:79) at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.lambda$resolveProjectInfo$0(RemoteExternalSystemProjectResolverImpl.java:37) at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59) at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37) at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:45) at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:66) at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:139) at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:125) at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3.execute(ExternalSystemUtil.java:388) at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$5.run(ExternalSystemUtil.java:445) at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:726) at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$1(CoreProgressManager.java:176) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:556) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:501) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:66) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:163) at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:137) at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:334) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.gradle.api.GradleException: Could not read cache value from 'C:\Users\kulkaa\.gradle\daemon\4.1\registry.bin'. at org.gradle.cache.internal.SimpleStateCache.deserialize(SimpleStateCache.java:139) at org.gradle.cache.internal.SimpleStateCache.access$000(SimpleStateCache.java:33) at org.gradle.cache.internal.SimpleStateCache$1.create(SimpleStateCache.java:49) at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock.readFile(DefaultFileLockManager.java:170) at org.gradle.cache.internal.OnDemandFileAccess.readFile(OnDemandFileAccess.java:38) at org.gradle.cache.internal.SimpleStateCache.get(SimpleStateCache.java:47) at org.gradle.cache.internal.FileIntegrityViolationSuppressingPersistentStateCacheDecorator.get(FileIntegrityViolationSuppressingPersistentStateCacheDecorator.java:32) at org.gradle.launcher.daemon.registry.PersistentDaemonRegistry.getAll(PersistentDaemonRegistry.java:69) at org.gradle.launcher.daemon.client.DefaultDaemonConnector.connect(DefaultDaemonConnector.java:109) at org.gradle.launcher.daemon.client.DaemonClient.execute(DaemonClient.java:138) at org.gradle.launcher.daemon.client.DaemonClient.execute(DaemonClient.java:92) at org.gradle.tooling.internal.provider.DaemonBuildActionExecuter.execute(DaemonBuildActionExecuter.java:60) at org.gradle.tooling.internal.provider.DaemonBuildActionExecuter.execute(DaemonBuildActionExecuter.java:41) at org.gradle.tooling.internal.provider.LoggingBridgingBuildActionExecuter.execute(LoggingBridgingBuildActionExecuter.java:60) at org.gradle.tooling.internal.provider.LoggingBridgingBuildActionExecuter.execute(LoggingBridgingBuildActionExecuter.java:34) at org.gradle.tooling.internal.provider.ProviderConnection.run(ProviderConnection.java:143) at org.gradle.tooling.internal.provider.ProviderConnection.run(ProviderConnection.java:128) at org.gradle.tooling.internal.provider.DefaultConnection.run(DefaultConnection.java:208) at org.gradle.tooling.internal.consumer.connection.CancellableConsumerConnection$CancellableActionRunner.run(CancellableConsumerConnection.java:99) at org.gradle.tooling.internal.consumer.connection.AbstractConsumerConnection.run(AbstractConsumerConnection.java:62) at org.gradle.tooling.internal.consumer.connection.ParameterValidatingConsumerConnection.run(ParameterValidatingConsumerConnection.java:53) at org.gradle.tooling.internal.consumer.DefaultBuildActionExecuter$1.run(DefaultBuildActionExecuter.java:71) at org.gradle.tooling.internal.consumer.connection.LazyConsumerActionExecutor.run(LazyConsumerActionExecutor.java:84) at org.gradle.tooling.internal.consumer.connection.CancellableConsumerActionExecutor.run(CancellableConsumerActionExecutor.java:45) at org.gradle.tooling.internal.consumer.connection.ProgressLoggingConsumerActionExecutor.run(ProgressLoggingConsumerActionExecutor.java:58) at org.gradle.tooling.internal.consumer.connection.RethrowingErrorsConsumerActionExecutor.run(RethrowingErrorsConsumerActionExecutor.java:38) at org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:55) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63) at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46) ... 3 more Caused by: java.io.UTFDataFormatException: malformed input around byte 13 at java.io.DataInputStream.readUTF(DataInputStream.java:656) at java.io.DataInputStream.readUTF(DataInputStream.java:564) at org.gradle.internal.serialize.InputStreamBackedDecoder.readString(InputStreamBackedDecoder.java:51) at org.gradle.launcher.daemon.context.DefaultDaemonContext$Serializer.read(DefaultDaemonContext.java:93) at org.gradle.launcher.daemon.context.DefaultDaemonContext$Serializer.read(DefaultDaemonContext.java:80) at org.gradle.launcher.daemon.registry.DaemonInfo$Serializer.read(DaemonInfo.java:131) at org.gradle.launcher.daemon.registry.DaemonRegistryContent$Serializer.readInfosMap(DaemonRegistryContent.java:138) at org.gradle.launcher.daemon.registry.DaemonRegistryContent$Serializer.read(DaemonRegistryContent.java:118) at org.gradle.launcher.daemon.registry.DaemonRegistryContent$Serializer.read(DaemonRegistryContent.java:112) at org.gradle.cache.internal.SimpleStateCache.deserialize(SimpleStateCache.java:134) ... 31 more 2018-03-21 10:41:50,051 [thread 206] WARN - nal.AbstractExternalSystemTask - Cause: malformed input around byte 13 com.intellij.openapi.externalSystem.model.ExternalSystemException: Cause: malformed input around byte 13 at com.android.tools.idea.gradle.project.sync.idea.ProjectImportErrorHandler.getUserFriendlyError(ProjectImportErrorHandler.java:85) at com.android.tools.idea.gradle.project.sync.idea.AndroidGradleProjectResolver.getUserFriendlyError(AndroidGradleProjectResolver.java:414) at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:158) at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:906) at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:886) at org.jetbrains.plugins.gradle.service.execution.GradleExecutionHelper.execute(GradleExecutionHelper.java:218) at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:139) at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:79) at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.lambda$resolveProjectInfo$0(RemoteExternalSystemProjectResolverImpl.java:37) at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59) at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37) at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:45) at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:66) at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:139) at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:125) at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3.execute(ExternalSystemUtil.java:388) at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$5.run(ExternalSystemUtil.java:445) at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:726) at com.intellij.openapi.progress.impl.CoreProgressManager.lambda$runProcess$1(CoreProgressManager.java:176) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:556) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:501) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:66) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:163) at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:137) at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:334) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: java.io.UTFDataFormatException: malformed input around byte 13 at java.io.DataInputStream.readUTF(DataInputStream.java:656) at java.io.DataInputStream.readUTF(DataInputStream.java:564) at org.gradle.internal.serialize.InputStreamBackedDecoder.readString(InputStreamBackedDecoder.java:51) at org.gradle.launcher.daemon.context.DefaultDaemonContext$Serializer.read(DefaultDaemonContext.java:93) at org.gradle.launcher.daemon.context.DefaultDaemonContext$Serializer.read(DefaultDaemonContext.java:80) at org.gradle.launcher.daemon.registry.DaemonInfo$Serializer.read(DaemonInfo.java:131) at org.gradle.launcher.daemon.registry.DaemonRegistryContent$Serializer.readInfosMap(DaemonRegistryContent.java:138) at org.gradle.launcher.daemon.registry.DaemonRegistryContent$Serializer.read(DaemonRegistryContent.java:118) at org.gradle.launcher.daemon.registry.DaemonRegistryContent$Serializer.read(DaemonRegistryContent.java:112) at org.gradle.cache.internal.SimpleStateCache.deserialize(SimpleStateCache.java:134) at org.gradle.cache.internal.SimpleStateCache.access$000(SimpleStateCache.java:33) at org.gradle.cache.internal.SimpleStateCache$1.create(SimpleStateCache.java:49) at org.gradle.cache.internal.DefaultFileLockManager$DefaultFileLock.readFile(DefaultFileLockManager.java:170) at org.gradle.cache.internal.OnDemandFileAccess.readFile(OnDemandFileAccess.java:38) at org.gradle.cache.internal.SimpleStateCache.get(SimpleStateCache.java:47) at org.gradle.cache.internal.FileIntegrityViolationSuppressingPersistentStateCacheDecorator.get(FileIntegrityViolationSuppressingPersistentStateCacheDecorator.java:32) at org.gradle.launcher.daemon.registry.PersistentDaemonRegistry.getAll(PersistentDaemonRegistry.java:69) at org.gradle.launcher.daemon.client.DefaultDaemonConnector.connect(DefaultDaemonConnector.java:109) at org.gradle.launcher.daemon.client.DaemonClient.execute(DaemonClient.java:138) at org.gradle.launcher.daemon.client.DaemonClient.execute(DaemonClient.java:92) at org.gradle.tooling.internal.provider.DaemonBuildActionExecuter.execute(DaemonBuildActionExecuter.java:60) at org.gradle.tooling.internal.provider.DaemonBuildActionExecuter.execute(DaemonBuildActionExecuter.java:41) at org.gradle.tooling.internal.provider.LoggingBridgingBuildActionExecuter.execute(LoggingBridgingBuildActionExecuter.java:60) at org.gradle.tooling.internal.provider.LoggingBridgingBuildActionExecuter.execute(LoggingBridgingBuildActionExecuter.java:34) at org.gradle.tooling.internal.provider.ProviderConnection.run(ProviderConnection.java:143) at org.gradle.tooling.internal.provider.ProviderConnection.run(ProviderConnection.java:128) at org.gradle.tooling.internal.provider.DefaultConnection.run(DefaultConnection.java:208) at org.gradle.tooling.internal.consumer.connection.CancellableConsumerConnection$CancellableActionRunner.run(CancellableConsumerConnection.java:99) at org.gradle.tooling.internal.consumer.connection.AbstractConsumerConnection.run(AbstractConsumerConnection.java:62) at org.gradle.tooling.internal.consumer.connection.ParameterValidatingConsumerConnection.run(ParameterValidatingConsumerConnection.java:53) at org.gradle.tooling.internal.consumer.DefaultBuildActionExecuter$1.run(DefaultBuildActionExecuter.java:71) at org.gradle.tooling.internal.consumer.connection.LazyConsumerActionExecutor.run(LazyConsumerActionExecutor.java:84) at org.gradle.tooling.internal.consumer.connection.CancellableConsumerActionExecutor.run(CancellableConsumerActionExecutor.java:45) at org.gradle.tooling.internal.consumer.connection.ProgressLoggingConsumerActionExecutor.run(ProgressLoggingConsumerActionExecutor.java:58) at org.gradle.tooling.internal.consumer.connection.RethrowingErrorsConsumerActionExecutor.run(RethrowingErrorsConsumerActionExecutor.java:38) at org.gradle.tooling.internal.consumer.async.DefaultAsyncConsumerActionExecutor$1$1.run(DefaultAsyncConsumerActionExecutor.java:55) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63) at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46) ... 3 more ``` **Steps:** I tried to fix it by clearing `gradle` cache and `lock` file. But it didn't work. I even uninstalled and reinstalled Android studio, but that didn't fix this problem. How do I fix this?<issue_comment>username_1: I fixed it by moving `.Gradle` folder to different location, then I restarted android studio, let android studio download required gradle files and build new project. It worked. But that malformed error was weird. Upvotes: 1 <issue_comment>username_2: Deleting the contents of folder daemon worked for me. Folder location is: `C:\Users\kulkaa\.gradle\daemon\**` Before I was deleting the entire `.gradle` folder and having Android studio reinstall gradle, which was a royal pain. Upvotes: 0
2018/03/21
1,947
4,485
<issue_start>username_0: I have a large data set divided into many small groups by a grouping variable = `grp`; all members of a group are contiguous in the order of the larger data set. The members of a group each have an id code (= `id`) and are numbered sequentially from 1. Within a group, some members meet a logical criterion = `is_child`. Each member has a variable (`momloc`) that contains either zero or the ID number of another of another group member (the mother if present). I wish to assign to each individual in the data set the number of group members who has momloc equal to their ID, and zero if none do. I am trying to do this in dplyr as I have the groups set up there, and I have code that works, but it is a Rube Goldberg contraption of nested ifelse functions that adds two additional columns for intermediate values, one of which contains a vector, goes through the data set three times, and is incredibly slow. There has to be a better way than that. I'm getting tangled in the different syntax for mutate, working on rows, and summary, working on groups. Below is a simplified data set and desired outcome ``` grp <- c(1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2) id <- c(1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7) is_child <- c(0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0) momloc <- c(0, 0, 2, 2, 0, 0, 0, 3, 2, 2, 2) data <- tibble(grp, id, is_child, momloc) ``` desired output: ``` out = c(0, 2, 0, 0, 0, 2, 1, 0, 0, 0, 0) ```<issue_comment>username_1: It could easily be the case that I misunderstood your question. But I think a `table()` of `momloc` and `grp` is what you are looking for: ```r library(tidyverse) grp <- c(1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2) %>% factor id <- c(1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7) %>% factor is_child <- c(0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0) momloc <- c(0, 0, 2, 2, 0, 0, 0, 3, 2, 2, 2) data <- tibble(grp, id, is_child, momloc) out = c(0, 2, 0, 0, 0, 2, 1, 0, 0, 0, 0) data2 <- filter(data, is_child == 1) data3 <- table(id = factor(data2$momloc, levels = levels(id)), grp = data2$grp) %>% as.data.frame(responseName = "out") left_join(data, data3, by = c("grp", "id")) #> # A tibble: 11 x 5 #> grp id is_child momloc out #> #> 1 1 1 0. 0. 0 #> 2 1 2 0. 0. 2 #> 3 1 3 1. 2. 0 #> 4 1 4 1. 2. 0 #> 5 2 1 0. 0. 0 #> 6 2 2 0. 0. 2 #> 7 2 3 0. 0. 1 #> 8 2 4 1. 3. 0 #> 9 2 5 1. 2. 0 #> 10 2 6 1. 2. 0 #> 11 2 7 0. 2. 0 all(cbind(data, out) == left\_join(data, data3, by = c("grp", "id"))) #> [1] TRUE ``` Note that I changed `grp` and `id` to factor in lines 2 and 3. Upvotes: 1 <issue_comment>username_2: Here is a solution using `dplyr`. ``` data.moms <- data %>% split(grp) %>% lapply(., function(data.grp) { data.grp %>% group_by(id, grp) %>% summarise(NumChildren = sum(.$momloc == id)) }) %>% do.call(rbind, .) ``` We first split the dataframe into multiple dataframes, one for every group, using `split(grp)`. Then, we use `lapply()` to apply an operation to every data.frame in the list. For each of these dataframes, we group by `id` and `grp` - even though this means unique 'groups'. We can also group only on `id`, but grouping on both means we get to keep both columns. Now each data.frame in the list contains 3 columns * id * grp * NumChildren Now, we can re-combine the summarized dataframes by using `do.call(rbind, .)`. ``` > data.moms # A tibble: 11 x 3 # Groups: id [7] id grp NumChildren 1 1.00 1.00 0 2 2.00 1.00 2 3 3.00 1.00 0 4 4.00 1.00 0 5 1.00 2.00 0 6 2.00 2.00 3 7 3.00 2.00 1 8 4.00 2.00 0 9 5.00 2.00 0 10 6.00 2.00 0 11 7.00 2.00 0 ``` Upvotes: 1 <issue_comment>username_3: I propose a solution only using `dplyr`. First, I only keep children (assuming that you only want to count them as your `out[6] = 2` instead of 3). Then, I create a frequency table of `momloc` using `count()`, and merge this to the original data. ``` data %>% filter(is_child == 1) %>% # only count for children group_by(grp) %>% count(momloc) %>% right_join(data, by = c("grp" = "grp", "momloc" = "id")) %>% rename( id = momloc, momloc = momloc.y, out = n ) %>% mutate(out = ifelse(is.na(out), 0, out)) #> # A tibble: 11 x 5 #> # Groups: grp [2] #> grp id out is_child momloc #> #> 1 1 1 0 0 0 #> 2 1 2 2 0 0 #> 3 1 3 0 1 2 #> 4 1 4 0 1 2 #> 5 2 1 0 0 0 #> 6 2 2 2 0 0 #> 7 2 3 1 0 0 #> 8 2 4 0 1 3 #> 9 2 5 0 1 2 #> 10 2 6 0 1 2 #> 11 2 7 0 0 2 ``` Upvotes: 1 [selected_answer]
2018/03/21
1,184
4,162
<issue_start>username_0: I've already searched for about 2 days for the answer but still no luck until now. Please help me to figure it out. When the event is not allDay, resize is not working and resize icon doesn't show at the end of the event. But when the event is allDay, it can now resizable. I've already tried putting `allDay: true` and `allDay: false` but it doesn't work. If `allDay: true` all the time becomes allDay after resizing. Please help me. This is my code. ``` $(document).ready(function() { $('#calendar').fullCalendar({ header: { left: 'today add_event', center: 'prev title next', right: 'month,basicWeek,basicDay' }, eventOrder: 'start', editable: true, eventLimit: true, selectable: true, selectHelper: true, select: function(start, end) { $('#ModalAdd #start').val(moment(start).format('YYYY-MM-DD HH:mm:ss')); $('#ModalAdd #end').val(moment(end).format('YYYY-MM-DD HH:mm:ss')); $('#ModalAdd').modal('show'); }, eventRender: function(event, element) { element.bind('dblclick', function() { $('#ModalEdit #id').val(event.id); $('#ModalEdit #start').val(event.start.format('dddd, MMM DD-YYYY')); $('#ModalEdit #end').val(event.end.format('dddd, MMM DD-YYYY')); }); }, eventDrop: function(event, delta, revertFunc) { edit(event); } eventResize: function(event,dayDelta,minuteDelta,revertFunc) { edit(event); }, events: [ php foreach($events as $event): $start = explode(" ", $event['start']); $end = explode(" ", $event['end']); if($start[1] == '00:00:00'){ $start = $start[0]; }else{ $start = $event['start']; } if($end[1] == '00:00:00'){ $end = $end[0]; }else{ $end = $event['end']; } ? { id: 'php echo $event['id']; ?', title: 'php echo $event['title']; ?', start: 'php echo $start; ?', end: 'php echo $end; ?', }, php endforeach;? ], }); function edit(event){ start = event.start.format('YYYY-MM-DD HH:mm:ss'); if(event.end){ end = event.end.format('YYYY-MM-DD HH:mm:ss'); } else{ end = start; } id = event.id; Event = []; Event[0] = id; Event[1] = start; Event[2] = end; $.ajax({ url: 'editEventDate.php', type: "POST", data: { Event:Event} , success: function(rep) { if(rep == 'OK'){ } else{ alert('Could not be saved. try again.'); } } } ); } } ); ``` I dont know where exactly the problem is. I just want to resize the event whether the time is allDay or Not. Currently i can only resize it if the time is 00:00:00. Is fullcalendar disabled resizing of non allDay event? If yes, can i remove it? so that i can resize the date only and maintain the time of the event.<issue_comment>username_1: Your calendar uses "month" and "basic" style views. But neither of these views even allows resizing by time, only by day. These views do not have any kind of time slot on them, so how would you expect to be able to resize by time? The calendar would not know how much to extend it by, and neither would the user know how big to drag the event to achieve the desired change of time. If you want resize by time, you have to use the "agenda" style views. ``` header: { left: 'today', center: 'prev title next', right: 'month,agendaWeek,agendaDay' }, ``` would add these views into your calendar. See here for a demo: <http://jsfiddle.net/sbxpv25p/419/> - in the "agenda" views you can drag and resize by time. Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is fiddle <http://jsfiddle.net/xyzdktm8/> you can resize the event if the event is allDay = true you just need to add extra hours in the event. ``` eventDataTransform: function (event) { event.end = moment(event.end).add({ hours: 47, minutes: 59, seconds: 59 }); return event; }, ``` Upvotes: 0
2018/03/21
420
1,521
<issue_start>username_0: I've tested this with a new project, nothing unique. `ng new debug-project` Then I added some tags in the head section that resulted in this. ``` DebugProject ``` After `ng build --prod`, the html is now looking like this, which can't be read by the browser. Notice the missing spaces in viewport meta tags values. `width, initial-scale=1`, become `width,initial-scale=1`. ``` DebugProject ``` Is there something wrong with my setup? Something I need to install on the project maybe?<issue_comment>username_1: Try using this command: ``` ng build -prod --no-aot ``` Upvotes: -1 <issue_comment>username_2: From the angular/cli documentation, it looks like the production build flag minifies all of the html files by default, including index.html <https://github.com/angular/angular-cli/issues/1861>. You can retain the formatting in the meta tags by wrapping them in an ignore tag as shown below: ``` DebugProject ``` Upvotes: 3 <issue_comment>username_3: I would try following this thread: [How to globally set the preserveWhitespaces option in Angular to false?](https://stackoverflow.com/questions/46018599/how-to-globally-set-the-preservewhitespaces-option-in-angular-to-false?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) The issue, form what i can tell, is that building in aot removes whitespace by default. Not building in aot is not a good idea, in my honest opinion. It saves a lot of work on the client and speeds your SPA up. Upvotes: 2
2018/03/21
329
1,198
<issue_start>username_0: Recently I had attended one of java interview and I am unable to answer this question: * Who will throw the exception in spring JDBC if any mistake occurs in the database?<issue_comment>username_1: Try using this command: ``` ng build -prod --no-aot ``` Upvotes: -1 <issue_comment>username_2: From the angular/cli documentation, it looks like the production build flag minifies all of the html files by default, including index.html <https://github.com/angular/angular-cli/issues/1861>. You can retain the formatting in the meta tags by wrapping them in an ignore tag as shown below: ``` DebugProject ``` Upvotes: 3 <issue_comment>username_3: I would try following this thread: [How to globally set the preserveWhitespaces option in Angular to false?](https://stackoverflow.com/questions/46018599/how-to-globally-set-the-preservewhitespaces-option-in-angular-to-false?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) The issue, form what i can tell, is that building in aot removes whitespace by default. Not building in aot is not a good idea, in my honest opinion. It saves a lot of work on the client and speeds your SPA up. Upvotes: 2
2018/03/21
930
3,423
<issue_start>username_0: I get a response from a public test api in swift as a JSONarray: ``` func getFlightData(airportCode: String, minutesBehind: String, minutesAhead:String){ let securityToken: String = "<KEY> var headers: HTTPHeaders = [:] headers["Authorization"] = securityToken let parameters: Parameters = ["city": airportCode, "minutesBehind" : minutesBehind, "miutesAhead" :minutesAhead] Alamofire.request("https://api.qa.alaskaair.com/1/airports/"+airportCode+"/flights/flightInfo", parameters: parameters, headers: headers).responseJSON { (response) in print(response) } ``` I have used almofire in swift4 to achieve this operation. Should I convert this JSONArray to NSData or NSDictionary? and How? Do I have to use JSONSerealization?<issue_comment>username_1: You can use following to achieve this. [ObjectMapper](https://github.com/Hearst-DD/ObjectMapper) [AlamofireObjectMapper](https://github.com/tristanhimmelman/AlamofireObjectMapper) [Moya-ObjectMapper](https://github.com/lyft/mapper) Upvotes: -1 <issue_comment>username_2: You are already using Alamofire as your network requester, So it is not necessary to convert the response object to JSON object or Data object. The library itself will provide to parsed JSON object. So check the below sample code to check the JSON object. ``` let urlString = "https://......" let securityToken: String = "<KEY> var headers: HTTPHeaders = [:] headers["Authorization"] = securityToken let parameters: Parameters = ["city": 100, "minutesBehind" : 60, "miutesAhead" :0] Alamofire.request(urlString, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: headers).validate().responseJSON { (response) in if let jsonObject = response.result.value{ print("response.result.value \(String(describing: jsonObject))") } if let jsonObject = response.value{ print("response.value \(String(describing: jsonObject))") } } ``` Upvotes: 1 [selected_answer]<issue_comment>username_3: ``` let urlPath: String = BASE_URL + uri let url = URL(string: urlPath)! let request = NSMutableURLRequest(url: url) request.addValue("no-cache", forHTTPHeaderField: "Cache-Control") Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:]) .responseJSON { response in print("S-E-R-V-E-R C-A-L-L C-O-M-P-L-E-T-E-D") switch response.result { case .success: if let json = response.result.value { var data = [String: AnyObject](); if let dict = json as? [String: AnyObject]{ // Dictionary found data = dict; } else if let list = json as? [AnyObject] { // Array found data = ["data":list as AnyObject]; } } case .failure(let error): print("status code: \(error.localizedDescription)") failure(error as NSError); } } ``` Upvotes: 0