text
stringlengths
15
59.8k
meta
dict
Q: C# Method overloading is calling the wrong method when using string args I'm trying to make a log plugin for myself and I want to have a method where I overload it with different parameters. The key is, it needs to be possible to add multiple strings, which I will print on different lines. I like the idea of using params, that way I don't need to add string[] { strings here } everytime. The issue I currently have is that the Log.L() method will not trigger the first, but the second method, which kinda makes sense. How can I solve this issue, while keeping the params? Log.L("line1", "line2", "line3"); public static class Log { public static void L(params string[] message) { Write(LogType.Log, message); } public static void L(string location, params string[] message) { Write(LogType.Log, message, false, location); } } A: It will always assume that the first string is location so, just use the second overload: public static void L(string location, params string[] message) { Write(LogType.Log, message, false, location); } you can simply pass null or empty string when location is not available and deal with it in the method. A: You can create two classes and use them to differentiate between the two overloads. You can even go so far as having one class inherit from the other if you want. public class LoginWithMessages { public string[] Messages {get; set;} } public class LoginWithLocation : LoginWithMessages { public string Location {get; set;} } Then your method signatures will be: public static void L(LoginWithMessages loginMessage) public static void L(LoginWithLocation loginLocation)
{ "language": "en", "url": "https://stackoverflow.com/questions/41945863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress Custom Post Types add Taxonomies/SubTaxonomies to URL Hi StackOverflow Heroes - I'm using CPT UI to manage my custom post types (that can change if needed). I'd like to be able to display posts within a custom post type in categories and subcategories in the URL. Right now, if I create a post in my custom post type and assign it a taxonomy and a category and sub category within that taxonomy - it lists the URL as: domainname.com/custom_post_type/post I'm confused as to why it won't show the post like this (Clearly I don't understand custom post types / taxonomies well enough and look to you for some enlightenment): domainname.com/custom_post_type/taxonomy/subtaxonomy/post The end result has to be flexible - meaning, sometimes the post will end up in a taxonomy and sometimes in a subtaxonomy. I would love to use a plugin that just solves it all, but have tried several and they don't seem to work. Basically, I'd like my custom post types to work just like the built in blog feature seems to work as it does show the correct folder structure when putting posts in to categories/subcategories. Here's the menu structure I'm trying to achieve (for clarification) Products(Top level - no page) -Category(page with content) --SubCategory(page displaying posts) ---Single Post Sometimes the structure might need to be like this: Products(Top level - no page) -Category(page with content) --Single Post I've been working at this for several hours, and searching high and low across the internet to find a solution, but haven't been able to find one that fits. I appreciate your help and suggestions! A: While you're using CPT UI, I thought use of another plugin to extend the functionality is a better solution in your case. Use Custom Post Type Permalinks and configure the permalink option as: /%custom-taxonomy-slug%/%postname%/
{ "language": "en", "url": "https://stackoverflow.com/questions/44729280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Change Firebase Public Facing Name How can I change the public-facing name? Let's say I want to use States as the public name, how can I change ...firebaseapp.com to States here? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/62867715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting the value of first array from the array In php I have an array look like this. Array ( [0] => [1] => Array ([id] => 9 [slot] => 2 [name] => Test Ad [alt] => Test Ad [dimension_width] => 300 [dimension_height] => 400 [clicks] => 1 [start_date] => 06/07/2013 [end_date] => 07/07/2013 [status] => 1 [target] => http://images.google.com [image_url] => http://localhost/WebSites/coffee/wp-content/uploads/2013/06/uwp5-1-151553.jpeg [pre_exp_email] => 0 ) [2] => Array ( [id] => 12 [slot] => 1 [name] => Test Ad [alt] => Test Ad [dimension_width] => 200 [dimension_height] => 300 [clicks] => 0 [start_date] => 06/08/2013 [end_date] => 07/08/2013 [status] => 1 [target] => http://facebook.com [image_url] => http://localhost/WebSites/coffee/wp-content/uploads/2013/06/uwp5-1-1515532.jpeg [pre_exp_email] => 0 ) [3] => Array ( [id] => 14 [slot] => 1 [name] => Test Ad [alt] => Test Ad [dimension_width] => 200 [dimension_height] => 300 [clicks] => 0 [start_date] => 06/08/2013 [end_date] => 07/08/2013 [status] => 1 [target] => http://facebook.com [image_url] => http://localhost/WebSites/coffee/wp-content/uploads/2013/06/uwp5-1-1515532.jpeg [pre_exp_email] => 0 ) ) From here I want to get the first value of array. For example I want to get the value of first array [1] => Array ([id] => 9 [slot] => 2 [name] => Test Ad [alt] => Test Ad [dimension_width] => 300 [dimension_height] => 400 [clicks] => 1 [start_date] => 06/07/2013 [end_date] => 07/07/2013 [status] => 1 [target] => http://images.google.com [image_url] => http://localhost/WebSites/coffee/wp-content/uploads/2013/06/uwp5-1-151553.jpeg [pre_exp_email] => 0 ) So can someone kindly tell me how to get the value of 1st array?Any help and suggestions will be really appreciable. Thanks A: say all your array was in a variable $myArray, then myArray[1] will give you your first array
{ "language": "en", "url": "https://stackoverflow.com/questions/16996362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django char field with choices list So, I want to implement a char field with choices list. The idea is that it looks like a common char field but when you click on it and start typing something in, a dropdown menu pops up and you can choose something (also it sorts choices depending on what user types in). How do we do that? A: You probably want something like django-easy-select2 [readthedocs.io]. You can install this (in your local environment) with: pip3 install django-easy-select2 Next you add 'easy_select2' to the INSTALLED_APPS setting [Django-doc]: # settings.py # … INSTALLED_APPS = [ # …, 'easy_select2', # …, ] # … Now you can make use of the Select2 widget in your Form (or ModelForm): from easy_select2 import Select2 class MyModelForm(forms.ModelForm): # … class Meta: model = MyModel widgets = { 'my_field': Select2 }
{ "language": "en", "url": "https://stackoverflow.com/questions/66323231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: where can i declare my custom functions in magento I want to declare some php functions and i would like to call those functions in various places in magento.Usually in my core php projects i'm declaring php functions in functions.php and i include that file in all pages.I'm not familiar with MVC structure.So where can i declare these kind of functions. Thanks Edit :- Mango_Myfunc.xml (app/etc/modules) <?xml version="1.0"?> <config> <modules> <Mango_Myfunc> <active>true</active> <codePool>local</codePool> </Mango_Myfunc> </modules> </config> Config.xml(app/code/local/Mango/Myfunc/etc/configure.xml) <?xml version="1.0"?> <config> <modules> <Mango_Myfunc> <version>0.1.0</version> </Mango_Myfunc> </modules> <global> <helpers> <Myfunc> <class>Mango_Myfunc_Helper</class> </Myfunc> </helpers> </global> </config> Data.php(app/code/local/Mango/Myfunc/helper/Data.php) class Mango_Myfunc_Helper_Data extends Mage_Core_Helper_Abstract { public function short_str ($str, $len, $suf = '...') { if (strlen($str) > $len) return substr($str, 0, $len - strlen($suf) ) . $suf; return $str; } } This is what i added i used bellow one to call the function in list.phtml echo $this->helper('Myfunc/Data')->short_str("test","3"); got the error Fatal error: Class 'Mage_Myfunc_Helper_Data' not found A: Magento has helper classes for those kind of methods. So make your extensions and add your methods and you can then later call them like follows Mage::helper('yourextension/yourhelper')->yourMethod(); Or you can make a library class out of your common methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7710528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WordPress Plugin: How do I avoid "tight coupling"? I am working on a WordPress Plugin and am trying to ensure best practices. I have two classes, my plugin class "Jargonaut" which is required and then another class called "Dictionary" which is included with require_once() into my main plugin file. Most of the code in the Jargonaut class addresses initialization and provides controller-like functionality but much of it is highly dependent upon using the Dictionary object (i.e. tightly coupled from my understanding of the term). I wish to keep the Dictionary class separated as it is acting more like a model (in MVC architecture) and interfaces with my database. I see a lot of gray area in the tight vs. loose coupling and am having a hard time deciding how much is too much? A: If your plugin needs the dictionary object, it has to ask for it: class MyPlugin { /** * @var Dictionary */ private $dictionary; private function __construct(Dictionary $dictionary) { $this->dictionary = $dictionary; } You now have loosely coupled your plugin with the Dictionary, the plugin class is not responsible any longer to create the Dictionary for itself, because it's injected. It takes what it needs. So how would that work? The plugin needs to be created somewhere, so this needs a factory. The factory build method knows what your plugin needs: class MyPluginFactory { public static function build($pluginName) { $plugin = NULL; switch($pluginName) { case 'MyPlugin': $dictionary = new Dictionary(); $plugin = new MyPlugin($dictionary); } return $plugin; } } As this is wordpress we know that the bootstrapping of the plugin is done by including the plugin file. So at it's beginning, the plugin needs to be created. As includes are done in the global scope we want to preserve the plugin object in memory but without being available as a global variable probably. This does not prevent you from creating more than one plugin instance, but it will ensure that when wordpress initializes your plugin (loads your plugin), it will make only use of that single instance. This can be done by making the plugin factory some additional function: class MyPluginFactory { ... public static $plugins; public static function bootstrap($pluginName) { $plugin = self::build($pluginName); self::$plugins[] = $plugin; return $plugin; } Take care here, that the only usage of the static class member variable is only to ensure that the plugin stays in memory. It technically is a global variable we normally want to prevent, however, the instance needs to be stored somewhere, so here it is (I changed this to public because it is a global variable and it shouldn't be shy about it. Having a public can help in some circumstances in which private or protected are too restrictive. Also it shouldn't be a problem. If it is a problem, there is another problem that should be fixed first). This basically decouples your plugin code from wordpress itself. You might want to also create a class that offers and interface to any wordpress function you're making use of, so you're not bound to these functions directly and your plugin code stays clean and loosely coupled to wordpress itself. class WordpressSystem { public function registerFilter($name, $plugin, $methodName) { ... do what this needs with WP, e.g. call the global wordpress function to register a filter. } ... } Then add it as a dependency again if your plugin needs the WordpressSystem to perform tasks (which normally is the case): class MyPlugin { ... public function __construct(WordpressSystem $wp, Dictionary $dictionary) ... So to finally wrap this up, only the plugin php file is needed: <?php /* * MyPlugin * * Copyright 2010 by hakre <hakre.wordpress.com>, some rights reserved. * * Wordpress Plugin Header: * * Plugin Name: My Plugin * Plugin URI: http://hakre.wordpress.com/plugins/my-plugin/ * Description: Yet another wordpress plugin, but this time mine * Version: 1.2-beta-2 * Stable tag: 1.1 * Min WP Version: 2.9 * Author: hakre * Author URI: http://hakre.wordpress.com/ * Donate link: http://www.prisonradio.org/donate.htm * Tags: my * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ Namespace MyPlugin; # if your file is named 'MyPlugin.php' this will be 'MyPlugin'. return PluginFactory::bootstrap(basename($plugin, '.php')); class PluginFactory { private static $plugins; public static function bootstrap($pluginName) { $plugin = self::build($pluginName); self::$plugins[] = $plugin; return $plugin; } public static function build($pluginName) { $plugin = NULL; switch($pluginName) { case 'MyPlugin': # Make your plugin work with different Wordpress Implementations. $system = new System\Wordpress3(); $dictionary = new Dictionary(); $plugin = new Plugin($system, $dictionary); } return $plugin; } } class Plugin { /** * @var System */ private $system; /** * @var Dictionary */ private $dictionary; private function __construct(System $system, Dictionary $dictionary) { $this->system = $system; $this->dictionary = $dictionary; } ... The bootstrap method can also take care of registering an autoloader or do the requires. Hope this is useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/8688738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: bootstrap Google Map not centering I am trying to center a Google Map API using bootstrap, but it is not working. Please see the image regarding the issue. The text is centering, but not the map. ![Map Issue Picture]:https://imgur.com/a/kql5OTK I have tried every which way of putting 'text-center' in surrounding elements, and putting the map in 'col-md-6' but nothing is working. I am sure I am missing something silly. Any help is greatly appreciated. <div class="container"> <h1 class="text-center">My Map</h1> <div class="text-center" id="map"></div> </div> A: Found it! The div #map needed the Bootstrap class: class = "mx-auto" A: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <div class="container text-center"> <div class="row"> <div class="col-md-12"> <h1>My Map</h1> </div> </div> <div class="row mt-5"> <div class="col-md-12"> <div id="map"> <iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3!1d14475.259566651797!2d91.88062475!3d24.90429495!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!5e0!3m2!1sen!2sbd!4v1563361490340!5m2!1sen!2sbd" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe> </div> </div> </div> </div> </body> </html> Wrap your <h1> and <div> tag within .row > .col * *Containers provide a means to center and horizontally pad your site’s contents. Use .container for a responsive pixel width or .container-fluid for width: 100% across all viewport and device sizes. *Rows are wrappers for columns. Each column has horizontal padding (called a gutter) for controlling the space between them. This padding is then counteracted on the rows with negative margins. This way, all the content in your columns is visually aligned down the left side. *In a grid layout, content must be placed within columns and only columns may be immediate children of rows. For reference go through https://getbootstrap.com/docs/4.0/layout/grid/ this link
{ "language": "en", "url": "https://stackoverflow.com/questions/57068204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Preventing a function call while another function is executing I have 2 functions. How can i stop executing SelectTD() function, when i am executing showAction() Function. Both functions are in different JS files. I tried with setting count but not working as expected. Can some one suggest me a better approach. ScriptFile 01: function ShowAction(title, artist, genre) { //showAction Stuff } ScriptFile 02: function SelectTD(StartIndex, EndIndex, Color) { //SelectTD Stuff } A: Since JS is single threaded, one function would run to its entirety and then only the control can go to any other function. Perhaps you have an async call such as an AJAX call that indeed calls a function asynchronously but still whatever callback you give to it, that function would again run to its entirety before passing control to the next function in queue. So the question comes, what is the exact scenario which you want to implement? Maybe you want to control which function gets executed depending on some condition. That you can do using another function probably var runTDfn = true; if(runTDfn){ ShowAction('Some title', 'Some artist', 'Some genre'); } else { SelectTD(0, 1, 'some color'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/52988189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: jqPlot doesn't display at all with Rails-added bootstrap footer I have a static page which displays a simple bar chart using jqplot, and when I throw that code into a Rails view it doesn't display anything. * *The javascript does get called, because if I toss an alert into the showGraph() function it shows up on page load. *The server doesn't complain about not being able to find the javascript or CSS. *If I take the Rails-generated code and put it in the public folder to get it shown statically, the graph doesn't show up. *BUT, if I take out the line containing "script src="/assets/jquery.js?body=1" type="text/javascript"" in the footer, then the graph shows up *If I instead remove the call to jquery.min.js that precedes the jqplot includes, there is no difference in behavior. EDIT: 6. More fooling around shows that the graph won't appear if I include jquery.js any time after I include jquery.jqplot.min.js. Is it possible to show this chart without messing with the footer? Is there a well-established way to do this correctly that I should know of? Here is the Rails-generated HTML, minus some stuff which doesn't affect the behavior I'm talking about: <!DOCTYPE html> <html> <head> <link href="/assets/application.css?body=1" media="all" rel="stylesheet" type="text/css" /> <link href="/assets/custom.css?body=1" media="all" rel="stylesheet" type="text/css" /> <link href="/assets/users.css?body=1" media="all" rel="stylesheet" type="text/css" /> <script src="/assets/jquery.js?body=1" type="text/javascript"></script> <script src="/assets/jquery_ujs.js?body=1" type="text/javascript"></script> <script src="/assets/users.js?body=1" type="text/javascript"></script> <script src="/assets/application.js?body=1" type="text/javascript"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="author" content=""> <!-- Le styles --> <link href="/assets/bootstrap.css?body=1" media="screen" rel="stylesheet" type="text/css" /> <style type="text/css"> body { padding-top: 60px; padding-bottom: 40px; } </style> <!--<link href="bootstrap/css/bootstrap-responsive.css" rel="stylesheet">--> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="/images/favicon.ico" /> <style type="text/css"> .navbar .brand { //float: right; padding-bottom: 6px; padding-top: 6px; //font-weight: 400; } .hero-unit h1 { //font-size:48px; } .hero-unit p { //font-size:24px; padding-top:12px; } .navbar .nav > li > a { line-height: 72px; padding-left: 15px; padding-right: 15px; font-size: 18px; } </style> <style type="text/css"> body { padding-top: 120px; padding-bottom: 40px; font-size: 14px; } footer { font-size:12px; } legend {margin-bottom: 10px;} </style> <style> table.cleanlink td a {text-decoration:none; color:inherit; display:block; padding:0px; height:100%;} table.cleanlink td a:hover {text-decoration:none; color:inherit;} div.data-scroller {width:910px; max-height:400px; overflow:scroll;} </style> <style> ul.nav li.dropdown:hover ul.dropdown-menu {display: block;} ul.nav li.dropdown ul.dropdown-menu {margin-top: 0px;} //a.menu:after, .dropdown-toggle:after {content: none;} </style> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="brand" href="/home"><img src="/images/B4-l-s-m-h-i-2-273x80.png" /></a> <ul class="nav"> </ul> <ul class="nav pull-right"> <li class="dropdown"> <a href="/account" class="dropdown-toggle" data-toggle="dropdown">My Account</a> <ul class="dropdown-menu pull-right"> <!--<li class="divider"></li>--> <li><a href="/signout" data-method="delete" rel="nofollow">Sign out</a></li> </ul> </li></ul> </div> </div> </div> <div class="container"> <html> <script language="javascript" type="text/javascript" src="/assets/jquery.min.js"></script> <script language="javascript" type="text/javascript" src="/assets/jquery.jqplot.min.js"></script> <script class="include" language="javascript" type="text/javascript" src="/assets/src/plugins/jqplot.barRenderer.min.js"></script> <script class="include" language="javascript" type="text/javascript" src="/assets/src/plugins/jqplot.categoryAxisRenderer.min.js"></script> <script class="include" language="javascript" type="text/javascript" src="/assets/src/plugins/jqplot.pointLabels.min.js"></script> <script> function showGraph() { var s1 = [20, 3, 2, 1]; // Can specify a custom tick Array. // Ticks should match up one for each y value (category) in the series. var xticks = ['A', 'B', 'C', 'D']; var plot1 = $.jqplot('chart1', [s1], { // The "seriesDefaults" option is an options object that will // be applied to all series in the chart. seriesDefaults:{ renderer:$.jqplot.BarRenderer, pointLabels: { show: true, location: 'n', edgeTolerance: -15 }, rendererOptions: {fillToZero: true} }, axes: { // Use a category axis on the x axis and use our custom ticks. xaxis: { renderer: $.jqplot.CategoryAxisRenderer, ticks: xticks }, // Pad the y axis just a little so bars can get close to, but // not touch, the grid boundaries. 1.2 is the default padding. yaxis: { pad: 1.05, tickOptions: {formatString: '%d'} } } }); }; $(document).ready(showGraph); </script> <div id="chart1" style="height:400px;width:600px; "></div> </html> </div> <!-- /container --> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="/assets/jquery.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-transition.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-alert.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-modal.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-dropdown.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-scrollspy.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-tab.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-tooltip.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-popover.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-button.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-collapse.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-carousel.js?body=1" type="text/javascript"></script> <script src="/assets/bootstrap-typeahead.js?body=1" type="text/javascript"></script> </body> </html> A: It looks like you are loading the jquery library in three places in your document? Why not add it to the asset pipeline? In app/assets/javascripts/application.js: //= require jquery This should speed up pageloads and you won't have to include the script tags on every page. A: OK, here's what I did to get it working: removed the line: <%= javascript_include_tag "jquery" %> which generates the offending line, from [appdir]/app/views/shared/_bootstrap2.html.erb (which generates the lines in the footer) and put it into [appdir]/app/views/shared/_bootstrap.html.erb (which generates the lines in the header). This isn't ideal since it means we're loading jquery before loading the rest of the page, so I'm still interested in a slicker solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/14513884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: onPress() function of TouchableOpacity does not work at first if the keyboard is open I have used TouchableOpacity as my submit button, after filling the form(Login/Registration/...) when I click on submit button(TouchableOpacity), the keyboard hides (if open), and then I need to press again on submit button and then the onPress method gets called. What I want to achieve is if I click on submit button, the onPress() method should call, regardless of the keyboard is open or not. I have to click two times to submit the form which does not look good. Also, I have not tested this behaviour on IOS, android only. EDIT:1 Login Screen Code => <KeyboardAvoidingView> <ScrollView> <View style={styles.container}> <View style={styles.container_one}> <Image style={{ height: 100, marginTop: 40 }} source={require("../images/logo.png")} /> </View> <View style={styles.container_three}> <View> <View style={styles.container_two}> <Text style={styles.text_style_two}>Login</Text> </View> <View> <Text style={styles.text_style_three}> Please enter mobile number </Text> <TextInput style={styles.text_input_1} autoCapitalize="none" keyboardType="numeric" onChangeText={text => { this.setState({ username: text }); }} value={this.state.username} /> </View> <View> <Text style={styles.text_style_three}> Please enter your password </Text> <TextInput style={styles.text_input_1} secureTextEntry={true} autoCapitalize="none" onChangeText={text => { this.setState({ password: text }); }} value={this.state.password} /> </View> <View style={{ width: screenWidth / 1.3, flexDirection: "row", justifyContent: "center" }} > <View> <TouchableOpacity style={styles.button_1} onPress={() => { if (this.state.username == "") { alert("Username can not be blank"); } else if (this.state.password == "") { alert("Password can not be blank"); } else { this.submitLogin( this.state.username, this.state.password ); } }} > <Text style={CommonStyles.buttonText}>Login</Text> </TouchableOpacity> </View> </View> </View> </View> <View style={{ alignItems: "center" }}> <View style={{ marginBottom: 10 }}> <Text style={{ fontSize: 20 }}>-OR-</Text> </View> <View style={{ marginBottom: 10 }}> <TouchableOpacity onPress={() => { this.props.navigation.navigate("Registration"); }} > <Text style={styles.text_style_one}>Sign up here</Text> </TouchableOpacity> </View> </View> <View style={{ alignItems: "center" }}> <View style={{ marginBottom: 10 }}></View> <View style={{ marginBottom: 10 }}> <TouchableOpacity onPress={() => { this.props.navigation.navigate("ForgotPassword"); }} > <Text style={styles.text_style_five}>forgot password?/Text> </TouchableOpacity> </View> </View> </View> </ScrollView> </KeyboardAvoidingView> A: Just add keyboardShouldPersistTaps={'handled'} to your ScrollView <ScrollView keyboardShouldPersistTaps={'handled'}> ...... .............. </ScrollView>
{ "language": "en", "url": "https://stackoverflow.com/questions/59985825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Pandas: How to set an index without sorting I have a df I wish to sort by two columns (say, by=['Cost','Producttype']) and set the index to be on a different column (df.what_if_cost.abs()) I am new to Python, so originally I sorted the df twice, where in the second time I kept the original index. It is too inefficient, even when doing it inplace. I tried stuff like set_index and reset_index but to no avail. Ideally, as described, I wish the output df to be sorted by two columns, but indexed by a different third column. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/65075248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retaining a comboBox within a grid I have a comboBox within a grid. Basically to get it I have to use findcontrol. I am thinking of another option however. Within the init method I was planning on getting the value and storing it to a private static field: private static RadComboBox theComboBox Can someone please tell me if this is not good practice. ie. Is it unwise to be storing a relatively complex object like this in a static field? A: I wouldn't recommend it. See this thread for answer why. If you really want to do this, I'd use a session instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/4307160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jenkins pipeline - function to remove properly a folder I need to implement a function in groovy (for a Jenkins pipeline) which will remove a specific folder into a linux server. def remove_folder(String path_of_the_folder) { sh "rm -rf <root_path>/${path_of_the_folder}" } It's pretty easy. But if the parameter is "" or " " or "/" or "." or "//" or... this will delete the <root_path> and it's absolutely critical. How I can assure that will not happen ? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/70985873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is Selenium InternetExplorerDriver Webdriver very slow in debug mode (visual studio 2010 and IE9) I'm using the example code from the SeleniumHq site - but in debug mode the performance is awful. In release mode the entire test takes about 6 seconds (including launching and closing IE) In Debug mode it takes 65 seconds ? The sample code is just : [Test] public void testBrowser() { // Do something here IWebDriver driver = new InternetExplorerDriver(); //Notice navigation is slightly different than the Java version //This is because 'get' is a keyword in C# driver.Navigate().GoToUrl("http://www.google.com"); IWebElement query = driver.FindElement(By.Name("q")); query.SendKeys("Cheese"); System.Console.WriteLine("Page title is: " + driver.Title); // TODO add wait driver.Quit(); } I've tried it in ie8 and have the same performance. Firefox is fine - but my clients use IE so I'm stuck with testing against it. Also - I don't have the same issues if I use Selenium RC. NB - I'm using .Net 4 and the latest version (2.16) of the webDriver.dll (running on a 64bit windows 7 box) A: For me, the fix was to switch to the 32 bit version of InternetExplorerDriver.exe from https://code.google.com/p/selenium/downloads/list Seemingly named IEDriverServer nowadays, but works if you just rename it to InternetExplorerDriver.exe. A: Using the C#, NUnit, C# webdriver client and IEDriverServer, I originally had the problem with slow input (e.g., sending keys to an input box would take about 5 seconds between keys, or clicking on a button same kind of delay). Then, after reading this thread, I switched to the 32-bit IEDriverServer, and that seemed to solve the problem. But today I was experimenting with the InternetExplorerOptions object in order to set some options on IE according to this documentation: https://code.google.com/p/selenium/wiki/InternetExplorerDriver Per the documentation, I created the registry value HKCU\Software\Microsoft\Internet Explorer\Main\TabProcGrowth with a value of 0 in order to use ForceCreateProcessApi = true and BrowserCommandLineArguments = "-private." After doing this, I noticed that the slow-input problem was back. I had made several changes to my code, but after rolling all of them back, the problem still persisted. When I removed the aforementioned registry key, however, the input was back to full speed (no delay). A: check 'prefer 32 bit' is not checked in your build properties. If it is and you are using the 64 bit IE driver it will run like an asthmatic snail.
{ "language": "en", "url": "https://stackoverflow.com/questions/8850211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: How to use sorl-thumbnail package together with django-tables2 package? I do have a table defined in tables.py that renders a column with recipes images. class ImageColumn(Column): def render(self, value): return format_html( '<img src="static/media/{url}" height="150px", width="150px">', url=value ) class RecipeTable(tables.Table): image = ImageColumn() name = Column(linkify=True) class Meta: model = Recipe template_name = "django_tables2/bootstrap4.html" fields = ( "image", "name", "directions", "ingredients", ) Each image has different size and when I render it with fixed height="150px", width="150px", aspect ratio messes up the image. Therefore I thought I could use sorl-thumbnail package to help mi with generating thumbnails, rather then resizing the whole images. It looks like it is not possible to easily use both django-tables2 and sorl-thumbnail since thumbnails are rendered in html template. My template contains only this to render the table: {% render_table table 'django_tables2/bootstrap4.html' %} I need to access the cell so that I can use thumbnail template tag where image should be placed. {% thumbnail item.image ‘200x100’ as im %} <img src=’{{ im.url }}’> {% endthumbnail %} The only solution I see could be to edit the bootstrap4.html, but is there a better way? Am I missing something?
{ "language": "en", "url": "https://stackoverflow.com/questions/66508344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C - Problems copying string from one struct to a node I am trying to copy strings from a field in one struct to another struct (a node), so that I can ultimately create a hashtable. However, I seem to be having some issues in the actual string copying. I've created a for loop to iterate over the strings in the source stuct, and I know the iteration is working fine, because if I printf the source strings (data[i].c_name), they print out fine. Unfortunately, when I try to printf the destination (class_id), it seems to be empty (and thus of course my hash function isn't doing much). Any insights into the potential problem here would be greatly appreciated. Please let me know if I haven't given enough context. #define LENGTH 30 #define MAX_OBS 80000 typedef struct { char c_name[LENGTH]; char s_name[LENGTH]; double value[MAX_OBS]; } sample; typedef struct node { char class_id[LENGTH]; struct node *next; } node; { char class_id[LENGTH]; for (int i = 0; i < total_columns; i++) { // malloc a new node pointer for each new class label node *new_node = malloc(sizeof(node)); // check that there was sufficient memory if (new_node == NULL) { return 6; } // copy c_name into node -- failing - class_id is empty strcpy(new_node->class_id, data[i].c_name); printf("%s\n", class_id); } } A: Drop the last char class_id[LENGTH]; that you print as it was never initialized. Then switch your printf() to use the actual target of the strcpy. strncpy(new_node->class_id, data[i].c_name, LENGTH); printf("%.*s\n", LENGTH, new_node->class_id); I've also put a few LENGTH limits in my code to assure you don't do bad things on bad input without a terminal \0. Never blindly trust your C input unless you generated it in a fail-safe manner. Disclaimer: desktop inspection changes. Actual debugging is left as an exercise to the student.
{ "language": "en", "url": "https://stackoverflow.com/questions/39842792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: create Plist in .net from list of objects I am working on an iPad app that is fed data via web service returning JSON. Watching some iTunes U episodes, it looks like sending back Plist would save me a ton of time and speed up my app quite a bit on the parsing side of things. Does anyone know of a .net library that converts objects into this Plist to return instead? EDIT (this is my very limited understanding of this topic): An Plist is a Property List that iOS can use to easily encode and/or parse data. It is very similar to JSON except parsing takes a fraction of the time and can be done in 1 line of code. If your server uses WebObjects then encoding can also be done in 1 line of code, I am using IIS so I need a solution for this if one exists before I write my own. You can see the videos here: http://developer.apple.com/videos/wwdc/2010/ In particular watch Session 117 - Building a Server-Driven User Experience A: You may checkout this project. Sample usage: object value = ... string plist = Plist.PlistDocument.CreateDocument(value); The only requirement is to decorate your object with [Serializable] attribute. A: If you're using WebObjects, the appserver from apple, there's a java mirror class of NSPropertyListSerialization that does all of this for you; you can pass it NSArray's, NSDictionaries, etc and it will just work. Not sure if that's what you're talking about; confused as to the WebObjects in your question. HTH's.
{ "language": "en", "url": "https://stackoverflow.com/questions/3223258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What version of Ruby is required for P4Ruby and where is P4Ruby installed? I am trying to set up Ruby and P4Ruby so I can use the p4replicate.rb script, but whenever I run the p4ruby18.exe (from the Perforce FTP) I get the following error: Perforce P4Ruby API for Ruby 1.8 - InstallShield Wizard There was a problem tying to get the P4Ruby install path. Possible reasons are: 1) Ruby is not installed. 2) An unsupported version of Ruby is installed. 3) The folder containing the Ruby executable is not in the system path. 4) The folder of another version's executable is in the system path before the supported version. 5) The P4Ruby install paths are not writable. OK I'm running Windows Vista, and have Ruby 1.8.6-p398 installed in C:\Ruby186. The directory C:\Ruby186\bin is the first thing on my Path variable (the Ruby installer put it there)! I've also confirmed it's accessible by running which ruby (cygwin is installed) which returns /cygdrive/c/Ruby186/bin/ruby. I've tried 1.8.7-p334 and 1.9.2-p290 as well. The P4Ruby release notes claim that Ruby 1.8 is supported for versions of P4Ruby 2007.3 onwards, so I thought I'd met this criteria but it will not install. As I'm fairly certainly I've met criteria 1, 3 and 4, I wondered whether anyone could tell me if they've managed to install P4Ruby on Windows with a specific version of Ruby (2), and if so what path P4Ruby installs to (5)? A: Just a sanity check: do you have admin rights when running the installer? A: To answer my own specific questions (rather than solve my problem as thankfully @p4-randall did): * *the p4rubynotes.txt manual says "The P4Ruby Windows installer requires Ruby 1.8." *P4Ruby is seemingly not installed anywhere! To clarify this, it looks like the P4 client is updated with a version supporting P4Ruby, so the directory it needs to write to is the Perforce installation directory (e.g. C:\program Files\Perforce\).
{ "language": "en", "url": "https://stackoverflow.com/questions/7067925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get rid of link error in FreeGLUT MS Visual Studio project build with Cmake + Conan? Im trying build freeGLUT project with cmake and conan for MS Visual Studio, but when I build it return link error LNK1104 "Cant open file "freeglut.lib" for Release and "Cant open file "freeglutd.lib" for Debug. Visual Studio 16 2019 Cmake 3.20.3 Conan 1.39.0 Project Tree CMakeLists.txt cmake_minimum_required(VERSION 3.20) project(OpenGLConan) include(${CMAKE_BINARY_DIR}/conan_paths.cmake) add_subdirectory(src) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) find_package(FreeGLUT) target_include_directories(${PROJECT_NAME} PUBLIC ${FreeGLUT_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} ${FreeGLUT_LIBRARIES}) conanfile.txt [requires] freeglut/3.2.1 [generators] cmake_find_package cmake_paths src/CMakeLists.txt add_executable(${PROJECT_NAME} main.cpp) src/main.cpp #include <iostream> #include <GL/glut.h> int main(int argc, char** argv) { glutInit(&argc, argv); /* Create a single window with a keyboard and display callback */ glutCreateWindow("GLUT Test"); /* Run the GLUT event loop */ glutMainLoop(); return EXIT_SUCCESS; } Edit In CMakeLists.txt I added ... if(${FreeGLUT_FOUND}) message(STATUS "-----LIB FOUND!!!-----") target_include_directories(${PROJECT_NAME} PUBLIC ${FreeGLUT_INCLUDE_DIRS}) target_link_libraries(${PROJECT_NAME} ${FreeGLUT_LIBRARIES}) endif() ... Information from the console. $ conan install .. Configuration: [settings] arch=x86_64 arch_build=x86_64 build_type=Release compiler=Visual Studio compiler.runtime=MD compiler.version=16 os=Windows os_build=Windows [options] [build_requires] [env] conanfile.txt: Installing package Requirements freeglut/3.2.1 from 'conancenter' - Cache glu/system from 'conancenter' - Cache opengl/system from 'conancenter' - Cache Packages freeglut/3.2.1:d72ca9d65490ffa06c751d72974c9906d3454d5c - Cache glu/system:5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9 - Cache opengl/system:5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9 - Cache Installing (downloading, building) binaries... opengl/system: Already installed! glu/system: Already installed! freeglut/3.2.1: Already installed! conanfile.txt: Generator cmake_paths created conan_paths.cmake conanfile.txt: Generator txt created conanbuildinfo.txt conanfile.txt: Generator cmake_find_package created FindFreeGLUT.cmake conanfile.txt: Generator cmake_find_package created Findglu.cmake conanfile.txt: Generator cmake_find_package created Findopengl_system.cmake conanfile.txt: Aggregating env generators conanfile.txt: Generated conaninfo.txt conanfile.txt: Generated graphinfo Антон@LAPTOP-4L8RSG2A MINGW64 /d/GitHub/OpenGLConan/build $ cmake .. -G "Visual Studio 16 2019" -- Selecting Windows SDK version 10.0.18362.0 to target Windows 10.0.19042. -- The C compiler identification is MSVC 19.29.30038.1 -- The CXX compiler identification is MSVC 19.29.30038.1 -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.29.30037/bin/Hostx64/x64/cl.exe - skipped -- Detecting C compile features -- Detecting C compile features - done -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.29.30037/bin/Hostx64/x64/cl.exe - skipped -- Detecting CXX compile features -- Detecting CXX compile features - done -- Conan: Using autogenerated FindFreeGLUT.cmake -- Found FreeGLUT: 3.2.1 (found version "3.2.1") -- Library glut found C:/Users/Anton/.conan/data/freeglut/3.2.1/_/_/package/d72ca9d65490ffa06c751d72974c9906d3454d5c/lib/glut.lib -- Found: C:/Users/Anton/.conan/data/freeglut/3.2.1/_/_/package/d72ca9d65490ffa06c751d72974c9906d3454d5c/lib/glut.lib -- Conan: Using autogenerated Findopengl_system.cmake -- Found opengl_system: system (found version "system") -- Conan: Using autogenerated Findglu.cmake -- Found glu: system (found version "system") -- Dependency opengl_system already found -- Library glut found C:/Users/Anton/.conan/data/freeglut/3.2.1/_/_/package/d72ca9d65490ffa06c751d72974c9906d3454d5c/lib/glut.lib -- Found: C:/Users/Anton/.conan/data/freeglut/3.2.1/_/_/package/d72ca9d65490ffa06c751d72974c9906d3454d5c/lib/glut.lib -- -----LIB FOUND!!!----- -- Configuring done -- Generating done -- Build files have been written to: D:/GitHub/OpenGLConan/build Антон@LAPTOP-4L8RSG2A MINGW64 /d/GitHub/OpenGLConan/build $ cmake --build . Microsoft (R) Build Engine версии 16.10.2+857e5a733 для .NET Framework (C) Корпорация Майкрософт (Microsoft Corporation). Все права защищены. Checking Build System Building Custom Rule D:/GitHub/OpenGLConan/src/CMakeLists.txt main.cpp LINK : fatal error LNK1104: не удается открыть файл "freeglutd.lib" [D:\GitHub\OpenGLConan\build\src\OpenGLConan.vcxproj] A: I think the problem here is in the conanfile of freeglut. Conan file be default says in packaging: self.cpp_info.components["freeglut_"].names["pkg_config"] = "freeglut" if self.settings.os == "Windows" else "glut" So it tries to find freeglut. At the same time be default conanfile sets "replace_glut": True. From Cmake this option sets: option to build either as "glut" (ON) or "freeglut" (OFF) So your library is built as glut, but conanfile still tries to find freeglut. I would suggest you try to build conan package with option replace_glut=False If that fixes the issue, pls open a bug here: https://github.com/conan-io/conan-center-index/issues
{ "language": "en", "url": "https://stackoverflow.com/questions/69197558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Manage multiple form inputs and it's value via React state Let me start with an example so you guys can know what is the issue and what I want to achieve. In my project I'll have multiple user form on the same page and number of forms will be dynamic (depends on user number if there are 3 users then 3 forms, if 10 users then 10 forms etc). Let's assume all forms will have 3 fields (keep it simple here) like firstName , middleName , lastName. Now let assume we have 3 users so 3 inputs will appear on the page. <form> <input type="text" name="firstName" value="" /> <input type="text" name="middleName" value="" /> <input type="text" name="lastName" value="" /> </form> We have 3 users this time so above form will appear 3 times. Here actually what I have taken only one form for all 3 users. What I have done is shown below. <form> for (let i = 1; i <= 3; i++) { <input type="text" name="firstName" value="" /> <input type="text" name="middleName" value="" /> <input type="text" name="lastName" value="" /> } <input type="submit" value="Submit">Apply</button> </form> When user submits the form I want an array of value for each form field. What and How result I want is below. ['tome hanks' , 'shahrukh khan', 'john'] // firstname of all 3 users ['tome hanks' , 'shahrukh khan', 'john'] // middlename of all 3 users ['tome hanks' , 'shahrukh khan', 'john'] // lastname of all 3 users I have tried this tutorial but not exactly what I need. Maybe I can achieve this using React state but don't know how? If Redux is helpful than it's fine for me. A: class App extends React.Component { constructor(props) { super(props); this.state = { users: [ { firstName: 'John1', middleName: 'Daniel1', lastName: 'Paul1' }, { firstName: 'John2', middleName: 'Daniel2', lastName: 'Paul2' }, { firstName: 'John3', middleName: 'Daniel3', lastName: 'Paul3' }, { firstName: 'John4', middleName: 'Daniel4', lastName: 'Paul4' }, ], }; } _onChangeUser = (index, field, event) => { const newValue = event.target.value; this.setState(state => { const users = [ ...state.users.slice(0, index), { ...state.users[index], [field]: newValue, }, ...state.users.slice(index + 1), ]; return { users, }; }); }; _onSubmit = event => { event.preventDefault(); // Do something with this.state.users. console.log(this.state.users); }; render() { return ( <div className="App"> <form onSubmit={this._onSubmit}> {this.state.users.map((user, index) => ( <div key={index}> <input value={user.firstName} onChange={this._onChangeUser.bind(this, index, 'firstName')} /> <input value={user.middleName} onChange={this._onChangeUser.bind(this, index, 'middleName')} /> <input value={user.lastName} onChange={this._onChangeUser.bind(this, index, 'lastName')} /> </div> ))} <button type="submit">Submit</button> </form> </div> ); } } ReactDOM.render( <App />, document.getElementById('root') ); <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"><div> A: Ok. Declare your state variable as an array. Below should fulfill your requirement. constructor(props){ super(props) this.state={ firstNameArray:[], middleNameArray:[], lastNameArray:[], fName:” “, mName:””, lName:”” } this.changeFirstName = this.changeFirstName.bind(this); this.changeMiddleName= this.changeMiddleName.bind(this); this.changeLastName=this.changeLastName.bind(this); } changeFirstName(event){ this.setState({ firstNameArray:event.target.value, fName: event.target.value }) changeMiddleName(event){ this.setState({ middleNameArray: event.target.value, mName: event.target.value }) } changeLastName(event){ this.setState({ lastNameArray: event.target.value, lName: event.target.value }) Call each function on your input field like below <input type=‘text’ name=‘fName’ value= {this.state.fName} onChange={this.changeFirstName} /> Do it in the same way for other two input fields as well. Hope this answers your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/48124591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I avoid several instances of the same model object in iOS (MVC) I am working on a project in which I have a model that is used by several different views and thereby viewcontrollers. These viewcontrollers have no knowledge of each others' existence, nor do they have any relationship to each other. This means that I have a model* in each of the viewcontrollers and when the views are loaded, I allocate the model in each class and make the pointers point at it. Or short: I allocate my model n times in n classes that use it, which I think is a waste of memory (not that I will run out of memory, but I think it's bad practice). Is there a way in iOS where I (while still maintaining good MVC practice) am able to create and use the same instance of my model? Usually I have been programming in c++ where I would pass a reference to the model to the constructor of each class that should know the model. Example (c++): // Let to classes know of the same model object MyModel model; ControllerA myControllerA(&model); ControllerB myControllerB(&model); Instead I do the following in each class that use my model (objective-c): // ControllerA model = [[MyModel alloc] init]; // Controller B model = [[MyModel alloc] init]; I don't want to make all models singleton objects and in this specific project I think using an observer pattern would be an overkill. So, my question is: How can i achieve this and is it even possible? A: You can write your own initializer that takes a pointer to the Model. in the .h file of your ControllerA and B @property(nonatomic,assign)Model* myModel; -(id)initWithModel:(Model*)model; in the .m file of your ControllerA and B @synthesize myModel; -(id)initWithModel:(Model*)model{ self = [super init]; if(self){ self.mymodel = model; } return self; } EDIT If you are using the IB you would write your initilizer in the following way: - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil model:(Model*)model { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.mymodel = model; } return self; } A: I think, you need to use a singleton pattern Trivial implementation of witch looks like this YourClass.h + (id)sharedInstance; YourClass.m: +(id)singleton { static dispatch_once_t pred; static MyClass *shared = nil; dispatch_once(&pred, ^{ shared = [[MyClass alloc] init]; }); return shared; } Good article about it apple reference A: You've got the right idea: provide the model to the view controllers that need it when you create them; don't make go looking to a singleton or other global for the information they need. Since you asked about view controllers, and since those are often instantiated from .xib or storyboard files, you may need to adjust your approach a little. Instead of providing a reference to the model in the initializer, you can simply add a property that stores a reference to the model to each of your view controllers. The object that's responsible for creating a view controller can then provide the model after the controller has been created. For example, your app delegate's -applicationDidFinishLaunchingWithOptions: method will be called after the root view controller is created, and that's a good time to set up the model and point the root view controller at it: -applicationDidFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // set up the model self.model = [[MyModel alloc] initWithFile:...]; // get the root controller and give it a pointer to the model MyFirstViewController *firstController = self.window.rootViewController; firstController.model = model; } The root view controller can then pass the model on to other view controllers that it creates. If you have a tab based app, the app delegate might instead pass the model on to all the view controllers under the tab controller. In that case, your tab controller will be the window's root view controller, and you'd get to your view controllers like this: NSArray *controllers = self.window.rootViewController.viewControllers; The big advantage here over the singleton approach is that your view controllers don't assume anything about the rest of the app. They'll each use whatever model you give them. That makes your code cleaner, easier to manage, easier to rearrange, and so on. A: Once you create your model objects, you can store these instances in a global dictionary with a key, in some class which you have only one instance of, i.e. a singleton. When a view controller needs this model, it can ask this singleton to give it the data it needs by providing a dictionary key. Or you can store your data in coredata, and fetch it from there whenever you need it from a view controller. This way you'll also achieve persistence, if you need it.
{ "language": "en", "url": "https://stackoverflow.com/questions/8929086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to codesign a shell script executable inside a Mac app bundle? I have an executable shell script under myApp.app/Contents/MacOS/. Our code-sign pipeline complains that the subcomponent (this script) is not signed. How should I sign it? Our current pipeline has codesign --sign calls with hardcoded certificate numbers and field details I don't quite get. Basically only the app and some plugin bundles inside the app got code-signed. I cannot find dedicated documentation on how to code-sign shell scripts. A: FWIW...late answer...however, it may help someone: if you have designated (through Info.plist's CFBundleExecutable key's value) the script to be your app's executable, by the time you attempt to sign said script, you should make sure everything else has already been signed. Note: this is my experience using codesign through a bash script (so, not using XCode). Apple's docs say that you should sign your app bundle "from inside out"; this was my interpretation and it seems to work just fine for us. A: Something similar to the following shell script in the Build Phases > Run Script section of your project settings should work... /usr/bin/codesign --force --sign "iPhone Developer" --preserve-metadata=identifier,entitlements --timestamp=none $BUILT_PRODUCTS_DIR/$PRODUCT_NAME.app/Frameworks/$framework
{ "language": "en", "url": "https://stackoverflow.com/questions/30444447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Scrolling text in android EditText widget I have a single line EditText in android which displays a long line of text. Now, the requirement is that when I scroll to the end of line, and keeps on deleting characters using backspace, the text should keep scrolling horizontally as more space is now available. After going through other SO questions and other online resources, I have set the following style: <style name="MyEditText" parent="@android:style/Widget.EditText"> <item name="android:maxLines">1</item> <item name="android:scrollHorizontally">true</item> <item name="android:singleLine">true</item> </style> But it does not work. I have seen this behavior in other applications, so I know it works on Android. Any help is much appreciated. Thanks in advance. A: try to add some constraints in the layout of edittext instead defining style <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ems="5" android:maxHeight="40dp" android:scrollbars="vertical" android:scrollbarStyle="outsideOverlay" > try this it may help u
{ "language": "en", "url": "https://stackoverflow.com/questions/26381507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a better way of getting retrieving 'closeTime' , which is within a function I have a simple counter that starts when user clicks a button on the pop up and I store that value in openTime, when user closes the popup I store the current time in closeTime but due to closeTime being within a function, I'm not sure the best way to retrieve that value so that I am able to subtract it from openTimer I want to avoid global variables. Right now I am setting closeTimer to local storage then retrieving it to do the calculations, but I wanted to know if there is a better way of doing this. background.js chrome.runtime.onConnect.addListener(function (port) { var openTime = localStorage.getItem('myCat') var closeTime = localStorage.getItem('closeTime') console.log("OPEN TIME:",openTime,"CLOSE TIME",closeTime) var timelaps = openTime - closeTime localStorage.setItem('timelaps', timelaps); console.log("TIMELAPS OF POPUP BEING CLOSED",timelaps) if (port.name === "popup") { console.log("popup has been opened") port.onDisconnect.addListener(function () { console.log("popup has been closed") var closeTime = localStorage.getItem('myCat') localStorage.setItem('closeTime', closeTime); console.log(closeTime) }); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/68026870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django Http404 returns status=200 When my application raises Http404 the status-code returned is 200, which I find odd. It returns and renders my 404-template, so it should work, but the status-code is wrong. Please find the views and urls-file below: #views.py from django.http import Http404 def test_404_view(request): raise Http404 def error_404(request, exception): return render(request,"MyApp/404.html") #urls.py handler404 = 'myapp.views.error_404' . . A: You should specify the status=… [Django-doc] code in your render call, this is by default a 200: def error_404(request, exception): return render(request,'MyApp/404.html', status=404)
{ "language": "en", "url": "https://stackoverflow.com/questions/68605933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need to know when a non-modal window has closed I have opened childwindow from parentWindow (non-modal) - what's the best approach to achieving a 'wait' so that parentWindow will know when childWindow has closed? For a couple of reasons I cannot use showDialog(). I have tried a while loop (testing the childWindow's visibility property) but it just breaks (no exception - but just doesn't open childWindow). Is it a case of multi-threading?? A: what's the best approach to achieving a 'wait' so that parentWindow will know when childWindow has closed? You could use events so the parent window is notified when the child window closes. For instance, there is the Closed event. Window childWindow = new .... childWindow.Closed += (sender, e) => { // Put logic here // Will be called after the child window is closed }; childWindow.Show(); A: I think you can use this: public ShowChild() { childWindow child = new childWindow(); child.Closed += new EventHandler(child_Closed); child.Show(); } void child_Closed(object sender, EventArgs e) { // Child window closed }
{ "language": "en", "url": "https://stackoverflow.com/questions/8910120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Icinga2 notification just once on state change I have set up icinga2 to monitor a few services with different intervals, so one service might be checked every 10 seconds. If it gives a critical error I will receive a notification, but I will receive it every 10 seconds if the error persists, or until I acknowledge it. I just want to receive it once for each state change. Then maybe after a specified time again, but it is not that important. Here is my config: This is more or less the standard template.conf, but I have added the "interval=0s", because I read that it should prevent notifications from being sent multiple times. template Notification "mail-service-notification" { command = "mail-service-notification" interval = 0s states = [ OK, Critical ] types = [ Problem, Acknowledgement, Recovery, Custom, FlappingStart, FlappingEnd, DowntimeStart, DowntimeEnd, DowntimeRemoved ] vars += { notification_logtosyslog = false } period = "24x7" } And here is the part of the notification.conf that includes the template: object NotificationCommand "telegram-service-notification" { import "plugin-notification-command" command = [ SysconfDir + "/icinga2/scripts/telegram-service-notification.sh" ] env = { NOTIFICATIONTYPE = "$notification.type$" SERVICEDESC = "$service.name$" HOSTNAME = "$host.name$" HOSTALIAS = "$host.display_name$" HOSTADDRESS = "$address$" SERVICESTATE = "$service.state$" LONGDATETIME = "$icinga.long_date_time$" SERVICEOUTPUT = "$service.output$" NOTIFICATIONAUTHORNAME = "$notification.author$" NOTIFICATIONCOMMENT = "$notification.comment$" HOSTDISPLAYNAME = "$host.display_name$" SERVICEDISPLAYNAME = "$service.display_name$" TELEGRAM_BOT_TOKEN = TelegramBotToken TELEGRAM_CHAT_ID = "$user.vars.telegram_chat_id$" } } apply Notification "telegram-icingaadmin" to Service { import "mail-service-notification" command = "telegram-service-notification" user_groups = [ "icingaadmins" ] assign where host.name } A: I think you had a typo. It should work if you set interval = 0 (not "interval = 0s") After that change you must restart the icinga service.
{ "language": "en", "url": "https://stackoverflow.com/questions/50871100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Cookie VS SessionState I need to store a site ID. Currently I store the ID in a file on the site folder and cache the ID once the site is first accessed. For reasons I don't want to get into right now, I can no longer use this option. I need to store the Id another way. I'm thinking either store it in a cookie or save to the session state. I need to know which will be most efficicent. CPU and memory is a big issue for the machine I'm running this on. Is it better to read it off the clients machine for the ID? Or store it in a session variable? A: Session state consumes either RAM or database resources, depending on which provider you use (InProc vs. SQL). It also requires a cookie, in order for the server to associate an incoming request with a particular Session collection. For something like a site ID, I would suggest storing it in a cookie if you can. For best performance, configure the cookie with a path property so the browser doesn't include it with requests for images and other static files.
{ "language": "en", "url": "https://stackoverflow.com/questions/9425850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: css swap images with sizing I have searched here, couldn't seem to find a solution. I know 'how' to essentially do mouseovers with jQuery if I use an actual "image" object, and have the image resized properly, I'm just trying to figure out if there is a way to do the same thing with CSS and use a specific class with background URL. Here's my code & css: .sample #img_id { width: 80px; height: 80px; background: url('sample.gif') left no-repeat top; } .sample #img_id:hover { width: 80px; height: 80px; background: url('sample-mouseover.gif') left no-repeat top; } and then my HTML code: <div class="sample"> <div id=img_id></div> </div> Now - if the image is say 200 pixels by 200 pixels - the image does NOT resize. (I.e., it will 'overflow'). I was expecting the image to be resized to 80px x 80px. I have also tried this: .sample img { width: 80px; height: 80px; background: url('sample.gif') left no-repeat top; } .sample img:hover { width: 80px; height: 80px; background: url('sample-mouseover.gif') left no-repeat top; } and then my HTML code: <div class="sample"> <img src=sample.gif> </div> But this doesn't work either. The 'initial' image is "resized" properly (i.e., to 80 x 80 px) - but with the mouseover, the image would be 200px x 200px (i.e., no resizing). How do I get my sample image properly resized/scaled to fit within the 80x80px on a mousever via CSS? (Like I said, I figured it out via jQuery, I just figure there should be an easy solution with CSS, and not quite sure just how to get it resized properly). Thanks! A: possibly syntax, it's working on this fiddle A: The background-size property allows you to change the dimensions of the background image, unless you need it to work in IE8 and perhaps Opera Mini.
{ "language": "en", "url": "https://stackoverflow.com/questions/37094538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: angular2 material and date - how to get the currently selected date Dudes of angular2 material apparently did not want to show how to get the currently selected date...selectedChanged returns the last date. <md-input-container> <input mdInput [mdDatepicker]="picker" placeholder="Choose a date" [(ngModel)]="wtf"> <button mdSuffix [mdDatepickerToggle]="picker"></button> </md-input-container> <md-datepicker #picker [startAt]="startDate" (selectedChanged)="duder()"></md-datepicker> duder(){ console.log('duder',this.startDate,this.wtf) console.log('duder--r',moment(this.wtf).format('DD-MM-YYYY')) } I mean wow..I make a change..and what I get is the last date..not the current date that I selected. If I change the date..how do I get the current date from my duder() function? A: So the trick is anytime you deal with @Output in angular, pass in the $event to emit the new value to the function. Just add that to your duder() and you will be set. (selectedChanged)="duder($event)" duder(date){ console.log('duder', date); this.wtf = date; } I have updated the demo
{ "language": "en", "url": "https://stackoverflow.com/questions/44856207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Parse a date from a complex string using python I have a number of strings that have different date formats in them. I would like to be able to extract the date from the string. For example: * *Today is August 2012. Tomorrow isn't *Another day 12 August, another time *12/08 is another format *have another ? 08/12/12 could be *finally august 12 would be What I would expect to get from each of these results is 2012-08-01 00:00:00, 2013-08-12 00:00:00, 2013-08-12 00:00:00, 2012-08-12 00:00:00, 2013-08-12 00:00:00. I currently have this code: from dateutil import parser print parser.parse("Today is August 2012. Tomorrow isn't",fuzzy=True) You will see from this that the date prints as 2012-08-27 00:00:00 (because today is the 27th of the month). What I would want in this example is 2012-08-01 00:00:00. How do I force it to always put the first of the month if a day is not given? (For example if I give August 2012 it should return 2012-08-01, if I give it 12 August 2012 it should return 2012-08-12.) A: Use the default argument to set the default date. This should handle all the cases except the third one, which is somewhat ambiguous and probably needs some parser tweaking or a mindreader: In [15]: from datetime import datetime In [16]: from dateutil import parser In [17]: DEFAULT_DATE = datetime(2013,1,1) In [18]: dates=["Today is August 2012. Tomorrow isn't", ...: "Another day 12 August, another time", ...: "12/08 is another format", ...: "have another ? 08/12/12 could be", ...: "finally august 12 would be"] In [19]: for date in dates: ...: print parser.parse(date,fuzzy=True, default=DEFAULT_DATE) ...: 2012-08-01 00:00:00 2013-08-12 00:00:00 2013-12-08 00:00:00 # wrong 2012-08-12 00:00:00 2013-08-12 00:00:00
{ "language": "en", "url": "https://stackoverflow.com/questions/14548285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How Can I Exit My Inplace-Editor AND Process the Button in Delphi? In my Delphi 2009 application, I have this window: It has a TPageControl that has a TTabSheet on it as well as buttons at the bottom that operate on all sheets. On the left of the TTabSheet is a TElXTree (a tree/grid component by LMD) and on the right of the TTabSheet is a TPanel containing buttons specific to just this sheet. When I have a row selected in the TElXTree, and I click on any button in either set of buttons, the buttons all work fine. Now within the TElXTree, the column labelled "Text" is editable with an Inplace-Editor supplied with TElXtree. When I click on the Text, it goes into edit mode. When in edit mode, when I click anywhere in the TElXTree (e.g. on the checkbox), it will exit the editor AND process the command (i.e. check or uncheck the checkbox). However, when in edit mode, when I click on any button in either set of buttons, it will simply exit the inplace-editor and NOT process the button. I then have to click on the button again to process that button. Is there something simple that I am not doing or not understanding here that would allow me to click on one of those buttons and allow it to both exit my inplace editor AND process the button? Followup: Thanks to @NGLN's answer, I got my workaround. I used his Application.OnMessage method, which I was previously using anyway for some Drag and Drop code. I had to make some changes though, and this is what I came up with: procedure TMainForm.AppMessageHandler(var Msg: TMsg; var Handled: Boolean); var P: TPoint; begin if Msg.message = WM_LBUTTONDOWN then if Screen.ActiveControl <> nil then if Screen.ActiveControl.ClassNameIs('TElInpEdit') then begin GetCursorPos(P); { When in the inplace editor, I need to go to its parent ElXTree } { because the ElXTree does not have the problem. } { Only components outside the ElXTree do } with Screen.ActiveControl.Parent do if not PtInRect(ClientRect, ScreenToClient(P)) then begin { The WM_Killfocus didn't work for me, but it gave me this idea: } { 1. Complete the operation, and 2. Simulate the mouse click } InplaceEdit.CompleteOperation(true); Mouse_Event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); Mouse_Event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); { Then skip the regular handling of this WM_LBUTTONDOWN } Handled := true; end; end; end; A: It indeed looks like a bug. Two possible (nasty) workarounds: Via Application.OnMessage: procedure TMainForm.ApplicationEventsMessage(var Msg: tagMSG; var Handled: Boolean); var P: TPoint; begin if Msg.message = WM_LBUTTONDOWN then if Screen.ActiveControl <> nil then if Screen.ActiveControl.ClassNameIs('TElInpEdit') then begin GetCursorPos(P); with Screen.ActiveControl do if not PtInRect(ClientRect, ScreenToClient(P)) then Perform(WM_KILLFOCUS, 0, 0); end; end; Or subclass the component: type TElXTree = class(ElXTree.TElXTree) private procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; end; TForm1 = class(TForm) ElXTree1: TElXTree; ... procedure TElXTree.CMMouseLeave(var Message: TMessage); var P: TPoint; begin GetCursorPos(P); if not PtInRect(ClientRect, ScreenToClient(P)) then if Screen.ActiveControl <> nil then if Screen.ActiveControl.ClassNameIs('TElInpEdit') then Screen.ActiveControl.Perform(WM_KILLFOCUS, 0, 0); inherited; end; Note: this one is nót preferred since it alters the behaviour of the component: just hovering the mouse outside of the grid closes the inplace editor. But I added it because it might bring others to other solutions. A: It can be a focus problem. Look at code you have written in OnExit OnEnter methods of your form.
{ "language": "en", "url": "https://stackoverflow.com/questions/6501417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Lisp function to return a number double and then the same number doubled plus one I am totally new to lisp and have no idea how I'll create this function. This is the pseudo code I created to help me solve it Binary tree children ; This function returns the children of binary tree node ; e.g., 3 -> (6,7) ; e.g., 11 -> (22,23) (defun tree-node(x)) The function is intended to take in a number, double it, and then double it and add 1. Please help. A: To double a number (which is stored in a variable named n here): (* 2 n). To add one: (1+ n). Note that 1+ is the name of a function. It is the same as (+ n 1). Now, let's say that you have some scope (e. g. a function body) where you have a variable named n. You now create a new variable d using let: (let ((d (* n 2))) …) This new variable is in scope for the body of the let (indicated by … above). Now we create another variable d1, which is one more. We need to use let* now, so that the scope of d is not just the body, but also the binding forms of the let*: (let* ((d (* n 2)) (d1 (+ d 1))) …) The function should maybe be called child-indices: (defun child-indices (n) (let* ((d (* n 2)) (d1 (+ d 1))) …)) The bodies of many forms like defun and let are so-called implicit progns, which means that these forms return the value of the last expression in their body. So, whatever forms we put into the place marked … above, the value (or values, but let's keep that aside for now) of the last is the return value of the function. There are several ways to do a “return this and then that”, but we'll use a list for now: (defun child-indices (n) (let* ((d (* n 2)) (d1 (+ d 1))) (list d d1)))
{ "language": "en", "url": "https://stackoverflow.com/questions/50956898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Rails precompile multiple javascript_includes_tag I'm actually building a new app under Rails 4. I used to put my javascript_includes_tag at the bottom of my layout. But for an unknown reason, it creates a bug when trying to use confirm: on delete link. So I put back this line at the top : !!! %html{ :lang => 'en' } %head = stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true = javascript_include_tag "application", "data-turbolinks-track" => true So far so good, the bug is now gone. Anyway, since my app is gonna use a lot of Javascript, I still need to load those third part library at the bottom. So, what I did is to only let the Rails library at the top : // application.js //= require jquery //= require jquery_ujs //= require turbolinks Then I tried to create another js file named third-part and try to do the same as application but including my third part libraries. Unfortunately, it does not work. // third-part.js //= require bootstrap //= require app //= require app.plugin How can I add another javascript_includes_tag at the bottom the same way I did for application? Here I mean that on production it will also compress those files. Thanks a lot for your help EDIT : It's actually loading my files well on DEVELOPMENT, but not on my production. On production I just got <script data-turbolinks-track="true" src="/javascripts/third-part.js"></script> and I can't access the file I've tried : config.assets.precompile += %w( third-part.js ) and rake assets:precompile RAILS_ENV=production but it still not working EDIT 2 : I made a test of precompliling on production mode from my local machine. It did work. It might be a problem with my server. EDIT 3 : Just earse my application from server and clone a new one from my Github but it's still not working. Don't know why :( A: In your config/environments/production.rb add this line to precompile the external assets config.assets.precompile += ["third-part.js"] and don't forget to mention env=production while precompiling assets on production.
{ "language": "en", "url": "https://stackoverflow.com/questions/18863884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Magento: Limit text field size in product custom attribute to 80 characters I have a problem by using the following tip from the magento forum: Quote: One option you could do is to add a backend model for this attribute. In this model you could write your own beforeSave function that will process the length of given value and trim it to be the desired length. The class should extend Mage_Eav_Model_Entity_Attribute_Backend_Abstract Code: public function beforeSave($object) { $attrCode = $this->getAttribute()->getAttributeCode(); if ($object->hasData($attrCode)) { $object->setData($attrCode, substr($object->getData($attrCode),0,50)); } return $this; } My question now is: how and where do I implement this snippet? I recently put it in /app/code/core/Mage/Eav/Model/Entity/Attribute/Backend/Default.php but it had no effect. A: first at all, you'll never should place custom code into core files. This destroys your upgradabillity. Create your own custom modules under app/code/local. There you can create your model which extends from Mage_Eav_Model_Entity_Attribute_Backend_Abstract. May this link helps you to create your module: http://www.smashingmagazine.com/2012/03/01/basics-creating-magento-module/ Also you can use magerun (an cli tool for magento) to create a module: http://magerun.net/
{ "language": "en", "url": "https://stackoverflow.com/questions/30569680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: IIS is not loading .css files Hi I just started working with an IIS server for my AngularJS project. So my problem is that my project loads angular, but not .css files, neither my own nor bootstraps. I have looked at the big fat web, and I noticed that most solutions is to check static content in Windows features. However that was already ticked for me. And I'm wondering if there are other solutions? index.html <!doctype html> <html ng-app="SimPlannerApp"> <head> ... <!-- Load Bootstrap CSS library --> <link type="text/css" href="lib/bootstrap-3.3.5-dist/css/bootstrap.min.css"> <!-- Load AngularJS modules --> <script src="lib/Angular-1.4.7/angular.min.js"></script> <script src="lib/Angular-1.4.7/angular-ui-router.min.js"></script> <!-- Load AngularJS Application --> <script src="core.js"></script> <!-- Our CSS --> <link type="text/css" href="assets/styles/main.css"> <link type="text/css" href="assets/styles/nav.css"> </head> <body> ... <!-- This is where page content is inserted to --> <div ui-view></div> </body> </html> File tree * *assets *styles * *main.css *nav.css *lib *Angular-1.4.7 * *angular.min.js *angular-ui-router.min.js *bootstrap-3.3.5-dist * *css * *bootstrap.min.css *index.html *core.js Files loaded to the browser A: A guy in my team found the solution. When referencing the stylesheets I've forgotten the rel="stylesheet" after each of them. so this <link type="text/css" href="assets/styles/main.css"> should be this <link type="text/css" href="assets/styles/main.css" rel="stylesheet">
{ "language": "en", "url": "https://stackoverflow.com/questions/33400895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ensure rotation takes the same amount of time regardless of angle to be rotated in Unity I hope somebody can help. I have a script that rotates a globe, over which a plane (which is stationary) flies from 1 country to another. This all works fine and is achieved with the following script while (!DestinationReached) { Vector3 planetToCountry = (Destination.localPosition - Vector3.zero);//.normalized; //vector that points from planet to country Vector3 planetToCamera = (camTr.position - tr.position).normalized; //vector that points from planet to camera/plane Quaternion a = Quaternion.LookRotation(planetToCamera); Quaternion b = Quaternion.LookRotation(planetToCountry); b = Quaternion.Inverse(b); newRotation = a * b; tr.rotation = Quaternion.Slerp(tr.rotation, newRotation, 0.01f); if (Approximately(tr.rotation, newRotation, 0.0001f)) //if here the plane has arrived { Debug.Log("Destination reached"); DestinationReached = true; } yield return new WaitForEndOfFrame(); } It essentially calculates the angle between the plane (the camera is attached to the plane GO and views it from above) and the destination the globe needs to rotate to so that the plane looks as though it flies to the destination. The issue I have is I need to make the flight time uniform regardless of the angle the globe must rotate, so lets say it must be 5 seconds, regardless if the plane flies from Paris to Ireland or Paris to Australia. Anybody have any ideas on how to do this. I have to admit, I nicked this script for the web, as my Vector and Quaternion mathematics is hopeless :) A: If you want to be flexible and e.g. add some easing at beginning and end but still finish within a fixed duration I would do it like this (I'll just assume here that your calculating the final rotation is working as intended) // Adjust the duration via the Inspector [SerializeField] private float duration = 5f; private IEnumerator RotateRoutine() { // calculate these values only once! // store the initial rotation var startRotation = tr.rotation; // Calculate and store your target ratoation var planetToCountry = (Destination.localPosition - Vector3.zero); var planetToCamera = (camTr.position - tr.position); var a = Quaternion.LookRotation(planetToCamera); var b = Quaternion.LookRotation(planetToCountry); b = Quaternion.Inverse(b); var targetRotation = a * b; if(duration <= 0) { Debug.LogWarning("Rotating without duration!", this); } else { // track the time passed in this routine var timePassed = 0f; while (timePassed < duration) { // This will be a factor from 0 to 1 var factor = timePassed / duration; // Optionally you can alter the curve of this factor // and e.g. add some easing-in and - out factor = Mathf.SmoothStep(0, 1, factor); // rotate from startRotation to targetRotation via given factor tr.rotation = Quaternion.Slerp(startRotation, targetRotation, factor); // increase the timer by the time passed since last frame timePassed += Time.deltaTime; // Return null simply waits one frame yield return null; } } // Assign the targetRotation fix in order to eliminate // an offset in the end due to time imprecision tr.rotation = targetRotation; Debug.Log("Destination reached"); } A: So the problem here is the t used on your Quaternion.Slerp method, it's constant. This t is the "step" the slerp will do, so if it's contstant, it won't depend on time, it will depend on distance. Try instead to do something like this, being timeToTransition the time you want that every rotation will match: public IEnumerator RotatintCoroutine(float timeToTransition) { float step = 0f; while (step < 1) { step += Time.deltaTime / timeToTransition; //...other stuff tr.rotation = Quaternion.Slerp(tr.rotation, newRotation, step); //...more stuff if you want yield return null; } } Edit: addapted to your code should look like this float timeToFly = 5f; while (!DestinationReached) { step += Time.deltaTime / timeToTransition; Vector3 planetToCountry = (Destination.localPosition - Vector3.zero);//.normalized; //vector that points from planet to country Vector3 planetToCamera = (camTr.position - tr.position).normalized; //vector that points from planet to camera/plane Quaternion a = Quaternion.LookRotation(planetToCamera); Quaternion b = Quaternion.LookRotation(planetToCountry); b = Quaternion.Inverse(b); newRotation = a * b; tr.rotation = Quaternion.Slerp(tr.rotation, newRotation, step); if (step >= 1) //if here the plane has arrived { Debug.Log("Destination reached"); DestinationReached = true; } yield return null(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/62503214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Functions of jdbc Driver Why jdbc odbc driver written as jdbc.odbc.JdbcOdbcDriver or sun.jadbc.odbc.JdbcOdbc Driver? In which file the name is stored? eg. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") And What are the functions of jdbcodbc driver and odbc driver? A: Why jdbc odbc driver written as jdbc.odbc.JdbcOdbcDriver or sun.jadbc.odbc.JdbcOdbc Driver? Because (presumably) there are two different JDBC->ODBC driver classes, and those are their respective fully qualified class names. (Your question is a bit like asking "why are tyres called Michelin and Goodyear?") In which file the name is stored? That entirely depends on the design of your application and/or the framework it is using for persistence. eg. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") In that example, the class name is hard-wired into the source code. Why? You'd need to ask the person who wrote it!! And What are the functions of jdbcodbc driver and odbc driver? A plain ODBC driver provides client-side ODBC APIs that an application can use to make calls to a database. The driver implements that functionality by interfacing with the vendor-specific native database protocols and / or APIs. Thus, the driver is hiding the database-specific stuff behind a database independent facade. A plain JDBC driver does the same thing except that it is providing JDBC APIs. A JDBC-ODBC driver is actually a "bridge" between the JDBC and ODBC APIs. The application makes JDBC calls that are mapped to ODBC class by the driver. This driver then calls a plain ODBC driver which talks to the actual database. (You would use this if you had a database that had only ODBC drivers, and you wanted to access it from an application implemented to use JDBC.) For more information on JDBC and ODBC, refer to the respective Wikipedia pages, etcetera. A: When you use Class.forName(), you create a new class with the given fully qualified name. Since you connect to a DB, you must use the DB driver specific to the type of connection you use. After that I assume you will use DriverManager to create a connection to that resource. The DriverManager will look for classes that can use the connection string you pass to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/21930501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I apply only one file or two classes from a Puppet Master server? Let us say that I have a case in which I need to apply only two files from a Puppet configuration on some production servers, without touching the rest of the configuration. /opt/aservice/myfile/thekey.conf /opt/myfile/thekey.salt Let's also say that these are controlled by the following Puppet manifest: # # author: Nathan Basanese ([email protected]) # date: 04/17/2048 # class keyconfig ( $cluster ){ notify {"Deploying key config. files to $fqdn":} file {'/opt/aservice/key/config/thekey.conf': ensure => present, mode => '0644', owner => 'aservice-serv', group => 'aservice-serv', source => "puppet:///modules/keyconfig/$cluster/thekey.conf", } file {'/opt/aservice/key/config/thekey.salt': ensure => present, mode => '0644', owner => 'aservice-serv', group => 'aservice-serv', source => "puppet:///modules/keyconfig/$cluster/thekey.salt", } } How would I apply ONLY these two files to a given server from a Puppet Master? Perhaps, in the puppet agent command that is run on the target server, could I specify a specific Puppet class to use? I have used the puppet resource command before, but I'm not sure that would work, here. A: Every resource is automatically tagged with the fully qualified name of the class or defined type in which it is declared, and with every namespace segment of the class or type name, among other tags. You can use those tags to filter the resources that will be applied during a given catalog run. In the particular example you describe, you could use puppet agent --no-daemonize --onetime --tags keyconfig to apply only the resources declared in class keyconfig (and in any other class declared by keyconfig, recursively, but in this case there are no such other classes). You can also declare tags manually by using the tag metaparameter in your resource declarations. That can allow you to provide for identifying custom collections of resources. And speaking of collections, you can use tags in the selection predicates of resource collectors, too. A: The only way to do that is to have that node contain only the class you are wanting to have applied. In your site.pp you would have the following where the 'myhost.dns' is your fqdn. and $mycluster would be replaced by your cluster string. node 'myhost.dns' { class { 'keyconfig': cluster => $mycluster, } }
{ "language": "en", "url": "https://stackoverflow.com/questions/34167567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Button click requires double click or long-press on mobile I'm trying to click a button in a React app, and while it works on desktop, it does not work properly on mobile. I need to long-press or double-click, and play a little bit until the button finally works. I have replicated my problem in this demo. If you open the page on a desktop browser and attempt to open the hamburger menu, it should open right away. However, if you open it in mobile, it will not work right away. You will also see the menu jitter a little bit off-screen. Attempting to close the menu by clicking on the overlay has the same problem in mobile. Why is this not working properly on mobile? How can I get the button to work when I tap it? I added cursor:pointer to the button after seeing this somewhat similar post, but this doesn't help. This problem has occurred in the past to me, and I was able to solve it using onMouseDown but it doesn't work this time, I'm guessing because I'm using a component that is imported from a package (react-burger-menu) and can't override its onClick function? I'm not sure what is happening. EDIT: Solved. See my answer. A: Turns out it works if I fix the stacking of elements. I had nested my navbar component inside the MapContainer, but this was making things wonky mobile-side. I moved my component outside the MapContainer, and things worked. I still don't understand why it went wonky mobile-side and in iOS only, but this problem at least is solvable. Fixed example is here. My map token has been removed, so you can use your own to substitute, but it is not necessary to have the map showing to see the problem/solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/66621855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to add my own classes in iReport when I change from Groovy to Java language? I'm working with iReport and JasperReports, when I began to do my report, iReport by default use Groovy, but I need to change to Java (constrains in my job), I make my report with Groovy and It's works perfectly but when I change to Java language, I get a trouble, because I use a class(fields from java of a class) in my report, so the Mistake is: myfield cannot be resolved or is not a field. The class that I use to do my report is: public final class GrupoEstadistico implements Serializable { private Estadistico ccDocumento; private Estadistico ccNombres; //another class that is an attribute of type Estadistico private Date periodo; private String tipoEntidad; //and another primitives atributes: strings, int //getters and setters } This is the Estadistico class: public final class Estadistico implements Serializable, Comparable<Estadistico> { private String nombreEntidad; private int codigo; private int numeroConsultas = 0; //and aother primitives atributes: strings, int //getters and setters } And I use all attributes of the class GrupoEstadistico in my report like a fields. And I use expressions to get the values of each Estadistico like: $F{ccDocumento}.numeroConsultasanyone The trouble that I get when I try to compile the report is: numeroConsultas cannot be resolved or is not a field. What I understand is happening is: * *iReport not find my class attributes thus this has *iRreport not understand the expressions I use. This is that I been tried to solve my problem: * *add a jar file with the classes required to classpath of iReport. *add the import like: reporte.model.GruoEstadistico in the properties of my report. *And I been edited the xml and I add the tag scriptlet: <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="ListaConsultaEstadistico" pageWidth="895" pageHeight="595" orientation="Landscape" columnWidth="855" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" scriptletClass="reporte.model.GrupoEstadistico" uuid="b0990d7b-fade-4200-a2ef-fb0416f5a9c2"> UPDATE: I'm calling my report from the Java code the following way: /**Create a List of GrupoEstadistico class. */ List<GrupoEstadistico> this.dataSource = new ArrayList<GrupoEstadistico>(); /**Fill my List....*/ JasperPrint jasperPrint= JasperFillManager.fillReport( reportPath,this.parametros, new JRBeanCollectionDataSource( this.dataSource )); The dataSource is a List<GrupoEstadistico> But still does not work. Can anyone help me? A: Send your object in ireport using java program. Define a field with name of your instance and attribute. e.g. Suppose you send your class instance with grupoEstadistico, define a field in ireport with name "grupoEstadistico.tipoEntidad". and Drag a textfield in any band. RightClick->Edit Expression-> remove ${field}-> double click on your field->click apply It will add you attribute in *iReport *. now if you download your file as pdf format , it will show data what ever you send in this instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/19122518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Do unselected columns in a SQL Table slow down a query? For example, say I have columns A,B,C in Table X. If I use the query "Select A, B from X", would that query be any slower than if I delete column C and just do "Select * from X" A: The performance of a query on a single table that selects all rows is pretty much driven by the I/O cost. The I/O cost, in turn, is based on the number of data pages read by the query. In general, having an additional column will increase the size of rows. Fewer rows fit on fewer pages, so the query could be a bit faster. Now for caveats. Here are some: * *If C is a varchar that is always NULL, it occupies no extra space. *If C is varchar(max) (or really large) it might be stored on a separate data page. *If an index exists with (A, B) (in either order), then the query should use the index. Because the index covers the query, the number of data pages is irrelevant. *SQL Server does look aheads on I/O and can interleave I/O with other processing. So, you might not notice the additional CPU time spend reading the data pages. I wouldn't be inclined to simply remove columns to speed up such a query, unless the columns are not being used. The increase in speed -- if any -- is likely to be small. But there may exist cases where that would be a good idea from a performance perspective.
{ "language": "en", "url": "https://stackoverflow.com/questions/52656197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Offset size and overlay of plots in R I have two plots that I would like to overlay in a particular way. Instead of side by side like when using par(), I would like one to sit inside the other, but be about a quarter the size. More details: one of my plots is a map, another is a scatterplot with colored quadrants. The colored quadrants represent the colors plotted onto the map, so I would like to inset it nicely in the same plot as the map so that it serves as a legend. Thanks in advance A: Here's an example, although the links in comments point to similar approaches. Grab a shapefile: download.file(file.path('http://www.naturalearthdata.com/http/', 'www.naturalearthdata.com/download/50m', 'cultural/ne_50m_admin_1_states_provinces_lakes.zip'), {f <- tempfile()}) unzip(f, exdir=tempdir()) Plotting: library(rgdal) shp <- readOGR(tempdir(), 'ne_50m_admin_1_states_provinces_lakes') plot(subset(shp, admin=='Australia'), col=sample(c('#7fc97f', '#beaed4', '#fdc086', '#ffff99'), 9, repl=TRUE)) opar <- par(plt=c(0.75, 0.95, 0.75, 0.95), new=TRUE) plot.new() plot.window(xlim=c(0, 1), ylim=c(0, 1), xaxs='i', yaxs='i') rect(0, 0, 0.5, 0.5, border=NA, col='#7fc97f') rect(0.5, 0, 1, 0.5, border=NA, col='#beaed4') rect(0, 0.5, 0.5, 1, border=NA, col='#fdc086') rect(0.5, 0.5, 1, 1, border=NA, col='#ffff99') points(runif(100), runif(100), pch=20, cex=0.8) box(lwd=2) par(opar) See plt under ?par for clarification. A: This is how I did it in the past grid.newpage() vp <- viewport(width = 1, height = 1) submain <- viewport(width = 0.9, height = 0.9, x = 0.5, y = 1,just=c("center","top")) print(p, vp = submain) subvp2 <- viewport(width = 0.2, height = 0.2, x = 0.39, y = 0.35,just=c("right","top")) print(hi, vp = subvp2) subvp1 <- viewport(width = 0.28, height = 0.28, x = 0.0, y = 0.1,just=c("left","bottom")) print(ak, vp = subvp1) in my case p, ak and hi were gg objects (maps created with ggplot) and I was inserting a small version of each near the main use map (p) - as it is typically done
{ "language": "en", "url": "https://stackoverflow.com/questions/21568300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to automatically add R^2 to a graph with facet wrap using ggplot2? I am trying to add R^2 values to each facet in a ggplot2 graph. This is the code I have so far and this is what the graph looks like currently. ggplot(BB_new, aes(x=Date, y=pH, color=Treatment)) + geom_point(pch=19, size=1,alpha = 1)+ geom_smooth(aes(color=NULL), method = "lm", formula = y ~ x + I(x^2), se = FALSE) + theme_classic()+ theme(legend.title = element_blank())+ theme(legend.position = c(0.9,0.93))+ scale_color_manual(labels = c("Reference"), values = c("coral1"))+ facet_wrap(~Hor) + ylim(2.5, 6)
{ "language": "en", "url": "https://stackoverflow.com/questions/73356573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: htc files: Why not to use them? I am developing a web application that aims to give a desktop feeling for the end user. That means I need a cross-browser feeling to the application (who doesn't? eheh). So, I found about .htc files, for working around some IE tweaks (doesn't support border-radius yet, for example). My doubt is: Why isn't everyone using them? Does it come with some problems I am ignoring? From the place I am seeing, it appears to be almost the holy grail for the front-end programmers... A: Quoting Wikipedia: HTML Components (HTCs) are a nonstandard mechanism to implement components in script as Dynamic HTML (DHTML) "behaviors"[1] in the Microsoft Internet Explorer web browser. Such files typically use an .htc extension. An HTC is typically an HTML file (with JScript / VBScript) and a set of elements that define the component. This helps to organize behavior encapsulated script modules that can be attached to parts of a Webpage DOM. In two paragraphs, the following are mentioned: * *Internet Explorer *JScript *VBScript *nonstandard I think it's obvious why not everybody is using this technology. A: How to use border-radius.htc with IE to make rounded corners The server has to server the HTC with the correct MIME type (text/x-component) That alone is enough to stop JavaScript frameworks such as jQuery or MooTools from being able to use them. The dependency on configuring anything a server in order to get client-side functionality working is beyond unacceptable. It's a real pity though, htc files really are capable of a lot of interesting things.
{ "language": "en", "url": "https://stackoverflow.com/questions/4335622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Return indexes of xRange in Dygrpahs Is it possible to retrieve the indexes of the visible xRange in Dygraphs? xAxisRange() returns the value of the low end and high end. Something similar how highlightCallback returns a "row". I'm using dygraphs 1.1.1
{ "language": "en", "url": "https://stackoverflow.com/questions/35184561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Print list from a dataframe based on another columns value I would like to slice the dataframe according to conditions. I want to keep the area name where the length of codes are 5 or 3. The dataframeAreaCode is as bellowed codes area 0 113 Leeds 2 115 Nottingham 3 116 Leicester ... ... ... 596 1985 Warminster 597 1986 Bungay 598 1987 Ebbsfleet * *This is the code I wrote, but it didn't work. # print([AreaCode['codes']>4]) for i in AreaCode['codes']: if len(i)>4: print(AreaCode['area'][i])
{ "language": "en", "url": "https://stackoverflow.com/questions/64897847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: vue 3 Property '...' does not exist on type export default { data() { return { isLoading: false }; }, methods: { async showMore(parentId) { if (this.isLoading) return; this.isLoading = true; await this.someAction({ parentId }); this.isLoading = false; } } } This code give error: Property 'isLoading' does not exist on type A: Need to use defineComponent wrapper export default defineComponent({ ... });
{ "language": "en", "url": "https://stackoverflow.com/questions/66435072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Integration Testing a rails API using devise_token_auth for authenticaton and cancancan for authorization using Rspec I have a rails-api application that I'm testing using Rspec. The Application uses devise_token_auth gem for authentication and cancancan gem for authorization. devise_token_auth requires that the client include these authentication headers in every request: access-token, client, expiry, uid. These headers are available in a response after successful authentication using email and password. I have decided to use a solution provided in this answer to set these headers during testing. In ability.rb I have this: ## models/ability.rb class Ability include CanCan::Ability def initialize(user) if user.role? :registered can :create, Post, user_id: user.id can :update, Post, user_id: user.id can :destroy, Post, user_id: user.id can :read, Post end end end posts#show action in PostsController looks like this: ## controllers/posts_controller.rb class PostsController < ApplicationController before_action :authenticate_user! load_and_authorize_resource def show render json: @post end end I have rescued CanCan::AccessDenied error to render a json message and a status of 403 forbidden in ApplicationController rescue_from CanCan::AccessDenied do |exception| render json: {"message" => "unauthorized"}.to_json, :status => 403 end I have this in spec/support/session_helper.rb module SessionHelper def retrieve_access_headers ##I have a user with these credentials and has a "registered" role. in the the test db. post "/auth/sign_in", params: {:email => "[email protected]", :password => "g00dP@ssword"}, headers: {'HTTP_ACCEPT' => "application/json"} ##These two pass expect(response.response_code).to eq 200 expect(response.body).to match(/"email": "[email protected]"/) access_headers = {"access-token" => response.headers["access-token"], "client" => response.headers["client"], "expiry" => response.headers["expiry"], "uid" => response.headers["uid"], "token-type" => response.headers["token-type"], 'HTTP_ACCEPT' => "application/json" } return access_headers end end I have this in spec/support/requests_helper.rb module RequestsHelper def get_with_token(path, params={}, headers={}) headers.merge!(retrieve_access_headers) get path, params: params, headers: headers #### this outputs the expected headers on a json string and they seem fine #### puts "headers: "+headers.to_json end end I have included the two helpers in rails_helper.rb as shown below: Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } RSpec.configure do |config| config.include SessionHelper, type: :request config.include RequestsHelper, type: :request end Finally I have a request spec in spec/request/posts/show_spec.rb require 'rspec/its' require 'spec_helper' require 'rails_helper' RSpec.describe 'GET /posts/:id', :type => :request do let(:post) {create(:post)} let(:id) {post.id} let(:request_url) {"/posts/#{id}"} context 'with a registered user' do it 'has a status code of 200' do get_with_token request_url expect(response).to have_http_status(:success) end end end I expect this to pass but it fails with message: Failure/Error: expect(response).to have_http_status(:success) expected the response to have a success status code (2xx) but it was 403 The application works as expected on a browser. What I'm a doing wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/34751750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby on Rails - Scope of Instance Variables with Partial Views I do not understand how to use instance variable properly with partial views, I am hoping someone here can enlighten me. For example: class MainController < ApplicationController def index @item_list = Item.find_all_item end def detail_display @current_selected = @item= Item.find(params[:id]) redirect_to :action => :index end end detail_display is invoked when the user clicks on an item in the list. The variable @current_selected is not available to the partial view invoked when the index is redirected to. How can I remedy this? Thank you A: When you do a redirect, the browser sends an entirely new request, so all of the data from the previous request is inaccessible. You probably don't want to be doing a redirect here; no amount of scope will help you when you're looking at separate runs through your controller. Think about your design a little bit - what are you trying to do? If the selection is something sticky, maybe it should go in the session. If the change is only in a partial, maybe you should use an Ajax call. Maybe the solution is as simple as rendering the index template instead of redirecting to the index action.
{ "language": "en", "url": "https://stackoverflow.com/questions/600498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Script to position chart misaligns when sheet isn't active? I have a script that essentially renders/updates an entire page, including two charts on it. These charts are positioned dynamically using the .top property. I write my scripts intentionally independent of the users currently selected sheet, so there is no .Select or .Activate here. This is the expected result, which works fine when the sheet is active: Notice the Immediate window in the bottom-right. This debug shows the calculation that determined what each chart's .Top property is, which determines the vertical position. The first (Spending) chart's .Top property: Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top = _ Sheets("Overview").Shapes.Range(Array("Add_Category_Button")).Top + 22 Debug.Print "1st: " & _ Sheets("Overview").Shapes.Range(Array("Add_Category_Button")).Top & _ " + 22" & _ " = " & _ Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top ' Note: The Add_Category_Button.Top property is consistent and doesn't change. The second (Income) chart's .Top property: Sheets("Overview").Shapes.Range(Array("Earning_Chart")).Top _ = Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top + _ Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Height Debug.Print "2nd: " & _ Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top & _ " + " & _ Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Height & _ " = " & _ Sheets("Overview").Shapes.Range(Array("Earning_Chart")).Top The second chart's position is determined by the bottom (.Top + .Height) of the first chart. They stack directly on top of eachother. However, when I run this script while on a different sheet, this is the result: First chart aligns fine, but the second one is miscalculated. My confusion is, looking at the debug, the values it retrieves to calculate the .Top are correct, but the result isn't. Also, when I run this function on each sheet, they consistently deliver unique results per sheet: One sheet even messed with the 1st chart calculation. What part of my code is relying on the currently selected sheet? I don't see anything, so it may be some sort of Excel behavior I don't understand. Edit Here's the code used to place the Add_Category_Button shape, which is the only other context there is regarding positioning the charts. I don't see how this could be useful but it was requested. Sheets("Overview").Shapes.Range(Array("Add_Category_Button")).Top = _ Sheets("Overview").Range("B" & Functions.GetCategoryCount + _ Functions.GetAccountCount + 6).Top + 4 The GetCategoryCount and GetAccountCount functions run a CountA worksheet function on a range inside of another sheet, and return that value. Throughout the screenshots provided, those numbers have been the same each time, so it wouldn't relate to the odd positioning issues. Note: The CountA functions are ran without 'selecting' any other sheets or ranges, so the context of the VBA interpreter doesn't change. Other than that information, none of the rest of the code relates to positioning the charts, so I don't see a reason to dump it here. A: It looks like the two sheets in your example are at different zoom levels, theorizing this may be an excel bug: Have you tried with the zoom levels set the same on the active sheet and the sheet containing the plot? If that works you could try getting the location of two vertically adjacent cells on both sheets and then using the difference of the .top values as the 'row height' on each sheet and using the ratio between the active sheet and the target plot's sheets row height as a conversion factor. Another thought (an ugly kludge, since the row height difference is probably not accurate enough) is that you could turn application.screenupdating off (if it's not already 'false'), then create a plot on the active page and get its height and width, then compare that to the height and width of a new plot on the target sheet (and use that for the conversion factor). A: I think it has something to do with not updating "graphically", try making the graph(s) invisible at the beginning of the code and visible again at the end: With Sheets("Overview").ChartObjects("Spending_Chart") .Visible = False 'Do all your stuff including setting the .Top .Visible = True End With A: Hard to say without more of your code. Your snippet works fine on my sample workbook. I don't think this is a code problem as much as an Excel/VBA bug you are hitting. More on that below. One quick comment up front... I don't like your syntax of Shapes.Range(Array("Add_Category_Button")). I would prefer the shorter Shapes("Add_Category_Button") but both work the same for me. Here is my test routine: Sub my_test() Dim i As Integer For i = 1 To ThisWorkbook.Sheets.Count ThisWorkbook.Sheets(i).Activate Debug.Print ActiveSheet.Name Sheets("Overview").Shapes("Pie_Chart").Top = _ Sheets("Overview").Shapes("Add_Category_Button").Top + 22 Debug.Print "1st: " & _ Sheets("Overview").Shapes("Add_Category_Button").Top & _ " + 22 = " & _ Sheets("Overview").Shapes("Pie_Chart").Top Sheets("Overview").Shapes("Column_Chart").Top = _ Sheets("Overview").Shapes("Pie_Chart").Top + _ Sheets("Overview").Shapes("Pie_Chart").Height Debug.Print "2nd: " & _ Sheets("Overview").Shapes("Pie_Chart").Top & _ " + " & _ Sheets("Overview").Shapes("Pie_Chart").Height & _ " = " & _ Sheets("Overview").Shapes("Column_Chart").Top Next i End Sub And my result: Overview 1st: 64 + 22 = 86 2nd: 86 + 216 = 302 Interval 1st: 64 + 22 = 86 2nd: 86 + 216 = 302 1-16 to 1-14 1st: 64 + 22 = 86 2nd: 86 + 216 = 302 1-17 to 1-15 1st: 64 + 22 = 86 2nd: 86 + 216 = 302 Control 1st: 64 + 22 = 86 2nd: 86 + 216 = 302 I tried using different view percentages and got consistent results, though the numbers above changed any time I altered the view percentage on the Overview sheet. I did find I could create some wrong results if I had 2 windows of the same workbook open via View > New Window: Interval 1st: 75.33331 + 22 = 114.6666 2nd: 114.6666 + 258.5001 = 445.3889 1-16 to 1-14 1st: 75.33331 + 22 = 114.6666 2nd: 114.6666 + 310.5001 = 508.9445 1-17 to 1-15 1st: 75.33331 + 22 = 114.6666 2nd: 114.6666 + 374.0557 = 584.0556 Control 1st: 75.33331 + 22 = 114.6666 2nd: 114.6666 + 449.1668 = 676.5002 In my case, I think the height of the chart was changing after setting the .top property. If you have more than one window or form open, I could imagine that you could have a similar issue. This was very finicky and hard to replicate, but I suspect it has to do with situations where .top was changed with different windows and view percentages involved. When I just had one window and no forms my results were solid. In my file, the chart height and width seemed to be altered as well, and I was seeing issues where the chart rendered improperly (for example, the selection box was a different size than the chart as displayed, or part of the chart was truncated). This is why I think this may be a bug. The rendering errors always reset when I reset the chart size, so maybe try also setting the height/width in your code? Sheets("Overview").Shapes("Add_Category_Button").Top = 58 Sheets("Overview").Shapes("Add_Category_Button").Height = 22 Sheets("Overview").Shapes("Pie_Chart").Height = 200 Sheets("Overview").Shapes("Pie_Chart").Width = 300 Sheets("Overview").Shapes("Column_Chart").Height = 200 Sheets("Overview").Shapes("Column_Chart").Width = 300
{ "language": "en", "url": "https://stackoverflow.com/questions/74944204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: building PyMC3 model incorporating different measurements I am trying to incorporate different types and replicates of measurements into one model in PyMC3. Consider the following model: P(t)=P0*exp(-kBt) where P(t), P0, and B are concentrations. k is a rate. We measure P(t) at different times and B once, all through counting of particles. k is the parameter of interest we are trying to infer. My question has two parts: (1) How to incorporate measurements on P(t) and B into one model? (2) How to use a variable number of replicate experiments to inform on the value of k? I think I can answer part (1), but am unsure about whether it is right or done in the right flavour. I failed to generalise the code to include a variable number of replicates. For one experiment (one replicate): ts=np.asarray([time0,time1,...]) counts=np.asarray([countforB,countforPattime0,countforPattime1,...]) basic_model = pm.Model() with basic_model: k=pm.Uniform('k',0,20) B=pm.Uniform('B',0,1000) P=pm.Uniform('P',0,1000) exprate=pm.Deterministic('exprate',k*B) modelmu=pm.math.concatenate(B*(np.asarray([1.0]),P*pm.math.exp(-exprate*ts))) Y_obs=pm.Poisson('Y_obs',mu=modelmu,observed=counts)) I tried to include different replicates along the lines of the above, but to no avail: ... k=pm.Uniform('k',0,20) # same within replicates B=pm.Uniform('B',0,1000,shape=numrepl) # can vary between expts. P=pm.Uniform('P',0,1000,shape=numrepl) # can vary between expts. exprate=??? modelmu=??? A: Multiple Observables PyMC3 supports multiple observables, that is, you can add multiple RandomVariable objects to the graph with the observed argument set. Single Trial In your first case, this would lend some clarity to the model: counts=[countforPattime0, countforPattime1, ...] with pm.Model() as single_trial: # priors k = pm.Uniform('k', 0, 20) B = pm.Uniform('B', 0, 1000) P = pm.Uniform('P', 0, 1000) # transformed RVs rate = pm.Deterministic('exprate', k*B) mu = P*pm.math.exp(-rate*ts) # observations B_obs = pm.Poisson('B_obs', mu=B, observed=countforB) Y_obs = pm.Poisson('Y_obs', mu=mu, observed=counts) Multiple Trials With this additional flexibility, hopefully it makes the transition to multiple trials more obvious. It should go something like: B_cts = np.array(...) # shape (N, 1) Y_cts = np.array(...) # shape (N, M) ts = np.array(...) # shape (1, M) with pm.Model() as multi_trial: # priors k = pm.Uniform('k', 0, 20) B = pm.Uniform('B', 0, 1000, shape=B_cts.shape) P = pm.Uniform('P', 0, 1000, shape=B_cts.shape) # transformed RVs rate = pm.Deterministic('exprate', k*B) mu = P*pm.math.exp(-rate*ts) # observations B_obs = pm.Poisson('B_obs', mu=B, observed=B_cts) Y_obs = pm.Poisson('Y_obs', mu=mu, observed=Y_cts) There might be some extra syntax stuff to get the matrices multiplying correctly, but this at least includes the correct shapes. Priors Once you get that setup working, it would be in your interest to reconsider the priors. I suspect you have more information about the typical values for those than is currently included, especially since this seems like a chemical or physical model. For instance, right now the model says, We believe the true value of B remains fixed for the duration of a trial, but across trials is a completely arbitrary value between 0 and 1000, and measuring it repeatedly within a trial would be Poisson distributed. Typically, one should avoid truncations unless they are excluding meaningless values. Hence, a lower bound of 0 is fine, but the upper bounds are arbitrary. I'd recommend having a look at the Stan Wiki on choosing priors.
{ "language": "en", "url": "https://stackoverflow.com/questions/56186587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Many to many getting "is invalid" error in Rails I am trying to do a many-to-many relation but I get :roles=>[{:error=>:invalid}] when trying to save. Models class User < ApplicationRecord has_many :user_roles, dependent: :destroy has_many :roles, through: :user_roles end class Role < ApplicationRecord has_many :children, :class_name => "Admin::Role", foreign_key: "parent_id" belongs_to :parent, :class_name => "Admin::Role" has_many :user_roles, dependent: :destroy has_many :users, through: :user_roles end class Admin::UserRole < ApplicationRecord belongs_to :user belongs_to :role end Controller def new @user = User.new end def create @user = User.new(user_params) respond_to do |format| if @user.save redirect_to users_url end end end def user_params params.require(:user).permit(:role_ids => []) end _form.html.erb form_with(model: user) do |form| form.collection_select(:role_ids, Roles.all, :id, :title, multiple: "multiple") end Params log "user"=>{"role_ids"=>["", "1"]}
{ "language": "en", "url": "https://stackoverflow.com/questions/52013287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: R: Data Quality Check: Zip Code matching the City Can someone help me to realize an idea in R? I want to achieve, that when R gets an Input File with e.g. a list of companies and their address, it will check wether the zip Code fits to the City for each Company. I have a list of all cities and Zip codes from a certain Country. How can I implement the list into an if sentence? Did someone Programm something similar before? Thanks for ur help! Sandra A: Just a quick example of what one could do. It is, however, probably better to use fuzzy matching for your cities. # City codes (all city codes can be found at https://www.allareacodes.com/) my_city_codes <- data.frame(code = c(201:206), cities = c("Jersey City, NJ", "District of Columbia", "Bridgeport, CT", "Manitoba", "Birmingham, AL", "Seattle, WA"), stringsAsFactors = FALSE) # Function for checking if city/city-code matches those in the registries adress_checker <- function(adress, citycodes) { # Finding real city real_city <- my_city_codes$cities[which(adress$code == my_city_codes$code)] # Checking if cities are the same if(real_city == adress$city) { return("Correct city") } else { return("Incorrect city") } } # Adresses to check right_city <- data.frame(code = 205, city = c("Birmingham, AL"), stringsAsFactors = FALSE) wrong_city <- data.frame(code = 205, city = c("Las Vegas"), stringsAsFactors = FALSE) # Testing function adress_checker(right_city, my_city_codes) [1] "Correct city" adress_checker(wrong_city, my_city_codes) [1] "Incorrect city"
{ "language": "en", "url": "https://stackoverflow.com/questions/53740246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Drawbacks to nesting of child windows? Just for fun I'm developing a native Win32 port of Mozilla XUL. XUL allows to create complex nested structures of all kinds of layout boxes (hbox, vbox, grid, deck..). For my Windows implemenation it would be convenient to implement them as STATIC child windows. Because then I can position their child windows using x & y offsets independent of the position of the parent box. However, this approach may lead to certain windows having a lot of nested child windows. And I wonder if there would be any disadvantages to such a situation. Does anyone here know? A: I've been down this path, and I don't recommend you actually make deep hierarchies of windows. Lots of Windows helper functions (e.g., IsDialogMessage) work better with "traditional" layouts. Also, windows in Windows are relatively heavy objects, mostly for historical reasons. So if you have tons of objects, you could run into limitations, performance problems, etc. What I've done instead is to represent the deeply-nested layout as a tree of regular C++ objects that parallels the flatter hierarchy of actual windows. Some nodes of the object hierarchy have the HWNDs of the "real" windows they represent. You tell the hierarchy to lay out, and the nodes apply the results to the corresponding windows. For example, the root of the hierarchy may represent a dialog window, and the leaf nodes represent the child windows. But the hierarchy has several layers of non-window objects in between that know about layout. A: A rough take on this: * *memory overhead for the window management on application- and os-side *reduced speed due to calls to external library / os which do way more for windows than needed for your application *possibly quite some overhead through long window message paths in complex layouts It probably depends on wether you want a very fast implementation and do efficient buffered drawing by yourself or want it to work more reliably and with less time invested.
{ "language": "en", "url": "https://stackoverflow.com/questions/1482584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create VectorDrawable from String (path)? Is there a way to get SVG path string from the API and create VectorDrawable dynamically? I have been trying to do this for hours without success. Even more, all (!) examples on the Internet explain creating VectorDrawable from XML resources. In my case, XML resource file is pointless as I am trying to fetch SVG path from the Internet API. A: Inflating a drawable from a XML file instead of from resources is actually impossible, because the drawable will try to cast the XmlPullParser to XmlResourceParser which is only implemented by private class XmlBlock.Parser. Even that parser is only used for parsing binary XML files. I tried every possible way of doing this without reflection, it's impossible. So I found documentation on binary XML files and learned how they were made, helped with some compiled binary XML vector drawable files I had. The documentation dates back to 2011 and is still valid, I guess it will most likely remain this way, so future compatibility isn't an issue. A previous version was tested for more than a thousand paths, without problem. The new version posted here should work just as well. (Previous versions are available in the answer history) Compared with loading a drawable directly from resources, I found that there's an average of 14 microseconds or so of extra loading, not noticeable. Here's the code: public class VectorDrawableCreator { private static final byte[][] BIN_XML_STRINGS = { "width".getBytes(), "height".getBytes(), "viewportWidth".getBytes(), "viewportHeight".getBytes(), "fillColor".getBytes(), "pathData".getBytes(), "path".getBytes(), "vector".getBytes(), "http://schemas.android.com/apk/res/android".getBytes() }; private static final int[] BIN_XML_ATTRS = { android.R.attr.height, android.R.attr.width, android.R.attr.viewportWidth, android.R.attr.viewportHeight, android.R.attr.fillColor, android.R.attr.pathData }; private static final short CHUNK_TYPE_XML = 0x0003; private static final short CHUNK_TYPE_STR_POOL = 0x0001; private static final short CHUNK_TYPE_START_TAG = 0x0102; private static final short CHUNK_TYPE_END_TAG = 0x0103; private static final short CHUNK_TYPE_RES_MAP = 0x0180; private static final short VALUE_TYPE_DIMENSION = 0x0500; private static final short VALUE_TYPE_STRING = 0x0300; private static final short VALUE_TYPE_COLOR = 0x1D00; private static final short VALUE_TYPE_FLOAT = 0x0400; /** * Create a vector drawable from a list of paths and colors * @param width drawable width * @param height drawable height * @param viewportWidth vector image width * @param viewportHeight vector image height * @param paths list of path data and colors * @return the vector drawable or null it couldn't be created. */ public static Drawable getVectorDrawable(@NonNull Context context, int width, int height, float viewportWidth, float viewportHeight, List<PathData> paths) { byte[] binXml = createBinaryDrawableXml(width, height, viewportWidth, viewportHeight, paths); try { // Get the binary XML parser (XmlBlock.Parser) and use it to create the drawable // This is the equivalent of what AssetManager#getXml() does @SuppressLint("PrivateApi") Class<?> xmlBlock = Class.forName("android.content.res.XmlBlock"); Constructor xmlBlockConstr = xmlBlock.getConstructor(byte[].class); Method xmlParserNew = xmlBlock.getDeclaredMethod("newParser"); xmlBlockConstr.setAccessible(true); xmlParserNew.setAccessible(true); XmlPullParser parser = (XmlPullParser) xmlParserNew.invoke( xmlBlockConstr.newInstance((Object) binXml)); if (Build.VERSION.SDK_INT >= 24) { return Drawable.createFromXml(context.getResources(), parser); } else { // Before API 24, vector drawables aren't rendered correctly without compat lib final AttributeSet attrs = Xml.asAttributeSet(parser); int type = parser.next(); while (type != XmlPullParser.START_TAG) { type = parser.next(); } return VectorDrawableCompat.createFromXmlInner(context.getResources(), parser, attrs, null); } } catch (Exception e) { Log.e(VectorDrawableCreator.class.getSimpleName(), "Vector creation failed", e); } return null; } private static byte[] createBinaryDrawableXml(int width, int height, float viewportWidth, float viewportHeight, List<PathData> paths) { List<byte[]> stringPool = new ArrayList<>(Arrays.asList(BIN_XML_STRINGS)); for (PathData path : paths) { stringPool.add(path.data); } ByteBuffer bb = ByteBuffer.allocate(8192); // Capacity might have to be greater. bb.order(ByteOrder.LITTLE_ENDIAN); int posBefore; // ==== XML chunk ==== // https://justanapplication.wordpress.com/2011/09/22/android-internals-binary-xml-part-two-the-xml-chunk/ bb.putShort(CHUNK_TYPE_XML); // Type bb.putShort((short) 8); // Header size int xmlSizePos = bb.position(); bb.position(bb.position() + 4); // ==== String pool chunk ==== // https://justanapplication.wordpress.com/2011/09/15/android-internals-resources-part-four-the-stringpool-chunk/ int spStartPos = bb.position(); bb.putShort(CHUNK_TYPE_STR_POOL); // Type bb.putShort((short) 28); // Header size int spSizePos = bb.position(); bb.position(bb.position() + 4); bb.putInt(stringPool.size()); // String count bb.putInt(0); // Style count bb.putInt(1 << 8); // Flags set: encoding is UTF-8 int spStringsStartPos = bb.position(); bb.position(bb.position() + 4); bb.putInt(0); // Styles start // String offsets int offset = 0; for (byte[] str : stringPool) { bb.putInt(offset); offset += str.length + (str.length > 127 ? 5 : 3); } posBefore = bb.position(); bb.putInt(spStringsStartPos, bb.position() - spStartPos); bb.position(posBefore); // String pool for (byte[] str : stringPool) { if (str.length > 127) { byte high = (byte) ((str.length & 0xFF00 | 0x8000) >>> 8); byte low = (byte) (str.length & 0xFF); bb.put(high); bb.put(low); bb.put(high); bb.put(low); } else { byte len = (byte) str.length; bb.put(len); bb.put(len); } bb.put(str); bb.put((byte) 0); } if (bb.position() % 4 != 0) { // Padding to align on 32-bit bb.put(new byte[4 - (bb.position() % 4)]); } // Write string pool chunk size posBefore = bb.position(); bb.putInt(spSizePos, bb.position() - spStartPos); bb.position(posBefore); // ==== Resource map chunk ==== // https://justanapplication.wordpress.com/2011/09/23/android-internals-binary-xml-part-four-the-xml-resource-map-chunk/ bb.putShort(CHUNK_TYPE_RES_MAP); // Type bb.putShort((short) 8); // Header size bb.putInt(8 + BIN_XML_ATTRS.length * 4); // Chunk size for (int attr : BIN_XML_ATTRS) { bb.putInt(attr); } // ==== Vector start tag ==== int vstStartPos = bb.position(); int vstSizePos = putStartTag(bb, 7, 4); // Attributes // android:width="24dp", value type: dimension (dp) putAttribute(bb, 0, -1, VALUE_TYPE_DIMENSION, (width << 8) + 1); // android:height="24dp", value type: dimension (dp) putAttribute(bb, 1, -1, VALUE_TYPE_DIMENSION, (height << 8) + 1); // android:viewportWidth="24", value type: float putAttribute(bb, 2, -1, VALUE_TYPE_FLOAT, Float.floatToRawIntBits(viewportWidth)); // android:viewportHeight="24", value type: float putAttribute(bb, 3, -1, VALUE_TYPE_FLOAT, Float.floatToRawIntBits(viewportHeight)); // Write vector start tag chunk size posBefore = bb.position(); bb.putInt(vstSizePos, bb.position() - vstStartPos); bb.position(posBefore); for (int i = 0; i < paths.size(); i++) { // ==== Path start tag ==== int pstStartPos = bb.position(); int pstSizePos = putStartTag(bb, 6, 2); // android:fillColor="#aarrggbb", value type: #rgb. putAttribute(bb, 4, -1, VALUE_TYPE_COLOR, paths.get(i).color); // android:pathData="...", value type: string putAttribute(bb, 5, 9 + i, VALUE_TYPE_STRING, 9 + i); // Write path start tag chunk size posBefore = bb.position(); bb.putInt(pstSizePos, bb.position() - pstStartPos); bb.position(posBefore); // ==== Path end tag ==== putEndTag(bb, 6); } // ==== Vector end tag ==== putEndTag(bb, 7); // Write XML chunk size posBefore = bb.position(); bb.putInt(xmlSizePos, bb.position()); bb.position(posBefore); // Return binary XML byte array byte[] binXml = new byte[bb.position()]; bb.rewind(); bb.get(binXml); return binXml; } private static int putStartTag(ByteBuffer bb, int name, int attributeCount) { // https://justanapplication.wordpress.com/2011/09/25/android-internals-binary-xml-part-six-the-xml-start-element-chunk/ bb.putShort(CHUNK_TYPE_START_TAG); bb.putShort((short) 16); // Header size int sizePos = bb.position(); bb.putInt(0); // Size, to be set later bb.putInt(0); // Line number: None bb.putInt(-1); // Comment: None bb.putInt(-1); // Namespace: None bb.putInt(name); bb.putShort((short) 0x14); // Attributes start offset bb.putShort((short) 0x14); // Attributes size bb.putShort((short) attributeCount); // Attribute count bb.putShort((short) 0); // ID attr: none bb.putShort((short) 0); // Class attr: none bb.putShort((short) 0); // Style attr: none return sizePos; } private static void putEndTag(ByteBuffer bb, int name) { // https://justanapplication.wordpress.com/2011/09/26/android-internals-binary-xml-part-seven-the-xml-end-element-chunk/ bb.putShort(CHUNK_TYPE_END_TAG); bb.putShort((short) 16); // Header size bb.putInt(24); // Chunk size bb.putInt(0); // Line number: none bb.putInt(-1); // Comment: none bb.putInt(-1); // Namespace: none bb.putInt(name); // Name: vector } private static void putAttribute(ByteBuffer bb, int name, int rawValue, short valueType, int valueData) { // https://justanapplication.wordpress.com/2011/09/19/android-internals-resources-part-eight-resource-entries-and-values/#struct_Res_value bb.putInt(8); // Namespace index in string pool (always the android namespace) bb.putInt(name); bb.putInt(rawValue); bb.putShort((short) 0x08); // Value size bb.putShort(valueType); bb.putInt(valueData); } public static class PathData { public byte[] data; public int color; public PathData(byte[] data, int color) { this.data = data; this.color = color; } public PathData(String data, int color) { this(data.getBytes(StandardCharsets.UTF_8), color); } } } A call to getVectorDrawable returns a VectorDrawable from a list of paths. The drawable can contain multiple paths with different colors. There are also parameters for the drawable and viewport size. Here's an example: List<PathData> pathList = Arrays.asList(new PathData("M128.09 5.02a110.08 110.08 0 0 0-110 110h220a109.89 109.89 0 0 0-110-110z", Color.parseColor("#7cb342")), new PathData("M128.09 115.02h-110a110.08 110.08 0 0 0 110 110 110.08 110.08 0 0 0 110-110z", Color.parseColor("#8bc34a")), new PathData("M207.4 115.2v-.18h-5.1l-61.43-61.43h-25.48v20.6h-6.5a11.57 11.57 0 0 0-11.53 11.53v26.09h.11c-.11.9.5 2 1.7 3.32.12.08.12.08.12.2l3.96 4-46.11 79.91c5.33 4.5 11.04 8.4 17 11.8a109.81 109.81 0 0 0 108.04 0 110.04 110.04 0 0 0 51.52-64.65c.38-1.28.68-2.57 1.1-3.78z", Color.parseColor("#30000000")), new PathData("M216.28 230.24a6.27 6.27 0 0 0-.9-2.8l-31.99-55.57-10.58-18.48-19.85-34.21-15.08 15.12 18.6 32.28 10.2 17.73 30.92 53.37a5.6 5.6 0 0 0 1.97 2.12l15.42 10.5c.6.39 1.29.39 1.9.08.6-.37.9-.98.9-1.7z", Color.parseColor("#e1e1e1")), new PathData("M186.98 115.02a58.9 58.9 0 0 1-30.5 51.6 58.4 58.4 0 0 1-56.7 0l18.6-32.28-15.13-15.12-62.48 108.22c-.5.9-.8 1.78-.9 2.8l-1.4 18.6c-.12.71.3 1.28.9 1.7.6.37 1.29.3 1.9-.12l15.41-10.4a7.87 7.87 0 0 0 1.97-2.07l30.92-53.53a78.74 78.74 0 0 0 77.23 0 76.65 76.65 0 0 0 16.6-12.4 79.3 79.3 0 0 0 24.07-56.89z", Color.parseColor("#f1f1f1")), new PathData("M147.3 74.12h-6.43v-20.6h-25.48v20.6h-6.5a11.57 11.57 0 0 0-11.53 11.5v26.07h.11c-.11 1.02.5 2.12 1.82 3.4l23.05 23.14a8.3 8.3 0 0 0 5.75 2.38v-.07l.07.07c2.12 0 4.2-.75 5.71-2.38l23.1-23.1c1.32-1.32 1.81-2.53 1.81-3.4h.12V85.7a11.68 11.68 0 0 0-11.6-11.6zm-19.14 40.9h-.07a15.4 15.4 0 0 1 0-30.8v-.2l.07.2a15.46 15.46 0 0 1 15.31 15.38 15.46 15.46 0 0 1-15.3 15.42z", Color.parseColor("#646464"))); A: @Andre.Anzi To extend the class to support strokeColor and strokeWidth, you can try to arrange the attributes in an alphabetical order.
{ "language": "en", "url": "https://stackoverflow.com/questions/33312157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Ionic Cordova Device UUID Hi i am developing a hybrid app using the Ionic framework and Cordova. I am looking to use the device uuid as an ID so i have added the cordova device plugin. Additionally i am using the NG-Cordova wrapper for calling my cordova plugins. However whenever i run my app in the xcode Simulator or on an actual Ipad all i get is {{uuid}} . There does not seem to be any error message i can only assume that the Device Plugin is not working. i have put my code below however im not sure this is the issue, Has anyone had this issue before and if so how did they work around it? Controller: angular.module('starter.controllers', []).controller('DashCtrl', function( $scope, $state, $cordovaDevice) { var init = function() { console.log("initializing device"); try { $scope.uuid = $cordovaDevice.getUUID(); } catch (err) { console.log("Error " + err.message); alert("error " + err.$$failure.message); } }; init(); }) Html <ion-view title="Dashboard"> <ion-content class="padding"> <h1>Dash</h1> {{uuid}} </ion-content> </ion-view> app.js angular.module('starter', ['ionic', 'starter.controllers', 'starter.services']) .run(function($ionicPlatform) { $ionicPlatform.ready(function() { if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar( true); } if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } }); }).config(function($stateProvider, $urlRouterProvider) { $stateProvider // setup an abstract state for the tabs directive .state('tab', { url: "/tab", abstract: true, templateUrl: "templates/tabs.html" }) // Each tab has its own nav history stack: .state('tab.dash', { url: '/dash', views: { 'tab-dash': { templateUrl: 'templates/tab-dash.html', controller: 'DashCtrl' } } }); // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/tab/dash'); }); A: the reason behind my issue was due to using a custom build of ngCordova. if i just the normal or Minified version of ngcordova it works perfectly. Thanks for all the help.
{ "language": "en", "url": "https://stackoverflow.com/questions/27313689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Docker Remote API to login to registry I am looking for documentation for docker login, I need to login to a registry to pull docker image and I need to do it remotely using docker remote APIs. But unfortunately I am unable to find docker remote API docs, any help would be greatly appreciated. API doc : https://docs.docker.com/engine/reference/api/docker_remote_api_v1.19/ Thanks in advance. Sarath Krishnan A: you go as docker login your.domain.to.the.registr.without.protocol.or.port enter username enter password now you can pull using docker pull your.domain.to.the.registr.without.protocol.or.port/youimage Ensure your registry runs behind a SSL proxy / termination, or you run into security issues. Consider reading this in this case https://docs.docker.com/registry/insecure/
{ "language": "en", "url": "https://stackoverflow.com/questions/39109712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Nginx conditional rewrite I am trying to redirect domain1.com to domain2.com based on http/https. * *So a request to http://domain1.com will go to http://domain2.com. *Request to https://domain1.com goes to https://domain2.com My current Nginx vhost file setup as: server { listen 80; listen 443 ssl; ssl_certificate /etc/nginx/xxx.crt; ssl_certificate_key /etc/nginx/xxx.key; server_name *.domain1.com; if ( $scheme = "https" ) { rewrite ^ https://domain2.com$request_uri? permanent; } rewrite ^ http://domain2.com$request_uri? permanent; } However visiting https://domain1.com just goes to http://domain2.com. I can't seem to detect https. What am I doing wrong? Thanks. EDIT: I have edited my vhost to the below but the same issue occurs.: server { listen 80; listen 443 ssl; ssl_certificate /etc/nginx/xxx.crt; ssl_certificate_key /etc/nginx/xxx.key; server_name *.domain1.com domain1.com; return 301 $scheme://domain2.com$request_uri; } A: There is no need to use if and rewrite return 301 $scheme://domain2.com$request_uri;
{ "language": "en", "url": "https://stackoverflow.com/questions/26396066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python: all index of list greater than x data = [10, 90, 20, 80, 30, 40, 70, 60] A_list=[A,B,C,D,E,F,G,H] How do I find all the values in data that are above 50. Next how do I print so that it displays B:90 D:80 H:60 G:70 Also I haven't used enumerate yet. A: If you just want to print all the values higher then 50 a simple loop will do. data = [10, 90, 20, 80, 30, 40, 70, 60] for value in data: if value > 50: print(value) If you need the indexes use this code. enumerate will give you an automatic counter. data = [10, 90, 20, 80, 30, 40, 70, 60] for index, value in enumerate(data): if value > 50: print(index) If you need a list of indexes to print the values (your question is unclear at that point) then construct this list and loop over it. data = [10, 90, 20, 80, 30, 40, 70, 60] indexes = [index for index, value in enumerate(data) if value > 50] for index in indexes: print(data[index]) According to the question in your comment you could do the following (based on the last solution). data = [10, 90, 20, 80, 30, 40, 70, 60] characters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] indexes = [index for index, value in enumerate(data) if value > 50] for index in indexes: print('{}: {}'.format(characters[index], data[index])) This code uses the index for both lists. If this is homework and you can't use enumerate you have to construct the indexes list with a standard for loop. indexes = [] for index in range(len(data)): if data[index] > 50: indexes.append(index) A pythonic solution would be something like this. data = [10, 90, 20, 80, 30, 40, 70, 60] characters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] for char, value in zip(characters, data): if value > 50: print('{}: {}'.format(char, value)) A: In case you want the elements of the list which are greater than 50, you can simply use a list comprehension: [el for el in lst if el>50] where lst is your input list. If you also wanted the index of those elements, you could: [(i,el) for (i,el) in enumerate(lst) if el>50] which would give you a list of tuples (index, element) A: You want an if loop; if x is greater than one of the numbers, print it? example: myList = list(range(0,100)) for numb in myList: if numb > 50: print numb Honestly, I'm not sure what OP wants to do. But this is just an example. A: If you would like to use enumerate(), and you would like to store both the indexes of the numbers above 50 and the values themselves, one way would be to do it like so: >>> a = [1,2,3,4,5,50,51,3,53,57] >>> b, c = zip(*[(d, x) for d, x in enumerate(a) if x > 50]) >>> print b (6, 8, 9) >>> print c (51, 53, 57) Enumerate takes any object that supports iteration, and returns a tuple, (count, value), when the next() method of the iterator is called. Since enumerate() defaults to start its count at 0, and increments the count by one each iteration, we can use it to count the index of the array that the iteration is currently on. Now, our list comprehension is returning a list of tuples, if we were to print the comprehension we would get: >>> print [(d, x) for d, x in enumerate(a) if x > 50] [(6, 51),(8, 53),(9, 57)] Zip creates a list of tuples when given two arrays, for example: >>> f = [1, 2, 3] >>> g = [4, 5, 6] >>> zipped = zip(f, g) >>> zipped [(1, 4), (2, 5), (3, 6)] When used with the * operator, zip() will "unzip" a list. So, when we "unzip" the list comprehension, two tuples are returned. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/30149084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: rails multiple belongs_to assignments with nested attributes My problem is that how to assign multiple belongs_to associations with nested attributes? I want to build a issue system. When I create a issue, I also want to create the first comment as the issue body. So, I have following Models: class Issue < ActiveRecord::Base has_many :comments, as: :commentable validates :title, presence: true accepts_nested_attributes_for :comments end class Comment < ActiveRecord::Base belongs_to :user belongs_to :commentable, polymorphic: true validates :content, :user, presence: true end and I have the IssuesController as follow: class IssuesController < ApplicationController before_action :authenticate_user! #devise authentication def new @issue = Issue.new @issue.comments.build end def create @issue = Issue.new(issue_params) @issue.save end private def issue_params params.require(:issue).permit(:title, comments_attributes: [:content]) end end and the following is my form (using slim template with simple_form and nested_form gems): = simple_nested_form_for @issue do |f| = f.input :title = f.fields_for :comments do |cf| = cf.input :content = f.button :submit In this case, I don't know how to assign current_user to the comment created by nested attributes. Any suggestions or other approaches? Thanks! A: As I wrote in the comments, there's two ways of doing this. The first way is to add a hidden field in your subform to set the current user: = simple_nested_form_for(@issue) do |f| = f.input :title = f.fields_for(:comments) do |cf| = cf.input(:content) = cf.hidden(:user, current_user) = f.submit If you do not trust this approach in fear of your users fiddling with the fields in the browser, you can also do this in your controller. class IssuesController < ApplicationController before_action :authenticate_user! #devise authentication def new @issue = Issue.new @issue.comments.build end def create @issue = Issue.new(issue_params) @issue.comments.first.user = current_user @issue.save end private def issue_params params.require(:issue).permit(:title, comments_attributes: [:content]) end end This way you take the first comment that is created through the form and just manually assign the user to it. Then you know for the sure that the first created comment belongs to your current user. A: You could also add user_id as current_user.id when you use params class IssuesController < ApplicationController before_action :authenticate_user! #devise authentication def new @issue = Issue.new @issue.comments.build end def create @issue = Issue.new(issue_params) @issue.save end private def issue_params params[:issue][:comment][:user_id] = current_user.id params.require(:issue).permit(:title, comments_attributes: [:content, :user_id]) end end
{ "language": "en", "url": "https://stackoverflow.com/questions/27505297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: htaccess not get index file after rewrite rule My htaccess is this : <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^([0-9a-zA-Z-]+)?$ show.php?id=$1 [L] </IfModule> So whenever browser get 'any thing' after root folder then it will go show.php and parameter will be 'any thing' . Note: it will not effect if it have extension or a folder. But there is index file in my root folder. So browser should take index file first. So that, i added this in .htaccess file : DirectoryIndex index.php But not working. So is there anything to do, to show at least index file whenever root folder visited ? A: You can have your .htaccess like this: DirectoryIndex index.php RewriteEngine On # request is not for a file RewriteCond %{REQUEST_FILENAME} !-f # request is not for a directory RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([0-9a-zA-Z-]+)/?$ /show.php?id=$1 [L,QSA]
{ "language": "en", "url": "https://stackoverflow.com/questions/21060467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Winform app GUI is not showing run as scheduled task using .BAT file I have created a winform app for sending bulk emails. I have scheduled this app using a .BAT file. The app is running as per the schedule and sending emails, but it is not showing the GUI. When I search I found this link Winforms app as Scheduled task, As per that I have confirmed that I am using the same user account for scheduling the task and login into the machine. When I double click on the .BAT file, the app is running by showing the GUI. Does anybody knows what is the issue. Here is the content in my .BAT file. c: cd\ cd ABC sendMailApp.exe A: On your last line, you could try using call start sendMailApp.exe I think this might fix it, call will cause start to run a new process and open a new window for the process which should show the GUI. Docs here: http://ss64.com/nt/call.html http://ss64.com/nt/start.html
{ "language": "en", "url": "https://stackoverflow.com/questions/15360456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ImageView on top of another imageview in Android I am having a navigation drawer (sliding menu) with header set in my app. I am trying out the following for the headerView.xml I am setting a background image to the relativeLayout from a particular URL. Instead I would like to have ImageView like below: By doing this I can use picasso library even for background image that I receive from an URL. This way the image loading is faster I don't need to save the background to any sd card etc. Here is what I have right now: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LayoutforbgImage" android:layout_width="match_parent" android:layout_height="match_parent" android:adjustViewBounds="true" android:baselineAligned="false" android:orientation="horizontal" > <LinearLayout android:id="@+id/LinearLayoutforImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="10dp" android:paddingLeft="5dp" android:paddingTop="10dp" tools:ignore="RtlSymmetry,RtlHardcoded" > <ImageView android:id="@+id/imageforprofile" android:layout_width="60dp" android:layout_height="60dp" android:src="@drawable/profilepic" /> </LinearLayout> <TextView android:id="@+id/textforprofile" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@+id/LinearLayoutforImage" android:gravity="left" android:paddingLeft="5dp" android:paddingTop="16dp" android:text="My Name My Name" android:textColor="#FFFFFF" android:textStyle="bold" tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" /> <TextView android:id="@+id/textforprofileemail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textforprofile" android:layout_toRightOf="@+id/LinearLayoutforImage" android:gravity="left" android:paddingBottom="10dp" android:paddingLeft="5dp" android:text="[email protected]" android:textColor="#FFFFFF" android:textStyle="bold" tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" /> </RelativeLayout> I am setting background image to layout for: LayoutforbgImage using: headerLayout = (RelativeLayout) header.findViewById(R.id.LayoutforbgImage ); BitmapDrawable background = new BitmapDrawable(decodeBase64(coverimage)); headerLayout.setBackgroundDrawable(background); headerprofileimage = (ImageView) header.findViewById(R.id.imageforprofile); Picasso.with(this).load(profileImage).placeholder(R.drawable.profilepic).error(R.drawable.profilepic).into(headerprofileimage); How do I create the ImageView for background image so that it fits perfectly in the layout specified like above? A: Try this layout i hope it will help you <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="fitXY" android:src="@drawable/top_header_bg" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="horizontal" > <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:src="@drawable/ic_launcher" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:layout_marginRight="20dp" android:orientation="vertical" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> </LinearLayout> </LinearLayout> </RelativeLayout> </LinearLayout> A: hi try the following code it will help you i didn't make any changes. i simply add an ImageView to your layout. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LayoutforbgImage" android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:baselineAligned="false" android:orientation="horizontal" > <ImageView android:id="@+id/your_image" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:background="@drawable/top_bar" /> <LinearLayout android:id="@+id/LinearLayoutforImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingBottom="10dp" android:paddingLeft="5dp" android:paddingTop="10dp" tools:ignore="RtlSymmetry,RtlHardcoded" > <ImageView android:id="@+id/imageforprofile" android:layout_width="60dp" android:layout_height="60dp" android:src="@drawable/images12" /> </LinearLayout> <TextView android:id="@+id/textforprofile" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@+id/LinearLayoutforImage" android:gravity="left" android:paddingLeft="5dp" android:paddingTop="16dp" android:text="My Name My Name" android:textColor="#FFFFFF" android:textStyle="bold" tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" /> <TextView android:id="@+id/textforprofileemail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textforprofile" android:layout_toRightOf="@+id/LinearLayoutforImage" android:gravity="left" android:paddingBottom="10dp" android:paddingLeft="5dp" android:text="[email protected]" android:textColor="#FFFFFF" android:textStyle="bold" tools:ignore="HardcodedText,RtlHardcoded,RtlSymmetry" /> </RelativeLayout> A: Try this way hope it will solve your problem <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <RelativeLayout android:id="@+id/topBarRelative" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" > <ImageView android:id="@+id/imageHeader" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:adjustViewBounds="true" android:cropToPadding="false" android:src="@drawable/right_top_bg" /> <ImageView android:id="@+id/imageforprofile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:layout_marginLeft="9dp" android:src="@drawable/ic_launcher" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginRight="9dp" android:layout_toRightOf="@+id/imageforprofile" android:gravity="center" android:orientation="vertical" > <TextView android:id="@+id/textforprofile" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="3dp" android:text="My Name My Name" android:textColor="#FFFFFF" android:textStyle="bold" /> <TextView android:id="@+id/textforprofileemail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="[email protected]" android:textColor="#FFFFFF" android:textStyle="bold" /> </LinearLayout> </RelativeLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_below="@+id/topBarRelative" android:layout_margin="8dp" android:background="@drawable/content_bg" android:orientation="vertical" > </LinearLayout> </RelativeLayout> Screen shot from Eclipse
{ "language": "en", "url": "https://stackoverflow.com/questions/25697042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Real time video player to embed in an Android app I need a library that supports real time video streaming from an RTSP connection to embed in an Android application I've built. It must have a really low latency (1-2s should be fine). I've already tried with a simple VideoView. It works but it has a HUGE latency (more than 10s) because its buffer size cannot be lowered. Is there any good and reliable solution? I would prefer not to build my own player from scratch... ExoPlayer doesn't seem to support RTSP. A: I have solved using a modified version of Exoplayer (RTSP Exoplayer GitHub pull request). The buffer size can be edited, so I think it's the best choice for this use case. It works flawlessly!
{ "language": "en", "url": "https://stackoverflow.com/questions/57760821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does the JVM JIT generate syscall instructions? I am wondering how does Java code make a syscall, does the JIT compiler generate syscall instructions directly, or that it just put calls to libc functions (or other basic library functions)? A: The Hotspot JVM generates machine code for Java code (which doesn't support making syscalls). All code which makes syscalls is in a native method. So when Java wants to make a syscalls, you have to call some native code to do it for you. There are libraries you can use to wrap native calls. E.g. JNA and JNR-FFI. This allows you call c libraries without writhing native code.
{ "language": "en", "url": "https://stackoverflow.com/questions/53690811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Reading a file with Rust - borrowed value only lives until here I have a function that should read a file and returns it's contents. fn read (file_name: &str) -> &str { let mut f = File::open(file_name) .expect(&format!("file not found: {}", file_name)); let mut contents = String::new(); f.read_to_string(&mut contents) .expect(&format!("cannot read file {}", file_name)); return &contents; } But I get this error: --> src\main.rs:20:13 | 20 | return &contents; | ^^^^^^^^ borrowed value does not live long enough 21 | } | - borrowed value only lives until here | What am I doing wrong? My Idea of what is happening here is this: * *let mut f = File::open(file_name).expect(....); - this takes a handle of a file and tells the OS that we want to do things with it. *let mut contents = String::new(); - this creates a vector-like data structure on the heap in order to store the data that we are about to read from the file. *f.read_to_string(&mut contents).expect(...); - this reads the file into the contents space. *return &contents; - this returns a pointer to the vector where the file data is stored. Why am I not able to return the pointer that I want? How do I close my file (the f variable)? I think that rust will close it for me after the variable goes out of scope, but what If I need to close it before that? A: You are correct about the file handle being closed automatically when its variable goes out of scope; the same will happen to contents, though - it will be destroyed at the end of the function, unless you decide to return it as an owned String. In Rust functions can't return references to objects created inside them, only to those passed to them as arguments. You can fix your function as follows: fn read(file_name: &str) -> String { let mut f = File::open(file_name) .expect(&format!("file not found: {}", file_name)); let mut contents = String::new(); f.read_to_string(&mut contents) .expect(&format!("cannot read file {}", file_name)); contents } Alternatively, you can pass contents as a mutable reference to the read function: fn read(file_name: &str, contents: &mut String) { ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/51179353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ffmpeg -r option I am trying to use ffmpeg (under linux) to add a small title to a video. So, I use: ffmpeg -i hk.avi -r 30000/1001 -metadata title="SOF" hk_titled.avi The addition of title seems to work, but, the problem is the output file is about a 1/3rd of the file size of the input file and I was wondering why this is? Is this at the expense of quality of the video? I am unsure.. How do I preserve the same quality/size as the input file? The main point I am unable to figure out is the use of -r option. Going through the ffmpeg docs, it seems to suggest that -r is frames per second (The input video is 23.9fps). At the moment, (30000/1001) works out to 29 fps, but I was unsure if I should be using this value. Thanks for your time. A: The default settings for ffmpeg do not always provide a good quality output when you encode, but this depends on your output format and the available encoders. With your output ffmpeg will use the default of -b 200k or -b:v 200k. However, you can tell ffmpeg to simply copy the input streams without re-encoding and this is recommended if you just want to add or edit metadata. These examples do the same thing but use different syntax depending on your ffmpeg version: ffmpeg -i hk.avi -vcodec copy -acodec copy -metadata title="SOF" hk_titled.avi ffmpeg -i hk.avi -c copy -metadata title="SOF" hk_titled.avi
{ "language": "en", "url": "https://stackoverflow.com/questions/10972569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Slice a list into batches based on byte size Haven't found a similar question I want to slice an array into smaller batches based on byte size limit. This is my implementation which is a little slow. In particular I want to know if there is a build-in functionality that can get me this, or maybe I can enhance my approach below. When i accumulated the size of individual items it didn't correlate correctly to the size of the batch. probably extra metadata on the stream itself.. private static List<List<T>> SliceLogsIntoBatches<T>(List<T> data) where T : Log { const long batchSizeLimitInBytes = 1048576; var batches = new List<List<T>>(); while (data.Count > 0) { var batch = new List<T>(); batch.AddRange(data.TakeWhile((log) => { var currentBatchSizeInBytes = GetObjectSizeInBytes(batch); // this will slow down as takewhile moves on return (currentBatchSizeInBytes < batchSizeLimitInBytes); })); batches.Add(batch); data = data.Except(batch).ToList(); } return batches; } private static long GetObjectSizeInBytes(object objectToGetSizeFor) { using (var objectAsStream = ConvertObjectToMemoryStream(objectToGetSizeFor)) { return objectAsStream.Length; } } A: You keep recalculating the size of the batch you are creating. So you are recalculating the size of some data items a lot. It would help if you would calculate the data size of each data item and simply add that to a variable to keep track of the current batch size. Try something like this: long batchSizeLimitInBytes = 1048576; var batches = new List<List<T>>(); var currentBatch = new List<T>(); var currentBatchLength = 0; for (int i = 0; i < data.Count; i++) { var currentData = data[i]; var currentDataLength = GetObjectSizeInBytes(currentData); if (currentBatchLength + currentDataLength > batchSizeLimitInBytes) { batches.Add(currentBatch); currentBatchLength = 0; currentBatch = new List<T>(); } currentBatch.Add(currentData); currentBatchLength += currentDataLength; } As a sidenote, I would probably only want to convert the data to byte streams only once, since this is an expensive operation. You currently convert to streams just to check the length, you may want ot have this method actually return the streams batched, instead of List<List<T>>. A: I think that your approach can be enhanced using the next idea: we can calculate an approximate size of the batch as sum of sizes of data objects; and then use this approximate batch size to form an actual batch; actual batch size is a size of list of data objects. If we use this idea we can reduce the number of invocations of the method GetObjectSizeInBytes. Here is the code that implements this idea: private static List<List<T>> SliceLogsIntoBatches<T>(List<T> data) where T : Log { const long batchSizeLimitInBytes = 1048576; var batches = new List<List<T>>(); var currentBatch = new List<T>(); // At first, we calculate size of each data object. // We will use them to calculate an approximate size of the batch. List<long> sizes = data.Select(GetObjectSizeInBytes).ToList(); int index = 0; // Approximate size of the batch. long dataSize = 0; while (index < data.Count) { dataSize += sizes[index]; if (dataSize <= batchSizeLimitInBytes) { currentBatch.Add(data[index]); index++; } // If approximate size of the current batch is greater // than max batch size we try to form an actual batch by: // 1. calculating actual batch size via GetObjectSizeInBytes method; // and then // 2. excluding excess data objects if actual batch size is greater // than max batch size. if (dataSize > batchSizeLimitInBytes || index >= data.Count) { // This loop excludes excess data objects if actual batch size // is greater than max batch size. while (GetObjectSizeInBytes(currentBatch) > batchSizeLimitInBytes) { index--; currentBatch.RemoveAt(currentBatch.Count - 1); } batches.Add(currentBatch); currentBatch = new List<T>(); dataSize = 0; } } return batches; } Here is complete sample that demostrates this approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/61083035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: libcurl fails (response code 0 - host not found) in program (built with MinGW) if using bundled libcurl-4.dll I've ported an application over to windows using MinGW and want to distribute it with all the dlls it needs to run. The app requires libcurl for some ssl (https) requests it makes. To distribute it I copied all the .dlls & put them alongside the .exe. That runs fine but whenever it attempts to make a request in curl it gets a 0 response (as in host not found - not zero okay). The program works fine if I don't use my copy of libcurl-4.dll but instead use the one bundled with msys2. Why does this happen? I checked in process explorer and the only difference between it working or not is if it uses my copy of libcurl-4.dll (all other dependencies of curl copied fine). ^ that's when it works (using git for window's .dll -- if I copied that dll to next to the program it'd fail) A: If your libcurl function invoke actually returns zero, then it was invoked fine and there's no problem with your DLLs or similar, but sounds like like you need to tweak your libcurl usage. A: I've found the reason but I don't know a decent solution. The bundled libcurl-4.dll only works for https requests if you also bundle the ssl folder that contains certificates. I feel like this is something where it should be using the OS' certs (Windows) but I don't know how to do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/61670389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MPMoviePlayer loading the video but never enters readyToPlay state I have been trying to get a video to play using MPMoviePlayerController for about a week with very little success! I have finally got it to the stage where it loads the video (or at least I presume it does as it can tell me the video duration). However, my video never becomes playable therefore I am just presented with a black square. My code is as follows: - (void)loadMovieWithURL:(NSURL *)movieURL { NSLog( @"Video URL = '%@'", [movieURL path]); NSData *data = [NSData dataWithContentsOfURL:movieURL]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerPlaybackStateDidChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil]; MPMoviePlayerController *mp = [[MPMoviePlayerController alloc] init]; self.moviePlayer = mp; [self.moviePlayer.view setFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)]; [self addSubview:self.moviePlayer.view]; [self.moviePlayer setContentURL:movieURL]; self.moviePlayer.movieSourceType = MPMovieSourceTypeFile; [self.moviePlayer setFullscreen:NO]; [self.moviePlayer setScalingMode:MPMovieScalingModeFill]; [self.moviePlayer setControlStyle:MPMovieControlStyleNone]; //[self.moviePlayer setShouldAutoplay:YES]; [self.moviePlayer prepareToPlay]; [self.moviePlayer play]; } I am printing out a lot of the values to NSLog just to check them, so thought I should provide them below too just to give a better idea of what I'm seeing: 2013-01-07 15:33:39.858 WildMap_iOS[9887:16703] Video URL = '/Users/elliott/Library/Application Support/iPhone Simulator/6.0/Applications/A233395A-3E8F-4E35-BF42-09D9B743EA33/test.3gp' 2013-01-07 15:33:40.100 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Disabling autoplay for pause 2013-01-07 15:33:40.101 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Disabling autoplay 2013-01-07 15:33:40.176 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Enabling autoplay 2013-01-07 15:33:40.179 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Likely to keep up or full buffer: 0 2013-01-07 15:33:40.180 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Skipping autoplay, not enough buffered to keep up. 2013-01-07 15:33:40.181 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Likely to keep up or full buffer: 0 2013-01-07 15:33:40.182 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Skipping autoplay, not enough buffered to keep up. 2013-01-07 15:33:40.259 WildMap_iOS[9887:16703] [MPCloudAssetDownloadController] Prioritization requested for media item ID: 0 2013-01-07 15:33:40.401 WildMap_iOS[9887:16703] [MPAVController] Autoplay: Enabling autoplay 2013-01-07 15:33:41.344 WildMap_iOS[9887:16703] Is ready to display 0 2013-01-07 15:33:41.344 WildMap_iOS[9887:16703] Duration: 45.267000 I did setup a notification to check for MPMoviePlayerLoadStateDidChangeNotification but it never changes. Has anyone had a similar issue, or know what could be wrong with my code? If you need anymore information feel free to ask. EDIT 1 (Testing danh's code) When using the following: NSLog( @"Video URL = '%@'", [movieURL path]); self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL]; self.moviePlayer.view.frame = self.bounds; [self addSubview:self.moviePlayer.view]; [self.moviePlayer prepareToPlay]; //NSData *data = [NSData dataWithContentsOfURL:movieURL]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerPlaybackStateDidChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerLoadStateChanged:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil]; My logs are: 2013-01-08 12:08:16.105 WildMap_iOS[705:16703] [MPAVController] Autoplay: Disabling autoplay for pause 2013-01-08 12:08:16.105 WildMap_iOS[705:16703] [MPAVController] Autoplay: Disabling autoplay 2013-01-08 12:08:16.138 WildMap_iOS[705:16703] [MPAVController] Autoplay: Skipping autoplay, disabled (for current item: 1, on player: 0) 2013-01-08 12:08:16.144 WildMap_iOS[705:16703] [MPAVController] Autoplay: Enabling autoplay 2013-01-08 12:08:16.153 WildMap_iOS[705:16703] [MPAVController] Autoplay: Likely to keep up or full buffer: 0 2013-01-08 12:08:16.153 WildMap_iOS[705:16703] [MPAVController] Autoplay: Skipping autoplay, not enough buffered to keep up. 2013-01-08 12:08:16.157 WildMap_iOS[705:16703] [MPCloudAssetDownloadController] Prioritization requested for media item ID: 0 2013-01-08 12:08:16.177 WildMap_iOS[705:16703] [MPAVController] Autoplay: Enabling autoplay 2013-01-08 12:08:17.244 WildMap_iOS[705:16703] Is ready to display 0 2013-01-08 12:08:17.244 WildMap_iOS[705:16703] Duration: 45.267000 So it seems to be the same as the original code where moviePlayerLoadStateChanged is never called. However, I'm still confused as to how the MPMoviePlayerController can pick up the duration of the video if it is unable to load it? Could this be a codec issue? Is there any way to check whether or not the video will work at all after downloaded? EDIT 2: Okay this looks like a possible codec issue. I have now tried it with 2 similar URLs, 1 mov / 1 3gp, and the mov one will play with sound but no video whilst the 3gp briefly shows "loading" on the video screen but never changes to the loaded state when this disappears. Can anyone suggest a way of getting this working, or another movie player with more types supported? A: Try replacing all of your setup code with this: // get the url as moveURL self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:movieURL]; self.moviePlayer.view.frame = self.view.bounds; [self.view addSubview:self.moviePlayer.view]; [self.moviePlayer prepareToPlay]; // notice what notification we subscribe to... [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayerLoadStateChanged:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil]; Log state changes in moviePlayerLoadStateChanged:. If that doesn't work, it's probably the url that's the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/14199159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python equivalent of Go Struct and Unmarshal So I'm working with some JSON data in Python. Its basically a wrapper for an API though I want to have dot access to my values like data.size, I've done a bit of research but I couldn't find the desired results. I was using json.loads to parse my data so I tried object hooks but that isn't what I want. Here's an example Go code that I want to replicate. type dat struct { ResponseTime int Body body } type body struct { Day int Month int Year int } var h dat // e here is my json data = json.Unmarshal(e, &h) My results in Python were similar but they were instances of the same class. My aim is to be able to parse nested dicts and I want to be able to define which dict assigns to which object... not sure if u understand but theres the Go code for you. A: Using dataclass and dacite from dataclasses import dataclass import dacite @dataclass class Body: day:int month:int year:int @dataclass class Dat: response_time: int body: Body data = {'response_time':12, 'body':{'day':1,'month':2,'year':3}} dat: Dat = dacite.from_dict(Dat,data) print(dat) output Dat(response_time=12, body=Body(day=1, month=2, year=3)) A: Using pymarshaler (Which is close to to golang approach) import json from pymarshaler.marshal import Marshal class Body: def __init__(self, day: int, month: int, year: int): self.day = day self.month = month self.year = year class Dat: def __init__(self, response_time: int, body: Body): self.response_time = response_time self.body = body marshal = Marshal() dat_test = Dat(3, Body(1, 2, 3)) dat_json = marshal.marshal(dat_test) print(dat_json) result = marshal.unmarshal(Dat, json.loads(dat_json)) print(result.response_time) see https://pythonawesome.com/marshall-python-objects-to-and-from-json/ A: So turns out it wasn't that hard, I just didn't want to try. For anyone with the same problem here's the code. class Typs(object): def __init__(self): self.type = int self.breed = str class Deets(object): def __init__(self): self.color = str self.type = Typs() class Base(object): def __init__(self): self.name = str self.details = Deets() d = { "name": "Hello", "details": {"color": "black", "type": {"type": 2, "breed": "Normal"}}, } h = Base() def unmarshal(d, o): for k, v in d.items(): if hasattr(o, k): if isinstance(v, dict): unmarshal(v, getattr(o, k)) else: setattr(o, k, v) return o x = unmarshal(d, h)
{ "language": "en", "url": "https://stackoverflow.com/questions/69415144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Image resizing script is not returning a proper stream for further handling Current project: * *ASP.NET 4.5.2 *MVC 5 I am trying to leverage the TinyPNG API, and if I just pipe the image over to it, it works great. However, since the majority of users will be on a mobile device, and these produce images at a far higher resolution than what is needed, I am hoping to reduce the resolution of these files prior to them being piped over to TinyPNG. It is my hope that these resized images will be considerably smaller than the originals, allowing me to conduct a faster round trip. My code: public static async Task<byte[]> TinyPng(Stream input, int aspect) { using(Stream output = new MemoryStream()) using(var png = new TinyPngClient("kxR5d49mYik37CISWkJlC6YQjFMcUZI0")) { ResizeImage(input, output, aspect, aspect); // Problem area var result = await png.Compress(output); using(var reader = new BinaryReader(await (await png.Download(result)).GetImageStreamData())) { return reader.ReadBytes(result.Output.Size); } } } public static void ResizeImage(Stream input, Stream output, int newWidth, int maxHeight) { using(var srcImage = Image.FromStream(input)) { var newHeight = srcImage.Height * newWidth / srcImage.Width; if(newHeight > maxHeight) { newWidth = srcImage.Width * maxHeight / srcImage.Height; newHeight = maxHeight; } using(var newImage = new Bitmap(newWidth, newHeight)) using(var gr = Graphics.FromImage(newImage)) { gr.SmoothingMode = SmoothingMode.AntiAlias; gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight)); newImage.Save(output, ImageFormat.Jpeg); } } } So the ResizeArea is supposed to accept a stream and output a stream, meaning that the TinyPNG .Compress() should work just as well with the output as it would with the original input. Unfortunately, only the .Compress(input) works -- with .Compress(output) TinyPNG throws back an error: 400 - Bad Request. InputMissing, File is empty I know TinyPNG has its own resizing routines, but I want to do this before the image is sent out over the wire to TinyPNG so that file size (and therefore transmission time) is reduced as much as possible prior to the actual TinyPNG compression. A: …Aaaaand I just solved my problem by using another tool entirely. I found ImageProcessor. Documentation is a royal b**ch to get at because it only comes in a Windows *.chm help file (it’s not online… cue one epic Whisky. Tango. Foxtrot.), but after looking at a few examples it did solve my issue quite nicely: public static async Task<byte[]> TinyPng(Stream input, int aspect) { using(var output = new MemoryStream()) using(var png = new TinyPngClient("kxR5d49mYik37CISWkJlC6YQjFMcUZI0")) { using(var imageFactory = new ImageFactory()) { imageFactory.Load(input).Resize(new Size(aspect, 0)).Save(output); } var result = await png.Compress(output); using(var reader = new BinaryReader(await (await png.Download(result)).GetImageStreamData())) { return reader.ReadBytes(result.Output.Size); } } } and everything is working fine now. Uploads are much faster now as I am not piping a full-sized image straight through to TinyPNG, and since I am storing both final-“full”-sized images as well as thumbnails straight into the database, I am now not piping the whole bloody image twice. Posted so that other wheel-reinventing chuckleheads like me will actually have something to go on.
{ "language": "en", "url": "https://stackoverflow.com/questions/40368651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: d3.js gantt chart issue var taskTypes = ["slot1", "slot2", "slot3","slot4","slot1","slot2","slot6"]; when var y = d3.scale.ordinal() .domain(taskTypes) .rangeRoundBands([ 0, height - margin.top - margin.bottom ], .1); I was doing var rectTransform = function(d) { return "translate(" + x(d.termStartDate) + "," + y(d.slotName) + ")"; }; and it was coming proper, but now I am taking var y = d3.scale.ordinal() .domain(d3.range(0, taskTypes.length)) .rangeRoundBands([ 0, height - margin.top - margin.bottom ], .1); and now var rectTransform = function(d) { return "translate(" + x(d.termStartDate) + "," + y(d.slotName) + ")"; }; where d.slotName = slot1, or slot2 or slot3 or any other value, y(d.slotName) is returning undefined, any suggestions How to make it work? A: As per this answer, the domain for the y scale is the array indices of taskTypes. That means that: y("slot3") = undefined y(taskTypes.indexOf("slot3")) = 54 // Or some valid value You need to determine the index of d.slotName in the array. Using indexOf won't behave well for repeated values (like "slot1"). If the item is present more than once, the indexOf method returns the position of the first occurence.
{ "language": "en", "url": "https://stackoverflow.com/questions/30077125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to display an base64 string into an image using javascript I am trying to display an base 64 string into image in html page ... It showing some error...error look like here is my code $(document).ready(function() { var username="srk"; var url = "http://localhost/login/image/displayimage.php?username="+username+""; $.getJSON(url, function(result) { console.log(result); $.each(result, function(i, field) { var id = field.id; var photo = field.photo; //base 64 string is stored in photo $("#listview").append("<img src='"+photo+"' alt='loading'>"); }); }); }); </script> <canvas id="canvas" width="50" height="50"></canvas> <ul id="listview" ></ul> base 64 string look like 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEUAAABlCAYAAAAbIS4fAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89 bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf bTAICd Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP 5c rcEAAAOF0ftH LC zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s wM 3zUAsGo AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4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/ZfAyWTyVBdXcPLL7z UrRuxrRv/fbNvnwgSHl1EW/cfTt TMrGjqFo Zl86 k3O1989f1ZC bNuWLS IlmX18f3id84fT/C1AURSGfz6EogutuvG7TlONPql945tWvpYNVzDvxeGoXzOOhJ9/hS9fcfePmA4cGzJ875z0hBJZl8kkf0fz/BpQPJ05ZTjvtlGRv2jv1a9c dsvDmxq54PZH c719y0///wLrhk dFg l8v9V73j/z0oQDqdpqgw5txy2ZVXPbR6/9QBM48vO/30z/zJ0NT/Wuz4V/Z/BgAq6lR5PJ79rAAAAABJRU5ErkJggg=='
{ "language": "en", "url": "https://stackoverflow.com/questions/41663134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: lag entire rows by zoo object in r Consider the following: library(dplyr) library(zoo) df <- structure(list(FILIAL_CODE = c(10L, 10L, 10L, 10L, 10L, 10L), UNIDADES = c(26394, 24314, 26280, 25056, 28827, 24781), MES_ZOO = structure(c(2010, 2010.08333333333, 2010.16666666667, 2010.25, 2010.33333333333, 2010.41666666667), class = "yearmon"), PRODUCTOSUNICOS = c(3592L, 3337L, 3459L, 3256L, 3355L, 3196L), DEVOLUCIONES = c(39L, 22L, 12L, 24L, 26L, 31L)), .Names = c("FILIAL_CODE", "UNIDADES", "MES_ZOO", "PRODUCTOSUNICOS", "DEVOLUCIONES"), class = c("tbl_df", "data.frame"), row.names = c(NA, -6L)) > df Source: local data frame [6 x 5] FILIAL_CODE UNIDADES MES_ZOO PRODUCTOSUNICOS DEVOLUCIONES 1 10 26394 ene 2010 3592 39 2 10 24314 feb 2010 3337 22 3 10 26280 mar 2010 3459 12 4 10 25056 abr 2010 3256 24 5 10 28827 may 2010 3355 26 6 10 24781 jun 2010 3196 31 How do I lag entire rows of variables to create a new set of variables in the previous month. For example, I would get: newdf<-structure(list(FILIAL_CODE = c(10, 10, 10, 10, 10, 10), UNIDADES = c(26394, 24314, 26280, 25056, 28827, 24781), MES_ZOO = structure(c(2L, 3L, 5L, 1L, 6L, 4L), .Label = c("abr 2010", "ene 2010", "feb 2010", "jun 2010", "mar 2010", "may 2010"), class = "factor"), PRODUCTOSUNICOS = c(3592, 3337, 3459, 3256, 3355, 3196), DEVOLUCIONES = c(39, 22, 12, 24, 26, 31), NEWMONTH = structure(c(2L, 4L, 1L, 5L, 3L, 6L), .Label = c("abr 2010", "feb 2010", "jun 2010", "mar 2010", "may 2010", "NA"), class = "factor"), NEW_PRODUCTOSUNICOS = structure(c(3L, 5L, 2L, 4L, 1L, 6L), .Label = c("3196", "3256", "3337", "3355", "3459", "NA"), class = "factor"), NEW_DEVOLUCIONES = structure(c(2L, 1L, 3L, 4L, 5L, 6L), .Label = c("12", "22", "24", "26", "31", "NA"), class = "factor")), .Names = c("FILIAL_CODE", "UNIDADES", "MES_ZOO", "PRODUCTOSUNICOS", "DEVOLUCIONES", "NEWMONTH", "NEW_PRODUCTOSUNICOS", "NEW_DEVOLUCIONES"), row.names = c(NA, -6L), class = "data.frame") > newdf FILIAL_CODE UNIDADES MES_ZOO PRODUCTOSUNICOS DEVOLUCIONES NEWMONTH NEW_PRODUCTOSUNICOS NEW_DEVOLUCIONES 1 10 26394 ene 2010 3592 39 feb 2010 3337 22 2 10 24314 feb 2010 3337 22 mar 2010 3459 12 3 10 26280 mar 2010 3459 12 abr 2010 3256 24 4 10 25056 abr 2010 3256 24 may 2010 3355 26 5 10 28827 may 2010 3355 26 jun 2010 3196 31 6 10 24781 jun 2010 3196 31 NA NA NA For added dificulty, I need to do this for every "FILIAL_CODE". This is an example but there can be "n" of these FILIAL_CODE, each with "n" months. The months don't repeat inside of each "FILIAL_CODE". A: Using dplyr, we can do this after converting the 'MES_ZOO' column to character class as the zoo class is not supported within the mutate (using dplyr_0.4.1.9000). We group by 'FILIAL_CODE', get the lead of columns MES_ZOO to DEVOLUCIONES using mutate_each, change the column names and left_join with the original dataset. df$MES_ZOO <- as.character(df$MES_ZOO) library(dplyr) df %>% group_by(FILIAL_CODE) %>% mutate_each(funs(lead), MES_ZOO:DEVOLUCIONES)%>% setNames(., c(names(.)[1:2], paste0('NEW_', nm1))) %>% left_join(df, .) Or we could use shift from the devel version of 'data.table' i.e. v1.9.5 (Instructions to install the devel version are here. We convert the 'data.frame' to 'data.table' (setDT(df)). Specify the columns to shift in the .SDcols, use shift with option type='lead' grouped by 'FILIAL_CODE'. Create new columns by assigning (:=) library(data.table)#v1.9.5+ nm1 <- colnames(df)[3:5] setDT(df)[, paste0("NEW_", nm1) :=shift(.SD, type='lead') , by = FILIAL_CODE, .SDcols = nm1] df # FILIAL_CODE UNIDADES MES_ZOO PRODUCTOSUNICOS DEVOLUCIONES NEW_MES_ZOO #1: 10 26394 Jan 2010 3592 39 Feb 2010 #2: 10 24314 Feb 2010 3337 22 Mar 2010 #3: 10 26280 Mar 2010 3459 12 Apr 2010 #4: 10 25056 Apr 2010 3256 24 May 2010 #5: 10 28827 May 2010 3355 26 Jun 2010 #6: 10 24781 Jun 2010 3196 31 <NA> # NEW_PRODUCTOSUNICOS NEW_DEVOLUCIONES #1: 3337 22 #2: 3459 12 #3: 3256 24 #4: 3355 26 #5: 3196 31 #6: NA NA
{ "language": "en", "url": "https://stackoverflow.com/questions/32234702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PyTorch attach extra connection when building model I have the following Resnet prototype on Pytorch: Resnet_Classifier( (activation): ReLU() (model): Sequential( (0): Res_Block( (mod): Sequential( (0): Conv1d(1, 200, kernel_size=(5,), stride=(1,), padding=same) (1): ReLU() (2): BatchNorm1d(200, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): Conv1d(200, 200, kernel_size=(5,), stride=(1,), padding=same) (4): ReLU() (5): BatchNorm1d(200, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (6): Conv1d(200, 200, kernel_size=(5,), stride=(1,), padding=same) (7): ReLU() (8): BatchNorm1d(200, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) (shortcut): Conv1d(1, 200, kernel_size=(1,), stride=(1,), padding=same) ) (1): ReLU() (2): Flatten(start_dim=1, end_dim=-1) (3): Dropout(p=0.1, inplace=False) (4): Linear(in_features=40000, out_features=2, bias=True) (5): Softmax(dim=1) ) ) Input sample shape is (1, 200). It seems to be absolutely okay but, when I try to get graph in tensorboard, I get the following structure: Somehow my Residual block connected with Linear. Does this connection really corresponds my net structure? Model definition: class Res_Block(nn.Module): def __init__(self, in_ch, out_ch, ks, stride, activation): super(Res_Block, self).__init__() self.mod = nn.Sequential( nn.Conv1d(in_ch, out_ch, ks, stride, padding='same'), deepcopy(activation), nn.BatchNorm1d(out_ch), nn.Conv1d(out_ch, out_ch, ks, stride, padding='same'), deepcopy(activation), nn.BatchNorm1d(out_ch), nn.Conv1d(out_ch, out_ch, ks, stride, padding='same'), deepcopy(activation), nn.BatchNorm1d(out_ch) ) self.shortcut = nn.Conv1d(in_ch, out_ch, kernel_size=1, stride=1, padding='same') def forward(self, X): return self.mod(X) + self.shortcut(X) layers = [] layers.append(Res_Block(1, 200, 5, 1, nn.ReLU())) layers.append(nn.ReLU()) layers.append(nn.Flatten()) layers.append(nn.Dropout(0.2)) layers.append(nn.Linear(200 * 200, 2)) layers.append(nn.Softmax(dim=1)) R = nn.Sequential(*layers) A: The model visualization seems incorrect, the main branch and skip connection are encapsulated inside your Res_Block definition, it should not appear outside of the red Res_Block[0] box, but instead inside. A: I solved the problem by removing nn.Sequential in Res_Block __init__ and adding self.l1, self.l2 ... instead. (I also removed some layers and added maxpool but only after I solved the problem) class Res_Block(nn.Module): def __init__(self, in_shape, out_ch, ks, stride, activation): super(Res_Block, self).__init__() self.l1 = nn.Conv1d(in_shape, out_ch, ks, stride, padding='same') self.l2 = deepcopy(activation) self.l3 = nn.BatchNorm1d(out_ch) self.l4 = nn.Conv1d(out_ch, out_ch, ks, stride, padding='same') self.l5 = nn.BatchNorm1d(out_ch) self.shortcut = nn.Conv1d(in_shape, out_ch, kernel_size=1, stride=1, padding='same') def forward(self, X): return self.l5(self.l4(self.l3(self.l2(self.l1(X))))) + self.shortcut(X) The corresponding tensorboard structure is The only one left question is why did that help me solve the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/69427862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Start ssh using systemctl inside the docker container I' m a beginner in the Docker; I have pulled a CentOS 7 image from Hub and ran it ; I need to ssh in to the docker container(CentOS 7) from my host. Got the docker container's IP using docker inspect container-id I have installed the following using initscripts systemd.x86_64 systemd-libs.x86_64 open-ssh firewalld net-tools when i tried to start the firewall to open the port for ssh(22) [root@a6f3e3eb095c ~]# systemctl start firewall Failed to get D-Bus connection: Operation not permitted Also tried, [root@a6f3e3eb095c ~]# /usr/lib/systemd/systemd --system & [1] 353 [root@a6f3e3eb095c ~]# systemd 219 running in system mode. (+PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ -LZ4 -SECCOMP +BLKID +ELFUTILS +KMOD +IDN) Detected virtualization xen. Detected architecture x86-64. Welcome to CentOS Linux 7 (Core)! Set hostname to <a6f3e3eb095c>. Cannot determine cgroup we are running in: No such file or directory Failed to allocate manager object: No such file or directory [1]+ Exit 1 /usr/lib/systemd/systemd --system How to start the firewall/ssh inside the docker container ? A: inside docker container run following commands : yum update -y glibc-common yum install -y sudo passwd openssh-server openssh-clients tar screen crontabs strace telnet perl libpcap bc patch ntp dnsmasq unzip pax which rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm yum install -y hiera lsyncd sshpass rng-tools service sshd start; sed -i 's/UsePAM yes/#UsePAM yes/g' /etc/ssh/sshd_config; sed -i 's/#UsePAM no/UsePAM no/g' /etc/ssh/sshd_config; sed -i 's/#PermitRootLogin yes/PermitRootLogin yes/' /etc/ssh/sshd_config; sed -i 's/enabled=0/enabled=1/' /etc/yum.repos.d/CentOS-Base.repo mkdir -p /root/.ssh/; rm -f /var/lib/rpm/.rpm.lock; echo "StrictHostKeyChecking=no" > /root/.ssh/config; echo "UserKnownHostsFile=/dev/null" >> /root/.ssh/config echo "root:password" | chpasswd ( or ) Simply you can pull docker image of centos with ssh in docker hub https://hub.docker.com/search/?isAutomated=0&isOfficial=0&page=1&pullCount=0&q=centos+ssh&starCount=0 https://hub.docker.com/r/kinogmt/centos-ssh/ https://hub.docker.com/r/jdeathe/centos-ssh/ A: You can avoid the "Failed to get D-Bus connection: Operation not permitted" / aka installing systemd inside a docker by using the https://github.com/gdraheim/docker-systemctl-replacement ... after that the docker-exec stuff should be all fine to do things inside a container. A: If you really do need an ssh or sftp container, then you can use my Docker Image as a source image for your own or run it directly: If using the official CentOS-7 Image and you require systemd, there are instructions on how to enable it under the section "Systemd integration". However, based on the following: I need to ssh in to the docker container(CentOS 7) from my host. You can use docker exec to run commands in a running, (backgrounded), container so, for images that have bash available, you can access an interactive tty and run bash as follows from your host - where container can be either the name or id: docker exec --tty --interactive <container> bash OR docker exec -ti <container> bash Finally, it's unlikely to be necessary to install the firewall package in your image as the operator will decide what ports to publish from those which are exposed and you can make use of Docker Networking to only expose the necessary public facing services. A: If you are using the Docker CLI, then you can get into the Docker container using the following command docker exec -it containerId bash I am not sure how to ssh into the docker container, but if you want to do basic operation inside the Docker container, you can make use of the above docker command.
{ "language": "en", "url": "https://stackoverflow.com/questions/47506171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Javascript (Node.js) - How to read and process multiple line provided as an input to a function? I am practicing to code in various languages and hence, am a newbie to node.js. The site I am using to practice the code mostly gives me multi-line inputs as an argument to my function, which I don't know how to process (I tried using split on \n, but, that, doesn't work). Following is a code that, gets multi-line input and then, this input is passed to a function. Can you please tell me how can I read/process the input in-order to store each line of an input in an array as a data item ? function main(input) { //Enter your code here // var arr = input.split("") process.stdout.write(input[6]); } process.stdin.resume(); process.stdin.setEncoding("utf-8"); var stdin_input = ""; process.stdin.on("data", function (input) { stdin_input += input; }); process.stdin.on("end", function () { main(stdin_input); }); Thanks' A: Splitting on a new line works for me. function main(input) { //Enter your code here var arr = input.split("\n") process.stdout.write(JSON.stringify(arr)); } process.stdin.resume(); process.stdin.setEncoding("utf-8"); var stdin_input = ""; process.stdin.on("data", function (input) { stdin_input += input; }); process.stdin.on("end", function () { main(stdin_input); }); It's important to note that process.stdout.write can only write a string. Trying to pass an array as an argument will cause an error. A: just a idea my code is just for many string or number have space between for example if you want sum two number we write in terminal : 23 56 notice i use here string_decoder for any one want to raplace number with string const {StringDecoder} = require('string_decoder'); const decode = new StringDecoder('utf8'); const sum = (a, b) => { let operation = a + b; return console.log('result is : ', operation); } process.stdin.on('readable', () => { const aa = process.stdin.read(); // read string from REPL const buffer = Buffer.from(aa); const j = decode.write(buffer).split(' '); const a = +j[0]; const b = +j[1]; // console.log(a + b) if((a & b) != null) // check if the value not empty { sum(a, b); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/46762894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: MongoDB Nested OR/AND Where? I am trying to figure out how to do nested OR/AND where queries like what you would do in MySQL Take for example SELECT first_name, id FROM table WHERE ( province = "nb" OR province = "on" ) AND ( city = "toronto" AND first_name = "steven" ) A: The query in MongoDB looks like: Database.collection_name.find( // This is the condition { $and: [ { $or: [ {province: 'nb'}, {province: 'on'} ] }, { city: "toronto" }, { first_name: "steven" } ] }, // Specify the fields that you need { first_name: 1, _id: 1 } ) Documentation for $and $or Some examples and the official documentation for MongoDB find here.
{ "language": "en", "url": "https://stackoverflow.com/questions/23118434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Angular 11 won't upload file to .NET 5 I'm not able to get a file from my Angular 11 application uploaded to my .NET 5 service. If I set a breakpoint at the first line of the controller method it's not hit. The angular app just gets an HttpErrorResponse with a status of 0. I'm able to POST without issue to other methods in this same controller, so I know all the "setup" type stuff is working properly. I'm doing the upload like so on the Angular side: postUploadLegacyData(files: File[]): Observable<string[]> { const formData = new FormData() files.forEach(x => formData.append('file', x, x.name)) return this.http.post<string[]>('requests/import', formData) } and then on the .NET side I have this: [Route("[controller]"), Produces("application/json"), Authorize, ApiController] public class RequestsController : ControllerBase { [HttpPost("import")] [Consumes("multipart/form-data")] public IActionResult PostImportExistingRequests(IEnumerable<IFormFile> files) Resolved I found that it should instead be this on the server side: public async Task<IActionResult> PostImportExistingRequestsAsync() { var form = await Request.ReadFormAsync(); var files = form.Files; A: Angular: scaffold a front end folder angular for your component ng g component upload --spec false import { Component, OnInit, Output, EventEmitter } from '@angular/core'; import { HttpEventType, HttpClient } from '@angular/common/http'; @Component({ selector: 'file-upload-toAspCore', templateUrl: './upload.component.html', styleUrls: ['./upload.component.css'] }) export class UploadComponent implements OnInit { public progress: progressPercentage; // you can yse this to display progress in HTML public message: string; @Output() public onUploadFinished = new EventEmitter(); constructor(private http: HttpClient) { } ngOnInit() {} public uploadFile = (files) => { if (files.length === 0) { return; } let filesToUpload = <File>files[0]; const formData = new FormData(); formData.append('file', filesToUpload, filesToUpload.name); this.http.post('https://localhost:4200/api/uploaderAction', formData, {reportProgress: true, observe: 'events'}) .subscribe(event => { if (event.type === HttpEventType.UploadProgress) // helps display progress to user this.progress = Math.round(100 * event.loaded / event.total); else if (event.type === HttpEventType.Response) { this.message = 'Upload success.'; this.onUploadFinished.emit(event.body); } }); } } ASP Action that receives the file [HttpPost, DisableRequestSizeLimit] public async Task<IActionResult> UploaderAction() { try { var formCollection = await Request.ReadFormAsync(); var file = formCollection.Files.First();
{ "language": "en", "url": "https://stackoverflow.com/questions/67235372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MSSQL Why is this function non-deterministic I have this user function, which is always flagged as non-deterministic, although the value will always be the same as long as the input parameter is the same. Everything I've read suggests this should be deterministic. Can anybody spot why? SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER FUNCTION [dbo].[udfGetCriteriaScore] ( @InputString varchar(max) ) RETURNS int WITH SCHEMABINDING AS BEGIN DECLARE @returnScore int; DECLARE @IdentifierChar NCHAR(1)= '"' DECLARE @overallScore int DECLARE @FirstID int DECLARE @SecondID int DECLARE @TargetString varchar(MAX) DECLARE @startDateCriteria varchar(MAX); DECLARE @endDateCriteria varchar(MAX); declare @scoringTable table ( Criterion varchar(max), CriteriaScore int, Occurances int, SumTotalScore int ) DECLARE @TotalCriterions int = (SELECT LEN(@InputString) - LEN(REPLACE(@InputString, '@', ''))) declare @COUNT int = 0 declare @Length int = 0 WHILE(@COUNT) < @TotalCriterions BEGIN Set @FirstID = CHARINDEX(@IdentifierChar, @InputString, @Length) Set @SecondID = CHARINDEX(@IdentifierChar, @InputString, @FirstID + 1) Set @Length = @SecondID - @FirstID Set @TargetString = SUBSTRING(@InputString, @FirstID + 1, @Length - 1) SET @COUNT = @COUNT + 1 Set @Length = @SecondID + 1 DECLARE @criteriaScore int DECLARE @criteriaCount int DECLARE @Criterion varchar(max) SET @Criterion = SUBSTRING(@TargetString, 0, CHARINDEX(':', @TargetString)) -- Calculate date range score IF (LOWER(@Criterion) = '@fromdate' OR LOWER(@Criterion) = '@todate') BEGIN IF LOWER(@Criterion) = '@fromdate' SET @startDateCriteria = SUBSTRING(@TargetString, CHARINDEX(':', @TargetString) + 2, LEN(@TargetString) - CHARINDEX(':', @TargetString)) IF LOWER(@Criterion) = '@todate' SET @endDateCriteria = SUBSTRING(@TargetString, CHARINDEX(':', @TargetString) + 2, LEN(@TargetString) - CHARINDEX(':', @TargetString)) IF @startDateCriteria IS NOT NULL AND @endDateCriteria IS NOT NULL BEGIN SET @criteriaScore = 5 SET @criteriaCount = DATEDIFF (dd, @startDateCriteria, @endDateCriteria) INSERT INTO @scoringTable (Criterion, CriteriaScore, Occurances, SumTotalScore) VALUES ('DateRange', @criteriaScore, @criteriaCount, (@criteriaScore * @criteriaCount)) END END ELSE -- Calculate individual criterion score BEGIN SET @criteriaScore = CASE WHEN LOWER(@Criterion) = '@branchid' THEN 10 WHEN LOWER(@Criterion) = '@locationid' THEN 10 WHEN LOWER(@Criterion) = '@salesexecid' THEN 1 WHEN LOWER(@Criterion) = '@thedate' THEN 5 ELSE 1 END SET @criteriaCount = (SELECT CASE WHEN LEN(REPLACE(@TargetString, @Criterion, '')) < 3 THEN 0 ELSE LEN(@TargetString) - LEN(REPLACE(@TargetString, ';', '')) + 1 END ) INSERT INTO @scoringTable (Criterion, CriteriaScore, Occurances, SumTotalScore) VALUES (@Criterion, @criteriaScore, @criteriaCount, (@criteriaScore * @criteriaCount)) END END IF EXISTS (SELECT Occurances from @scoringTable where Occurances > 0 AND LOWER(Criterion) in ('@salesexecid', '@locationid')) UPDATE @scoringTable SET SumTotalScore = 0 where LOWER(Criterion) = '@branchid' set @returnScore = (select SUM(SumTotalScore) from @scoringTable) Return @returnScore; END It is designed to split out strings like this: ["@BranchID: 154","@FromDate: 2018-02-01T00:00:00","@ToDate: 2018-02-26T00:00:00","@SalesExecID: "] and return an overall score based on date range, number of branches included etc. The following IsDeterministic check is always 0? SELECT OBJECTPROPERTY(OBJECT_ID('[dbo].[udfGetCriteriaScore]'), 'IsDeterministic') A: Other people have the same problem: https://www.sqlservercentral.com/Forums/Topic1545616-392-1.aspx There, the solution was to convert the string date to an actual date: You need to do an explicit CONVERT to use the string literal. I changed your code a little bit to remove the +1 CREATE TABLE Test( DayDate DATE, DayNumber AS (DATEDIFF( DD, CONVERT( DATE, '2014-04-30', 120), DayDate)) PERSISTED) INSERT INTO Test(DayDate) VALUES(GETDATE()) SELECT * FROM Test DROP TABLE Test The same answer explains this is because there are date formats that are non-deterministic and therefore you need to explicitly set a (deterministic) date format for the string conversion to be considered deterministic.
{ "language": "en", "url": "https://stackoverflow.com/questions/49175741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I iterate through each column of data in a LINQ to SQL query? Imagine my LINQ to SQL query is this: var query = (from q in db.GetTable<potato>() where q.ID == dbID select q).FirstOrDefault(); How would I iterate horizontally instead of vertically?. So there's just the one row, I want to iterate through each data item in a column per column basis, instead of row by row. Theres quite a few properties so I'd just like to iterate instead of writing them all manually. Thanks! A: If data you want is Property: var values = typeof(potato) .GetProperties() .Select(p=>p.GetValue(query,null)) .ToArray(); If data is Field: var values = typeof(potato) .GetFields() .Select(p=>p.GetValue(query)) .ToArray(); If some property must be returned you can filter PropertyInfoes or FieldInfoes like below: typeof(potato) .GetFields() .Where(p=>...labla...) .Select... A: You can get this through reflection foreach (PropertyInfo propertyInfo in potato.GetType().GetProperties()) { if (propertyInfo.CanRead) { string val= propertyInfo.GetValue(potato, null).ToString(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/32295855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: get modifiers on windows platform Anyone knows how to get modifier on Windows platform? I know there is a function called GetKeyState(), but I could not get windows or meta key with it. Its document is here.. Any advices will apperciate. Thx A: The Windows key is covered by VK_LWIN and VK_RWIN, respectively the left and the right key. The "meta" key is presumably the one that brings up the context menu for the active window, same one you'd see if you right-click the mouse. It is VK_APPS. Beware that it is not a modifier key.
{ "language": "en", "url": "https://stackoverflow.com/questions/23864878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Parse Error - Unexpected End of File I'm a complete newbie to programming and php, my code's throwing back an error saying there's an unexpected end to the file and I can't for the life of me see what's missing or there that shouldn't be. Can anyone spot it? <html> <head> <title><?php echo $firstname; ?> <?php echo $lastname; ?>'s Profile</title> </head> <body> <?php if (isset($_GET['username'])){ $username = $_GET['username']; mysql_connect("localhost","root", "") or die ("Could not connect to the server"); mysql_select_db("users") or die ("That database could not be found."); $userquery = mysql_query("SELECT * FROM users WHERE username='$username'") or die ("The query could not be completed, please try again later."); if(mysql_num_rows($userquery) !=1){ die ("That user could not be found."); } while($row = mysql_fetch_array($userquery, MYSQL_ASSOC)) { $firstname = $row['firstname']; $lastname = $row['lastname']; $email = $row['email']; $dbusername = $row['dbusername']; $access = $row['access']; } if($username != $dbusername){ die ("There has been a fatal error, please try again."); } if($access == 1) { $access = "Level 1 User"; } else if($access == 2) { $access = "Level 2 User"; } else if($access == 3) { $access = "Level 3 User"; } else if($access == 4) { $access = "Administrator."; } else die ("This user has an access level beyond the realms of possibility. Beware."); ?> <h2><?php echo $firstname; ?> <?php echo $lastname; ?>'s Profile</h2><br /> <table> <tr><td>Firstname:</td><td><?php echo $firstname; ?></td></tr> <tr><td>Lastname:</td><td><?php echo $lastname; ?></td></tr> <tr><td>email:</td><td><?php echo $email; ?></td></tr> <tr><td>dbusername:</td><td><?php echo $dbusername; ?></td></tr> <tr><td>access:</td><td><?php echo $access; ?></td></tr> </table> </body> </html> A: Is the main if code block that needs to be closed with a } <html> <head> <title><?php echo $firstname; ?> <?php echo $lastname; ?>'s Profile</title> </head> <body> <?php if (isset($_GET['username'])){ $username = $_GET['username']; mysql_connect("localhost","root", "") or die ("Could not connect to the server"); mysql_select_db("users") or die ("That database could not be found."); $userquery = mysql_query("SELECT * FROM users WHERE username='$username'") or die ("The query could not be completed, please try again later."); if(mysql_num_rows($userquery) !=1){ die ("That user could not be found."); } while($row = mysql_fetch_array($userquery, MYSQL_ASSOC)) { $firstname = $row['firstname']; $lastname = $row['lastname']; $email = $row['email']; $dbusername = $row['dbusername']; $access = $row['access']; } if($username != $dbusername){ die ("There has been a fatal error, please try again."); } if($access == 1) { $access = "Level 1 User"; } else if($access == 2) { $access = "Level 2 User"; } else if($access == 3) { $access = "Level 3 User"; } else if($access == 4) { $access = "Administrator."; } else die ("This user has an access level beyond the realms of possibility. Beware."); }//THIS IS WHAT IS MISSING ?> <h2><?php echo $firstname; ?> <?php echo $lastname; ?>'s Profile</h2><br /> <table> <tr><td>Firstname:</td><td><?php echo $firstname; ?></td></tr> <tr><td>Lastname:</td><td><?php echo $lastname; ?></td></tr> <tr><td>email:</td><td><?php echo $email; ?></td></tr> <tr><td>dbusername:</td><td><?php echo $dbusername; ?></td></tr> <tr><td>access:</td><td><?php echo $access; ?></td></tr> </table> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/26447745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Is there a better way to implement this memory management? This is a follow-up to my previous question regarding exceptions. I have some legacy code that I am attempting to maintain. It has a custom memory management component that I am having difficulty understanding. My understanding of the system is as follows: Calling function asks for a some memory to be allocated for it, providing an initial amount of memory needed (needed), and a maximum amount (max). This calls: base = VirtualAlloc(0, max, MEM_RESERVE, PAGE_NOACCESS); Which I understand reserves the memory but does not provide access. In other words, if I try to write to the reserved segment, I would get an access violation. It then calls: VirtualAlloc(base, needed, MEM_COMMIT, PAGE_READWRITE); Which makes needed amount of memory starting at base accessible. The sticky part comes when trying to detect when more memory needs to be made accessible. My understanding is that the system attempts to catch access violation exceptions when they happen and call VirtualAlloc on the address to make the memory accessible. It does this by declaring the following method: unsigned long __cdecl exceptionCatch(struct _EXCEPTION_RECORD* er, void*, struct _CONTEXT* cr, void*) { if( er->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && ExtendBuffer( (void*)er->ExceptionInformation[1] ) ) return ExceptionContinueExecution; return ExceptionContinueSearch; } Then, it registers this as the exception handler for the top of the stack (I think), using this particularly horrible piece of code: void __cdecl SetHandler(bExceptionRegistration& v) { __asm { mov eax, 8[ebp] ; get exception register record to install mov ecx, fs:[0] ; get current head of chain cmp ecx, eax ; should we be at head? jb search mov [eax], ecx ; save current head mov fs:[0], eax ; install new record at head jmp short ret1 search: cmp [ecx], eax ; at proper location yet? ja link mov ecx, [ecx] ; get next link jmp search link: mov edx, [ecx] mov [eax], edx ; point to next mov [ecx], eax ret1: } } This method is called by instantiating a particular class in a method scope. It looks like it only applies the handler to the current stack context; as in, exceptions thrown in called functions are not handled by the current method if the exception is not propagated to the current method. The result of all this is that not only is the access violation not caught, but it disables exception handling at the current top of the stack. I have set break points in the exceptionCatch function and execution doesn't appear to enter it. I suppose my main questions are: * *Is there any particular reason why this shouldn't work? Edit: based on my own testing and comments here, I think the assembly code is the problem area. *More importantly, is there a better way to do what I think the code is attempting to do? I don't think something like set_unexpected is feasible, since the memory management is applying only to this particular library and the client application may (and in our case, does) have its own unexpected exception handler. Edit: The setting and unsetting of the handler per stack is done by declaring a class bExceptionRegistration with the following class constructor and destructor: bExceptionRegistration :: bExceptionRegistration() : function(exceptionCatch) { SetHandler(*this); } bExceptionRegistration :: ~bExceptionRegistration() { UnsetHandler(*this); } So, to actually set the handler for a particular stack scope, you would have: void someFunction() { bExceptionRegistration er; // do some stuff here } Edit: I'm guessing that probably the most appropriate solution to all this is to replace the bExceptionRegistration declarations in the code with __try, __except blocks. I was hoping to avoid this however, as it is in a lot of places. A: I'm not 100% sure about this without seeing more code. It doesn't register the exception handler at the top of the stack but it uses a trick to insert the exception handling where the EXCEPTION_REGISTRATION structure is defined. So for example (maybe in your case it's implemented a bit differently): void function3(EXCEPTION_REGISTRATION& handler) { SetHandler(handler); //Do other stuff } void function2(EXCEPTION_REGISTRATION& handler) { __try { //Do something function3(handler); } __except(expression) { //... } } void function() { EXCEPTION_REGISTRATION handler; //..Init handler function2(handler) } When you call SetHandler it will insert the exception handling like it was in the scope of function. So in this case at the moment you call SetHandler it will appear as if there is a __try __except block in function. Therefor if there's an exception inside function3 the handler in function will first be called and if that handler doesn't handle it, the handler installed by SetHandler will be called.
{ "language": "en", "url": "https://stackoverflow.com/questions/8352151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: RxJava2: onErrorResumeNext not intercepting 400 response code I have below code for error handling. My issue is that when server sends a 400 error code the onErrorResumeNext is not being called. Is this expected? I thought onErrorResumeNext would be called when server sends a non 200 code(200-300). public Single adapt(Call c) { return ((Single) adapt(c) .onErrorResumeNext(new Function() { //BELOW NOT BEING EXECUTED ON 400 error from server. @Override public Object apply(Object throwable) throws Exception { return Single.error(DoSomethingWithException((Throwable) throwable)); } }).subscribeOn(Schedulers.newThread()) .observerOn(AndroidSchedulers.mainThread()) .flatMap( response -> { } );}
{ "language": "en", "url": "https://stackoverflow.com/questions/53035441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Joins and Output format Can any one help me with the below sql? **Table A** Id Seq First_Name Last_Name 1 1 John Walter 1 2 Michael Jordan 1 3 Sally May I want my output to look something like below where for a given Id, for each sequence number, I want to get first name and last name of the other sequence numbers. Example Output Id Seq Name 1 1 Michael Jordan | Sally May 1 2 John Walter | Sally May 1 3 John Walter | Michael Jordan Any help with the SQL? A: You want to use the collect() aggregate function. Here's a link to it's Oracle documentation. For your case, this would be: create or replace type names_t as table of varchar2(50); / create or replace function join_names(names names_t) return varchar2 as ret varchar2(4000); begin for i in 1 .. names.count loop if i > 1 then ret := ret || ','; end if; ret := ret || names(i); end loop; return ret; end join_names; / create table tq84_table ( id number, seq number, first_name varchar2(20), last_name varchar2(20) ); insert into tq84_table values (1, 1, 'John' , 'Walter'); insert into tq84_table values (1, 2, 'Michael', 'Jordan'); insert into tq84_table values (1, 3, 'Sally' , 'May' ); select t1.id, t1.seq, join_names( cast(collect(t2.first_name || ' ' || t2.last_name order by t2.seq) as names_t) ) from tq84_table t1, tq84_table t2 where t1.id = t2.id and t1.seq != t2.seq group by t1.id, t1.seq If you're using Oracle 11R2 or higher, you can also use LISTAGG, which is a lot simpler (without the necessity of creating a type or function): The query then becomes select listagg(t2.first_name || ' ' || t2.last_name, ',') within group (order by t2.seq) over (partition by id) as names from .... same as above ... A: Will work not only for 3 columns.This is in general. DECLARE @Names VARCHAR(8000) SELECT @Names = COALESCE(@Names + ', ', '') + First_Name +' '+Last_Name FROM A WHERE Seq !=2 and Id IS NOT NULL select Id,Seq,@Names from A where Seq = 2 print @Names You need to pass the Seq value so that you can get the records. Thanks, Prema
{ "language": "en", "url": "https://stackoverflow.com/questions/8571197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C++ write a function to print all divisors of a float So I have been trying to write this function and implement it without luck. The function has to be written as void divisor (float x ) and it will ask a user for a int number and run until the user inputs a value of 0 . I get a few errors one which concerns me the most is invalid operands of types ‘float’ and ‘int ’ to binary ‘operator I have tried writing it so: #include <iostream> using namespace std ; void divisor (float x ) { int result ; int a ; result = x % a << endl ; a++ return 0 ; } }; int main () { int n ; float arg; cin >> arg ; cin >> n ; cin >> arg; if ( n =! 0 ){ divisor ( arg) ; }else{ cin >> n ; } return 0 ; } ; A: The expression x % a is only valid for integral types x and a. Since x is a float type, compilation fails. If you want the floating point modulus for a float type, then use std::fmodf instead. (Note that a will be implicitly converted to a float.) Reference: https://en.cppreference.com/w/cpp/numeric/math/fmod
{ "language": "en", "url": "https://stackoverflow.com/questions/65956227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Fluentd : Is there a way to add multiple tags in single match block I have multiple source with different tags. Im trying to add multiple tags inside single match block like this. <source> @type tail @label @TESTLABEL path /var/log/containers/app-one-*.log pos_file /var/log/app-one.log.pos tag app.one <parse> @type none </parse> read_from_head true </source> <source> @type tail @label @TESTLABEL path /var/log/containers/app-two-*.log pos_file /var/log/app-two.log.pos tag app.two <parse> @type none </parse> read_from_head true </source> <source> @type tail @label @TESTLABEL path /var/log/containers/app-three-*.log pos_file /var/log/app-three.log.pos tag app.three <parse> @type none </parse> read_from_head true </source> <label @TESTLABEL> <match app.*> @type Test(confidential so adding test) subsystemname ${tag_parts[1]} is_json true </match> </label> Trying to set subsystemname value as tag's sub name like(one/two/three). ${tag_prefix[1]} is not working for me. Not sure if im doing anything wrong. A: Use whitespace <match tag1 tag2 tagN> From official docs When multiple patterns are listed inside a single tag (delimited by one or more whitespaces), it matches any of the listed patterns: * *The patterns match a and b *The patterns <match a.** b.*> match a, a.b, a.b.c (from the first pattern) and b.d (from the second pattern).
{ "language": "en", "url": "https://stackoverflow.com/questions/68466083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: testcase failed when getting variable output from bot using botium box I am using botium-box. I have the following convo file: Here the date is a variable and changes everyday so I have to change it everyday in convo file otherwise the testcase is failing. I have tried few solutions: * *setting SCRIPTING_ENABLE_MEMORY to true in advance settings and using placeholder for variables. For eg. *I tried setting INTENT_CONFIDENCE to 70 in advance settings and using in convo file. For eg: *I tried INTENT_CONFIDENCE directly in convo file without setting it in advance capabilities. For eg. *I tried using %s in place of variable. For eg. Testcases are still failing. Is it a bug? Do I have to change any Botium settings? How can I do partial matching of responses? A: Solution 1 should be working (see here and here). If it doesn't work, please attach log file for analysis. Options 2 and 3 are for something totally different (verification of intent resolution confidence), and Option 4 is not a Botium feature. What you can try as well: Botium by default does substring matching for assertions, so your convo file could look something like this: #me what is the date today ? #bot Today is
{ "language": "en", "url": "https://stackoverflow.com/questions/54630859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to write the jquery for the following I am new to jquery I want to hide a particular division when a particular element a drop downlist is selected, I also want to increase the size of the adjasent column when the particular is hidden $(function() { $('#d1').change(function() { $('#group3').hide(); $('#' + $(this).val()).show(); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="group1" id="d1"> <select class="cls1"> <option value="">Type</option> <option value="QS">1</option> <option value="SP">2</option> <option value="XL">3</option> </select> </div> <div class="div2"> <div class="group2" , width="50%"> Division2: Hide when 3 is selected </div> <div class="group3" , width="50%"> Hide when 1 or 2 is selected </div> </div> but this hide division group3 every time How can I change it so that it would hide different divisions as per my choice A: First you need to give all groups wich u want to hide in JS, a main class name (groupclass) like this : <div class="group1" id="d1"> <select class="cls1"> <option value="">Type</option> <option value="QS">1</option> <option value="SP">2</option> <option value="XL">3</option> </select> </div> <div class="div2"> <div class="group2 groupclass" , width="50%"> Division2: Hide when 3 is selected </div> <div class="group3 groupclass" , width="50%"> Hide when 1 or 2 is selected </div> </div> Then you need to say in JS, hide all first and show just selected group like this : <script> $('#d1 > select').change(function() { $('.groupclass').hide(); $('.group' + $('option:selected', this).text()).show(); }); </script> A: Here you go $d1 = $('#d1'); $d1.change(function() { $("[id^=group]").show(); var value = $d1.val(); if (value === "QS" || value === "SP") { $('#group3').hide(); } else if (value === "XL") { $('#group2').hide(); } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="group1"> <select class="cls1" id="d1"> <option value="">Type</option> <option value="QS">1</option> <option value="SP">2</option> <option value="XL">3</option> </select> </div> <div class="div2"> <div id="group2" style="width:50%"> Division2: Hide when 3 is selected </div> <div id="group3" style="width:50%"> Hide when 1 or 2 is selected </div> </div> A: You can try following, $(function() { $('#d1').change(function(){ var selected_valule = $("#d1").val(); console.log(selected_valule); if(selected_valule == "XL" ){ $('#group3').hide(); $('#group2').show(); }else{ $('#group2').hide(); $('#group3').show(); } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="group1" > <select class="cls1" id="d1"> <option value="">Type</option> <option value="QS">1</option> <option value="SP">2</option> <option value="XL">3</option> </select> </div> <div class="div2"> <div id="group2" style="width:50%"> Division2: Hide when 3 is selected </div> <div id="group3" style="width:50%"> Hide when 1 or 2 is selected </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/50739752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to write a test method for createNewToken Method? I am new to this Mockito J-Unit Testing and I want to test my createNewToken()-Method but I cant understand the logic of it. This is my method: public String createNewToken(String usertoken) { WebToken oldToken = getTokenByUserToken(usertoken); if (!Assert.isNull(oldToken)) { em.remove(oldToken); } WebToken webToken = new WebToken(); webToken.setToken(UUID.randomUUID().toString()); webToken.setUserToken(usertoken); em.persist(webToken); return webToken.getToken(); } And this is my test method but i am sure it is wrong: @RunWith(Enclosed.class) public class WebTokenPSTest extends AbstractPersistenceTest { @InjectMocks WebTokenPS cut; @RunWith(MockitoJUnitRunner.class) public static class createNewToken extends WebTokenPSTest { @Test public void happyPath() { String token = cut.createNewToken("token"); String result = token; assertThat(result).isEqualTo(token); } } } A: Tthe main parts of your method works with Hibernate EntityManager, as I can see. So you should test this part, or mock it if possible. Also you can mock getTokenByUserToken(userToket). Here you can write several cases. So the possible test cases: * *getTokenByUserToken(usertoken) return null. So your method creates new Token and persist token to DB. The assertion em.createQuery("select token t...."). Here you validate that new token persists to DB *getTokenByUserToken(usertoken) return not persisted in DB token. Here you can expect the exception, when the EntityManager tries to remove this token. It's a good way to find, that some exception cases aren't properly handled in the code *getTokenByUserToken(usertoken) returns existing token (you can insert it to DB before this test for example). Here you test the removing of existing token and creating of the new token.
{ "language": "en", "url": "https://stackoverflow.com/questions/50016601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set Windows Forms Application (C++) to have an Aero/Glass background? I am working on creating a Windows Forms Application in C++ using Visual Studio 2010 Pro. I wanted to create a transparent background, that is, using the Aero Glass effect, similar to the way it surrounds the bottom of the UI in Windows Photo Viewer. At this point, I've looked through all of the features, and while you can change color and opacity, it's not exactly what I'm looking for. I want that nice blurred glass effect. I started this project from the template code that Visual Studio gives you, so I don't really have much to link. I just added a few items from the toolbox and linked them to functions in the Form1.h file. I apologize for my lack of input, I'm quite new to Windows UI programming; I wish I could add more information. For the sake of simplicity, here is the Form1.h code: #pragma once namespace Secret { //my project's name is "Secret" using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Summary for Form1 /// </summary> public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~Form1() { if (components) { delete components; } } private: System::Windows::Forms::Button^ button1; private: System::Windows::Forms::RichTextBox^ richTextBox1; private: System::Windows::Forms::TextBox^ textBox1; private: Microsoft::VisualBasic::PowerPacks::ShapeContainer^ shapeContainer1; private: Microsoft::VisualBasic::PowerPacks::RectangleShape^ rectangleShape1; private: Microsoft::VisualBasic::PowerPacks::LineShape^ lineShape1; private: Microsoft::VisualBasic::PowerPacks::OvalShape^ ovalShape2; private: Microsoft::VisualBasic::PowerPacks::OvalShape^ ovalShape1; protected: private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->button1 = (gcnew System::Windows::Forms::Button()); this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox()); this->textBox1 = (gcnew System::Windows::Forms::TextBox()); this->shapeContainer1 = (gcnew Microsoft::VisualBasic::PowerPacks::ShapeContainer()); this->lineShape1 = (gcnew Microsoft::VisualBasic::PowerPacks::LineShape()); this->ovalShape2 = (gcnew Microsoft::VisualBasic::PowerPacks::OvalShape()); this->ovalShape1 = (gcnew Microsoft::VisualBasic::PowerPacks::OvalShape()); this->rectangleShape1 = (gcnew Microsoft::VisualBasic::PowerPacks::RectangleShape()); this->SuspendLayout(); // // button1 // this->button1->Location = System::Drawing::Point(107, 171); this->button1->Name = L"button1"; this->button1->Size = System::Drawing::Size(75, 23); this->button1->TabIndex = 0; this->button1->Text = L"Save"; this->button1->UseVisualStyleBackColor = true; this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click); // // richTextBox1 // this->richTextBox1->Location = System::Drawing::Point(12, 12); this->richTextBox1->Name = L"richTextBox1"; this->richTextBox1->Size = System::Drawing::Size(260, 126); this->richTextBox1->TabIndex = 1; this->richTextBox1->Text = L""; this->richTextBox1->TextChanged += gcnew System::EventHandler(this, &Form1::richTextBox1_TextChanged); // // textBox1 // this->textBox1->Location = System::Drawing::Point(13, 145); this->textBox1->Name = L"textBox1"; this->textBox1->Size = System::Drawing::Size(259, 20); this->textBox1->TabIndex = 2; this->textBox1->Text = L"filename.txt"; // // shapeContainer1 // this->shapeContainer1->Location = System::Drawing::Point(0, 0); this->shapeContainer1->Margin = System::Windows::Forms::Padding(0); this->shapeContainer1->Name = L"shapeContainer1"; this->shapeContainer1->Shapes->AddRange(gcnew cli::array< Microsoft::VisualBasic::PowerPacks::Shape^ >(4) {this->lineShape1, this->ovalShape2, this->ovalShape1, this->rectangleShape1}); this->shapeContainer1->Size = System::Drawing::Size(290, 268); this->shapeContainer1->TabIndex = 3; this->shapeContainer1->TabStop = false; // // lineShape1 // this->lineShape1->Name = L"lineShape1"; this->lineShape1->X1 = 14; this->lineShape1->X2 = 270; this->lineShape1->Y1 = 228; this->lineShape1->Y2 = 228; // // ovalShape2 // this->ovalShape2->Location = System::Drawing::Point(135, 207); this->ovalShape2->Name = L"ovalShape2"; this->ovalShape2->Size = System::Drawing::Size(20, 44); // // ovalShape1 // this->ovalShape1->Location = System::Drawing::Point(16, 208); this->ovalShape1->Name = L"ovalShape1"; this->ovalShape1->Size = System::Drawing::Size(252, 42); // // rectangleShape1 // this->rectangleShape1->Location = System::Drawing::Point(14, 206); this->rectangleShape1->Name = L"rectangleShape1"; this->rectangleShape1->Size = System::Drawing::Size(257, 46); // // Form1 // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->BackColor = System::Drawing::SystemColors::Control; this->BackgroundImageLayout = System::Windows::Forms::ImageLayout::None; this->ClientSize = System::Drawing::Size(290, 268); this->Controls->Add(this->textBox1); this->Controls->Add(this->richTextBox1); this->Controls->Add(this->button1); this->Controls->Add(this->shapeContainer1); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::Fixed3D; this->MaximizeBox = false; this->Name = L"Form1"; this->Text = L"Secret"; this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void richTextBox1_TextChanged(System::Object^ sender, System::EventArgs^ e) { } private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) { } }; } Thank you for any and all help! I appreciate it. A: What you're looking for is the DWM (Desktop Window Manager) API, especially the function DwmExtendFrameIntoClientArea. Here's some C# code that demonstrates how to do this: CodeProject Also, make sure not to extend the frame when desktop composition is enabled, or you'll run into problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/6785733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to solve team provision issue without giving someone login information? Sometimes, other team members receive certificates and provision files from me. And it is finely installed but, 'team ID' warning is shown sometime. When they login to ADC account in xcode (by clicking 'fix issue' button on xcode) it is solved. But, some developers are from other team/company, so it is hard to tell them login information. In this case, how to solve team provision (team prefix) problem ? Thanks A: You simply (I say simply, but if can be one of the most aggravating parts of iOS development) need to make sure you are providing the developers with the private key for the certificate, the certificate, and provisioning profile for development. If your project settings are correct, you should not get the team prefix problem. Also, I would encourage the other team members to delete all their other certificates and profiles before installing yours. The other option would be to add their Apple IDs to your account as a team member. They can have their own credentials, but still access the account through xCode.
{ "language": "en", "url": "https://stackoverflow.com/questions/35220478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: convert the image value array into x/y coordinates I want to find the x/y coordinate of the edge after using canny edge detection with openCV import numpy as np import cv2 as cv from matplotlib import pyplot as plt img = cv.imread('star.png',0) edges = cv.Canny(img,100,200) plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Original Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(edges,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.show() before after turning it into grey scale and canny's edge detection the data values is stored in variable "edges", is there a way to take the value of the actual edge and turn it into x,y coord Thank you A: You can get the edge coordinates by using numpy library: xAxis, yAxis = np.nonzero(edges) In here xAxis and yAxis include all the x and y axis respectively belong to the edge which canny detected. You can also simply calculate the average of these coordinates which mean the center of detected edge coordinates: centerX = int(np.mean(xAxis)) centerY = int(np.mean(yAxis)) Here is the whole code: import numpy as np import cv2 as cv from matplotlib import pyplot as plt from numpy.core.defchararray import center img = cv.imread('/home/yns/Downloads/st.jpg',0) edges = cv.Canny(img,100,200) xAxis, yAxis = np.nonzero(edges) centerX = int(np.mean(xAxis)) centerY = int(np.mean(yAxis)) cv.circle(img,(centerX,centerY),5,(0,255,255),3) plt.subplot(121),plt.imshow(img,cmap = 'gray') plt.title('Original Image'), plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(edges,cmap = 'gray') plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) plt.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/69096680", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ms-access Combo Populate For some reason my Combo box will not populate a text box field, i have done this on previous forms and even have working in different fields on this very form, but i cannot seem to get it to populate one text box. here is a picture to show what is happening, as well as the code. in theory it should work and all the properties are set correct. This combo box is from another table though. Private Sub ProjectID_Change() Me.Client_Name.Value = Me.ProjectID.Column(2) End Sub A: Combobox columns are numbered from (0) so you need to reference column 1 ; Private Sub ProjectID_Change() Me.Client_Name.Value = Me.ProjectID.Column(1) End Sub And as suggested move it to the AfterUpdate event.
{ "language": "en", "url": "https://stackoverflow.com/questions/51322286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Inserting Javascript based on Ruby If Statement I am trying to trigger a bootstrap modal based on conditions about the current user. Essentially, to do anything in the page the user is accessing, they need to have created a hotel in the system. If they haven't, I want a modal to pop up with the creation form. Currently, I have: <%= unless current_user.hotels.exists? "<script> $('#createhotelModal').modal('toggle') </script>" end %> Which simply inserts the as text. Trying to next a <%= javascript_tag do %> command doesn't work with the controller throwing various errors. Is this the smart way to do it, or should I just create a completely separate page and use the controller to send people to the correct page? A: Follow advice listed in this railscast <%= javascript_tag do %> $('#createhotelModal').modal('toggle') <% end %>
{ "language": "en", "url": "https://stackoverflow.com/questions/12303140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Asp.net MVC5 async action result executed, but response not sent till web server shutdown I have an async action, which is supposed to return a JSON message to the browser after awaiting some task. Though the ActionResult is built and executed successfully(I'm using my own JsonResult, so I confirmed this by stepping into the source), the browser still gets no response(confirmed by Fiddler). Meanwhile, it works if I'm awaiting for Task.Delay(), and returning a dummy message. Strangely, if I rebuild my projects with VS2013 while the IIS Express running my website, all the sudden the browser receives the message that was supposed to be sent several minutes ago! I think it's shutting down the web server makes this happen, however I can't figure out how exactly this is happening. I've been debugging for a day, disabled everything that I thought could have been related, with no luck. So any help about what could be the cause to this strange behavior is welcome. Thanks, here is the code: [HttpPost] public async Task<JsonResult> Update(string token) { try { //This works //await Task.Delay(TimeSpan.FromSeconds(1)); //return Json(new { error = "testing." }); //This won't work var feedback = await ServerConnectionKeeper.UpdateStation(token); return feedback.Success ? Json(new { redirect = Url.Action("Index", "Home") }) : Json(new { error = feedback.Error }); } catch (Exception ex) { return Json(new { error = ex.Message }); } } A: It turns out that I called an async void method, which made some strange unknown(by me) things happen. Here is the some conceptual code: [HttpPost] public async Task<JsonResult> Data() { await SomeTask(); return Json(new { message = "Testing" }); } private async Task SomeTask() { FireAndForget(); await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false); } private async void FireAndForget() { await Task.Delay(TimeSpan.FromSeconds(100)).ConfigureAwait(false); } With above code, I thought the response would come 1 second after requesting. But it does not, not even 100 seconds after. In some cases I get a InvalidOperationException, in other cases I get nothing. If I change the async void to async Task, either ConfigureAwait(false) or not, every thing works: [HttpPost] public async Task<JsonResult> Data() { await SomeTask(); return Json(new { message = "Testing 4" }); } private async Task SomeTask() { FireAndForget(); await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false); } private async Task FireAndForget() { await Task.Delay(TimeSpan.FromSeconds(100)).ConfigureAwait(false); } The reason responses are sent when web server shutting down in my production code, is because my FireAndForget() method there is an async loop reading network messages, and never returns untill the connection closed, and shutting down the web server closes the connection. It's still strange to me that I didn't get InvalidOperationException there though.
{ "language": "en", "url": "https://stackoverflow.com/questions/20428899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }