source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0007292308.txt" ]
Q: How to invoke a method on a managed bean when pressing backbutton or F5? How can I invoke a method on a managed bean when pressing backbutton or F5? A: If the bean is request scoped and the page is served with response headers which instructs the browser to not cache the page, then you can do that job in the bean's constructor or @PostConstruct method. E.g. public class Bean { public Bean() { // Here, in the constructor. } @PostConstruct public void init() { // Or here, in the postconstructor. } } The @PostConstruct method is particularly useful if you're injecting dependencies by @ManagedProperty, @EJB or @Inject, etc and want to do the initialization job based on those dependencies.
[ "stackoverflow", "0027577975.txt" ]
Q: How to pass a language variable to layout in ZF2? I just started Zend Framework 2 and i want to make it possible to attach a language to the doctype. Bootstrap: $this->layout()->setVariable('language', 'nl'); Layout.phtml <html lang="<?php echo $language;?>"> This only works from the Controller, how can i fix this for the bootstrap? The awnser: public function onBootstrap(MvcEvent $e) { $viewModel = $e->getApplication()->getMvcEvent()->getViewModel(); $viewModel->language = 'en'; } // Now in your layout: <html lang="<?php echo $this->language ?>"> A: You have at least two options: You can write a custom view helper to resolve and return the language and use it in your layout like: <html lang="<?php echo $this->langHelper() ?>"> In your Module.php's onBootstrap() method, you can pass any variable to the layout like this: public function onBootstrap(MvcEvent $e) { $viewModel = $e->getApplication()->getMvcEvent()->getViewModel(); $viewModel->language = 'en'; } // Now in your layout: <html lang="<?php echo $this->language ?>">
[ "stackoverflow", "0018182953.txt" ]
Q: left join to count unmatched row gives incorrect count I am using left join to count unmatched rows but although my query is correct i am having some logical problem. check this fiddle the query should return count 1 but instead returns 0.I know the reason is because it finds a matched row but i don't know other ways to solve the problem.I need to count the unseen questions by a user. A: You need to put your qv.question_view_id IS NULL clause as part of the JOIN, not the WHERE. SELECT qt.user_id, count(q.question_id) cnt FROM questions q INNER JOIN questions_to qt ON qt.question_id = q.question_id LEFT JOIN question_view qv ON q.question_id = qv.question_id -- Not that I've moved this clause into the JOIN condition. AND qv.question_view_id IS NULL WHERE qt.user_id = 13 GROUP BY qt.user_id
[ "stackoverflow", "0016778801.txt" ]
Q: How To crop Image using ajax, jQuery in Codeigniter? I see Lot's of image Crop example But i'm not find like what's i want. So i post in Stackoverflow. A complete script in Codeigniter FrameWork as view as like 1. Click upload and select .jpg/.png file 2. auto upload in server and Show like http://i.stack.imgur.com/VTtO5.png 3. After upload User crop Profile Pic preDifiend Size. 4. and save in my DB. I'm unable to ajax. Plz.. If you have complete this Provide me. Ebrahim Khalil A: I am using JCrop Plugin, Check out their PHP cropping example. Basically what happens when you select are to crop, It will be saved in X,Y for co-ordinates and H,W for height and width. Codeigniter's image_lib gives simple way to crop or resize image. Read the docs for that .. My code Snippet : //crop it $data['x'] = $this->input->post('x'); $data['y'] = $this->input->post('y'); $data['w'] = $this->input->post('w'); $data['h'] = $this->input->post('h'); $config['image_library'] = 'gd2'; //$path = 'uploads/apache.jpg'; $config['source_image'] = 'uploads/'.$data['user_data']['img_link']; //http://localhost/resume/uploads/apache.jpg // $config['create_thumb'] = TRUE; //$config['new_image'] = './uploads/new_image.jpg'; $config['maintain_ratio'] = FALSE; $config['width'] = $data['w']; $config['height'] = $data['h']; $config['x_axis'] = $data['x']; $config['y_axis'] = $data['y']; $this->load->library('image_lib', $config); if(!$this->image_lib->crop()) { echo $this->image_lib->display_errors(); } redirect('profile'); Here original Uploaded image is cropped , you can also create new image. Just make create_thumb = true for that.
[ "stackoverflow", "0049132494.txt" ]
Q: Yield Return All Remaining Items I have an IEnumerable list of items from which I yield items. Within the IEnumerable, I am parsing strings which I split with a regex (splits the string by spaces). The string is split into what I refer to as 'sections'. After getting the 5th and 6th sections, I need to get all sections after that, how can I do that without specifying the explicitly? Here is what I have so far: yield return new Item { Product = sections[5], Price = sections[6], // Medadata = sections[?], ////This part is comprised of many sections }; A: You can use Skip: Medadata = sections.Skip(7).ToArray() It skips the number of items in the parameter and will continue reading from there on, yielding the 'remaining' items. If you want to put all the remaining items in a single string, you can join them (I used a space as separator as example): Medadata = string.Join(" ", sections.Skip(7))
[ "stackoverflow", "0025424297.txt" ]
Q: How Bootstrap need a size of container into container? I would create into section BODY of this layout different section row. Is the grid system is resetting to 12 in this area or is 9? If I need to create into BODY section 12 column can I do? or not? <div class="container"> <div class="row"> <div class="col-sm-3">SX BAR</div> <div class="col-sm-9">BODY</div> </div> </div> Tnx a lot! A: containers contains rows which can contain up to 12 columns. If you put 12 columns in a row, and you build another row just after, it won't be affected by the number of columns in the previous row. So it will be basically 12. So, if you build antoher container after the first one, then you'll have to build another row in it, and thus the number will still be 12. I would advise you to read carefully Bootstrap CSS Grid System Doc because you seem to have misunderstood the concept of Bootstrap "Grid".
[ "stackoverflow", "0027903282.txt" ]
Q: Searching for better multitype validation I need to check if variable is of specified scalar type - but I cannot use general function like is_scalar - because this would accept also those types (that type) I don't want to accept. It is possible to check types step by step: with in-built functions like is_string with separate comparation of value given by gettype but it is a bit incomfortable because it would give a very long code. So, I prepared following (relatively short - if you ignore external parts) code: !in_array(gettype($Item), MarC::Show_Options_Scalars()) where function Show_Options_Scalars() represents allowed accepted scalar types. That one prepares array of allowed types - from constants written in interface. That is why I wrote that own validation is relatively short if you ignore external parts. And still I am not sure if multitype validation could be done better - it means if can I validate variable type by else better way. That external code is not reason why search for better multitype validation. A: i like your code. i would only make a function for it function val( &$value ) { return !in_array( gettype( $value ), array( 'boolean', 'integer', 'what ever' ) ); } I use & to save some res. useage: if( val( $test ) ) die( 'pass' );
[ "stackoverflow", "0039237415.txt" ]
Q: What is inside a Docker Ubuntu Image if Docker doesn't encapsulate an OS? I'm starting a new Django Project using Docker. I'm confused about the existence of the Ubuntu Docker image which is mentioned in many tutorials as well as being one of the most popular images in the Docker Repo. I thought Docker is a containerization system built ON TOP of the OS, so why is there an Ubuntu Docker Image? Perhaps a common use scenario on when/who would use this would help. A: With a Linux distro you normally get: A bootloader which loads a kernel A kernel which manages the system and loads an init system An init system that sets up and runs everything else Everything else Docker itself replaces most of the init system. Docker images replace "Everything else", which can still be a large portion of any normal distro. An Ubuntu image contains the minimal set of Ubuntu binaries and shared libraries compiled with the Ubuntu build tools to run a shell, do some normal linuxy things and use the apt package manager. A Centos image does the same with Centos binaries, shared libraries and the yum package manager. etc. A Docker image doesn't need to be a complete distribution. You can run a single statically compiled binary in a container and you only need that binary in the image, nothing else. The busybox image is a good example of building a largely normal Linux environment from a single static binary. The Kernel All containers share the one host kernel. The container is separated from the rest of the system using kernel cgroups and namespaces. To anything running in the container, this appears to be it's own system. All flavours of Linux don't use the exact same kernel but the kernel interfaces are largely compatible which allows the portability of Docker images. Docker itself requires a 3.10+ kernel to be able to run which narrows the range of kernel possibilities. It's possible to have some esoteric software that requires some esoteric kernel feature to be compiled in that wouldn't run across different Docker hosts. That's pretty rare and easily identifiable as you've had to compile a kernel to get said software working.
[ "stackoverflow", "0063483111.txt" ]
Q: Join nested JSON dataframe and another dataframe I am trying to join a dataframe1 generated by the JSON with dataframe2 using the field order_id, then assign the "status" from dataframe2 to the "status" of dataframe1. Anyone knows how to do this. Many thanks for your help. dataframe1 [{ "client_id": 1, "name": "Test01", "olist": [{ "order_id": 10000, "order_dt_tm": "2012-12-01", "status": "" <== use "status" from dataframe2 to populate this field }, { "order_id": 10000, "order_dt_tm": "2012-12-01", "status": "" } ] }, { "client_id": 2, "name": "Test02", "olist": [{ "order_id": 10002, "order_dt_tm": "2012-12-01", "status": "" }, { "order_id": 10003, "order_dt_tm": "2012-12-01", "status": "" } ] } ] dataframe2 order_id status 10002 "Delivered" 10001 "Ordered" A: Here is your raw dataset as a json string: d = """[{ "client_id": 1, "name": "Test01", "olist": [{ "order_id": 10000, "order_dt_tm": "2012-12-01", "status": "" }, { "order_id": 10000, "order_dt_tm": "2012-12-01", "status": "" } ] }, { "client_id": 2, "name": "Test02", "olist": [{ "order_id": 10002, "order_dt_tm": "2012-12-01", "status": "" }, { "order_id": 10003, "order_dt_tm": "2012-12-01", "status": "" } ] } ]""" Firstly, I would load it as json: import json data = json.loads(d) Then, I would turn it into a Pandas dataframe, notice that I remove status field as it will be populated by the join step : df1 = pd.json_normalize(data, 'olist')[['order_id', 'order_dt_tm']] Then, from the second dataframe sample, I would do a left join using merge function: data = {'order_id':[10002, 10001],'status':['Delivered', 'Ordered']} df2 = pd.DataFrame(data) result = df1.merge(df2, on='order_id', how='left') Good luck UPDATE # JSON to Dataframe df1 = pd.json_normalize(data) # Sub JSON to dataframe df1['sub_df'] = df1['olist'].apply(lambda x: pd.json_normalize(x).drop('status', axis=1)) # Build second dataframe data2 = {'order_id':[10002, 10001],'status':['Delivered', 'Ordered']} df2 = pd.DataFrame(data2) # Populates status in sub dataframes df1['sub_df'] = df1['sub_df'].apply(lambda x: x.merge(df2, on='order_id', how='left').fillna('')) # Sub dataframes back to JSON def back_to_json_str(df): # turns a df back to string json return str(df.to_json(orient="records", indent=4)) df1['olist'] = df1['sub_df'].apply(lambda x: back_to_json_str(x)) # Global DF back to JSON string parsed = str(df1.drop('sub_df', axis=1).to_json(orient="records", indent=4)) parsed = parsed.replace(r'\n', '\n') parsed = parsed.replace(r'\"', '\"') # Print result print(parsed) UPDATE 2 here is a way to add index colum to a dataframe: df1['index'] = [e for e in range(df1.shape[0])]
[ "stackoverflow", "0008453116.txt" ]
Q: Repository pattern with PLinq I am fairly new to Plinq and Repo pattern. I nee some references and guidlines from you for implementation of Repository pattern using dbml, PLinq in fx 4.0 A: Repository pattern provides you with abstraction over the data storage. PLINQ with repository pattern will work if the underlined storage is (source): (in-memory) T[], List<T>, or any other kind of IEnumerable<T> XML documents loaded using the System.Xml.Linq APIs It will not work with: LINQ-to-SQL or LINQ-to-Entities (source) NHibernate
[ "stackoverflow", "0029551437.txt" ]
Q: Update form row in php error I'm trying to update multiple row/rows in my form. I'm getting the error Notice: Array to string conversion in C:\wamp..... I'm also getting another error Warning: Cannot modify header information - headers already sent by (output started at C:\wamp\.... Both of these are now fixed. Form $ad = "<form action='updaterecords.php' method='post' id='update'> \n"; $records = $this->query_recs(); foreach ($records as $record) { $ad .= "<p id='id{$record->id}'>"; $ad .= "<input type='hidden' name='id[]' value='" .$this->render_i18n_data($record->id) . "' />\n"; $ad .= "<input type='text' name='paname[]' value='". $this->render_i18n_data($record->pa_name) . "' class='paname' />\n"; $ad .= "<input type='text' name='pcname[]' value='". $this->render_i18n_data($record->pc_name) . "' class='pcname' />\n"; $ad .= "<input type='text' name='pdname[]' value='". $this->render_i18n_data($record->pd_name) . "' class='pdname' />\n"; $ad .= "<input type='text' name='pfname[]' value='". $this->render_i18n_data($record->pf_name) . "' class='pfname' />\n"; $ad .= "<input type='submit' name='update' value='Update' />"; $ad .= "</p>"; } echo($ad); PHP <?php include 'dbdetails.php'; $con = new mysqli($server, $user, $pass, $db); // Check connection if ($con->connect_error) { die("Connection failed: " . $con->connect_error); } echo "Connected successfully"; if(isset($_POST['update'])){ $id = $_POST['id']; $paname = $_POST['paname']; $pcname = $_POST['pcname']; $pdname = $_POST['pdname']; $pfname = $_POST['pfname']; mysqli_query($con, "UPDATE wp_pbcbc_records SET pa_name = '$paname', pc_name='$pcname', pd_name='$pdname', pf_name='$pfname' WHERE id = '$id' "); header("location: localhost/myp"); exit; } ?> Update: This has now been solved. Thanks to the people who gave me an answer! A: Note: You passed values in array. You must run them in a loop before using them in your query. On top of your isset() function, there must have no output of HTML entities, which is the common reason for header() function to fail and cause an error. Your connection to your database: include("dbdetails.php"); $con = new mysqli($server, $user, $pass, $db); /* MAKE SURE THAT THE VALUES OF YOUR VARIABLES ARE CORRECT CORRESPONDING TO YOUR DATABASE */ /* CHECK CONNECTION */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } Your updated code: /* THERE MUST HAVE NO OUTPUT IN THIS SECTION TO FIX THE HEADER ERROR */ if(isset($_POST['update'])){ $counter = count($_POST["paname"]); for($x = 0; $x<=$counter; $x++){ if(!empty($_POST["paname"][$x])){ $id = mysqli_real_escape_string($con,$_POST['id'][$x]); $paname = mysqli_real_escape_string($con,$_POST['paname'][$x]); $pcname = mysqli_real_escape_string($con,$_POST['pcname'][$x]); $pdname = mysqli_real_escape_string($con,$_POST['pdname'][$x]); $pfname = mysqli_real_escape_string($con,$_POST['pfname'][$x]); mysqli_query($con, "UPDATE wp_pbcbc_records SET pa_name = '$paname', pc_name='$pcname', pd_name='$pdname', pf_name='$pfname' WHERE id = '$id' "); } /* END OF IF CHECKING paname */ } /* END OF FOR LOOP */ header("location: localhost/myp"); exit; } /* END OF ISSET */ ?> On the side note: You must use mysqli_real_escape_string() to sanitize the values of your variables before using them in your query to prevent SQL injections. Better recommendation, is to use mysqli_* prepared statement. It will sanitize the variables automatically and no need to escape the strings per variable. Your code using mysqli_* prepared statement: /* THERE MUST HAVE NO OUTPUT IN THIS SECTION TO FIX THE HEADER ERROR */ if(isset($_POST['update'])){ $counter = count($_POST["paname"]); for($x = 0; $x<=$counter; $x++){ if(!empty($_POST["paname"][$x])){ if($stmt = $con->prepare("UPDATE wp_pbcbc_records SET pa_name=?, pc_name=?, pd_name=?, pf_name=? WHERE id=?")){ $stmt->bind_param("ssssi",$_POST["paname"][$x],$_POST["pcname"][$x],$_POST["pdname"][$x],$_POST["pfname"][$x],$_POST["id"][$x]); $stmt->execute(); $stmt->close(); } /* END OF PREPARED STATEMENT */ } /* END OF IF CHECKING paname */ } /* END OF FOR LOOP */ header("location: localhost/myp"); exit; } /* END OF ISSET */ ?>
[ "stackoverflow", "0038501058.txt" ]
Q: Search query for 2 text box My sql query is : $sel = "select * from search where name like '$search%' and price >'$price' "; but I didn't get the correct result. There are some problems in price Database A: Try to put the price without '...' just like a numeric value not like a varchar. select * from search where name like '$search%' and price > $price;
[ "stackoverflow", "0035323986.txt" ]
Q: CentOS 5 - Install PHP intl Server: CENTOS 5.11 i686 WHM 54.0 I've tried several approaches installing intl PHP extension. First approach is straight forward. In WHM i enter PHP PECL, and when trying to install intl: downloading intl-3.0.0.tgz ... Starting to download intl-3.0.0.tgz (248,200 bytes) ....................................................done: 248,200 bytes 150 source files, building running: phpize Configuring for: PHP Api Version: 20121113 Zend Module Api No: 20121212 Zend Extension Api No: 220121212 Specify where ICU libraries and headers can be found [DEFAULT] : building in /root/tmp/pear/pear-build-rootnuhZM5/intl-3.0.0 running: /root/tmp/pear/intl/configure --with-php-config=/usr/local/bin/php-config --with-icu-dir=DEFAULT checking for egrep... grep -E checking for a sed that does not truncate output... /bin/sed checking for cc... cc checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether cc accepts -g... yes checking for cc option to accept ANSI C... none needed checking how to run the C preprocessor... cc -E checking for icc... no checking for suncc... no checking whether cc understands -c and -o together... yes checking for system library directory... lib checking if compiler supports -R... no checking if compiler supports -Wl,-rpath,... yes checking build system type... i686-pc-linux-gnu checking host system type... i686-pc-linux-gnu checking target system type... i686-pc-linux-gnu checking for PHP prefix... /usr/local checking for PHP includes... -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib checking for PHP extension directory... /usr/local/lib/php/extensions/no-debug-non-zts-20121212 checking for PHP installed headers prefix... /usr/local/include/php checking if debug is enabled... no checking if zts is enabled... no checking for re2c... re2c checking for re2c version... invalid configure: WARNING: You will need re2c 0.13.4 or later if you want to regenerate PHP parsers. checking for gawk... gawk checking whether to enable internationalization support... yes, shared checking for icu-config... /usr/bin/icu-config checking for location of ICU headers and libraries... /usr checking for ICU 4.0 or greater... found 3.6 configure: error: ICU version 4.0 or later is required ERROR: `/root/tmp/pear/intl/configure --with-php-config=/usr/local/bin/php-config --with-icu-dir=DEFAULT' failed The intl.so object is not in /usr/local/lib/php/extensions/no-debug-non-zts-20121212 Tidying /usr/local/lib/php.ini... No changes Tidying /usr/local/cpanel/3rdparty/php/54/etc/php.ini... No changes Tried finding that intl.so object manually online, no luck. I'm afraid I might get non-compatible version and screw things up. Nonetheless, this would be a bad solution. Second approach is running pecl library via ssh: root@ns1 [/]# /usr/bin/pecl install intl and the response: downloading intl-3.0.0.tgz ... Starting to download intl-3.0.0.tgz (248,200 bytes) ....................................................done: 248,200 bytes could not extract the package.xml file from "/root/tmp/pear/cache/intl-3.0.0.tgz" Download of "pecl/intl" succeeded, but it is not a valid package archive Error: cannot download "pecl/intl" Download failed install failed Researching online, I tried to update icu via yum. It finds php53-intl.i386 package and says it's already installed. Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: centos.spd.co.il * extras: centos.spd.co.il * updates: centos.spd.co.il Excluding Packages in global exclude list Finished Installed Packages php53-intl.i386 PHP was excluded in the config, and I had to remove it from the list. I wonder why, in addition when I yum list php Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: centos.spd.co.il * extras: centos.spd.co.il * updates: centos.spd.co.il Excluding Packages in global exclude list Finished Available Packages php.i386 5.1.6-45.el5_11 updates And php -v says PHP 5.5.31 (cli) (built: Jan 14 2016 18:46:05) This also might be useful, rpm -qa | grep php response: cpanel-php54-Horde-Auth-2.1.8-4.cp1152 cpanel-php54-Horde-Compress-2.1.2-5.cp1152 cpanel-php54-Horde-Argv-2.0.11-4.cp1152 cpanel-php54-Horde-Secret-2.0.4-4.cp1152 cpanel-php54-Horde-Service-Twitter-2.1.1-4.cp1152 cpanel-php54-SOAP-0.13.0-4.cp1152 cpanel-php54-Date-Holidays-Denmark-0.1.3-4.cp1152 cpanel-php54-Horde-CssMinify-1.0.2-4.cp1152 cpanel-php54-Cache-1.5.6-4.cp1152 cpanel-php54-HTML-Template-IT-1.3.0-4.cp1152 cpanel-php54-Horde-Prefs-2.7.3-4.cp1152 cpanel-php54-Horde-Itip-2.1.0-4.cp1152 cpanel-php54-Horde-Serialize-2.0.3-4.cp1152 cpanel-php54-Horde-Css-Parser-1.0.6-4.cp1152 cpanel-php54-Horde-Support-2.1.3-4.cp1152 cpanel-php54-Horde-Constraint-2.0.2-4.cp1152 cpanel-php54-Horde-Service-Facebook-2.0.5-4.cp1152 cpanel-php54-Date-Holidays-Brazil-0.1.2-4.cp1152 cpanel-php54-Date-Holidays-Venezuela-0.1.1-4.cp1152 cpanel-php54-HTTP-1.4.1-4.cp1152 cpanel-php54-Text-Figlet-1.0.2-4.cp1152 cpanel-php54-Horde-Smtp-1.9.1-4.cp1152 cpanel-php54-Horde-ListHeaders-1.2.2-4.cp1152 cpanel-php54-Horde-Injector-2.0.4-4.cp1152 cpanel-php54-Horde-Image-2.3.1-4.cp1152 cpanel-php54-XML-Parser-1.3.4-4.cp1152 cpanel-php54-Horde-Kolab-Format-2.0.4-4.cp1152 cpanel-php54-Date-Holidays-Spain-0.1.3-4.cp1152 cpanel-php54-Date-Holidays-Iceland-0.1.2-4.cp1152 cpanel-php54-Console-Table-1.1.5-4.cp1152 cpanel-php54-MDB2-2.4.1-4.cp1152 cpanel-php54-trean-1.1.1-5.cp1152 cpanel-php54-zendopt-6.0.0-1.cp1142 cpanel-php54-Horde-Translation-2.2.0-4.cp1152 cpanel-php54-Horde-Stream-Filter-2.0.3-4.cp1152 cpanel-php54-Horde-Routes-2.0.2-4.cp1152 cpanel-php54-Horde-Oauth-2.0.1-4.cp1152 cpanel-php54-Mail-1.2.0-4.cp1152 cpanel-php54-Date-Holidays-Ireland-0.1.3-4.cp1152 cpanel-php54-Date-Holidays-Croatia-0.1.1-4.cp1152 cpanel-php54-Horde-Mail-2.6.0-4.cp1152 cpanel-php54-nag-4.2.4-7.cp1152 cpanel-php54-Horde-Browser-2.0.9-4.cp1152 cpanel-php54-Horde-Cache-2.5.0-4.cp1152 cpanel-php54-Horde-View-2.0.5-4.cp1152 cpanel-php54-Horde-Log-2.1.2-4.cp1152 cpanel-php54-Horde-Feed-2.0.1-4.cp1152 cpanel-php54-Date-Holidays-Finland-0.1.2-4.cp1152 cpanel-php54-Date-Holidays-USA-0.1.1-4.cp1152 cpanel-php54-Horde-Pack-1.0.5-4.cp1152 cpanel-php54-Horde-Core-2.20.2-4.cp1152 cpanel-php54-Horde-Crypt-2.5.3-4.cp1152 cpanel-php54-Horde-Socket-Client-2.0.0-5.cp1152 cpanel-php54-Horde-Autoloader-2.1.1-4.cp1152 cpanel-php54-Horde-Xml-Element-2.0.3-4.cp1152 cpanel-php54-Horde-Perms-2.1.4-4.cp1152 cpanel-php54-Horde-Queue-1.1.2-4.cp1152 cpanel-php54-Horde-Kolab-Session-2.0.1-4.cp1152 cpanel-php54-Date-Holidays-Japan-0.1.2-4.cp1152 cpanel-php54-Date-Holidays-Italy-0.1.1-4.cp1152 cpanel-php54-Horde-Idna-1.0.3-4.cp1152 cpanel-php54-PEAR-Command-Packaging-0.3.0-4.cp1152 cpanel-php54-Horde-Dav-1.1.2-4.cp1152 cpanel-php54-Horde-Yaml-2.0.2-4.cp1152 php53-common-5.3.3-26.el5_11 cpanel-php54-Horde-Exception-2.0.5-4.cp1152 cpanel-php54-Net-Socket-1.0.14-4.cp1152 cpanel-php54-Horde-SpellChecker-2.1.2-4.cp1152 cpanel-php54-Horde-Cli-2.0.6-4.cp1152 cpanel-php54-Net-URL-1.0.15-4.cp1152 cpanel-php54-Net-DNS2-1.4.1-4.cp1152 cpanel-php54-Date-Holidays-Serbia-0.1.0-4.cp1152 cpanel-php54-Date-Holidays-Germany-0.1.2-4.cp1152 cpanel-php54-Console-Color-1.0.3-4.cp1152 cpanel-php54-Horde-Icalendar-2.0.11-4.cp1152 cpanel-php54-turba-4.2.6-6.cp1152 cpanel-php54-Horde-Imap-Client-2.28.1-4.cp1152 cpanel-php54-Horde-Group-2.0.5-4.cp1152 cpanel-php54-Horde-Vfs-2.2.2-4.cp1152 cpanel-php54-Horde-Text-Flowed-2.0.2-4.cp1152 cpanel-php54-Horde-Xml-Wbxml-2.0.1-4.cp1152 cpanel-php54-Horde-History-2.3.4-4.cp1152 cpanel-php54-Horde-SessionHandler-2.2.4-4.cp1152 cpanel-php54-horde-lz4-1.0.8-2.cp1152 cpanel-php54-Horde-Pdf-2.0.3-4.cp1152 cpanel-php54-Services-Weather-1.4.7-4.cp1152 cpanel-php54-Date-Holidays-Romania-0.1.2-4.cp1152 cpanel-php54-Date-Holidays-Slovenia-0.1.2-4.cp1152 cpanel-php54-Date-Holidays-PHPdotNet-0.1.2-4.cp1152 cpanel-php54-Horde-JavascriptMinify-1.1.2-4.cp1152 cpanel-php54-Net-FTP-1.3.7-4.cp1152 cpanel-php54-XML-SVG-1.1.0-4.cp1152 cpanel-php54-horde-5.2.5-13.cp1152 cpanel-php54-Horde-Timezone-1.0.9-4.cp1152 cpanel-php54-webmail-5.2.6-6.cp1152 cpanel-php54-Horde-Token-2.0.6-4.cp1152 cpanel-php54-Date-1.4.7-4.cp1152 cpanel-php54-Horde-Share-2.0.7-4.cp1152 cpanel-php54-Horde-HashTable-1.2.3-4.cp1152 cpanel-php54-Date-Holidays-Australia-0.2.1-4.cp1152 cpanel-php54-Date-Holidays-SanMarino-0.1.1-4.cp1152 cpanel-php54-Log-1.12.7-4.cp1152 cpanel-php54-File-Fstab-2.0.3-4.cp1152 cpanel-php54-Horde-Rpc-2.1.4-4.cp1152 cpanel-php54-Horde-Mail-Autoconfig-1.0.2-4.cp1152 cpanel-php54-5.4.31-4.cp1150 cpanel-php54-Horde-Role-1.0.1-5.cp1152 cpanel-php54-Horde-Notification-2.0.2-4.cp1152 cpanel-php54-Horde-Lock-2.1.1-4.cp1152 cpanel-php54-XML-Serializer-0.20.2-4.cp1152 cpanel-php54-Horde-Imsp-2.0.5-4.cp1152 cpanel-php54-Date-Holidays-Norway-0.1.2-4.cp1152 cpanel-php54-Date-Holidays-UNO-0.1.3-4.cp1152 cpanel-php54-ingo-3.2.5-6.cp1152 cpanel-php54-Horde-Text-Filter-2.3.1-4.cp1152 cpanel-php54-Horde-Compress-Fast-1.1.0-4.cp1152 cpanel-php54-Horde-Stream-Wrapper-2.1.2-4.cp1152 cpanel-php54-Horde-Template-2.0.2-4.cp1152 cpanel-php54-Horde-ElasticSearch-1.0.2-4.cp1152 cpanel-php54-Date-Holidays-Netherlands-0.1.3-4.cp1152 cpanel-php54-Date-Holidays-Turkey-0.1.1-4.cp1152 cpanel-php54-Auth-SASL-1.0.6-4.cp1152 cpanel-php54-Horde-Mime-Viewer-2.1.0-4.cp1152 cpanel-php54-kronolith-4.2.7-7.cp1152 php53-intl-5.3.3-26.el5_11 cpanel-php54-Horde-Nls-2.0.5-4.cp1152 cpanel-php54-Horde-Alarm-2.2.4-4.cp1152 cpanel-php54-Horde-Http-2.1.5-4.cp1152 cpanel-php54-Horde-Controller-2.0.3-4.cp1152 cpanel-php54-Net-IMAP-1.1.2-4.cp1152 cpanel-php54-Date-Holidays-Portugal-0.1.0-4.cp1152 cpanel-php54-Date-Holidays-Sweden-0.1.3-4.cp1152 cpanel-php54-Net-Sieve-1.3.2-4.cp1152 cpanel-php54-File-Find-1.3.2-4.cp1152 cpanel-php54-Horde-Form-2.0.9-4.cp1152 cpanel-php54-imp-6.2.8-6.cp1152 cpanel-php54-Horde-Util-2.5.5-4.cp1152 cpanel-php54-Horde-LoginTasks-2.0.4-4.cp1152 cpanel-php54-Horde-Editor-2.0.4-4.cp1152 cpanel-php54-Horde-Date-Parser-2.0.4-4.cp1152 cpanel-php54-Date-Holidays-0.21.8-4.cp1152 cpanel-php54-Mail-Mime-1.8.3-4.cp1152 cpanel-php54-Date-Holidays-Austria-0.1.5-4.cp1152 cpanel-php54-Date-Holidays-Russia-0.1.0-4.cp1152 cpanel-php54-DB-1.7.14-4.cp1152 cpanel-php54-Net-UserAgent-Detect-2.5.2-4.cp1152 cpanel-php54-Horde-Mime-2.9.1-4.cp1152 cpanel-php54-mnemo-4.2.6-4.cp1152 cpanel-php54-ioncube-4.5.2-1.cp1142 cpanel-php54-Horde-Url-2.2.4-4.cp1152 cpanel-php54-Horde-Stream-1.6.2-4.cp1152 cpanel-php54-Horde-Text-Diff-2.1.1-4.cp1152 cpanel-php54-Horde-Crypt-Blowfish-1.0.3-4.cp1152 cpanel-php54-HTTP-Request-1.4.4-4.cp1152 cpanel-php54-Date-Holidays-Czech-0.1.0-4.cp1152 cpanel-php54-HTTP-WebDAV-Server-1.0.0RC8-4.cp1152 cpanel-php54-XML-RPC-1.5.5-4.cp1152 cpanel-php54-Horde-Data-2.1.2-4.cp1152 cpanel-php54-timeobjects-2.1.0-4.cp1152 cpanel-php54-sourceguardian-8.3-1.cp1142 cpanel-php54-Horde-Date-2.1.0-4.cp1152 cpanel-php54-Horde-Tree-2.0.4-4.cp1152 cpanel-php54-Horde-Db-2.2.3-4.cp1152 cpanel-php54-Horde-Rdo-2.0.4-4.cp1152 cpanel-php54-Net-SMTP-1.6.2-4.cp1152 cpanel-php54-Date-Holidays-EnglandWales-0.1.5-4.cp1152 cpanel-php54-Date-Holidays-Ukraine-0.1.2-4.cp1152 cpanel-php54-File-1.4.1-4.cp1152 cpanel-php54-content-2.0.4-5.cp1152 cpanel-php54-Horde-SyncMl-2.0.3-4.cp1152 I am lost here. A: Since you're already using EasyApache, you can install the Intl extension within EasyApache (not through the WHM PHP Extension install area), which I would recommend. EasyApache is very sensitive to outside modifications/changes due to the nature of the script :) WHM 54.0 build 12 Easy Apache v3.32.10 Go to EasyApache3 in WHM Under "cPanel Recommended Profiles" next to "Basic Apache 2.4" click on the gear icon to customize this profile Step 1: Keep Apache 2.4 (unless you absolutely need Apache 2.2) Step 2: Select your PHP version, I recommend php 5.5 or 5.6 depending on application requirements Step 3: Usually the default settings here are sufficient, but the next click the "Exhaustive Options List" button Step 4: You can skip the "Apache" modules section, the "PHP Modules" section is about 50% down the page. Select any PHP modules you need (including Intl) add-on together. You can also leave the rest default as well. Click "Save & Build" If you run into any errors during the build process I highly recommend you contact cPanel support or your server provider if you have technical assistance. Most all of the plugins you need for PHP are installable via EasyApache and it is the safest way to install them. If you tried this already, use a fresh "cPanel Recommended Profile" and be sure to only check the minimum required options, as some addons might not be compatible with others in some cases. Starting fresh generally works for me when I am having issues with EasyApache.
[ "stackoverflow", "0040138730.txt" ]
Q: How can I declare a function that optionally takes a callback, and returns a Promise only if there is no callback? TypeScript v2.0.2 on a Mac running El Capitan 10.11.6 I have a single function that performs an async operation, and: either takes a callback, and returns nothing, calling the callback later, or doesn't take a callback, and returns a Promise, that resolves later. It seems that I've been had similar code work, (see https://github.com/psnider/mongodb-adaptor/blob/master/src/ts/MongoDBAdaptor.ts) but right now this is failing, and I can't figure out why! // these declarations look correct to me, the caller uses one or the other declare abstract class SlimDocumentDatabase<T> { create(obj: T): Promise<T> create(obj: T, done: (error: Error, result?: T) => void): void } class SlimAdaptor<DocumentType> implements SlimDocumentDatabase<DocumentType> { create(obj: DocumentType, done?: (error: Error, result?: DocumentType) => void) : void | Promise<DocumentType> { if (done) { done(undefined, obj) return } else { return Promise.resolve<DocumentType>(obj) } } } I can get this to compile by removing the return type specifications from the implementation of create(), by replacing them with any. But this seems so wrong! Here is the code in the TypeScript Playground: http://www.typescriptlang.org/play/index.html#src=declare%20abstract%20class%20SlimDocumentDatabase%3CT%3E%20%7B%0A%20%20%20%20create(obj%3A%20T)%3A%20Promise%3CT%3E%0A%20%20%20%20create(obj%3A%20T%2C%20done%3A%20(error%3A%20Error%2C%20result%3F%3A%20T)%20%3D%3E%20void)%3A%20void%0A%7D%0A%0A%0Aclass%20SlimAdaptor%3CDocumentType%3E%20implements%20SlimDocumentDatabase%3CDocumentType%3E%20%7B%0A%20%20%20%20%2F%2F%20create(obj%3A%20DocumentType)%3A%20Promise%3CDocumentType%3E%0A%20%20%20%20%2F%2F%20create(obj%3A%20DocumentType%2C%20done%3A%20ObjectCallback%3CDocumentType%3E)%3A%20void%0A%20%20%20%20create(obj%3A%20DocumentType%2C%20done%3F%3A%20(error%3A%20Error%2C%20result%3F%3A%20DocumentType)%20%3D%3E%20void)%20%3A%20void%20%7C%20Promise%3CDocumentType%3E%20%7B%0A%20%20%20%20%20%20%20%20if%20(done)%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20done(undefined%2C%20obj)%0A%20%20%20%20%20%20%20%20%20%20%20%20return%0A%20%20%20%20%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20return%20Promise.resolve%3CDocumentType%3E(obj)%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%0A%0A%7D%0A A: Answered in https://github.com/Microsoft/TypeScript-Handbook/issues/427#issuecomment-257648196 In short, the code in the class definition must include declarations as well as the implementation. In the code example above, linked to the TypeScript Playground, uncomment the first two lines of the class, and the code will compile.
[ "stackoverflow", "0044609393.txt" ]
Q: Cant call a function more than two time using seperate buttons I'm assigning different arguments with the same function, equip, but to different buttons. When i made the third button to call this function, it doesn't work. IS it a limitation with JavaScript? or is there a way to do this? HTML: <head> <link rel='stylesheet' type='text/css' href='css/styles.css'> </head> <body> <p id="para">dud</p> <button type="button" onclick="monsterFound();">Test monster</button> <button type="button" onclick="d20();">Test a Die 20</button> <button type="button" onclick="showChance();">Test Chance</button> <button type="button" onclick="d20(); damageAccuracy(damage,dice1,calculateChance());">Test Accuracy</button> <button type="button" onclick="equip(loot[1]);">equip weapon1</button> <button type="button" onclick="equip(loot[5]);">equip weapon2</button> <button type="button" onclick="equip(loot[8]);">equip weapon3</button> <script src='https://code.jquery.com/jquery-3.1.0.min.js'></script> <script src='main.js'></script> </body> JS: var loot = [ 'rusty iron dagger', 'rusty iron claymore', 'rusty iron axe', 'rusty iron hammer', 'rusty iron spear', 'rusty iron warhammer', 'rusty iron waraxe', 'rusty iron short sword', 'rusty iron long sword', 'rusty iron helmet', 'rusty iron breast-plate', 'rusty iron greaves', 'rusty iron left pauldron', 'rusty iron right pauldron']; // x = 14; var onHandOut = 0; var offHandOut = 0; var onHand = "empty"; // right hand var offHand = "empty"; // left hand var damage = 0; // when you equip a weapon, base damage is set ------------------- alert(onHand); alert(damage); function equip(item) { onHand = item; if (onHand === "empty") { alert("Empty"); onHandOut = 0.65; damage = onHandOut; } else if (onHand === "rusty iron dagger") { onHandOut = 1.25; damage = onHandOut; alert("Dagger equiped, Damage = " + onHandOut); } else if (onHand === "rusty iron claymore") { onHandOut = 2.25; damage = onHandOut; alert("claymore equiped, Damage = " + onHandOut); } else if (onHand === "rusty iron axe") { onHandOut = 1.25; damage = onHandOut; alert("axe equiped, Damage = " + onHandOut); } else if (onHand === "rusty iron hammer") { onHandOut = 1.5; damage = onHandOut; alert("hammer equiped, Damage = " + onHandOut); } else if (onHand === "rusty iron spear") { onHandOut = 1.75; damage = onHandOut; alert("spear equiped, Damage = " + onHandOut); } else if (onHand === "rusty iron warhammer") { onHandOut = 2.5; damage = onHandOut; alert("warhammer equiped, Damage = " + onHandOut); } else if (onHand === "rusty iron waraxe") { onHandOut = 2.25; damage = onHandOut; alert("waraxe equiped, Damage = " + onHandOut); } else if (onhand === "rusty iron short sword") { onHandOut = 2.25; damage = onHandOut; alert("short sword equiped, Damage = " + onHandOut); } else if (onHand === "rusty iron long sword") { onHandOut = 2.5; damage = onHandOut; alert("long sword equiped, Damage = " + onHandOut); } else if (onhand === "empty") { onHandOut = 0.625; damage = onHandOut; alert("no weapon equiped, Damage = " + onHandOut); } else { // Do nothing! } } A: Actually, it is just a typo on your code (onhand instead of onHand). Where you have this line } else if (onhand === "rusty iron short sword") { It should be: } else if (onHand === "rusty iron short sword") {
[ "stackoverflow", "0018109600.txt" ]
Q: Is this a bug in ServiceStack / Authentication? Trying to use ServiceStack for authentication, and have it re-direct to a login page as follows: Plugins.Add(new AuthFeature( () => new CustomUserSession(), //Use your own typed Custom UserSession type new IAuthProvider[] { new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials new TwitterAuthProvider(appSettings), //Sign-in with Twitter new FacebookAuthProvider(appSettings), //Sign-in with Facebook new DigestAuthProvider(appSettings), //Sign-in with Digest Auth new BasicAuthProvider(), //Sign-in with Basic Auth new GoogleOpenIdOAuthProvider(appSettings), //Sign-in with Google OpenId new YahooOpenIdOAuthProvider(appSettings), //Sign-in with Yahoo OpenId new OpenIdOAuthProvider(appSettings), //Sign-in with Custom OpenId }, "http://www.anyURIhereisignored.com")); However the URI argument in this case "http://www.anyURIhereisignored.com" is simply ignored. Looking at the class definition for AuthFeature, I see that the htmlRedirect param is declared as optional with a default value of "~/login", however it appears that it is always using that value and ignoring whatever was passed in. It seems that although the htmlRedirect value gets set initially to the passed URI, somehow internally it is never using that, instead always defaulting to "~/login". Is anyone else experiencing the same issue? A: If you're using MVC4 and your controllers are inheriting from the ServiceStackController<> as per the ServiceStack doco, then you may want to try overriding the LoginRedirectUrl property: public override string LoginRedirectUrl { get { return "/Account/Login?redirect={0}"; } } This will redirect any unauthenticated requests for secured actions to the login url composed from the specified value. You should also make sure you remove the ASP.NET membership modules from the web.config if you want to use ServiceStack auth in MVC.
[ "stackoverflow", "0023790314.txt" ]
Q: Using Moq with overloaded method Why doesn't my Moq Test resolve to the appropriate Method. Calling the Service in my Test: var service = new EmployeeService(mockScoreRep); Uses the following Method public EmployeeService(ICMS_Repository cmsrepository) { _cmsRepository = cmsrepository; } public EmployeeService(IRepository<Score> scoreRep) { _scoreRepository = scoreRep; } I get the following Error: Cannot convert from 'Moq.Mock<IRepository<Score>>' to 'ICMS_Repository' A: I suspect the problem is that you want the mock object, not the wrapper: var service = new EmployeeService(mockScoreRep.Object); In other words, you want to pass an IRepository<Score> - not a Moq.Mock<IRepository<Score>>.
[ "gamedev.stackexchange", "0000147620.txt" ]
Q: Still not get it, How to display cameras movement speed value in inspector? using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SwitchCameras : MonoBehaviour { [Header("Cameras Init")] public Camera[] cameras; public Vector3[] originalPosition; [Space(5)] [Header("Cameras Switch")] public string currentCameraName; public Vector3[] lastCameraPosition; public float cameraSpeed; [Space(5)] [Header("Cameras Target")] public float nextTargetDistance; public Vector3 nextTargetPosition; public Transform nextTarget; private int currentCamera = 0; void Start() { cameras = Camera.allCameras; lastCameraPosition = new Vector3[cameras.Length]; if (cameras.Length >= 1) { originalPosition = new Vector3[cameras.Length]; for (int i = 0; i < cameras.Length; i++) { originalPosition[i] = cameras[i].transform.position; } } if (cameras.Length == 1) { Debug.LogError("Need more then 1 camera for switching.."); } else { Debug.Log("Found " + cameras.Length + " cameras"); } for (int i = 0; i < cameras.Length; i++) { cameras[i].enabled = false; } cameras[0].enabled = true; currentCameraName = cameras[0].name; } void LateUpdate() { if (Input.GetKeyDown(KeyCode.C)) { cameras[currentCamera].enabled = false; if (++currentCamera == cameras.Length) currentCamera = 0; cameras[currentCamera % cameras.Length].enabled = true; cameraSpeed = (cameras[currentCamera].transform.position - lastCameraPosition[currentCamera]).magnitude / Time.deltaTime; lastCameraPosition[currentCamera] = cameras[currentCamera].transform.position; currentCameraName = cameras[currentCamera].name; Debug.Log(cameras[currentCamera].name + " Last position " + cameras[currentCamera].transform.position); } } } Two things i want to do: When running the game display the movement speed of cameras[0] in the Update i want to see the speed in real time not only once like still. Then when i click on C to switch between the cameras display each camera in real time the movement speed. Now when i click on C and switch between the cameras i see still speed value and not real time running value of the speed. A: So I think you want to move the speed calculation out of your key-check if-statement. So your late update function should look something like this: void LateUpdate() { if (Input.GetKeyDown(KeyCode.C)) { cameras[currentCamera].enabled = false; if (++currentCamera == cameras.Length) currentCamera = 0; cameras[currentCamera].enabled = true; currentCameraName = cameras[currentCamera].name; } cameraSpeed = (cameras[currentCamera].transform.position - lastCameraPosition[currentCamera]).magnitude / Time.deltaTime; lastCameraPosition[currentCamera] = cameras[currentCamera].transform.position; Debug.Log(cameras[currentCamera].name + " Last position " + cameras[currentCamera].transform.position); } So here, when the key is pressed, we only update the camera index and name, and leave the speed calculation out of there. The actual speed calculation is now done each frame instead of only when a key is pressed.
[ "stackoverflow", "0030080572.txt" ]
Q: Redcarpet Markdown Conversion Method, NoMethodError Working on an assignment here. Was just introduced to Redcarpet and the Markdown conversion Method. This was placed inside my Helper: def markdown_to_html(markdown) renderer = Redcarpet::Render::HTML.new extensions = { fenced_code_blocks: true } redcarpet = Redcarpet::Markdown.new(renderer, extensions) (redcarpet.render markdown).html_safe end And I could call the method in my views like so: views/posts/show.html.erb: <h1><%= markdown_to_html @post.title %></h1> <div class="row"> <div class="col-md-8"> <p><%= markdown_to_html @post.body %> </div> <div class="col-md-4"> <% if policy(@post).edit? %> <%= link_to "Edit", edit_topic_post_path(@topic, @post), class: 'btn btn-success' %> <% end %> </div> </div> Now I have to do the following: The goal is to render markdown like so: <%= post.markdown_title %> <%= post.markdown_body %> Add Post#markdown_title and Post#markdown_body to Post: Create a private Post#render_as_markdown method that markdown_title and markdown_body can call. This will keep the markdown_title and markdown_body DRY. Remove the markdown_to_html method from application_helper.rb. Update your views to use the Post#markdown_title and Post#markdown_body methods. I have so far attempted to do this: models/post.rb: class Post < ActiveRecord::Base has_many :comments belongs_to :user belongs_to :topic # Sort by most recent posts first default_scope { order('created_at DESC') } # Post must have at least 5 characters in the title validates :title, length: { minimum: 5 }, presence: true # Post must have at least 20 characters in the body validates :body, length: { minimum: 20 }, presence: true # Post must have an associated topic and user validates :topic, presence: true validates :user, presence: true def render_as_markdown(markdown) renderer = Redcarpet::Render::HTML.new extensions = { fenced_code_blocks: true } redcarpet = Redcarpet::Markdown.new(renderer, extensions) (redcarpet.render markdown).html_safe end private def markdown_title(markdown) render_as_markdown(markdown).title end def markdown_body(markdown) render_as_markdown(markdown).body end end If we go back to my views/posts/show.html.erb: <h1><%= @post.title.markdown_title %></h1> Will render: NoMethodError in Posts#show undefined method `markdown_title' for "chopper mag":String Extracted source (around line #1): <h1><%= @post.title.markdown_title %></h1> <div class="row"> <div class="col-md-8"> <p><%= markdown_to_html @post.body %> </div> What am I doing wrong and how can I rectify this issue? Thanks kindly. A: A few things here. First, you've made markdown_title a private method in your class, so it won't be accessible in your view. You need to remove the word private from above your markdown_title and markdown_body methods in order to make them available to your views. In addition, since the requirement is to make render_as_markdown private, you need to move that below the private keyword. Long story short, your methods should be structured in your class as follows: def markdown_title(markdown) ... end def markdown_body(markdown) ... end private def render_as_markdown(markdown) ... end Second, if you take a look at how markdown_title and markdown_body are supposed to be called (below), they don't take in any parameters. <%= post.markdown_title %> <%= post.markdown_body %> So, your Post object methods markdown_title and markdown_body shouldn't take in any parameters. And since they are called on a specific object of class Post, they don't need to take in any. def markdown_title render_as_markdown(self.title) end def markdown_body render_as_markdown(self.body) end Then, in your view, you can use markdown_title and markdown_body according to the requirements: <h1><%= @post.markdown_title %></h1> <div class="row"> <div class="col-md-8"> <p><%= @post.markdown_body %> </div> ... </div>
[ "stackoverflow", "0059518259.txt" ]
Q: Convert data in Laravel 5.8 dive wrong result I am beginner in Laravel. I use in my project Laravel 5.8. I have this code: $dataTimeFromDb = '2019-12-28T23:54:04.000000Z'; $userLastActivity = Carbon::parse($dataTimeFromDb)->format('Y-m-d H:m'); In result I have: 2019-12-29 00:12. I need value from DB in format: Y-m-d H:m. My timezone is Warsaw/Berlin and I save in this format in DB. How can I repeir it? A: I think using format only can do the trick. Try it and let me know. $dataTimeFromDb->format('Y-m-d H:i')
[ "stackoverflow", "0031815727.txt" ]
Q: Result of QJSEngine evaluation doesn't contain a function I'm migrating QScriptEngine code over to QJSEngine, and have come across a problem where I can't call functions after evaluating scripts: #include <QCoreApplication> #include <QtQml> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QJSEngine engine; QJSValue evaluationResult = engine.evaluate("function foo() { return \"foo\"; }"); if (evaluationResult.isError()) { qWarning() << evaluationResult.toString(); return 1; } if (!evaluationResult.hasProperty("foo")) { qWarning() << "Script has no \"foo\" function"; return 1; } if (!evaluationResult.property("foo").isCallable()) { qWarning() << "\"foo\" property of script is not callable"; return 1; } QJSValue callResult = evaluationResult.property("foo").call(); if (callResult.isError()) { qWarning() << "Error calling \"foo\" function:" << callResult.toString(); return 1; } qDebug() << "Result of call:" << callResult.toString(); return 0; } The output of this script is: Script has no "activate" function That same function could be called when I was using QScriptEngine: scriptEngine->currentContext()->activationObject().property("foo").call(scriptEngine->globalObject()); Why doesn't the function exist as a property of the evaluation result, and how do I call it? A: That code will result in foo() being evaluated as a function declaration in the global scope. Since you don't call it, the resulting QJSValue is undefined. You can see the same behaviour by opening the JavaScript console in your browser and writing the same line: You can't call the function foo() of undefined, because it doesn't exist. What you can do, is call it through the global object: This is the same as what your C++ code sees. Therefore, to access and call the foo() function, you need to access it through the globalObject() function of QJSEngine: #include <QCoreApplication> #include <QtQml> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QJSEngine engine; QJSValue evaluationResult = engine.evaluate("function foo() { return \"foo\"; }"); if (evaluationResult.isError()) { qWarning() << evaluationResult.toString(); return 1; } if (!engine.globalObject().hasProperty("foo")) { qWarning() << "Script has no \"foo\" function"; return 1; } if (!engine.globalObject().property("foo").isCallable()) { qWarning() << "\"foo\" property of script is not callable"; return 1; } QJSValue callResult = engine.globalObject().property("foo").call(); if (callResult.isError()) { qWarning() << "Error calling \"foo\" function:" << callResult.toString(); return 1; } qDebug() << "Result of call:" << callResult.toString(); return 0; } The output of this code is: Result of call: "foo" This is roughly the same as the line you posted that uses QScriptEngine. The benefit of this approach is that you don't need to touch your scripts to get it to work. The downside is that writing JavaScript code this way can cause issues if you're planning on reusing the same QJSEngine to call multiple scripts, especially if the functions therein have identical names. Specifically, the objects that you evaluated will stick around in the global namespace forever. QScriptEngine had a solution for this problem in the form of QScriptContext: push() a fresh context before you evaluate your code, and pop() afterwards. However, no such API exists in QJSEngine. One way around this problem is to just create a new QJSEngine for every script. I haven't tried it, and I'm not sure how expensive it would be. The documentation looked like it might hint at another way around it, but I didn't quite understand how it would work with multiple functions per script. After speaking with a colleague, I learned of an approach that solves the problem using an object as an interface: #include <QCoreApplication> #include <QtQml> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QJSEngine engine; QString code = QLatin1String("( function(exports) {" "exports.foo = function() { return \"foo\"; };" "exports.bar = function() { return \"bar\"; };" "})(this.object = {})"); QJSValue evaluationResult = engine.evaluate(code); if (evaluationResult.isError()) { qWarning() << evaluationResult.toString(); return 1; } QJSValue object = engine.globalObject().property("object"); if (!object.hasProperty("foo")) { qWarning() << "Script has no \"foo\" function"; return 1; } if (!object.property("foo").isCallable()) { qWarning() << "\"foo\" property of script is not callable"; return 1; } QJSValue callResult = object.property("foo").call(); if (callResult.isError()) { qWarning() << "Error calling \"foo\" function:" << callResult.toString(); return 1; } qDebug() << "Result of call:" << callResult.toString(); return 0; } The output of this code is: Result of call: "foo" You can read about this approach in detail in the article that I just linked to. Here's a summary of it: Declares an object that you can add properties to whenever you define something that needs to be "exported" to C++. The "module function" takes its interface object as an argument (exports), allowing code outside of the function to create it and store it in a variable ((this.object = {})). However, as the article states, this approach does still use the global scope: The previous pattern is commonly used by JavaScript modules intended for the browser. The module will claim a single global variable and wrap its code in a function in order to have its own private namespace. But this pattern still causes problems if multiple modules happen to claim the same name or if you want to load two versions of a module alongside each other. If you want to take it further, follow the article through to its end. As long as you're using unique object names, though, it will be fine. Here's an example of how a "real life" script would change to accommodate this solution: Before function activate(thisEntity, withEntities, activatorEntity, gameController, activationTrigger, activationContext) { gameController.systemAt("WeaponComponentType").addMuzzleFlashTo(thisEntity, "muzzle-flash"); } function equipped(thisEntity, ownerEntity) { var sceneItemComponent = thisEntity.componentOfType("SceneItemComponentType"); sceneItemComponent.spriteFileName = ":/sprites/pistol-equipped.png"; var physicsComponent = thisEntity.componentOfType("PhysicsComponentType"); physicsComponent.width = sceneItemComponent.sceneItem.width; physicsComponent.height = sceneItemComponent.sceneItem.height; } function unequipped(thisEntity, ownerEntity) { var sceneItemComponent = thisEntity.componentOfType("SceneItemComponentType"); sceneItemComponent.spriteFileName = ":/sprites/pistol.png"; var physicsComponent = thisEntity.componentOfType("PhysicsComponentType"); physicsComponent.width = sceneItemComponent.sceneItem.width; physicsComponent.height = sceneItemComponent.sceneItem.height; } function destroy(thisEntity, gameController) { } After ( function(exports) { exports.activate = function(thisEntity, withEntities, activatorEntity, gameController, activationTrigger, activationContext) { gameController.systemAt("WeaponComponentType").addMuzzleFlashTo(thisEntity, "muzzle-flash"); } exports.equipped = function(thisEntity, ownerEntity) { var sceneItemComponent = thisEntity.componentOfType("SceneItemComponentType"); sceneItemComponent.spriteFileName = ":/sprites/pistol-equipped.png"; var physicsComponent = thisEntity.componentOfType("PhysicsComponentType"); physicsComponent.width = sceneItemComponent.sceneItem.width; physicsComponent.height = sceneItemComponent.sceneItem.height; } exports.unequipped = function(thisEntity, ownerEntity) { var sceneItemComponent = thisEntity.componentOfType("SceneItemComponentType"); sceneItemComponent.spriteFileName = ":/sprites/pistol.png"; var physicsComponent = thisEntity.componentOfType("PhysicsComponentType"); physicsComponent.width = sceneItemComponent.sceneItem.width; physicsComponent.height = sceneItemComponent.sceneItem.height; } exports.destroy = function(thisEntity, gameController) { } })(this.Pistol = {}); A Car script can have functions with the same names (activate, destroy, etc.) without affecting those of Pistol. As of Qt 5.12, QJSEngine has support for proper JavaScript modules: For larger pieces of functionality, you may want to encapsulate your code and data into modules. A module is a file that contains script code, variables, etc., and uses export statements to describe its interface towards the rest of the application. With the help of import statements, a module can refer to functionality from other modules. This allows building a scripted application from smaller connected building blocks in a safe way. In contrast, the approach of using evaluate() carries the risk that internal variables or functions from one evaluate() call accidentally pollute the global object and affect subsequent evaluations. All that needs to be done is to rename the file to have an .mjs extension, and then convert the code like so: export function activate(thisEntity, withEntities, activatorEntity, gameController, activationTrigger, activationContext) { gameController.systemAt("WeaponComponentType").addMuzzleFlashTo(thisEntity, "muzzle-flash"); } export function equipped(thisEntity, ownerEntity) { var sceneItemComponent = thisEntity.componentOfType("SceneItemComponentType"); sceneItemComponent.spriteFileName = ":/sprites/pistol-equipped.png"; var physicsComponent = thisEntity.componentOfType("PhysicsComponentType"); physicsComponent.width = sceneItemComponent.sceneItem.width; physicsComponent.height = sceneItemComponent.sceneItem.height; } export function unequipped(thisEntity, ownerEntity) { var sceneItemComponent = thisEntity.componentOfType("SceneItemComponentType"); sceneItemComponent.spriteFileName = ":/sprites/pistol.png"; var physicsComponent = thisEntity.componentOfType("PhysicsComponentType"); physicsComponent.width = sceneItemComponent.sceneItem.width; physicsComponent.height = sceneItemComponent.sceneItem.height; } export function destroy(thisEntity, gameController) { } The C++ to call one of these functions looks something like this: QJSvalue module = engine.importModule("pistol.mjs"); QJSValue function = module.property("activate"); QJSValue result = function.call(args);
[ "stackoverflow", "0040314823.txt" ]
Q: JavaScript - Gravity setInterval() - Platform Collision I programmed an img element to "fall" down the window with parseInt(its.style.top) triggered by a setInterval(fall,1000) function in the body. An error occurs after the Moves() function is triggered, and the fall() function stops being called. Is there an if-statement for Moves() function to call the setInterval(fall,1000) again after the img s.style.left >= r.style.width?? Thanks! :-) <html> <body onload="setInterval(fall,1000)" onkeydown="Moves()"> <img id="square" style="position:absolute; left:10px; top:0px; width:50px; height:50px; background-color:red;" /> <img id="rectangle" style="position:absolute; left:10px; top:130px; width:150px; height:10px; background-color:blue;" /> <script> function fall(){ var s = document.getElementById("square"); s.style.top = parseInt(s.style.top) + 25 + 'px'; var r = document.getElementById("rectangle"); r.style.top=130 + 'px'; if(s.style.top>=r.style.top){s.style.top=r.style.top;} } function Moves(){ var s = document.getElementById("square"); if (event.keyCode==39) { s.style.left = parseInt(s.style.left)+10+'px';} var r = document.getElementById("rectangle"); r.style.width=150 + 'px'; if(s.style.left>=r.style.width){setInterval(fall,1000);} } </script> </body> </html> A: I believe this is what you were trying to do: <html> <body onload="setTimeout(fall,1000)" onkeydown="Moves()"> <img id="square" style="position:absolute; left:10px; top:0px; width:50px; height:50px; background-color:red;" /> <img id="rectangle" style="position:absolute; left:10px; top:130px; width:150px; height:10px; background-color:blue;" /> <script> var over_edge = false; var can_fall = true; function fall(){ var s = document.getElementById("square"); s.style.top = parseInt(s.style.top) + 25 + 'px'; var r = document.getElementById("rectangle"); //r.style.top=130 + 'px'; if(!over_edge) { if(parseInt(s.style.top) >= parseInt(r.style.top) - parseInt(s.style.height)) { s.style.top = parseInt(r.style.top) - parseInt(s.style.height); can_fall = false; } } if(can_fall || over_edge) setTimeout(fall, 1000); } function Moves(){ var s = document.getElementById("square"); if (event.keyCode==39) { s.style.left = parseInt(s.style.left)+10+'px';} var r = document.getElementById("rectangle"); //r.style.width=150 + 'px'; if(parseInt(s.style.left) >= parseInt(r.style.left) + parseInt(r.style.width)) { if(!over_edge) { over_edge = true; fall(); // trigger falling over the edge but only once } } } </script> </body> </html>
[ "stackoverflow", "0035682854.txt" ]
Q: MEF & optional plugin dependencies - best practice? so I have a rather stupid question, but I just can't think of a really good way to solve this "dilemma". I'm developing an application with MEF and trying to come up with a good way to handle optional dependencies. Random example, assume there are two plugins; "MyPlugin", and a StatusBar plugin which may or may not be loaded by the main application. MyPlugin is supposed to have an optional dependency to the Status Bar Manager; if that plugin is loaded by MEF, it'll use it to output something to the status bar; if not, it simply won't. [ModuleExport(typeof(MyPlugin))] public class MyPlugin : IModule { [ImportingConstructor] public MyPlugin([Import(AllowDefault = true)] StatusBarManager optionalStatusBarManager OptionalStatusBar) { if(optionalStatusBarManager != null) optionalStatusBarManager.Display("Hi from MyPlugin!"); } } In order to be aware of the type "StatusBarManager", the MyPlugin-project would need a reference to the StatusBarManager project / its dll. Now from my gut feeling, it makes little sense to have an optional dependency, if MyPlugin needs the StatusBarManager's dll to be accessible anyway because it relies on its exposed types. But what are my options? Is there any decent way to have such optional dependencies without requiring the main application to have access to the optional dependency's dlls? So far, I could only come up with importing these by contract name using the "dynamic" type. But then I'd lose any and all compile time safety obviously in MyPlugin. Or I could create another project, such as StatusBarManagerAbstractions which contains only interface definitions. Then at least MyPlugin would only have a hard dependency to the relatively small interface project, without requiring the (potentially large) implementation libraries to be there. Better than nothing, but still doesn't strike me as a fully "optional" dependency. Am I just overthinking this?! Is there any best practice to handle such an issue? A: tldr; you're probably over-thinking this :) Long Version I'm developing an application with MEF and trying to come up with a good way to handle optional dependencies. As the dependencies are optional, the current sample code should suffice. However, as a general best practice, all dependencies will be referenced / coded against by interface, not the concrete type. During the dependency resolution in MainModule, the implementation of interfaces defined in CommonModule are resolved by the MEF container through assembly references, file directory scanning, etc... and builds up the dependency graphs as needed. Is there any decent way to have such optional dependencies without requiring the main application to have access to the optional dependency's dlls? The MainModule does not need to have a reference to the StatusBarModule as long as the dll is deployed to the MainModule bin; a DirectoryCatalog can then be built up to compose the MEF container. As you're using "plugins", you'd want to use a DirectoryCatalog anyhow so that the dll's can be discovered at runtime. For example, based on the given scenario, the solution structure should look something like the following which removes all references except the CommonModule to the MainModule: Solution - MainModule - starts the app (console, winform, wpf, etc...) - references: CommonModule (no other project references) - CommonModule - references: no other modules - purpose: provides a set of common interfaces all projects can reference - note: the actual implementations will be in other projects - MyPluginModule - references: CommonModule - purpose: provides plugins for the app - Implements interfaces from CommonModule - note: uses dependencies defined by interfaces in CommonModule and implemented by other modules - build: build step should copy the dll to the MainModule's bin - StatusBarModule - references: CommonModule - purpose: provides plugin dependencies required by the application - note: uses dependencies defined by interfaces in CommonModule and implemented by other modules - build: build step should copy the dll to the MainModule's bin The MyPluginModule and StatusBarModule are almost identical where neither references each other; rather, they share interfaces through the CommonModule interface definitions. The dependencies/concrete implementations are resolved at runtime through a DirectoryCatalog. The underlying code/implementations would be as follows. Note, that there are 2 options for the optional dependency where one (MyPlugin) is using .ctor injection while the other (MyOtherPlugin) is using property injection: MainModule class Program { static void Main() { // will output 'Hi from MyPlugin!' when resolved. var myPlugin = MefFactory.Create<IMyPlugin>().Value; // will output 'Hi from MyOtherPlugin!' when resolved. var myOtherPlugin = MefFactory.Create<IMyOtherPlugin>().Value; Console.ReadLine(); } } public static class MefFactory { private static readonly CompositionContainer Container = CreateContainer(); public static Lazy<T> Create<T>() { return Container.GetExport<T>(); } private static CompositionContainer CreateContainer() { // directory where all the dll's reside. string directory = AppDomain.CurrentDomain.BaseDirectory; var container = new CompositionContainer( new DirectoryCatalog( directory ) ); return container; } } CommonModule public interface IModule { } public interface IMyPlugin { } public interface IMyOtherPlugin { } public interface IStatusBarManager { void Display( string msg ); } MyPluginModule [Export( typeof( IMyPlugin ) )] internal class MyPlugin : IModule, IMyPlugin { private readonly IStatusBarManager _manager; [ImportingConstructor] public MyPlugin( [Import( AllowDefault = true )] IStatusBarManager manager ) { _manager = manager; if( _manager != null ) { _manager.Display( "Hi from MyPlugin!" ); } } } [Export( typeof( IMyOtherPlugin ) )] internal class MyOtherPlugin : IModule, IMyOtherPlugin { private IStatusBarManager _statusManager; [Import( AllowDefault = true )] public IStatusBarManager StatusManager { get { return _statusManager; } private set { _statusManager = value; _statusManager.Display( "Hi from MyOtherPlugin!" ); } } } StatusBarModule [Export( typeof( IStatusBarManager ) )] internal class StatusBarManager : IStatusBarManager { public void Display( string msg ) { Console.WriteLine( msg ); } }
[ "stackoverflow", "0014271069.txt" ]
Q: MySQL has indexed tables and EXPLAIN looks good, but still not using index I am trying to optimize a query, and all looks well when I got to "EXPLAIN" it, but it's still coming up in the "log_queries_not_using_index". Here is the query: SELECT t1.id_id,t1.change_id,t1.like_id,t1.dislike_id,t1.user_id,t1.from_id,t1.date_id,t1.type_id,t1.photo_id,t1.mobile_id,t1.mobiletype_id,t1.linked_id FROM recent AS t1 LEFT JOIN users AS t2 ON t1.user_id = t2.id_id WHERE t2.active_id=1 AND t1.postedacommenton_id='0' AND t1.type_id!='Friends' ORDER BY t1.id_id DESC LIMIT 35; So it grabs like a 'wallpost' data, and then I joined in the USERS table to make sure the user is still an active user (the number 1), and two small other "ANDs". When I run this with the EXPLAIN in phpmyadmin it shows id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra 1 | SIMPLE | t1 | index | user_id | PRIMARY | 4 | NULL | 35 | Using where 1 | SIMPLE | t2 | eq_ref | PRIMARY,active_id | PRIMARY | 4 | hnet_user_info.t1.user_id | 1 | Using where It shows the t1 query found 35 rows using "WHERE", and the t2 query found 1 row (the user), using "WHERE" So I can't figure out why it's showing up in the log_queries_not_using_index report. Any tips? I can post more info if you need it. A: tldr; ignore the "not using index warning". A query execution time of 1.3 milliseconds is not a problem; there is nothing to optimize here - look at the entire performance profile to find bottlenecks. Trust the database engine. The database query planner will use indices when it determines that doing so is beneficial. In this case, due to the low cardinality estimates (35x1), the query planner decided that there was no reason to use indices for the actual execution plan. If indices were used in a trivial case like this it could actually increase the query execution time. As always, use the 97/3 rule.
[ "stackoverflow", "0037670075.txt" ]
Q: Ionic, Cannot re-enable the geolocation permission after click NEVER in the permission dialog I am developing an Ionic application on an Android phone with version 6.0.1, and I am encountering an issue about the geolocation permission. The app successfully asked user for geolocation permission, but when user clicks NEVER in the dialog, the app fails to ask again. After the user clicking NEVER, the geolocation premission for our app in the Android App permissions is still enabled. (toggling that doesn't help) Only reinstalling the app, the app ask for the permission again. Solution: The dialog is asking enabling the location rather than asking for permission. The dialog is opened by the plugin https://github.com/mapsplugin/cordova-plugin-googlemaps, while the never button doesn't link to the android settings. I solve the problem by using another plugin to handle turnning on the location service, which doesnt has a Never option. A: The app successfully asked user for geolocation permission, but when user clicks NEVER in the dialog, the app fails to ask again. This is the intended behaviour on Android 6.0: once a user has permanently denied permission by checking the "Never ask again" box, the app is not allowed to programatically prompt the user with a dialog. The only option is to instruct the user how to manually allow the permissions via the Settings page. To assist with this you can use switchToSettings()from cordova-diagnostic-plugin to switch the user to your app's settings page. After the user clicking NEVER, the geolocation premission for our app in the Android App permissions is still enabled. (toggling that doesn't help) This should not be the case: manually allowing the permission via the app settings page will allow the app to use that functionality. You can confirm this for yourself using the Android permissions example app for cordova-diagnostic-plugin. However, it depends how the plugin you are using to handle the permission requests responds to the "never ask again" situation. It maybe that you need to use cordova-diagnostic-plugin to manually check the permission status and switch to the app settings page if it's DENIED_ALWAYS.
[ "stackoverflow", "0043702731.txt" ]
Q: Center element vertically and new element should be added in new line Center element vertically and new element should be added in the next line (without using <br/>) .parent { position: relative; background: #FF0000; text-align: left; width: 100%; height: 200px; text-align: center; vertical-align: middle; } .children { background: #000; width: 10%; height: 200px; display: inline-block; position: relative; vertical-align: middle; } Jsfiddle is in here: http://jsfiddle.net/richersoon/m8kp92yL/5/ Result should be something like this A: You need to modify .parent to have a height:auto; to accommodate the height of each .children element and padding:20px 0; was added to show 20px worth of red background above the first child. In your .children css display:inline-block was removed and margin: 0 auto allows each child to center within .parent element, after each child element margin-bottom:5px; displays the 5px gap. .parent { position: relative; background: #FF0000; text-align: left; width: 100%; height: auto; text-align: center; vertical-align: middle; padding:20px 0px; } .children { background: #000; width: 200px; height: 200px; position: relative; vertical-align: middle; display:flex; margin: 0 auto; margin-bottom:5px; } <div class="parent"> <div class="children"></div> <div class="children"></div> <div class="children"></div> </div>
[ "stackoverflow", "0055999393.txt" ]
Q: How to bind a template element property in DataTemplate I want to let a template element property create a binding with another element property, but I found a lot articles and none of them talk about. So I ask for what should I do. <Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp1" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.Resources> <local:StringsJoinConverter x:Key="join_converter" /> </Window.Resources> <Grid DataContext="{Binding Source={StaticResource SampleDataSource}}"> <ListBox ItemsSource="{Binding Collection}" > <ListBox.ItemTemplate> <DataTemplate> <StackPanel Margin="5"> <StackPanel Orientation="Horizontal"> <TextBlock Background="#FF83C9A9" > <TextBlock Text="Name:"> </TextBlock> <TextBox Width="50" x:Name="input_name"></TextBox> </TextBlock> </StackPanel> <StackPanel Orientation="Horizontal"> <TextBlock Background="#FFB683C9" > <TextBlock Text="Value:"> </TextBlock> <TextBox Width="50" x:Name="input_value"></TextBox> </TextBlock> </StackPanel> <TextBlock > <TextBlock.Text> <MultiBinding Converter="{StaticResource join_converter}"> <Binding> <!--Bind input_name.Text--> </Binding> <Binding> <!--Bind input_value.Text--> </Binding> </MultiBinding> </TextBlock.Text> </TextBlock> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Window> enter image description here A: You can directly bind CompplexProperty.PartA and PartB also you can use ElementName method, In the below code you can see the both ways also. <TextBlock > <TextBlock.Text> <MultiBinding Converter="{StaticResource join_converter}"> <Binding ElementName="ATextblock" Path="Text"> </Binding> <Binding Path="ComplexProperty.PartB"> </Binding> </MultiBinding> </TextBlock.Text> </TextBlock>
[ "math.stackexchange", "0001790222.txt" ]
Q: Stone–Čech compactification of real line I know that $[0,1]$ and a unit circle $\mathbb{S}^1$ are one-point compactifications of $\mathbb{R}$ under some suitable homeomorphism. But how does one construct the Stone–Čech compactification? A: You cannot really construct it, as such. You can define it, and prove its existence (using the Axiom of Choice) but you cannot give a concrete, definable example of a point in the remainder $\beta\mathbb{R}\setminus\mathbb{R}$. It is common to define the half-line $\mathbb{H} = [0,\infty)$ and consider $\beta\mathbb{H} \setminus \mathbb{H}$, because one can show that $\beta \mathbb{R} \setminus \mathbb{R}$ is a disjoint union of two copies of $\beta\mathbb{H} \setminus \mathbb{H}$ (one on the right, and one on the left). This sort of makes sense, because the reals have no holes to fill internally (it's already locally compact and complete), it's compactified at the boundaries, so to say. Adding a single point at infinity yields the (essentially unique) one-point compactification which is homeomorphic to $\mathbb{S}^1$, and because it is ordered we can add two points (at both ends) to get an orderable compactification which is homeomorphic to $[0,1]$. The Cech-Stone compactification of $X$ is characterised by the function extension property (if we assume for simplicity that $X \subseteq \beta X$): every continuous function $f: X \rightarrow Y$, where $Y$ is any compact Hausdorff space, can be extended to $\beta f: \beta X \rightarrow Y$. This extension $\beta f$ is automatically unique because the co-domain $Y$ is Hausdorff and $X$ is dense in $\beta X$. In fact we could suffice to check this for $Y = [0,1]$ only, it turns out, to have it for all compact Hausdorff $Y$. This gives unicity: if $\gamma X$ has the same property (where again we assume for simplicity that $X \subseteq \gamma X$), we extend $1_{X,\beta}: X \rightarrow \beta Y$ with $1_X(x) = x$ to $\gamma 1_{X,\beta} : \gamma X \rightarrow \beta X$, and in the same way we have a continuous $\beta 1_{X,\gamma} : \beta X \rightarrow \gamma X$. As these maps are each other's inverses on the dense set $X$ (which we have in both), because the maps are just the identity there, they are each other's inverses on $\gamma X$ and $\beta X$ as well, making these spaces homeomorphic. This extension property means that we must extend $f(x) = \sin(x)$ from the reals to $[-1,1]$ to all of $\beta \mathbb{R}$, and it's clear we cannot extend it just using one or two points, so that the well-known compactifications are certainly not the Cech-Stone one. E.g. if $f(\infty)$ should equal the limit of $f(2n\pi)$ as well as $f(2n\pi + \frac{1}{2})$, and these are already different. A function can only be extended to the one-point compactification of the reals, if the values outside of $f[-n,n]$ vary less and less for larger $n$, roughly speaking. So this is just a limit class. We need to be able to extend all bounded continuous functions. Constructions (sketches of them) can be found on Wikipedia or good books like Engelking's "General Topology", or Gillman and Jerrison's "Rings of continuous functions". For the reals (which is normal) the new points of $\beta \mathbb{R}$ correspond to ultrafilters of closed subsets of $\mathbb{R}$ (free ones, i.e. their intersection is empty). But these cannot even be proved to exist without some form of the Axiom of Choice, and no explicit examples of these can be given. We can e.g. define a filter base $\mathscr{F}$ of closed sets by taking the complements of all open intervals of the form $(a,b)$, where $a < b, a, b \in \mathbb{R}$. These have empty intersection in the reals (as $x \notin \mathbb{R}\setminus (x-1,x+1)$) but any two or finitely many of them intersect (as can easily be checked). Then Zorn's lemma (or some other such principle) tells us there exists some maximal filter of closed sets that contains $\mathscr{F}$, in fact plenty of them, and each of those gives us a point of $\beta \mathbb{R} \setminus \mathbb{R}$. Note that in a compact space any family of closed sets with the finite intersection property has non-empty intersection (so $\mathscr{F}$ witnesses the non-compactness of the reals), so the closure of the sets in $\mathscr{F}$ in $\beta \mathbb{R}$ should have non-empty intersection, and in fact those ultrafilters (considered as points) will be in that intersection in $\beta \mathbb{R}$. In fact there are $2^\mathfrak{c}$ many new points in $\beta \mathbb{R} \setminus \mathbb{R}$ (as many as points added to $\mathbb{N}$, and as many as there are subsets of $\mathbb{R}$). It's a very large, very non-metrisable space, that still has the reals (and thus $\mathbb{Q} \subseteq \mathbb{R}$ as well) as a dense subspace. One of the few spaces that we have that the Cech-Stone equals the one-point compactification is $\omega_1$ (the first uncountable ordinal in the order topology) which has $\omega_1+1$ as its unique compactification. So here it is concrete, but this situation is quite rare. A: The Stone-Čech compactification of $\mathbb{R}$ can be functorially built as the maximal spectrum of $C_b(\mathbb{R})$, the ring of bounded continuous real functions on $\mathbb{R}$. The maximal spectrum $\operatorname{Max}(R)$ of a commutative ring is the set of all maximal ideals, with the spectral topology, where a basis of closed sets is given by $$ V(I)=\{\mathfrak{m}\in\operatorname{Max}(R):\mathfrak{m}\supseteq I\} $$ where $I$ is any ideal of $R$. In general this topology is not Hausdorff, but it can be proved that if $X$ is a completely regular Hausdorff space, then the space $\beta X=\operatorname{Max}(C_b(X))$ is compact Hausdorff. Suppose $f\colon X\to Y$ is a continuous map, where $Y$ is completely regular Hausdorff. Then we have an induced ring homomorphism $f^*\colon C_b(Y)\to C_b(X)$, mapping $\varphi\in C_b(Y)$ to $\varphi\circ f$. If $\mathfrak{m}$ is a maximal ideal of $C_b(X)$, then $\beta f(\mathfrak{m})=(f^*)^{-1}(\mathfrak{m})$ is a maximal ideal of $C_b(Y)$. It's easy to show that $\beta f$ is continuous under the spectral topology, so we get a continuous function $\beta f\colon\beta X\to\beta Y$. Moreover we get an embedding $X\to \beta X$ by mapping $x\to\mathfrak{m}_x$ defined by $$ \mathfrak{m}_x=\{\varphi\in C_b(X):\varphi(y)=0\} $$ In the special case when $Y$ is compact, the maximal ideals of $C_b(Y)=C(Y)$ are all of the form $\mathfrak{m}_y$, for a unique $y\in Y$, so $Y$ can be identified with $\beta Y$. This shows that $\beta X$ indeed satisfies the universal property of the Stone-Čech compactification, that is, every continuous map $X\to Y$, where $Y$ is compact Hausdorff, can be extended to a continuous map $\beta X\to Y$. You should be able to find this construction of the Stone-Čech compactification in several books on topology, I believe it is also in Kelley's book. There's no “explicit” description, because the ideals of $C_b(X)$ can be described in terms of nonprincipal ultrafilters, whose existence depends on the axiom of choice. Only some cases admit an explicit description, because of special properties of $X$.
[ "dsp.stackexchange", "0000015569.txt" ]
Q: Extracting common signal from 4 sets of observations I am working on a signal processing assignment where I need to find out one common time domain signal from 4 observation. The math is like this: \begin{array}{lcl} y_1(t) & = & a_1(t)*x(t) + b_1(t) \\ y_2(t)& = & a_1(t)*x(t) + b_1(t) \\ . & & \\ . & & \\ y_n(t) & = & a_n(t)*x(t) + b_n(t)\end{array} where: $n$ is up to 4 in my case, and $x(t)$ is my signal of interest which I want to extract from observed signals $y_n(t)$. What is the general direction I should take in doing background study for this kind of application? Thanks, K A: Because you have a set of linear equations, why don't you set up a linear system (for each data point) and solve the system (using SVD for example) to obtain the solution? Write in the the matrix form such as $Y=\beta X$ where $\beta$ are known and $X$ is unknown.
[ "stackoverflow", "0060229974.txt" ]
Q: How to match, lookup and project with filtering on the other table in MongoDB? My goal is to get a list of active alerts and the corresponding read dates for a given user. I have an alerts collection { "id" : "id", "field1": 1, "field2": 1, "field3": 1, "field4": 1, "status" : { "name": "ACTIVE" } } I am tracking when a user has read an alert using a alertstracking collection { "alertid" : "alertidvalue", "userid" : "useridvalue", "id" : "id", "readdate" : ISODate("2020-02-14T00:45:45.959+0000") } This is the working query I have but was wondering if there are better/faster ways to do it. I was going to index alertid, userid fields on the alertstracking collection. db.getCollection("alerts").aggregate([ { $match: { "status.name": "ACTIVE" } }, { $lookup: { from: "alertstracking", localField: "id", foreignField: "alertid", as: "alerttrack" } }, { $project: { "id": 1, "field1": 1, "field2": 1, "field3": 1, "field4": 1, "useralerttrack": { $filter: { input: "$alerttrack", as: "track", cond: { $eq: ["$$track.userid", "useridvalue"] } } } } }, { $project: { "id": 1, "field1": 1, "field2": 1, "field3": 1, "field4": 1, "readdate": { $arrayElemAt: ["$useralerttrack.readdate", 0] } } } ]) I am hoping to avoid using $project twice and repeating the fields I want. I had to do it to be able to access useralerttrack. A: You can try that like this : db.getCollection("alerts").aggregate([ { $match: { "status.name": "ACTIVE" } }, { $lookup: { from: "alertstracking", let: { id: "$id" }, pipeline: [ { $match: { $expr: { $and: [ { $eq: ["$alertid", "$$id"] }, { $eq: ["$userid", "useridvalue"] } ] } } }, { $project: { _id: 0, readdate: 1 } } ], as: "readdate" } }, { $addFields: { readdate: { $arrayElemAt: ["$readdate.readdate", 0] } } } ]) Test : MongoDB-Playground
[ "stackoverflow", "0021248666.txt" ]
Q: Java decrement over time I'm looking for some help with a problem I've been having lately. I want to decrement from 200 down to 0, but I don't want it to be instant, but rather I want it to decrement over the course of a second. For example, at 0.5 seconds it would be at 100, 0.75 it would be a 50 and so on. If this is at all possible, I would love to hear from you guys! -Thanks so much, Brandon A: To do what you want, here's the answer: int index = 200; while(index != 0) { index--; System.out.println("The value is: " + index); try { //200 * 5 milliseconds = 1 second Thread.sleep((long) 5); } catch (InterruptedException e) { e.printStackTrace(); } } You might want to put this in a thread. Here's a page that could help you: http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
[ "codereview.stackexchange", "0000062910.txt" ]
Q: Write a function to extract a given number of randomly selected elements from a list I'm going through the 99 Haskell problems and I have a few question about the solution I implemented for Problem 23. It asks: Extract a given number of randomly selected elements from a list. This is the code I came up with: -- Extract a given number of randomly selected elements from a list. import System.Random randomFromList :: StdGen -> Int -> [a] -> ([a], StdGen) randomFromList generator 0 _ = ([], generator) randomFromList generator toDo xs = let (nextInt, generator') = next generator index = mod nextInt (length xs) (otherNumbers, generator'') = randomFromList generator' (toDo -1) xs in ((xs !! index) : otherNumbers, generator'') It works, but I'm not sure this is idiomatic Haskell nor that it is the best way to address this problem. None of the solutions in the Haskell wiki uses the let approach so I was wondering if it is discouraged for some reason. A: Your solution looks good to me, no reason to discourage using let as far as I know. Tip: if you make the type randomFromList :: Int -> [a] -> StdGen -> ([a], StdGen), then you can call it like this: main = getStdGen >>= print . randomFromList 7 ['A'..'Z'] Also, if the requirement is interpreted as selecting randomly without replacement, your version only needs slight modification (this also uses randomR rather than mod): dropAt :: Int -> [a] -> [a] dropAt k xs = take k xs ++ drop (k+1) xs randomFromList :: Int -> [a] -> StdGen -> ([a], StdGen) randomFromList 0 _ generator = ([], generator) randomFromList _ [] generator = ([], generator) randomFromList toDo xs generator = let (index, generator') = randomR (0, length xs - 1) generator (otherNumbers, generator'') = randomFromList (toDo -1) (dropAt index xs) generator' in ((xs !! index) : otherNumbers, generator'') See also this shuffle implementation for some attempt at optimisation. (You could potentially solve the random selection by something like take n . shuffle.)
[ "codereview.meta.stackexchange", "0000005342.txt" ]
Q: Not-so-[random] tag for [dice] I created the dice tag this morning. At over 60 candidate questions, it was time. Here is the list of candidate questions. When adding the tag, please be sure to make all appropriate edits. Of special note, random will probably be appropriate on many of these. Add it too, as necessary. This is a significant number of questions to bump, so please work on small batches as not to flood the main page. A: I've completed the retag and 5gon2eder created a tag wiki.
[ "stackoverflow", "0021805722.txt" ]
Q: Jquery plugin with prototype I was trying on the basics of Jquery plugin and the prototype concept, but ended up in an unusual behavior. HTML : <div> <span> <textarea>Text Area with 500 characters. Adding Some text.</textarea> <span class="cl"></span> </span> <span> <textarea>Text Area with 100 characters</textarea> <span class="cl"></span> </span> </div> JQuery : (function ($) { var tisCharsLeftCntxt = null; function fnCharsLeft(ele, genStngs) { this.jqe = $(ele); this.maxChars = genStngs.maxChars; tisCharsLeftCntxt = this; this.fnInit(); } fnCharsLeft.prototype = { fnInit: function () { tisCharsLeftCntxt.fnUpdateRemainingChars(); tisCharsLeftCntxt.jqe.keyup(function (event) { key = event.keyCode ? event.keyCode : event.which; if ((37 != key) && (38 != key) && (39 != key) && (40 != key)) { tisCharsLeftCntxt.fnUpdateRemainingChars(); } }); }, fnUpdateRemainingChars: function () { var charsLft = tisCharsLeftCntxt.maxChars - tisCharsLeftCntxt.jqe.val().length, jqeDestToUpdt = tisCharsLeftCntxt.jqe.siblings('.cl'); charsLft = (charsLft < 0) ? 0 : charsLft; if (charsLft) { jqeDestToUpdt.text(charsLft + ' more of ' + tisCharsLeftCntxt.maxChars + ' characters'); } else { tisCharsLeftCntxt.jqe.val(tisCharsLeftCntxt.jqe.val() .substring(0, tisCharsLeftCntxt.maxChars)); tisCharsLeftCntxt.jqe.scrollTop(tisCharsLeftCntxt.jqe[0].scrollHeight); jqeDestToUpdt.text("Maximum limit of " + tisCharsLeftCntxt.maxChars + " characters reached"); return false; } } }; $.fn.fnCharsLeftPlgn = function (genStngs) { return $(this).data("charsleft", new fnCharsLeft(this, genStngs)); }; })(window.jQuery); $('div span:nth-child(1) textarea').fnCharsLeftPlgn({maxChars: 500}); $('div span:nth-child(2) textarea').fnCharsLeftPlgn({maxChars: 100}); Fiddle : http://jsfiddle.net/5UQ4D/ & http://jsfiddle.net/5UQ4D/1/ Requirement is, the plugin should show the number of characters that can be added in a text-area. If there is only one text-area in a page this is working good. But if there are more than one, only the text-area which is last associated with the plugin is working properly. With respect to code here, In both the text-area number of characters left is updated correctly during initialization (only for the first time). But later when the text area content is changed, only the second with 100 chars (or the most recent text-area associated with the plugin) is working properly. Seems like, I'm failing to restrict the plugin context independently to a text-area. Please Advice,.. A: Problem 1: As mentioned in the comments, you're creating a variable named tisCharsLeftCntxt outside of the other contexts, then assigning this to it in your constructor. Every time you run your plugin you stomp on tisCharsLeftCntxt with a new this. There is no reason to use a reference to this in the wholesale fashion in which you have. There is only one place in your code where the scope changes such that this is no longer your instance. That place is inside of the keyup event handling function. You should localize your aliasing of this to just the method which contains that event handler. Problem 2: I believe another part of your problem (this would be seen if you ran the plugin against a selector which matched more than one element) is inside of the plugin function (the one which lives off of $.fn). $.fn.fnCharsLeftPlgn = function (genStngs) { return $(this).data("charsleft", new fnCharsLeft(this, genStngs)); }; It should be: $.fn.fnCharsLeftPlgn = function (genStngs) { return this.each(function () { $(this).data("charsleft", new fnCharsLeft(this, genStngs)); }); }; When directly inside of a method which has been added to the jQuery prototype ($.fn), this refers to the entirety of the current collection, not an element. A plugin should each itself in order to run element specific logic against its individual members. Without using .each() you are calling .data() against an entire collection, setting all of their charsleft data properties to the one instance of fnCharsLeft. By using .each() you create a new instance of fnCharsLeft for each of the elements in the collection. Since the .each() then returns the collection, and a plugin should be chainable, you simply return it. A rule of thumb is that if you're passing this into the jQuery factory ($()) directly inside of a plugin, function then you're doing something wrong since it is already the collection. As a second rule of thumb, almost all plugin definitions except those which are intended to return info about an element (such as .val(), .html(), or .text() when not given a param) should start with return this.each(function() {... Solutions: Bringing those changes together results in this fiddle: http://jsfiddle.net/5UQ4D/4/ And this code: (function ($) { var fnCharsLeft = function (ele, genStngs) { this.jqe = $(ele); this.maxChars = genStngs.maxChars; this.fnInit(); }; fnCharsLeft.prototype = { fnInit: function () { var instance = this; this.fnUpdateRemainingChars(); this.jqe.on('keyup', function (e) { key = e.keyCode ? e.keyCode : e.which; if (37 != key && 38 != key && 39 != key && 40 != key) { instance.fnUpdateRemainingChars(); } }); }, fnUpdateRemainingChars: function () { var charsLft = this.maxChars - this.jqe.val().length, jqeDestToUpdt = this.jqe.siblings('.cl'); charsLft = charsLft < 0 ? 0 : charsLft; if (charsLft) { jqeDestToUpdt.text(charsLft + ' more of ' + this.maxChars + ' characters'); } else { this.jqe .val(this.jqe.val().substring(0, this.maxChars)) .scrollTop(this.jqe[0].scrollHeight); jqeDestToUpdt.text("Maximum limit of " + this.maxChars + " characters reached"); return false; } } }; $.fn.fnCharsLeftPlgn = function (genStngs) { return this.each(function () { $(this).data('charsleft', new fnCharsLeft(this, genStngs)); }); }; }(window.jQuery));
[ "cogsci.stackexchange", "0000001926.txt" ]
Q: Why people choose "boring" colors for new cars? I've been interested in this question for a few years, sorry if this is not the right place to ask it. As I've been driving around the US for the last few years, I noticed that some community parking lots "lack color" - the vehicles can be defined as colorless - they are white, black, various shades of gray or beige. Yet I've seen several new car catalogs and see that most cars come in several colors. I was surprised to see this "lack of color" again and again, so I googled it, and found that the trend is not just in America, but worldwide: 2009 Top 10 world car colors This is interesting, because I've never ever heard of white, silver or black being called people's favorite color. Most search results point to "blue" being the favorite color (at least in the United States) for English search results. This begs the question: Why do people go for boring/conservate exterior car colors, like white or silver when buying a new car, instead of choosing their favorite color? Here are my wild guesses, and it would be great to debunk them: Is this due to conformity, resale value, or an attempt to stand out less on a highway? Is this because a car is big enough to be seen with rods in the eye? Or do people see their cars as just another "appliance", like a toaster, microwave or a fridge, and pick a color similar to what they see in their kitchen? I appreciate your input! PS. This article is especially interesting, because it predicts orange/brown becoming the "new color" of expensive cars, while most color psychology results I've seen list people naming orange as "cheap" color, and advise to avoid it. America's favorite car colors for 2012 are ... boring A: Mainly, because they're too noticeable. You don't really see houses in electric green, pink, or yellow. No one wants to stand out in a crowd or be the sore thumb. Here: http://www.usnews.com/news/articles/2012/10/12/survey-americans-pretty-much-the-whole-world-prefers-boring-colored-cars I'll post more sources when I can.
[ "salesforce.stackexchange", "0000025000.txt" ]
Q: Eclipse Kepler and Force.com IDE Warning "Package Manifest Content Warning" Each time I create a new force.com project I receive this warning/error message in regards to Flexipage. I can still create a project afterwards, however Eclipse does not respond for 90 - 120 seconds. Below is a capture of the warning/error along with some of the log entries. Has anyone seen this error before? Thanks A: This is a error from eclipse plugin. You have Force.com IDE plugin earlier the release of "Flexipage". "FlexiPage" basically related to Salesforce1. So Force.com IDE or plugin is not much compatible with Salesforce1 components. Therefore, you are getting this exception telling that there is a new type of component details are available in metadata which plugin can not handle. Just ignore it for now. When the plugin will become compatible with Salesforce1 components this exception will disappear.
[ "stackoverflow", "0041201642.txt" ]
Q: Python3 pip install gives “Command ”python setup.py egg_info“ failed with error code 1” in pydns package I'm new to python and have been trying to install some packages with pip. I always get this error message though: Right now i'm using python3 and virtual environment i.e. "everify" Any suggestions? A: probably because you are using the incorrect package. I think you might need py3dns package since you are using Python 3.
[ "stackoverflow", "0024413295.txt" ]
Q: Powershell Console Menu Options - Need to add line breaks? I've created a console menu from some code I modified. I use the following code and use the switch command to go to the menu choices outlined in this code: # new menu for remote tasks ps1 $Title = "Remote Tasks" $Message = "Please enter your selection below:" $remoteRestartComputer = New-Object System.Management.Automation.Host.ChoiceDescription "&1 Restart one or more remote computer(s)", ` "Restart one or more remote computer(s)" $remoteShutdownComputer = New-Object System.Management.Automation.Host.ChoiceDescription "&2 Shutdown one or more remote computer(s)", ` "Shutdown one or more remote computer(s)" $wakeOnLanComputer = New-Object System.Management.Automation.Host.ChoiceDescription "&3 Start/Wake VM Station", ` "Start/Wake VM Station" $getOutThisB = new-object System.Management.Automation.Host.ChoiceDescription "&4 Exit", ` "Exit" $Options = [System.Management.Automation.Host.ChoiceDescription[]]($remoteRestartComputer, $remoteShutdownComputer, $wakeOnLanComputer, $getOutThisB) $selectRemoteTask = $host.ui.PromptForChoice($Title, $Message, $Options, 0) The problem is in the console window it shows a couple of the choices on the same line, i.e.: Remote Tasks Please enter your selection below: [1] 1 Restart one or more remote computer(s) [2] 2 Shutdown one or more remote computer(s)[3] 3 Start/Wake VM Station [4] 4 Exit[?] Help (default is "1"): Any way to add line breaks so this looks nicer? Thanks in advance. A: I made this a while ago as an answer for some question on here, I don't even remember what it was. I think it had to do with ASCII pipe characters to make borders. This will make your menu, with an optional title, and display it. Then you just need to display your Get-Host, put it in a loop, and then move on to your switch. Function MenuMaker{ param( [string]$Title = $null, [parameter(Mandatory=$true, ValueFromPipeline = $true)][String[]]$Selections ) $Width = if($Title){$Length = $Title.Length;$Length2 = $Selections|%{$_.length}|Sort -Descending|Select -First 1;$Length2,$Length|Sort -Descending|Select -First 1}else{$Selections|%{$_.length}|Sort -Descending|Select -First 1} $Buffer = if(($Width*1.5) -gt 78){(78-$width)/2}else{$width/4} if($Buffer -gt 4){$Buffer = 4} $MaxWidth = $Buffer*2+$Width+$($Selections.count).length $Menu = @() $Menu += "╔"+"═"*$maxwidth+"╗" if($Title){ $Menu += "║"+" "*[Math]::Floor(($maxwidth-$title.Length)/2)+$Title+" "*[Math]::Ceiling(($maxwidth-$title.Length)/2)+"║" $Menu += "╟"+"─"*$maxwidth+"╢" } For($i=1;$i -le $Selections.count;$i++){ $Item = "$i`. " $Menu += "║"+" "*$Buffer+$Item+$Selections[$i-1]+" "*($MaxWidth-$Buffer-$Item.Length-$Selections[$i-1].Length)+"║" } $Menu += "╚"+"═"*$maxwidth+"╝" $menu } You would call it as such: MenuMaker -Title $Title -Selections "Restart one or more remote computer(s)","Shutdown one or more remote computer(s)","Start/Wake VM Station","Exit" Sure, it doesn't include Help, but it does make a nice pretty menu for you. You could probably modify the function to add a -Help switch to display a ? - Help line, or just include Help as one of your selections. Then you just do something like: Do{ MenuMaker -Title $Title -Selections "Restart one or more remote computer(s)","Shutdown one or more remote computer(s)","Start/Wake VM Station","Exit" $Selection = Read-Host "Please enter your selection (? for Help)"}While($Selection -notin (1..4) -or $Selection -eq "?") Edit: Switch example (updated above code to include ? for help!): Switch($Selection){ 4 {Continue} 3 {Run code to Start/Wake VM Station} 2 {Run code to shutdown remote computer} 1 {Run code to restart remote computer} "?" {Run code to display Help} }
[ "tex.stackexchange", "0000346981.txt" ]
Q: Broken rectangle border and custom borders I'm looking for a way to define a style (I do not want to manually draw the edges by hand for each node) that provides a node containing three "normal" edges, and one zigzag edge. Here is an example : I tried to use decorate, but I didn't obtain good results... By the way, any "general" solution to deal with custom boarders are welcome. Here is a MWE : \documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture}[ broken/.style = { draw, rectangle } ] \node[broken] {Hello}; \end{tikzpicture} \end{document} Thank you. === EDIT === I found a solution, but I cannot fill the shape, properly, so the question is still open. A: Here a solution based on your code, filling and drawing of nodes must be done within brokenrect style. \documentclass{article} \usepackage{tikz} \usetikzlibrary{decorations.pathmorphing} \begin{document} \tikzset{ brokenrect/.style={ append after command={ \pgfextra{ \path[draw,#1] decorate[decoration={zigzag,segment length=0.4em, amplitude=.3mm}] {(\tikzlastnode.north east)--(\tikzlastnode.south east)} -- (\tikzlastnode.south west)|-cycle; }}}} \begin{tikzpicture} \node [brokenrect={fill=orange,draw=blue},inner sep=10pt] {Coucou}; \end{tikzpicture} \end{document}
[ "stackoverflow", "0009187547.txt" ]
Q: Rails 3.1.3 and Inherited Resources tests fail I'm using Rails 3.1.3 for a project with Inherited Resources 1.3.0. When I have a controller like so: class PostsController < InheritedResources::Base end And I test with rspec the following describe "PUT update" do describe "with invalid params" do it "re-renders the 'edit' template" do post = Post.create! valid_attributes # Trigger the behavior that occurs when invalid params are submitted Post.any_instance.stub(:save).and_return(false) put :update, {:id => post.to_param, :post => {}}, valid_session response.should render_template("edit") end end end I get the following error: 3) PostsController PUT update with invalid params re-renders the 'edit' template Failure/Error: response.should render_template("edit") expecting <"edit"> but rendering with <""> # ./spec/controllers/posts_controller_spec.rb:115:in `block (4 levels) in <top (required)>' Why is this? Do I have to stub something else out? A: Just add this: Post.any_instance.stub(:errors).and_return(['error']) right after: Post.any_instance.stub(:save).and_return(false)
[ "stackoverflow", "0046989662.txt" ]
Q: Extending the range of bins in seaborn histogram I'm trying to create a histogram with seaborn, where the bins start at 0 and go to 1. However, there is only date in the range from 0.22 to 0.34. I want the empty space more for a visual effect to better present the data. I create my sheet with import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import seaborn as sns %matplotlib inline from IPython.display import set_matplotlib_formats set_matplotlib_formats('svg', 'pdf') df = pd.read_excel('test.xlsx', sheetname='IvT') Here I create a variable for my list and one that I think should define the range of the bins of the histogram. st = pd.Series(df['Short total']) a = np.arange(0, 1, 15, dtype=None) And the histogram itself looks like this sns.set_style("white") plt.figure(figsize=(12,10)) plt.xlabel('Ration short/total', fontsize=18) plt.title ('CO3 In vitro transcription, Na+', fontsize=22) ax = sns.distplot(st, bins=a, kde=False) plt.savefig("hist.svg", format="svg") plt.show() Histogram It creates a graph bit the range in x goes from 0 to 0.2050 and in y from -0.04 to 0.04. So completely different from what I expect. I google searched for quite some time but can't seem to find an answer to my specific problem. Already, thanks for your help guys. A: There are a few approaches to achieve the desired results here. For example, you can change the xaxis limits after you have plotted the histogram, or adjust the range over which the bins are created. import seaborn as sns # Load sample data and create a column with values in the suitable range iris = sns.load_dataset('iris') iris['norm_sep_len'] = iris['sepal_length'] / (iris['sepal_length'].max()*2) sns.distplot(iris['norm_sep_len'], bins=10, kde=False) Change the xaxis limits (the bins are still created over the range of your data): ax = sns.distplot(iris['norm_sep_len'], bins=10, kde=False) ax.set_xlim(0,1) Create the bins over the range 0 to 1: sns.distplot(iris['norm_sep_len'], bins=10, kde=False, hist_kws={'range':(0,1)}) Since the range for the bins is larger, you now need to use more bins if you want to have the same bin width as when adjusting the xlim: sns.distplot(iris['norm_sep_len'], bins=45, kde=False, hist_kws={'range':(0,1)})
[ "money.stackexchange", "0000052217.txt" ]
Q: £600 per month after rent: is this good? After income tax, I will take home a pay of £1880 per month. After rent, this becomes around £600 per month. But I haven't included council tax in this, so it will be less than £600. Is this reasonable? I don't live in London, so I guess food costs won't be too high. Would you think that this is sensible financial planning? Or am I spending too much for my salary on rent? I need to live like this for 6 months, and I am wondering whether I am being silly. A: One rule of thumb is that housing should be no more than 1/3 of gross income. But, there's always a reasonable excuse to adjust this number. Move to a city with great transportation, or a company van, etc, eliminating the need for a car, and that number can go up. In your case, without a compelling reason to go what seems 50% of gross, your number is way too high. For a six month stint, if this helps your career or is the only work available, it may be the right thing to do. Long term, it's awful. To be fair, long term, in this flat, my advice would be to get a roommate. Even 500/mo would fix your numbers.
[ "math.stackexchange", "0000991797.txt" ]
Q: Prove a function Let $f(n)$ and $g(n)$ be arbitrary functions from $\mathbb{N}$ to $\mathbb{R}^{+}$. Prove the following: $$\max\left \{ f(n), g(n) \right \} = \Theta (f(n)+g(n))$$ Please help me prove (or disprove) this function as I am unsure how to resolve it. Thanks A: First, as $f,g\ge 0$: $$\max\left \{ f(n), g(n) \right \} \le f(n)+g(n)$$ and for the other inequality: $$ f(n) \le \max\left \{ f(n), g(n) \right \}\\ g(n) \le \max\left \{ f(n), g(n) \right \}\\ \\\implies f(n) + g(n) \le 2\max\left \{ f(n), g(n) \right \}\\ $$ Conclusion: $$\max\left \{ f(n), g(n) \right \} = \Theta (f(n)+g(n))$$
[ "stackoverflow", "0000600332.txt" ]
Q: visual studio 2005: skipping builds for unknown reason? I have a visual studio solution with a number of projects. Configuration manager is carefully configured to build all projects except one ( the one skipped is a test project ). After building solution in command-line i got following: "building XXX Debug|x64" ------ Skipped Build: Project: AAA ------ ------ Skipped Build: Project: BBB, Configuration: Debug Win32 ------ Project not selected to build for this solution configuration ------ Build started: Project: CCC, Configuration: YYY Debug ia64 ------ < here goes build > As you can see, project BBB is skipped becouse it is not selected in configuration manager, project CCC and rest build ok and project AAA is skipped with NO REASON GIVEN. Anyone knows why visual studio may skip project build without any reason? All configuration names ( XXX, YYY Debug, Debug ) and platforms ( x64 / Win32 / ia64 ) are correctly configured in configuration manager. A: Is project AAA selected for configuration Debug|x64 ? Also I had the same situation when freshly downloaded solution (without .soa file) had the default configuration to Itanium, so all system without its support were skipping all solution projects to build. Properly build was starting only after selecting win32 manually.
[ "stackoverflow", "0023287188.txt" ]
Q: Where to get custom progress bar like in google android apps? In one of google apps I noticed cute round progress bar which animated like two divided parts leafing one to another one. It seems like I saw it some time ago in gmail app but maybe I'm wrong. A: I believe you are looking for something like this. It can be found on GitHub : Google Progress Bar
[ "tex.stackexchange", "0000297599.txt" ]
Q: How to align column of mixed fractions (after whole number) in tabular? I have a table that has a column with mixed fractions (that is, whole number plus fraction part) as entries which I need to reproduce in latex. The problem is that the fraction part of the mixed number have differing widths because the size of the numbers involved is changing. I'd like to align the numbers just to the right of the whole number. Here is a short example that illustrates the problem: \documentclass{article} \begin{document} \begin{tabular}{c | c} Truman & $4\frac{1}{8}$ \\ Ford & $33\frac{1}{16}$ \\ Clinton & $105\frac{7}{107}$ \end{tabular} \end{document} I've tried made various attempts at a solution such as \documentclass{article} \begin{document} \begin{tabular}{c | r l} Truman & $4$ &$\frac{1}{8}$ \\ Ford & $33$&$\frac{1}{16}$ \\ Clinton & $105$&$\frac{7}{107}$ \end{tabular} \end{document} but no luck. Ideas how I can proceed? A: \documentclass{article} \usepackage{dcolumn} \begin{document} \renewcommand\arraystretch{1.4} \begin{tabular}{c | r l} \textbf{Person}&\multicolumn{2}{c}{\textbf{Score}}\\ Truman & $4$ &$\frac{1}{8}$ \\ Ford & $33$&$\frac{1}{16}$ \\ Clinton & $105$&$\frac{7}{107}$ \end{tabular} \bigskip \begin{tabular}{c | r@{}l} \textbf{Person}&\multicolumn{2}{c}{\textbf{Score}}\\ Truman & $4$ &$\frac{1}{8}$ \\ Ford & $33$&$\frac{1}{16}$ \\ Clinton & $105$&$\frac{7}{107}$ \end{tabular} \bigskip \begin{tabular}{c | D{.}{}{-1}} \textbf{Person}& \multicolumn{1}{c}{\textbf{Score}}\\ Truman & 4.\frac{1}{8} \\ Ford & 33.\frac{1}{16} \\ Clinton & 105.\frac{7}{107} \end{tabular} \end{document}
[ "puzzling.stackexchange", "0000096612.txt" ]
Q: Untitled (Not Just a) Word Search I wrote this for a puzzle swap, and I'm somewhat proud of how it turned out. I'd like to know what you think. T I U C R I C Z T A S R E J H U T N A L L A G A I J U N K E T U T E M N O I P M A H C N F G I P Z K Q N O I T A N I R G E R E P C U T O F F F F O R G E D Q E D V E P M N P G N I T U O M O Z O E S S F A L S E T H C A T E D N T R E D H E R R I N G T M X O F A E U X I M N U D N U O R I L E L V D Y Z X P T E I Q Z S P U G U A O X S A R S P D S R T Z X A S R Q U L A I J X P U J Z Q A Y N T G A V U Q M E C H M O H T O I O D E R O V Z X O Q O M I E V B I L C Z Y R E V E S Z N Y N H N C A V A L I E R C Y G N Y N N I've tried to minimize their existence, but words shorter than 5 letters are spurious. The solution is a short phrase, you'll know it when you get it. Yes, there is more to this puzzle than the simple word search. Hint: All words fall into a small number of distinct categories. Meta: I want to add more tags but they are spoilery. I don't really know what I normally accepted on this site. Guidance? Hint policy: I will be adding hints once every day. Daily Hint #1: Good job on solving the word search. The categories are your clues to proceed further, but you may have already guessed that. So I will say that two of the clues tell you what to do. One clue tells you how do to it. And the final clue tells you what to use it on. Daily Hint #2: I checked Wikipedia, and it looks like there are 18 quadrillion different Knight tours possible on an 8x8 board. So even if there was some hint telling you where to start (X marks the spot was clever, and I wish I had thought of that), I'd have to also specify where you go next approx 54 more times. Clearly, I'm not doing that, so how can I tell you which tour to use only using one of the hints? Daily Hint #2.5 (Bonus): The relevant hint is the group meaning "separated" or "disconnected." How can a knight's tour be separated from itself? Daily Hint #3: The actual root words for each of the four groups are "knight", "fake", "tour", and "uncrossed" A: The final phrase: The black knight always triumphs! Which is A quote from Monty Python's Holy Grail The Completed Word Search: All the words in the word search: Forward words: Cutoff, Forged, False, Red herring, Cavalier, Junket Down/Up words: Pseudo, expedition, insulate, traverse, voyage, luxate (Credit Lanny Strack) Back words: Circuit, gallant, champion, peregrination, detach, round, sever, ersatz, unmix, outing (credit Gareth for the last three, would never have even known that 'ersatz' was a word lol) Diagonal words: Excursion, bogus, paladin, travel, cruise, phony, dummy, disjoin (Credit Jens) These words can be put under 4 distinct groups: Tour: Expedition, traverse, circuit, excursion, travel, cruise, junket, voyage, outing, peregrination (credit Zimonze) Fake: Forged, false, red herring, bogus, phony, dummy, pseudo, ersatz 'Uncrossed': Cutoff, sever, detach, insulate, unmix, disjoin, luxate Knight (spotted by Rand and Gareth): Cavalier, gallant, paladin, champion Also notice that 'round' can fit in both the knight and tour groups, which shows a connection. So now what? These categories are actually instructions: Knight Tour, Fake, Uncrossed: What do we have to do? A knight's tour How do we do it? Fake What do we use it on? Uncrossed i.e. - an 'uncrossed' knight's tour after removing the fake letters, So: If we remove all the letters in the wordsearch which are part of a word (i.e. 'fake') we get left with exactly 64 letters, which just so happens to be the number of squares on a chessboard. So these letters can be re-arranged into a 8x8 grid: J H U A I U T E M N F G I P Z K Q F Q E D V M N P M O Z O T M X F Y Z X Q Z P X T Z Q J Z Q Q M H O V Z O Q Z Y Z H C Y G N N N So the next thing is to do An 'uncrossed' knights tour. The 'uncrossed' tour leads us to the longest uncrossed tour on an 8x8 grid, via wikipedia: Applying this, and starting at the left hand starting point gives 'ONETIMEPADFJFFQMXQOPVXQNQJGVZZZZZZZZ'. And a one-time pad is a type of vigenere cipher So what next? (Huge credit to Lanny Strack here, who managed to work this out) Using all the letters in the 8x8 grid that the knight doesn't pass over as the cipher-text: HUIUTMGZKQNPMYQXTQMHOOYHCYNN And then removing the Zs at the end of the knights tour string so the key is ONETIMEPADFJFFQMXQOPVXQNQJGV Using a one time pad cipher we get the answer: 'THE BLACK KNIGHT ALWAYS TRIUMPHS'
[ "salesforce.stackexchange", "0000014658.txt" ]
Q: How to do inner or sub-query for the same object in SOQL Currently I'm facing an issue to select the value from the same object. below here i provided the query. I'm migration java-j2ee application to a salesforce, thisbelow query works in my sql. I'm trying to do the same here in SOQL. But it doesn't works. Could somebody can help me. SELECT DATA1__c, TEXT__c FROM PARAMETERS__c WHERE ( (TYPE__c = 'ADMINISTRATEUR') AND (KEY1__c LIKE 'MONTAGE%') (AND KEY2__c = '')) AND (DATA1__c IN (SELECT KEY1__c FROM Parameters__c WHERE TYPE__c = 'PERE_TECHNIQUE')) Here in the above query i need to take the value where TYPE is based on 'TECHNIQUE' where KEY1_c should be matched to DATA1_c from the outer query. Here query is very similar to below example SELECT Id FROM Idea WHERE ((Idea.Title LIKE 'Vacation%') AND (CreatedDate > YESTERDAY) AND (Id IN (SELECT ParentId FROM Vote WHERE CreatedById = '005x0000000sMgYAAU')) The only difference is here they have used IN clause with different object, in my query i'm trying to use IN clause from the same object parameters. Kindly let me know in case of any further clarifications. Regards, Arun A: The inner and outer selects should not be on the same object type when using subqueries in SFDC.So for your case you can either break the queries in two equivalent queries
[ "stackoverflow", "0030630347.txt" ]
Q: How to merge two sorted Observables into a single sorted Observable? Given: Integer[] arr1 = {1, 5, 9, 17}; Integer[] arr2 = {1, 2, 3, 6, 7, 12, 15}; Observable<Integer> o1 = Observable.from(arr1); Observable<Integer> o2 = Observable.from(arr2); How to get an Observable that contains 1, 1, 2, 3, 5, 6, 7, 9, 12, 15, 17? A: Edit: Please see the_joric's comment if you're going to use this. There is an edge case that isn't handled, I don't see a quick way to fix it, and so I don't have time to fix it right now. Here's a solution in C#, since you have the system.reactive tag. static IObservable<int> MergeSorted(IObservable<int> a, IObservable<int> b) { var source = Observable.Merge( a.Select(x => Tuple.Create('a', x)), b.Select(y => Tuple.Create('b', y))); return source.Publish(o => { var published_a = o.Where(t => t.Item1 == 'a').Select(t => t.Item2); var published_b = o.Where(t => t.Item1 == 'b').Select(t => t.Item2); return Observable.Merge( published_a.Delay(x => published_b.FirstOrDefaultAsync(y => x <= y)), published_b.Delay(y => published_a.FirstOrDefaultAsync(x => y <= x))); }); } The idea is summarized as follows. When a emits the value x, we delay it until b emits a value y such that x <= y. When b emits the value y, we delay it until a emits a value x such that y <= x. If you only had hot observables, you could do the following. But the following would not work if there were any cold observables in the mix. I would advise always using the version that works for both hot and cold observables. static IObservable<int> MergeSortedHot(IObservable<int> a, IObservable<int> b) { return Observable.Merge( a.Delay(x => b.FirstOrDefaultAsync(y => x <= y)), b.Delay(y => a.FirstOrDefaultAsync(x => y <= x))); } A: You can merge, sort and flatten the sequences, but it will have a significant overhead: o1.mergeWith(o2).toSortedList().flatMapIterable(v -> v).subscribe(...) or o1.concatWith(o2).toSortedList().flatMapIterable(v -> v).subscribe(...) Otherwise, you need to write a fairly complicated operator. Edit 04/06/2015: Here is an operator that does this sorted-merge more efficiently. A: I was also looking for a merge sort solution that supports a backpressure along and could not find it. So decided to implement it on my own loosely based on the existing zip operator. Similarly to zip, the sorted merge operator collects an item from each source observable first, but then puts them into a priority queue, from which emits them one by one according to their natural order or the specified comparator. You can grab it from GitHub as a ready to use library or just copy/paste the code: https://github.com/ybayk/rxjava-recipes See unit tests for usage.
[ "stackoverflow", "0003233149.txt" ]
Q: How do I create a custom class from a class that already exists? (Existing class does not support NSCoding) What I'm trying to do is convert an EKEvent into NSData, and then convert it back into an EKEvent. I looked around and noticed that in order to use NSKeyedArchiver, the class must conform to the NSCoding protocol. I also found that if I was creating a custom class, I could make it conform to the NSCoding protocol by implementing encodeWithCoder: on such a custom class. Essentially, I assume that in order to convert my EKEvent to NSData and back, I will need to create a custom class (let us call it CustomEvent) I need to do the following: EKEvent --> CustomEvent --> NSData --> CustomEvent --> EKEvent Can I get any help on learning how to create a custom class which DUPLICATES an existing class with the exception that I implement encodeWithCoder: to make it conform to NSCoding? I'm looking at EKEvent.h, and I know that it involves other classes which I must also duplicate (because they too don't conform to NSCoding). Can anyone send me a tutorial link or help me out? Thanks in advance! A: What you're describing appears to be a subclass. However, in Objective-C, you have the simpler option of defining a category on an existing class to add the functionality you want.
[ "stackoverflow", "0008744316.txt" ]
Q: Check loaded shared libraries from another shared library on Linux/Android Is it possible to check which shared libraries are loaded by the calling process from another shared library (.so)? I know there are command line tools for that, but is it possible to perform such a check in C++ code? I need to somehow get the list of native shared libraries loaded by an Android application, but it doesn't seem to be possible from a Java code. A: You could use /proc/<pid>/maps file or just /proc/self/maps for the calling process: lines that ends with '.so' are for linked shared libraries. It's a hack, but should work. Note that one library could be mapped multiple times so you need to skip the repetitions. And good news: you could do it from java. The code snippet below prints shared libraries for the current process to the logcat. try { Set<String> libs = new HashSet<String>(); String mapsFile = "/proc/self/maps"; BufferedReader reader = new BufferedReader(new FileReader(mapsFile)); String line; while ((line = reader.readLine()) != null) { if (line.endsWith(".so")) { int n = line.lastIndexOf(" "); libs.add(line.substring(n + 1)); } } Log.d("Ldd", libs.size() + " libraries:"); for (String lib : libs) { Log.d("Ldd", lib); } } catch (FileNotFoundException e) { // Do some error handling... } catch (IOException e) { // Do some error handling... } The output on my device is: D/Ldd (11286): 55 libraries: D/Ldd (11286): /system/lib/libc.so D/Ldd (11286): /system/lib/libdbus.so D/Ldd (11286): /system/lib/librpc.so D/Ldd (11286): /system/lib/libEGL.so D/Ldd (11286): /system/lib/libstagefright_color_conversion.so D/Ldd (11286): /system/lib/libmedia.so D/Ldd (11286): /system/lib/libemoji.so D/Ldd (11286): /system/lib/libcrypto.so D/Ldd (11286): /system/lib/libstagefright_avc_common.so D/Ldd (11286): /system/lib/libnativehelper.so D/Ldd (11286): /system/lib/libskiagl.so D/Ldd (11286): /system/lib/libopencore_player.so D/Ldd (11286): /system/lib/libjpeg.so D/Ldd (11286): /system/lib/libsurfaceflinger_client.so D/Ldd (11286): /system/lib/libstagefright.so D/Ldd (11286): /system/lib/libdrm1.so D/Ldd (11286): /system/lib/libdvm.so D/Ldd (11286): /system/lib/libwebcore.so D/Ldd (11286): /system/lib/libGLESv1_CM.so D/Ldd (11286): /system/lib/libhardware.so D/Ldd (11286): /system/lib/libexif.so D/Ldd (11286): /system/lib/libgps.so D/Ldd (11286): /system/lib/liblog.so D/Ldd (11286): /system/lib/libexpat.so D/Ldd (11286): /system/lib/libopencore_common.so D/Ldd (11286): /system/lib/libbluedroid.so D/Ldd (11286): /system/lib/libm.so D/Ldd (11286): /system/lib/libicui18n.so D/Ldd (11286): /system/lib/libomx_amrenc_sharedlibrary.so D/Ldd (11286): /system/lib/libwpa_client.so D/Ldd (11286): /system/lib/libstdc++.so D/Ldd (11286): /system/lib/libandroid_runtime.so D/Ldd (11286): /system/lib/libz.so D/Ldd (11286): /system/lib/libETC1.so D/Ldd (11286): /system/lib/libsonivox.so D/Ldd (11286): /system/lib/libstlport.so D/Ldd (11286): /system/lib/libutils.so D/Ldd (11286): /system/lib/libicudata.so D/Ldd (11286): /system/lib/libsqlite.so D/Ldd (11286): /system/lib/libhardware_legacy.so D/Ldd (11286): /system/lib/libpixelflinger.so D/Ldd (11286): /system/lib/libvorbisidec.so D/Ldd (11286): /system/lib/libstagefright_amrnb_common.so D/Ldd (11286): /system/lib/libcutils.so D/Ldd (11286): /system/lib/libui.so D/Ldd (11286): /system/lib/libmedia_jni.so D/Ldd (11286): /system/lib/libomx_sharedlibrary.so D/Ldd (11286): /system/lib/libcamera_client.so D/Ldd (11286): /system/lib/libskia.so D/Ldd (11286): /system/lib/libopencore_net_support.so D/Ldd (11286): /system/lib/libnetutils.so D/Ldd (11286): /system/lib/libbinder.so D/Ldd (11286): /system/lib/libssl.so D/Ldd (11286): /system/lib/libicuuc.so D/Ldd (11286): /system/lib/libGLESv2.so Also if necessary pid could be obtained by android.os.Process.myPid().
[ "math.stackexchange", "0001750114.txt" ]
Q: Unknown distribution of a random variable $X_1, X_2, \ldots, X_{400}$ is a random sample from given distribution with median of m ($P(X_i \le m)=0.5$). Calculate $P(X_{220:400} \le m)$. How to calculate that? I am lost with this question. $X_{220:400}$ means that we have 400 observations arranged in an ascending order and we are choosing observation numbered 220. A: This is just a rephrasing of the answers given in the comments, but note that the definition (in some sense, "purpose") of the median $m$ is so that there is a 50% chance that the random variable assumes a value lower than m. This is where the analogy with tossing the fair coin 400 times comes in. Therefore, each event "$X_i \le m$" is just a Bernoulli trial with probability 1/2. We have 400 such events, each is independent, so we have the sum of 400 independent Bernoulli trials. Such a sum is binomially distributed. Use the binomial distribution (or better yet, since n=400 is so large, the normal approximation to the binomial distribution) to calculate the probability.
[ "stackoverflow", "0033513719.txt" ]
Q: "Type Error: class or module required" for two-to-many relationship In my rails app, I have essentially an "account" and a "transaction" model. The "transaction" model belongs_to the "account" model twice, once as a credited_account and once as a debited_account. It looks something like this: class Account < ActiveRecord::Base has_many :credits, :class_name => "Transaction", :foreign_key => 'credited_account_id' has_many :debits, :class_name => "Transaction", :foreign_key => 'debited_account_id' # ... validators and such ... # end class Transaction < ActiveRecord::Base belongs_to :credited_account, :class => "Account" belongs_to :debited_account, :class => "Account" end This all works, but I am running into some issues with my specs. Using RSpec and Factory_Girl, I get a TypeError every time I run a spec which calls for the transaction factory. Rspec output as follows: Failure/Error: transaction = build(:transaction) TypeError: class or module required below is my spec/factories.rb FactoryGirl.define do factory :account do #... account factory ...# end factory :transaction do association :credited_account, factory: :account #... other attributes set here ...# association :debited_account, factory: :account end end Any insight is greatly appreciated! Regards A: You should change class Transaction < ActiveRecord::Base belongs_to :credited_account, :class => "Account" belongs_to :debited_account, :class => "Account" end to class Transaction < ActiveRecord::Base belongs_to :credited_account, :class_name => "Account" belongs_to :debited_account, :class_name => "Account" end
[ "math.stackexchange", "0001308627.txt" ]
Q: About the definition of Sobolev Spaces I'm studying Sobolev Space and I have a question about the definition: Def.: The Sobolev Space $W^{k,p}(U)$ consists of all locally summable functions $u:U\to \mathbb{R}$ such that for each multiindex $\alpha$ with $|\alpha|\geq k,$ $D^\alpha u$ exist in the weak sense and belongs to $L^p(U).$ Observation: If $k=0$ and $p=2$, then $W^{0,2}(U)=L^2(U)$. We have that $ u\in W^{k,p}(U)$ since $u\in L^1_{loc}(U),$ so every $u\in L^2(U)$ belong to $L^1_{loc}(U)?$ How can I show that? Thanks. A: Indeed this is just Holder's inequality: Pick $V \subset U$ with $|V|<\infty$, then $$||u||_{L^1(V)}=\int_V |u| dx\le \sqrt{\int_V 1^2 dx}\sqrt{\int_V |u|^2 dx} = \sqrt{|V|}\ ||u||_{L^2(U)}$$ then $u \in L^1_{loc}(U)$.
[ "stackoverflow", "0001171819.txt" ]
Q: How to check whether EnableViewStateMac is set at runtime? In ASP.NET, the ViewState is typically protected from tampering on the client with a signature generated by the machine secret on the server. But this protection can be easily turned off with: <%@ Page ... EnableViewStateMac="false" %> I'm writing an ASP.NET control that may store security-sensitive information (not secret... but it must not be tampered with), depending on whether EnableViewStateMac is true. How can I test to see whether it's on or off at runtime? A: You should just be able to reference Page.EnableViewStateMac From within your code. http://msdn.microsoft.com/en-us/library/system.web.ui.page.enableviewstatemac.aspx
[ "stackoverflow", "0035638988.txt" ]
Q: How do i capture a variable from a text file with a batch script? Hi I'm trying to write a batch script that reads a long text file, finds a line that says: Location: xxxxxxxx And saves xxxxxxxx (only) as a variable that i can use later in the script. xxxxxxxx is an ID and there is nothing else on that line. Can someone help? A: This works, too. for /f "tokens=2" %a in ('type longtextfile.txt ^|findstr /b "Location"') do set location=%a echo %location% EDIT: Adding Aacini's more efficient way of doing this: for /f "tokens=2" %a in ('findstr /b "Location" longtextfile.txt') do set location=%a echo %location%
[ "math.stackexchange", "0003697649.txt" ]
Q: Measure of an angle "subtended by each pentagon" in a truncated icosahedron A soccer ball is a truncated icosahedron; it consists of 12 black regular pentagons and 20 white regular hexagons; the edge lengths of the pentagons and hexagons are congruent. What is the measure of the solid angle (in ste-radian) subtended by each pentagon of the soccer ball? My Explanation: If the edge length of the regular pentagon is $a$, according to mathworld.wolfram.com, the radius of the circle circumscribing the pentagon is \begin{equation*} R = \left(\frac{1}{10}\sqrt{50 + 10\sqrt{5}}\right)a \approx 0.8507 a , \end{equation*} and the radius of the circle inscribed in the pentagon is \begin{equation*} r = \left(\frac{1}{10}\sqrt{25 + 10\sqrt{5}}\right)a \approx 0.6882 a. \end{equation*} So, the length of the line segment between a vertex of a pentagon and the midpoint of the side of the same pentagon across from this vertex is \begin{equation*} R + r = \left(\frac{1}{10}\sqrt{50 + 10\sqrt{5}}\right)a + \left(\frac{1}{10}\sqrt{25 + 10\sqrt{5}}\right)a \approx 1.5388 a. \end{equation*} According to wikipedia.org/wiki/Truncated_icosahedron, the radius of the sphere circumscribing the truncated icosahedron is \begin{equation*} \frac{a}{4} \sqrt{58 + 18\sqrt{5}} \approx 2.478 a. \end{equation*} An implementation of Heron's Formula yields the distance between the center of the sphere and the midpoint of a side of the pentagon of about $2.427a$. An implementation of the Law of Cosines shows that the angle with its vertex at the center of the icosahedron and its endpoints at a vertex of a pentagon and the midpoint of the side of the same pentagon across from this vertex is approximately $36.5^\circ$. Is that correct? Is that what is meant by "the angle subtended by each pentagon"? A: The wikipedia about solid angle says that The solid angle of a right $n$-gonal pyramid, where the pyramid base is a regular $n$-sided polygon of circumradius $r$, with a pyramid height $h$ is $$2\pi -2n\arctan\bigg(\frac{\tan(\frac{\pi}{n})}{\sqrt{1+r^2/h^2}}\bigg)$$ Note here that our $r$ is the circumradius of the pentagon (not the radius of the sphere circumscribing the soccer ball). So, according to the wikipedia about regular pentagons, we get $$r=a\sqrt{\frac{2}{5-\sqrt 5}}=a\sqrt{\frac{5+\sqrt 5}{10}}$$ Now, considering a right triangle $OAB$ where $O$ is the center of the soccer ball, $A$ is the center of the pentagon and $B$ is a vertex of the pentagon, we get $$\small h=OA=\sqrt{OB^2-AB^2}=\sqrt{\bigg(\frac{a}{4}\sqrt{58+18\sqrt 5}\bigg)^2-\bigg(a\sqrt{\frac{5+\sqrt 5}{10}}\bigg)^2}=a\sqrt{\frac{41+25\sqrt 5}{8\sqrt 5}}$$ So, the solid angle we seek is $$2\pi -10\arctan\bigg(\frac{\tan(\frac{\pi}{5})}{\sqrt{1+r^2/h^2}}\bigg)\approx 0.29507$$
[ "stackoverflow", "0041494288.txt" ]
Q: Mixing Scalar Types in Eigen #include <iostream> #include <Eigen/Core> namespace Eigen { // float op double -> double template <typename BinaryOp> struct ScalarBinaryOpTraits<float, double, BinaryOp> { enum { Defined = 1 }; typedef double ReturnType; }; // double op float -> double template <typename BinaryOp> struct ScalarBinaryOpTraits<double, float, BinaryOp> { enum { Defined = 1 }; typedef double ReturnType; }; } int main() { Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> m1(2, 2); m1 << 1, 2, 3, 4; Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> m2(2, 2); m2 << 1, 2, 3, 4; std::cerr << m1 * m2 <<std::endl; // <- boom!! } I'd like to know why the above code does not compile. Here is the full error messages. Please note that if I define m1 and m2 to have fixed sizes, it works fine. I'm using Eigen3.3.1. It's tested on a Mac running OSX-10.12 with Apple's clang-800.0.42.1. A: This is because the general matrix-matrix product is highly optimized with aggressive manual vectorization, pipelining, multi-level caching, etc. This part does not support mixing float and double. You can bypass this heavily optimized implementation with m1.lazyProduct(m2) that corresponds to the implementations used fro small fixed-size matrices, but there is only disadvantages of doing so: the ALUs does not support mixing float and double, so float values have to be promoted to double anyway and you will loose vectorization. Better cast the float to double explicitly: m1.cast<double>() * m2
[ "electronics.stackexchange", "0000313761.txt" ]
Q: Speed of FPGA fabric What limits the speed of FPGA fabric to Mhz range, while CPU pipelines are clocked much faster? Is it the interconnect delays that places a limit on signal timing? A: Reconfigurability comes at a steep price. Logic cells in FPGAs are complex, making them much slower than the equivalent (but not reconfigurable) hard logic on an ASIC. Routing between logic cells requires long wires and pass gates, both of which increase parasitic resistance and capacitance, slowing signal propagation.
[ "stackoverflow", "0042822664.txt" ]
Q: multiply numpy.array a with leading dimension of numpy.array b I have two numpy arrays, a and b, where a has dimension 1 and the same length as the leading dimension as b, e.g., import numpy a = numpy.random.rand(5) b1 = numpy.random.rand(5) b2 = numpy.random.rand(5, 3, 11) I would like to multiply each "row" of b with the corresponding entry in a, and get an array of the same shape as b. Something like a[:, None, None] * b2 only works if I know the dimensionality of b beforehand. A: You could use (a * b.T).T This produces a contiguous array if b is contiguous (a*b.T).flags.contiguous # False (a*b.T).T.flags.contiguous # True
[ "stackoverflow", "0056684350.txt" ]
Q: can i limit number of onScrolled() method call per touch event in recyclerview? How to be limit number of times call and runs method OnScrolled() in RecyclerView ?? Because there are a number of conditions in it, very much executing this code,Cause slowdown the application. condition : if (dy < 0 && mLinearLayoutManager.findFirstCompletelyVisibleItemPosition() >= 10 && !mStateScrollTop) { YoYo.with(Techniques.SlideInUp) .duration(150) .playOn(iv_go_to_top); mStateScrollTop = true; } else if (dy > 0 && mStateScrollTop) { YoYo.with(Techniques.SlideOutDown) .duration(150) .playOn(iv_go_to_top); mStateScrollTop = false; } A: I would do something like this: onScrolled() { synchronized(this) { if(!ready) return; else ready = false; } // your current onScroll body } And then you would launch a thread setting a ready variable to true in regular intervals. Something like this: private void launchOnScrollThread() { new Thread() { @Override public void run() { // endless loop - maybe you would like to put some condition to end the loop for(;;) { ready = true; Thread.sleep(100); // wait here for 100 milliseconds } } }.start(); } This would ensure that your current code in onScroll will be executed at most every 100 milliseconds, which should speed it up. Sorry that it's kind of a pseudocode, hope it makes sense to you and will be helpful.
[ "stackoverflow", "0048904556.txt" ]
Q: How to run multiple python files at the same time? How can I run multiple python files at the same time? There are 3 files: bot_1.py, bot_2.py, bot_3.py. I would like to run them at the same time. I attached the code. What should I write in the worker function to make this script work? I will appreciate any help. import multiprocessing import subprocess def worker(file): #your subprocess code subprocess.Popen(['screen', './bot_1.py']) subprocess.Popen(['screen', './bot_2.py']) subprocess.Popen(['screen', './bot_3.py']) if __name__ == '__main__': files = ["bot_1.py","bot_2.py","bot_3.py"] for i in files: p = multiprocessing.Process(target=worker(i)) p.start() A: Assuming that your bot files execute something when you run them at the command line, we can load them and execute them by importing them into our python process (instead of the shell). As each python file defines a package we can do this as follows: import bot_1, bot_2, bot_3 This however will run them one after another, and also prevent you from running the same one twice. To get them to run at once, we can use multiprocessing as you suggest: import multiprocessing for bot in ('bot_1', 'bot_2', 'bot_3'): p = multiprocessing.Process(target=lambda: __import__(bot)) p.start() Processes need a function to run, so we use an anonymous lambda to give it one, and then dynamically import the name. It's not shown here, but as long as you don't import a module into the parent process, the children will be forced to load it, meaning you can run the same one over and over in the separate process if you need to.
[ "stackoverflow", "0058388204.txt" ]
Q: toString method deleting certain strings image if cant see above: https://imgur.com/5sOHtgj The above image on the left side is what it's supposed to print when the jar1 stone is == null vs the right side which is what my program prints. I'm trying to create a toString method so that when jar1's stone in class ground is == null, it does not print anything in between brackets "[""]" So in the code below I was able to get rid of stones name if == null, but was not able to get rid of the "#" and its weight which is seen above where it prints [#0] instead of just []. How am I supposed to approach this toString problem? I've tried using an if statement in the getName() method where if stone == null it returns ""; This made sense in my head but for the other methods which return an integer it really doesn't make sense to me. public class Ground { private Jar jar1; private Jar jar2; private Jar jar3; private Player player; private Chest chest; /** * Constructor for objects of class Ground */ public Ground() { player = new Player(); jar1 = new Jar(1, new Stone()); jar2 = new Jar(2, new Stone()); jar3 = new Jar(3, new Stone()); chest = new Chest(); } public boolean isChestUnlocked(){ if (chest.jar1.getWeight() + chest.jar2.getWeight() * chest.jar3.getWeight() == chest.combination) return true; else return false; } public String toString() { return player.getName() + "[]" + "(" + player.getPosition() + ")" + " [" + jar1.getName()+ "#" + jar1.getWeight() + "]" + "(" + jar1.getPosition() + ")" + " [" + jar2.getName() + "#" + jar2.getWeight() + "]" + "(" + jar2.getPosition() + ")" + " [" + jar3.getName() + "#" + jar3.getWeight() + "]" + "(" + jar3.getPosition() + ")" + " /" + chest.combination + "\\" + "(" + chest.getPosition() + ")" ; } } public class Jar { private int position; private Stone stone; public Jar() { position = 0; stone = null; } public Jar(int initPos, Stone stone) { position = initPos; this.stone = stone; } public void move(int distance) { position = position + distance; } public void moveTo(Jar jar) { jar.stone = stone; stone = null; } public int getWeight() { if (stone == null){ return 0; } return stone.getWeight(); } public String getName() { if (stone == null){ return ""; } return stone.getName(); } public int getPosition() { return position; } } A: You probably want a toString() in the Jar class as well. That could return "" in case stone == null and name # weight otherwise. Then you can use Jar.toString() from Ground.toString().
[ "stackoverflow", "0022045108.txt" ]
Q: How to ignore placeholder expressions for Flyway? I am using flyway version 2.3, I have an sql patch which inserts a varchar into a table having character sequence that Flyway treats as placeholders. I want to flyway to ignore placeholders and run the script as is. The script file is insert into test_data (value) values ("${Email}"); And the Java code is package foobar; import com.googlecode.flyway.core.Flyway; public class App { public static void main( String[] args ) { // Create the Flyway instance Flyway flyway = new Flyway(); // Point it to the database flyway.setDataSource("jdbc:mysql://localhost:3306/flywaytest", "alpha", "beta"); // Start the migration flyway.migrate(); } } A: This can be done by splitting $ and { in the expression: insert into test_data (value) values ('$' || '{Email}') A: You can change the value of the placeholder suffix or prefix to a different value and you should be OK. A: try this properties: final var flyway = Flyway.configure() .dataSource(DataSourceProvider.getInstanceDataSource(instance.getInstanceId())) .locations(MIGRATION_PATH + "instance_db") .outOfOrder(true) .table("schema_version") .validateOnMigrate(false) .placeholderReplacement(false) .load();
[ "stackoverflow", "0044305415.txt" ]
Q: Run all the tests but in the report only there are the methods that I want to run I have to assemblies, one for the tests and the other one is the main assembly that has the methods that I want to test. In my test assembly I have many classes, each class tests the methods of the class of the main assembly. In total, in all the classes, I have about 300 test methods, but in MyClass01Test I have only 30 test methods. I would like to run only the methods in this class and not all the tests. I am trying to use this filter: "-filter:+[*]*.MyMainClass -[*Tests]*" The problem is that it runs all the tests, no only the tests in MyMainClassTest class in my test assembly. However, in the report that I get with reportgenerator, I get only the methods from MyClass01, that it is correct. The complete command that I use is this: "D:\programas\OpenCover\OpenCover.Console.exe" -register:user "-filter:+[*]*.MyMainClass01 -[*Tests]*" -target:"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\MSTest.exe" -targetargs:"/testcontainer:\"F:\.MyAssmeblyTests.dll\"" -output:"F:\tests\resutlts.xml" A: You have to tell MSTest which tests it should execute. This has nothing to do with OpenCover and ReportGenerator. They only track the execution and create a report. You can find the relevant parameters for MSTest here: https://msdn.microsoft.com/en-US/library/ms182489.aspx
[ "stackoverflow", "0043643685.txt" ]
Q: Entity Framework 6 DbSet AddRange vs IDbSet Add - How Can AddRange be so much faster? I was playing around with Entity Framework 6 on my home computer and decided to try out inserting a fairly large amount of rows, around 430k. My first try looked like this, yes I know it can be better but it was for research anyway: var watch = System.Diagnostics.Stopwatch.StartNew(); foreach (var event in group) { db.Events.Add(event); db.SaveChanges(); } var dbCount = db.Events.Count(x => x.ImportInformation.FileName == group.Key); if (dbCount != group.Count()) { throw new Exception("Mismatch between rows added for file and current number of rows!"); } watch.Stop(); Console.WriteLine($"Added {dbCount} events to database in {watch.Elapsed.ToString()}"); Started it in the evening and checked back when I got home from work. This was the result: As you can see 64523 events were added in the first 4 hours and 41 minutes but then it got a lot slower and the next 66985 events took 14 hours and 51 minutes. I checked the database and the program was still inserting events but at an extremely low speed. I then decided to try the "new" AddRange method for DbSet. I switched my models from IDbSet to DbSet and replaced the foreach loop with this: db.Events.AddRange(group); db.SaveChanges(); I could now add 60k+ events in around 30 seconds. It is perhaps not SqlBulkCopy fast but it is still a huge improvement. What is happening under the hood to achieve this? I thought I was gonna check SQL Server Profiler tomorrow for queries but It would be nice with an explanation what happens in code as well. A: As Jakub answered, calling SaveChanges after every added entity was not helping. But you would still get some performance problems even if you move it out. That will not fix the performance issue caused by the Add method. Add vs AddRange That's a very common error to use the Add method to add multiple entities. In fact, it's the DetectChanges method that's INSANELY slow. The Add method DetectChanges after every record added. The AddRange method DetectChanges after all records are added. See: Entity Framework - Performance Add It is perhaps not SqlBulkCopy fast, but it is still a huge improvement It's possible to get performance VERY close to SqlBulkCopy. Disclaimer: I'm the owner of the project Entity Framework Extensions (This library is NOT free) This library can make your code more efficient by allowing you to save multiples entities at once. All bulk operations are supported: BulkSaveChanges BulkInsert BulkUpdate BulkDelete BulkMerge BulkSynchronize Example: // Easy to use context.BulkSaveChanges(); // Easy to customize context.BulkSaveChanges(bulk => bulk.BatchSize = 100); // Perform Bulk Operations context.BulkDelete(customers); context.BulkInsert(customers); context.BulkUpdate(customers); // Customize Primary Key context.BulkMerge(customers, operation => { operation.ColumnPrimaryKeyExpression = customer => customer.Code; });
[ "stackoverflow", "0034370916.txt" ]
Q: how to count click and change it values in looping javascript? i have a problem to count how many i click on add more button and add a input box on same time, so here is my javascript : var i = $('table tr').length; var count = $('table tr').length; var row = i; var a = 0; for (a = 0; a <= i; a++) { $(".addmore_" + a).on('click', function (a) { return function() { var s = 1; var data = "<td><input class='form-control sedang' type='text' id='packinglist_" + a + "' name='packinglist[]'/></td>"; $("#keatas_" + a).append(data); $('#jumrow_'+a).val(s++); } ; } (a)); }; and here is my html : <div class='table-responsive'> <table class='table table-bordered'> <tr> <th>No</th> <th>Jenis Benang</th> <th>Warna</th> <th>Lot</th> <th>Netto</th> <th>Box</th> <th>Cones</th> <th>Keterangan</th> <th></th> </tr>"; $s=mysql_query("SELECT * FROM surat_jalan order by identitas_packing_surat DESC"); $a=mysql_fetch_array($s); for($i=1;$i<=$_POST['jumlahdata'];$i++) { $nomor = $a[19]; $iden = $nomor + $i; echo" <tr> <td><span id='snum'>$i.</span></td> <input class='form-control' type='hidden' id='hiddenlot_$i' name='hiddenlot[]' /> <input class='form-control' type='hidden' id='hiddencustomer_$i' name='hiddencustomer[]' /> <input class='form-control' type='hidden' id='hiddenprice_$i' name='hiddenprice[]' /> <td><input class='form-control' type='text' id='jenisbenang_$i' name='jenisbenang[]' readonly/></td> <td><input class='form-control' type='text' id='warna_$i' name='warna[]' readonly/></td> <td><input class='form-control' type='text' id='lot_$i' name='lot[]' required/></td> <td><input class='form-control sedang' type='text' id='netto_$i' name='netto[]' required/> </td> <td><input class='form-control pendek' type='text' id='box_$i' name='box[]'/> </td> <td><input class='form-control pendek' type='text' id='cones_$i' name='cones[]'/> </td> <td><input class='form-control' type='text' id='keterangan_$i' name='keterangan[]'/> <input class='form-control' type='text' id='keterangan_$i' name='identitas[]' value='$iden'/> <input class='form-control' type='text' id='jumrow_$i' name='jumpack' value=''/> </td> <td><a><span class='glyphicon glyphicon-plus addmore' id='$i'></span></a> </td> </tr> <tr> <td colspan='10'> <table id='keatas_$i' class='keatas'> <tr></tr> </table> </td> </tr>"; } echo" </table> so every time i click on addmore , the values will increase by 1 but only in same row.and for the different row the values will start from 1 again. i mix html and php in 1 file , but its not the main problem . any suggest would be appreciated and thank you for spent your time on my post i hope you understand what i mean cause my english is the worst. lol A: use html like remove $i from it: for($i=1;$i<=5;$i++) { <input class='form-control' type='text' id='jumrow_$i' name='jumpack' value=''/> </td> <td><a><span class='glyphicon glyphicon-plus addmore' id='$i'></span></a> </td> </tr> </tr>"; } Instead of loop use single event like : $(".addmore").on('click', function (a) { var cell= $(this).parents('td') var currentValue = cell.find("[name=jumpack]").data('addmore'); if(currentValue==null || currentValue == undefined) { currentValue =0; } else { currentValue=parseInt(currentValue); } var data = "<td><input class='form-control sedang' type='text' id='packinglist_" + $(this).index() + "' name='packinglist[]'/></td>"; cell.parents('tr').append(data); currentValue++; cell.find("[name=jumpack]").val(currentValue).data('addmore',currentValue) });
[ "stackoverflow", "0029694770.txt" ]
Q: Should arguments be passed in the child class or the parent class Let's say I have a class public class Child { public Child(Object arg1) { super(arg1); } } and I have a parent class public class Parent { Object object; public Parent(Object arg1) { this.object=arg1; } } So my question is which would be a better coding practice Inserting the argument in the child and then passing it over to the parent OR Inserting the argument in the parent itself without going through the child. For clarity's sake let's say currently the child does not need the argument. A: By the looks of your code, calling super will result to an error, you need to extend your Child to the parent ie. public class Child extends Parent{ ... } Since you created a constructor for the parent: public Parent(Object arg1) the no-arguement constructor is gone by default. If the Parent needs this object how else will you then initialize the Parent when you create the Child? public Child() { super(); //ERROR } super() now won't work cause you created constructor for the parent with a parameter. super is looking for Parent() without any arguements
[ "stackoverflow", "0037671340.txt" ]
Q: How to change foreground/text color of JFormattedTextField on its input text not obeying the RegEx format? I am following, http://www.java2s.com/Tutorial/Java/0240__Swing/RegexFormatterwithaJFormattedTextField.htm. In the given example, How to change foreground/text color of JFormattedTextField on its input text not obeying the RegEx format of the formatter? A: You can change the foreground color of the JFormattedTextField when the user attempts to change focus using an InputVerifier. Starting from this complete example, condition the color in your implementation of shouldYieldFocus(). @Override public boolean shouldYieldFocus(JComponent input) { if (verify(input)) { tf.setValue(date); tf.setForeground(Color.black); return true; } else { tf.setForeground(Color.red); return false; } } To see changes while typing, use a DocumentListener that evaluates DateFormat instances in a similar way.
[ "expatriates.stackexchange", "0000000360.txt" ]
Q: As a French PhD student in the US, what can I do to get the US citizenship as quickly as possible? I (French citizen) started a PhD in computer science in the US one year and a half ago: what can I do to get the US citizenship as quickly as possible? A: There are several options: Marry a US citizen. Once the US government is satisfied that your marriage is not a sham marriage (i.e.: you didn't get married just for the immigration benefits) - you'll get a green card (permanent residency). After three years as permanent resident married to a US citizen, you can apply for US citizenship. Get a green card on your own. Either through an employer (EB1/EB2 process) or because you're such a distinguish scholar that the US would want to keep you (EB1 self sponsored process). After 5 years as a permanent resident you can apply for US citizenship. Have a congressman introduce legislation to the US Congress to grant you a citizenship. Once the bill passes and is signed into law by the President - you'll become a US citizen. Join the US military. After 4 (IIRC...) years in the military, as long as you're not dishonorably discharged, you can apply for US citizenship.
[ "stackoverflow", "0033977085.txt" ]
Q: Swift 2.1- tabBarController!.selectedIndex return massive integer I am needing to put the tabBarController!.selectedIndex number inside a constant. I am expecting a number between 0 and 3 depending on what tab I choose, but instead I get numbers like 2147483647 Any ideas why this is? The code is: let selectedTab = tabBarController!.selectedIndex print(selectedTab) A: That value is NSNotFound. In this case it seems to represent "no selection".
[ "stackoverflow", "0024509053.txt" ]
Q: IllegalStateException In Android? I have spinner and listview in my Activity. I'm retrieving all of the columns with average from my SQLite database table in my listview. I'm using the average function in the raw query with a group by clause. When I run the app my application crashes. I'm getting null pointer exception: Bad request for field slot 0,-1. numRows = 1, numColumns = 6 and java.lang.IllegalStateException: get field slot from row 0 col -1 failed. Can someone help me someone please. Thanks in advance. Here is my Activity code public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.performance_details); databaseHelper = new DatabaseHelper(this); databaseHelper.onOpen(db); spinneEmployeeName = (Spinner)findViewById(R.id.spinnerPerformance_EmployeeName); loadSerachEmpName(); spinneEmployeeName.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub selectedEmployeeName = spinneEmployeeName.getSelectedItem().toString().trim(); System.out.println("selectedEmployeeName " + selectedEmployeeName); String[] separated = selectedEmployeeName.split(" "); strSeparated_Id = separated[0].trim(); Log.e("strSeparated_Id = ",""+strSeparated_Id); System.out.println("strSeparated_Id = " +strSeparated_Id); strSeparated_EmpName = separated[1].trim(); Log.e("strSeparated_EmpName = ",""+strSeparated_EmpName); System.out.println("strSeparated_EmpName = " +strSeparated_EmpName); showPerformanceDetails(); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); } private void showPerformanceDetails() { list_PerformanceDetails = (ListView)findViewById(R.id.list_PerformanceDetails); ArrayList<Performance_Pojo> Performance_PojoList = new ArrayList<Performance_Pojo>(); Performance_PojoList.clear(); SQLiteDatabase sqlDatabase = databaseHelper.getWritableDatabase(); Log.e("strSeparated_Id = ",""+strSeparated_Id); Log.d("Tag", strSeparated_Id); Cursor cursor = sqlDatabase.rawQuery("SELECT performance_month, AVG(performance_rate_one), AVG(performance_rate_two), AVG(performance_rate_three), AVG(performance_rate_four), AVG(performance_rate_five) FROM performance where "+ "Emp_id" + " = ? " +" GROUP BY performance_month",new String[]{String.valueOf(strSeparated_Id)}); if (cursor != null && cursor.getCount() != 0) { if (cursor.moveToFirst()) { do { Performance_Pojo Performance_PojoListItems = new Performance_Pojo(); Performance_PojoListItems.set_strPerformanceMonth(cursor.getString(cursor.getColumnIndex("performance_month"))); Performance_PojoListItems.set_strPerformance_rate_one(cursor.getString(cursor.getColumnIndex("performance_rate_one"))); Performance_PojoListItems.set_strPerformance_rate_two(cursor.getString(cursor.getColumnIndex("performance_rate_two"))); Performance_PojoListItems.set_strPerformance_rate_three(cursor.getString(cursor.getColumnIndex("performance_rate_three"))); Performance_PojoListItems.set_strPerformance_rate_four(cursor.getString(cursor.getColumnIndex("performance_rate_four"))); Performance_PojoListItems.set_strPerformance_rate_five(cursor.getString(cursor.getColumnIndex("performance_rate_five"))); Performance_PojoList.add(Performance_PojoListItems); }while (cursor.moveToNext()); } sqlDatabase.close(); cursor.close(); } PerformanceList_Adapter performanceList_Adapter = new PerformanceList_Adapter(Performance_Details.this, Performance_PojoList); list_PerformanceDetails.setAdapter(performanceList_Adapter); } Here is my Adapter Class public class PerformanceList_Adapter extends BaseAdapter { Context context; ArrayList<Performance_Pojo> Performance_List; public PerformanceList_Adapter(Context context, ArrayList<Performance_Pojo> performance_List) { super(); this.context = context; Performance_List = performance_List; } @Override public int getCount() { // TODO Auto-generated method stub return Performance_List.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return Performance_List.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub Performance_Pojo PerformanceListItems =Performance_List.get(position); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.performance_list_items, null); } TextView textView_Month = (TextView) convertView.findViewById(R.id.textView_PerformanceMonth); textView_Month.setText(PerformanceListItems.get_strPerformanceMonth()); TextView textView_RateOne = (TextView) convertView.findViewById(R.id.textView_performance_rate_one); textView_RateOne.setText(PerformanceListItems.get_strPerformance_rate_one()); TextView textView_RateTwo = (TextView) convertView.findViewById(R.id.textView_performance_rate_two); textView_RateTwo.setText(PerformanceListItems.get_strPerformance_rate_two()); TextView textView_RateThree = (TextView) convertView.findViewById(R.id.textView_performance_rate_three); textView_RateThree.setText(PerformanceListItems.get_strPerformance_rate_three()); TextView textView_RateFour = (TextView) convertView.findViewById(R.id.textView_performance_rate_four); textView_RateFour.setText(PerformanceListItems.get_strPerformance_rate_four()); TextView textView_RateFive = (TextView) convertView.findViewById(R.id.textView_performance_rate_five); textView_RateFive.setText(PerformanceListItems.get_strPerformance_rate_five()); return convertView; } } Error and Exception AT the line Performance_PojoListItems.set_strPerformance_rate_one(cursor.getString(cursor.getColumnIndex("performance_rate_one"))); Here is my Log Cat Error Info 07-01 16:43:31.746: E/CursorWindow(15747): Bad request for field slot 0,-1. numRows = 1, numColumns = 6 07-01 16:43:31.746: D/AndroidRuntime(15747): Shutting down VM 07-01 16:43:31.746: W/dalvikvm(15747): threadid=1: thread exiting with uncaught exception (group=0x40015560) 07-01 16:43:31.766: E/AndroidRuntime(15747): FATAL EXCEPTION: main 07-01 16:43:31.766: E/AndroidRuntime(15747): java.lang.IllegalStateException: get field slot from row 0 col -1 failed 07-01 16:43:31.766: E/AndroidRuntime(15747): at android.database.CursorWindow.getString_native(Native Method) 07-01 16:43:31.766: E/AndroidRuntime(15747): at android.database.CursorWindow.getString(CursorWindow.java:329) 07-01 16:43:31.766: E/AndroidRuntime(15747): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:49) 07-01 16:43:31.766: E/AndroidRuntime(15747): at com.sqlitedemo.Performance_Details.showPerformanceDetails(Performance_Details.java:92) 07-01 16:43:31.766: E/AndroidRuntime(15747): at com.sqlitedemo.Performance_Details.access$0(Performance_Details.java:70) 07-01 16:43:31.766: E/AndroidRuntime(15747): at com.sqlitedemo.Performance_Details$1.onItemSelected(Performance_Details.java:56) 07-01 16:43:31.766: E/AndroidRuntime(15747): at android.widget.AdapterView.fireOnSelected(AdapterView.java:871) 07-01 16:43:31.766: E/AndroidRuntime(15747): at android.widget.AdapterView.access$200(AdapterView.java:42) 07-01 16:43:31.766: E/AndroidRuntime(15747): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:837) 07-01 16:43:31.766: E/AndroidRuntime(15747): at android.os.Handler.handleCallback(Handler.java:587) 07-01 16:43:31.766: E/AndroidRuntime(15747): at android.os.Handler.dispatchMessage(Handler.java:92) 07-01 16:43:31.766: E/AndroidRuntime(15747): at android.os.Looper.loop(Looper.java:123) 07-01 16:43:31.766: E/AndroidRuntime(15747): at android.app.ActivityThread.main(ActivityThread.java:3683) 07-01 16:43:31.766: E/AndroidRuntime(15747): at java.lang.reflect.Method.invokeNative(Native Method) 07-01 16:43:31.766: E/AndroidRuntime(15747): at java.lang.reflect.Method.invoke(Method.java:507) 07-01 16:43:31.766: E/AndroidRuntime(15747): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 07-01 16:43:31.766: E/AndroidRuntime(15747): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 07-01 16:43:31.766: E/AndroidRuntime(15747): at dalvik.system.NativeStart.main(Native Method) A: this is happeninig because you are fetching the value AVG(performance_rate_one) and while searching for the column with the name performance_rate_one. So getColumnIndex will return -1 and hence the error you are getting. Either use alias in your query or use the column name as AVG(performance_rate_one) while fetching. EDIT For example: if in Query you select field as AVG(performance_rate_one) as col1 Then while fetching you should write cursor.g‌​etColumnIndex("col1") Hope this helps.
[ "pt.stackoverflow", "0000128396.txt" ]
Q: Calcular o numero de horas entre duas horas e transformar em float Necessitava de criar uma funcção que recebesse duas horas no formato (00:00:00), calcula-se o número de horas entre elas, e me converte-se para float. No entanto o float seria deste gênero: Resultado: 2 horas e 30 min -> 2,30 Resultado: 3 horas e 45 min -> 3,45 Resultado: 3 horas e 1 min -> 3,01 resultado: 3 horas e 59 min -> 3,59 A: Existe um problema de conceito, no caso 2 horas e 30 minutos deveria em ponto flutuante ser representado como 2,50 isso porque 1 hora que no caso é avaliado como 1.0 em ponto flutuante são 60 minutos, partindo desse princípio 30 minutos deveria equivaler 0.5 sendo assim 2 horas e 30 minutos ==> 2,50 e não 2,30 como apontado acima! usando-se regra de 3 você converte baseando-se em minutos (se a precisão for em minutos) basta converter o período em minutos. 02:30 (duas horas e trinta minutos) ==> 150 minutos na regra de 3 a relação 1 para 60, ou seja 1 em ponto flutuante equivale a sessenta minutos e obter o valor em ponto flutuante equivalente ao que se quer converter (150 minutos) considerando-se a proporção estabelecida, obtendo-se assim a expressão abaixo 60X = 150*1 ==> X = 150/60 ==> X = 2,50
[ "stackoverflow", "0032773522.txt" ]
Q: autocompletion for sublime text 3 package anaconda is slow I have my anaconda package installed with package installer for Sublime Text 3. The autocompletion feature takes ~ 2-4 seconds after "." to show available options. Has anyone encountered this, if so can you please advise if there is a method to correct this? I am using a MAC for reference. Thanks! A: Open your user preferences (Sublime Text → Preferences → Settings—User) and add the following to the top, just after the opening {: "auto_complete_triggers": [ { "characters": ".", "selector": "source" } ], then save the file and restart Sublime (so that Anaconda reloads and sees the new settings). This should now trigger autocomplete as soon as you hit .. You can also try adding: "auto_complete_delay": 0, to instantly trigger autocomplete, but I find the default value of 50 (milliseconds) is fine.
[ "stackoverflow", "0037926351.txt" ]
Q: Adding subscripts to the variable names of a PCA using ggbiplot? I have the following PCA plot with 7 variables (see data and code below), where I want the variable names to be put in subscript. In ggbiplot() however, the variable names are automatically taken from the column names of the matrix that was used to generate the PCA, and (as far as I know) no options are available to add these manually. Therefore I tried to create subscripts in my actual column names by using c(expression("j"["d"]),expression("k"["1"]), etc.) which only results in the variable names turning into "j"["d"],"k"["1"] on the PCA plot. Is there a workaround for this problem? e.g. making the second character smaller or something alike? The plot was generated using the data: Param.clean <- structure(c(0.314689287410068, 0.279479887056815, 0.448790689537864, 0.25336455455925, 0.289008161177184, 0.314501392595033, 0.291144087910652, 0.30630205659933, 0.283940162753961, 0.293902791758693, 0.384490609026053, 0.287376099118374, 0.308181312257512, 0.295516976083076, 0.299962079750977, 0.377418190053724, 0.577708482228635, 0.548861542714413, 0.445100820783724, 0.454234613160057, 0.509303280474031, 0.485557486397235, 0.512794671011103, 0.438809386918853, 0.584488774396788, 0.485077847448695, 0.54242611837146, 0.50295109738886, 0.462140343335828, 0.482811895512131, 0.505123975906175, 0.454883826310242, 0.270198900375524, 0.375171915727647, 0.415330703464691, 0.335520417496773, 0.337301727971001, 0.414448624199441, 0.413407199816623, 0.480251511263297, 0.381597639419929, 0.299997369191106, 0.716363262901133, 0.334190348030789, 0.339749957548872, 0.615860520668703, 0.399995858493781, 0.290916481482953, 0.271565709782391, 0.434971269297489, 0.426102875513371, 0.245620918873499, 0.350757895503111, 0.314711831388176, 0.233155192989713, 0.248289747469244, 0.260316266382216, 0.435133707574921, 0.270357707406285, 0.460714026041302, 0.300202262584418, 0.283894965208827, 0.286731230742906, 0.476076636930455, 0.496419713185873, 0.449716335449948, 0.414301742272173, 0.517741851053675, 0.452096411019313, 0.503619428840069, 0.46590684730812, 0.426164828533173, 0.526710272381684, 0.60162289738927, 0.501571299694807, 0.5204289094248, 0.501944294148778, 0.420989057029306, 0.486676941655541, 0.581232141136961, 0.388451077003248, 0.348575471498664, 0.541637601056563, 0.280529225927791, 0.474527715587717, 0.427368925204716, 0.247233045036043, 0.371205006512827, 0.350378420436755, 0.334934610173675, 0.672485054825788, 0.387370130421541, 0.442394016641109, 0.410245000087745, 0.554591956294395, 0.292541225836523, 4.53967830833669, 4.07671677879989, 6.31220323958745, 5.53951495559886, 6.14831664270411, 2.49250044245273, 3.56566691364472, 0.905669305473566, 5.65883946946512, 2.64297457644716, 3.05508165226008, 3.18054619676744, 6.40823390030613, 3.37302493648604, 3.66350222987433, 2.54057804516827, 8.20203100920965, 2.71440979468947, 2.91087136765321, 1.99383332931126, 2.54861955298111, 2.76731871856997, 2.8168199171933, 1.87471640761942, 2.36744814319536, 2.70068269921467, 3.73984078429639, 3.14727020682767, 2.44860090082511, 2.96811391366646, 3.15924824448302, 2.75038693333045, 0.571991651163747, 0.0795687369691844, 0.199285715352744, 0.278876264579594, 0.0878147967159748, 0.776516450569034, 0.109050695318729, 0.214585168287158, 0.0733157177455723, 4.99666969059035, 0.681611322797835, 0.511083496330927, 0.103351746220142, 2.09765716294448, 0.163525143420944, 1.15420421690991, 3.94337840843946, 3.16239102048179, 5.81127347030366, 5.75235136287908, 2.48392526193832, 2.46317023644224, 1.81044878205284, 4.65439113788307, 5.15721979085356, 2.87866174476221, 2.5224589696154, 5.64499958222732, 1.54218871717652, 2.67105548409745, 3.03890538634732, 4.12773523628712, 2.30713835917413, 1.77077499361088, 2.28220948716626, 2.27822186658159, 2.22687301691622, 2.78089357145751, 2.10296940756962, 1.62778628757223, 2.64038743038351, 2.90401477599517, 2.85171007970348, 2.15843657962978, 2.22618574043736, 2.01146884588525, 7.50444248911614, 2.78893498703837, 0.369707935024053, 0.640407053288072, 1.16690336726606, 1.19069673353806, 0.369720328599215, 0.222492094617337, 1.97003725056226, 0.0771822298566498, 0.0491951033473015, 1.58942595124245, 0.56345314020291, 3.61783248605207, 0.470429616980255, 4.25140980218227, 0.416233133369436, 0.838344213552773, 2.73752116598189, 3.02740207407624, 1.11222450388595, 2.30047973571345, 2.45276295114309, 2.64581680834914, 2.78265510452911, 3.27471463242546, 3.1145193031989, 2.56884276599934, 3.15895244479179, 3.14939826028422, 2.39397626441593, 3.8150685878781, 2.75754480964194, 2.56850058445707, 1.10134650183221, 1.90155507440989, 1.71837465837598, 2.29802527697757, 1.24960316416497, 1.95164571283385, 1.49695883272216, 2.51760663697496, 1.04954799870029, 1.59203378250822, 1.33138975808397, 1.30761714885011, 1.6880701482296, 1.33289409801364, 1.18721167324111, 2.10289117880166, 4.97532397741452, 4.08132408546905, 4.83296488539005, 5.65673472359776, 1.52374835970501, 4.90433675702661, 6.09970323707287, 4.9611738567551, 4.98475494328886, 1.58062443907062, 6.51368894614279, 5.82539446347704, 4.37618843046948, 6.41044923532754, 1.36502551613376, 2.11988553637639, 2.87185357650742, 1.99067048101375, 2.6186517810449, 1.56325603065391, 3.18718514405191, 2.67383103277534, 3.39795261013011, 3.97267814834292, 3.7929962793986, 2.75519806658849, 2.67046403462688, 1.61068025619412, 3.21088001991933, 2.72053461754695, 2.89008031133562, 2.44437138317153, 1.87622146913782, 2.30537068654473, 1.77740855213876, 1.46343538770452, 2.23820108221844, 1.83238286990672, 1.70535395620391, 3.20611382601783, 1.42552105011418, 1.35411406867206, 1.67505901074037, 1.27963638935859, 1.50879823369905, 3.20626547553887, 1.34457757696509, 1.4350421866402, 3.01776180580879, 4.42168406192213, 2.68915122840554, 5.10021819965914, 5.7995775481686, 3.69961343705654, 5.6582765411896, 5.42690238449723, 4.12574668414891, 2.88072699628149, 7.37651169135546, 0.877918794285506, 3.48383912583813, 7.16048748052369, 1.10681456684445, 2.0056554214408, 0.843951161950827, 0.892569730058312, 1.82299897540361, 1.4852886760508, 1.34192016645273, 1.12837524153292, 0.788718643598258, 2.59369957595567, 1.03540072683245, 0.767321502789855, 1.23622662722568, 0.784033099189401, 0.784212271682918, 1.25203002375116, 0.76296656858176, 0.985467154532671, -0.220396793447435, 0.106205735355616, 0.124459093059103, -0.00892141033460625, -0.10377890299509, 0.0926174888437004, -0.0549866305664182, 0.278899986296892, 0.0474233353460836, -0.109990653581917, 0.0474225463395319, 0.0338427349925041, 0.0972763542085886, 0.114185092970729, -0.00886052381247282, -0.0589170539751649, -2.3298938000525, -1.84932016064972, -3.90579685030132, -6.07330848347147, 1.8304963277777, -2.75582764982432, -4.77531149517745, -3.8228796642224, 1.27799427995086, -5.45959737020979, -2.00253919902196, -2.22745593055834, -2.6610222319141, -3.21496389806271, -6.01237997648368, -3.13309627585113, 0.733061715583007, 1.04009207207213, 1.51182846035312, 1.92732659168541, 1.29081471823156, 0.809032674878836, 0.954354595015446, 1.5407008677721, 0.961584224718311, 0.949504360179106, 1.17135864682496, 0.758904917165637, 1.27744460012764, 1.13802453503013, 1.12143621314317, 0.923086409457028, -0.207958693792422, -0.112425229889651, -0.114883695351581, -0.0418341891790419, 0.00953924376517534, 0.0761805102229118, 0.06189932115376, -0.279747098684311, -0.139795616269112, -0.0957655208185315, -0.211875131353736, 0.15934879556795, -0.307479116310674, -0.171517195557555, -0.147559982724488, -0.151702696457505, -3.2736393770054, -3.77255320500831, -2.50166923739016, -3.38403152301908, -3.54271008856346, -5.98730765748769, -3.46145537216216, 4.08535061942786, -5.5706409165586, -5.12871207815409, -2.00980313849697, -1.74987012389551, -4.99012113984178, -5.52220372986048, -4.09768380224705, -2.65192667357127, 0.368457175791264, 0.276677635120849, 0.660357913002372, 0.536901503801346, 0.122066596522927, 0.248441367586455, 0.326834246516228, 0.414462564513087, 0.374505277723074, 0.157977417111397, 0.147561579942703, 0.327407247386873, 0.481645831460754, 0.471423282288015, 0.402634991332889, 0.600018523255984, -0.754529740661383, -0.333761049988369, -0.479209786502022, -0.338527356651923, -1.15156446321805, -0.187009451910853, -1.59113974179576, -0.26058504227052, -0.629410240799189, -1.30694395600756, -0.916838761041562, -1.07011808082461, -1.22627768199891, -0.492068426683545, -1.54347744450718, -0.104520670138299, 1.40759190544486, 7.8479420303603, 2.75170721710225, 3.93423731307934, 9.85715725720922, 5.37083122879267, 6.15668724537641, 4.96914687916388, 6.46718368138125, 1.0871206430619, 9.84838488511741, 9.75057146977633, 1.26769720241924, 9.92010527290404, 9.98543933499604, 9.69677802640945, 0.169932479038835, 0.409494925844172, 0.409328970126808, 0.740250064991415, 0.193447070196271, 0.51206505260865, 0.250175041146576, 0.391306541860104, 0.295244073495269, 0.243191891349852, 0.293793072924018, 0.408511371351779, 0.281213674316803, 0.680068365474543, 0.41473192628473, 0.371123384684324, -0.753847653398911, -0.768953422084451, -1.10839967615902, -0.771105247549713, -0.155546843451758, -0.282887876386441, -0.444554830901325, -0.305730849504471, -0.499526713974774, -0.561585665126642, -0.731248073279858, -0.888600847683847, -0.92906893696636, -0.32135354558875, -0.635939710773528, -0.817948141487935, 1.6278464008073, 3.22130429296692, 3.22974945083757, 7.91888088977089, 9.00321571025501, 2.45285976212472, 6.25077115575721, 5.03100211266428, 2.74867731204381, 1.44042827261984, 5.0080717401579, 9.99481210485101, 1.47605382240812, 5.14414160776883, 7.90287723037352, 9.74082155153155, 6.49911883796255, 4.32981192308168, 8.23767292803774, 4.77091148030013, 9.32961360147844, 2.72199803938468, 3.16884732668598, 0.829324850315849, 5.05701699654261, 2.34405943658203, 3.72586945071816, 2.25735736116767, 6.09207524452358, 4.18884709620227, 3.34469041476647, 2.58207156453282, 0.749518116253117, 10.288818734698, 4.99554592402031, 12.6404861267656, 7.78458069656044, 5.22634824855874, 19.4536860734845, 18.1442198018854, 2.79630955830216, 9.58980514369905, 7.07662330872069, 2.31912315823138, 4.37504726642122, 10.6357821771254, 4.86855507971098, 15.2487045279394, 2.38136078696698, 2.2241358395045, 2.6578728514413, 2.00018415475885, 14.3105512278154, 2.79016453381628, 2.82581362407655, 3.00503022968769, 0.867751725018024, 19.840897029452, 2.76507987820854, 2.18780075665563, 2.29634886607528, 5.24806297849864, 3.00219499040395, 3.75070014856756, 4.70993515464167, 2.90138749877612, 7.88213442545384, 6.81599063475927, 2.61536476109177, 2.09377944457034, 1.96296699593464, 5.57947221212089, 5.20963124415527, 3.33875400945544, 2.79699660371989, 4.58355573223283, 1.3866287143901, 2.73741390556097, 3.83854200132191, 3.64578404258937, 8.6152262147516, 7.4471927308167, 10.7907397029921, 3.60064423537503, 2.21575071569532, 13.2584175148358, 6.69871457573026, 7.57425001679609, 10.597095658568, 6.29717063158751, 19.982005469501, 4.82507357889165, 12.0198037318264, 12.1128156222403, 0.971864601969719, 7.90290065680941, 2.69096855397026, 3.41408452807615, 3.34672867252181, 3.73752327635884, 2.59765107041846, 3.69969989638776, 6.49256678763777, 1.34200508563469, 2.58853476804991, 6.08448572133978, 2.86518771201372, 8.80958803463727, 3.21931545517097, 13.9356314451744, 3.31248219124973, 2.6213849833856, 6.81703055885931, 4.57180783512692, 0.800920105539262, 1.6915382258594, 1.97274463716894, 8.35091653894633, 4.07009290065616, 4.70143776244173, 3.73712390195578, 3.32298003757993, 2.70389301739633, 9.40504621323198, 5.22653986488779, 6.91535883117467, 4.01246708252778, 6.83368936007222, 5.52582112283756, 9.52527065730343, 5.19140504300594, 8.41044230709473, 6.70183763448149, 6.82530618272722, 9.10367484707385, 14.269079283004, 4.7895190725103, 6.59831102186193, 5.62791180796921, 6.17603897117078, 7.14836313854903, 5.96534776215752, 6.33691875052949, 4.8933652261893, 13.8731955783442, 17.7908931604276, 13.79737106661, 12.8477370319888, 1.87629146464169, 19.782149810344, 19.4288346171379, 18.9387338103106, 18.204667886657, 1.15545298295716, 19.7008843562255, 17.4563148757443, 14.7906976851945, 17.3621598140026, 1.16834398824722, 1.00026320200414, 15.0063681416214, 3.00477131232619, 5.1401701791212, 0.385864693671465, 4.36085817695906, 8.55562331421922, 5.70195167902857, 5.37442221703629, 4.73609448876232, 3.56490389804045, 5.62534291626265, 1.87125703754524, 4.91213823029151, 5.71994946518292, 5.81859005757918, 4.93084813430905, 8.53895935813586, 8.24653955462078, 5.77503573757907, 8.75251863257339, 6.42709499839693, 6.27165456948181, 6.44690599292517, 16.0425839032357, 5.03840921912342, 5.87823822697004, 4.41305622781316, 5.94650622780124, 5.56597112355133, 1.1121899643292, 5.33032094594091, 5.42635044082999, 6.6131685036545, 11.4281271025538, 6.12669843180726, 14.5658381014441, 18.4343010187149, 10.0486588804051, 19.8108604625488, 19.3252983829007, 9.68507033698261, 7.62796785042932, 14.9589012558262, 0.670023332349956, 11.1040308237076, 17.0357564882065, 1.06506975100686, 0.740390195945899), .Dim = c(96L, 7L), .Dimnames = list(NULL, c("jd", "k1", "k2", "b1", "b2", "p1", "p2"))) and code: library(ggbiplot) Param.pca <- prcomp(Param.clean,scale=TRUE) groups <- factor(c(rep("Cercis L",16),rep("Cornus L",16),rep("Ginkgo L",16),rep("Cercis R",16),rep("Cornus R",16),rep("Ginkgo R",16))) g <- ggbiplot(Param.pca, choices=c(1,2), obs.scale = 1, var.scale = 1, ellipse.prob=0.95, groups = groups, ellipse = TRUE, alpha=0, varname.size=6,labels.size = 10) g <- g + geom_point(aes(shape=groups,col=groups)) g <- g + theme(legend.direction = 'vertical', legend.position = 'right', axis.text=element_text(size=14),axis.title=element_text(size=14), legend.text=element_text(size=14),legend.title=element_text(size=14)) plot(g) A: Following up on @RichardTelford's comment, you can get the code for ggbiplot by typing ggbiplot in your console. Then copy and paste this into a script file and assign it to a new name, say, my_ggbiplot. Then change the last if statement in the function from this: if (var.axes) { g <- g + geom_text(data = df.v, aes(label = varname, x = xvar, y = yvar, angle = angle, hjust = hjust), color = "darkred", size = varname.size) } to this: if (var.axes) { df.v$varname = paste0(substr(df.v$varname,1,1),"[",substr(df.v$varname,2,2),"]") g <- g + geom_text(data = df.v, aes(label = varname, x = xvar, y = yvar, angle = angle, hjust = hjust), color = "darkred", size = varname.size, parse=TRUE) } Note the addition of the line that creates the new text labels and then the addition of parse=TRUE to geom_text. This hard-codes the labels to work specifically for your case, but you can make the function more general if you're going to do this a lot. To run the function (once you've loaded it into your environment): my_ggbiplot(Param.pca, choices=c(1,2), obs.scale = 1, var.scale = 1, ellipse.prob=0.95, groups = groups, ellipse = TRUE, alpha=0, varname.size=6, labels.size = 10) + geom_point(aes(shape=groups, col=groups)) + theme(axis.text=element_text(size=14), axis.title=element_text(size=14), legend.text=element_text(size=14), legend.title=element_text(size=14)) And here's the result:
[ "stackoverflow", "0031480222.txt" ]
Q: PhoneGap/Cordova iOS playing sound disables microphone I am currently working on a PhoneGap application that, upon pressing a button, is supposed to play an 8 seconds long sound clip, while at the same time streaming sound from the microphone over RTMP to a Wowza server through a Cordova plugin using the iOS library VideoCore. My problem is that (on iOS exclusively) when the sound clip stops playing, the microphone - for some reason - also stops recording sound. However, the stream is still active, resulting in a sound clip on the server side consisting of 8 seconds of microphone input, then complete silence. Commenting out the line that plays the sound results in the microphone recoding sound without a problem, however we need to be able to play the sound. Defining the media variable: _alarmSound = new Media("Audio/alarm.mp3") Playing the sound and starting the stream: if(_streamAudio){ startAudioStream(_alarmId); } if(localStorage.getItem("alarmSound") == "true"){ _alarmSound.play(); } It seems to me like there is some kind of internal resource usage conflict occuring when PhoneGap stops playing the sound clip, however I have no idea what I can do to fix it. A: I've encountered the same problem on iOS, and I solved it by doing two things: AVAudioSession Category In iOS, apps should specify their requirements on the sound resource using the singleton AVAudioSession. When using Cordova there is a plugin that enables you to do this: https://github.com/eworx/av-audio-session-adapter So for example, when you want to just play sounds you set the category to PLAYBACK: audioSession.setCategoryWithOptions( AVAudioSessionAdapter.Categories.PLAYBACK, AVAudioSessionAdapter.CategoryOptions.MIX_WITH_OTHERS, successCallback, errorCallback ); And when you want to record sound using the microphone and still be able to playback sounds you set the category as PLAY_AND_RECORD: audioSession.setCategoryWithOptions( AVAudioSessionAdapter.Categories.PLAY_AND_RECORD, AVAudioSessionAdapter.CategoryOptions.MIX_WITH_OTHERS, successCallback, errorCallback ); cordova-plugin-media kills the AVAudioSession The Media plugin that you're using for playback handles both recording and playback in a way that makes it impossible to combine with other sound plugins and the Web Audio API. It deactivates the AVAudioSession each time it has finished playback or recording. Since there is only one such session for your app, this effectively deactivates all sound in your app. There is a bug registered for this: https://issues.apache.org/jira/browse/CB-11026 Since the bug is still not fixed, and you still want to use the Media plugin, the only way to fix this is to download the plugin code and comment out/remove the lines where the AVAudioSession is deactivated: [self.avSession setActive:NO error:nil];
[ "photo.stackexchange", "0000041026.txt" ]
Q: Is there any good method to invert a negative image (duplicated with a digital camera) in Lightroom? I made some duplicates picture (of negatives) with my digital camera using a bellows and a repro-dia. The image is obviously in a negative format but in RAW. Is the invertion function exists in Lightroom or I have to buy Photoshop or to find another software who can do this? I tried to invert the curve from the development in Lightroom but it does not work for color negatives, because it is not only the inversion but also the orange filter to correct (which become cyan on the inverted picture). A: If you are using Lightroom 4 or greater, you have access to full RGB curves. These are fully featured curves, just like you might find in Photoshop, so you should be able to apply an inverse color negative reversing curve to the RGB curves, then switch back to the standard tone curve and have the ability to edit your inverted negative with your standard Lightroom technique. I've provided some more detailed information about using curves to correct a color negative in this answer: Does a filter exist to color-correct color negatives when copying them with a DSLR? A: I've been trying to do a simple conversion of a black and white negative, and Tone Curves in LightRoom 4 seemed almost impossible to invert. I've known how to do this for years with Photoshop, but this morning found it a complete pain in LightRoom 4 until I figured it out. Google and YouTube were no help The answer: Go to Tone Curve. Below the box with the graph/curve is Point Curve: Select Custom. This allows you to slide the D-max (Black) and D-min (White) points bottom to top and top to bottom. Note: it doesn't solve the color cast problem for color negs.
[ "stackoverflow", "0057222849.txt" ]
Q: Converting all Terms in a List to Title case I have a list: ['CHEVRON' 'GUNVOR' 'P66' 'SHELL'] I need them to be converted to title case format. I'm currently looping through them but there must be a simpler way. Intended output: ['Chevron', 'Gunvor', 'P66', 'Shell'] A: In [35]: L = ['CHEVRON', 'GUNVOR', 'P66', 'SHELL'] In [36]: list(map(str.title, L)) Out[36]: ['Chevron', 'Gunvor', 'P66', 'Shell'] In [37]: [s.title() for s in L] Out[37]: ['Chevron', 'Gunvor', 'P66', 'Shell']
[ "stackoverflow", "0056222092.txt" ]
Q: Missing connections in Dymola Diagram view I am using Dymola to design a small model of some DC motors and a power source. After I finished my work I saved everything and closed Dymola. When I opened it the next time some (not all) of the connections did not show up anymore. So I tried to draw them again, but Dymola tells me that the connections already exist. When I look at the connections in the Text section they are still there. I am using Ubuntu 18.04 and Dymola Version 2019 FD01 (64-bit), 2018-10-10. I also tried to open the model in Openmodelica. But there also were the same connections missing. Screenshot: and the text representation: connect(controlSoftware.s1, switches.s1); connect(controlSoftware.s12, switches.s12); connect(controlSoftware.s2, switches.s2); connect(controlSoftware.r1, switches.r1); connect(controlSoftware.r2, switches.r2); connect(switches.p, constantVoltage.p); connect(switches.pin_n, motorWithCurrentSensor.n); connect(switches.pin_n1, motorWithCurrentSensor1.n); connect(controlSoftware.cur1, motorWithCurrentSensor.Currenctsensor); connect(motorWithCurrentSensor.pin, constantVoltage.n); connect(motorWithCurrentSensor1.pin, constantVoltage.n); connect(motorWithCurrentSensor.Speedsensor, controlSoftware.speed1); connect(controlSoftware.speed2, motorWithCurrentSensor1.Speedsensor); connect(controlSoftware.cur2, motorWithCurrentSensor1.Currenctsensor); connect(ground.p, constantVoltage.n); What can I do to get the connections back? I have a really hard time fixing things without graphical representation. Thank you for your help Best regards Gerald A: I see that you are on Ubuntu and there is actually a bug in (at least) Dymola2019FD01 where it does mix up komma and decimal point when writing out annotation coordinates. So if you check you might see some graphical annotations having {10,5,10} instead of {10.5,10} rendering them invalid. I haven't tested if this has been resolved in Dymola2020 but until then you can use the workaround to start Dymola like this: #!/bin/sh export LC_ALL=C exec /usr/local/bin/dymola-2019FD01-x86_64 $* I.e., make sure the local is set to "C" so that Dymola does not get confused.
[ "stackoverflow", "0005235084.txt" ]
Q: Testing Sessions in Rails 3 with Rspec & Capybara I'm trying to write integration tests with rspec, factory_girl & capybara. I also have cucumber installed, but I'm not using it (to my knowledge). I basically want to prepopulate the db with my user, then go to my home page and try to log in. It should redirect to user_path(@user). However, sessions don't seem to be persisted in my /rspec/requests/ integration tests. My spec: /rspec/requests/users_spec.rb require 'spec_helper' describe "User flow" do before(:each) do @user = Factory(:user) end it "should login user" do visit("/index") fill_in :email, :with => @user.email fill_in :password, :with => @user.password click_button "Login" assert current_path == user_path(@user) end end Returns: Failures: 1) User flow should login user Failure/Error: assert current_path == user_path(@user) <false> is not true. # (eval):2:in `send' # (eval):2:in `assert' # ./spec/requests/users_spec.rb:16 Instead, it redirects to my please_login_path - which should happen if the login fails for any reason (or if session[:user_id] is not set). If I try to put session.inspect, it fails as a nil object. If I try to do this in the controller tests (/rspec/controllers/sessions_spec.rb), I can access the session with no problem, and I can call session[:user_id] A: If you are using Devise, you'll need to include Warden::Test::Helpers (right after the require of spec_helper is a good place) as outlined in the warden wiki. The call to session is returning nil because capybara doesn't provide access to it when running as an integration test. A: I have the same problems and although filling out a form might be an option for some, I had to roll my own authentication ruby because I was using a third party auth system (Janrain to be exact).... in my tests I ended up using something like this: Here is what I have in my spec/support/test_helpers_and_stuff.rb module AuthTestHelper class SessionBackdoorController < ::ApplicationController def create sign_in User.find(params[:user_id]) head :ok end end begin _routes = Rails.application.routes _routes.disable_clear_and_finalize = true _routes.clear! Rails.application.routes_reloader.paths.each{ |path| load(path) } _routes.draw do # here you can add any route you want match "/test_login_backdoor", to: "session_backdoor#create" end ActiveSupport.on_load(:action_controller) { _routes.finalize! } ensure _routes.disable_clear_and_finalize = false end def request_signin_as(user) visit "/test_login_backdoor?user_id=#{user.id}" end def signin_as(user) session[:session_user] = user.id end end Then in my request spec, with capybara and selenium, I did the following: describe "Giveaway Promotion" do context "Story: A fan participates in a giveaway", js: :selenium do context "as a signed in user" do before :each do @user = Factory(:user) request_signin_as @user end it "should be able to participate as an already signed in user" do visit giveaway_path .... end end end end BTW, I came up with solutions after trying the proposed solutions to this post and this post and neither of them worked for me. (but they certainly inspired my solution) Good luck!
[ "stackoverflow", "0051320691.txt" ]
Q: Connect a Qt signal to a slot using std::bind I have many QActions and I would like to connect their triggered(bool) signal to a specific slot which gets an integere number as input, let's say setX(int x). I need to specify x in connect callback. For example: connect(actionV, &QAction::triggered, this, &TheClass::setX /* somehow x=10 */); I tried using std::bind and it does not work: connect(actionV, &QAction::triggered, std::bind(this, &TheClass::setX, 10)); A: You can solve this easily using a lambda: connect(actionV, &QAction::triggered, [&] { m_theClass.setX(10); });
[ "stackoverflow", "0006341828.txt" ]
Q: QT progress bar speed Does QT provide any functions to control a progress bar's speed? For example, if I want it to increase by 1% every 1 second, is there any QT way to do it instead of using a loop and sleeping for 1 second between each value change? A: You can use QTimeLine for this. The detailed description in the documentation gives an example of exactly what you want. A: Use a QTimer. Connect the signal timeout() to a slot that increases the value in the QProgressBar. QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(update())); timer->start(1000); In this cas, update() will be call each second.
[ "stackoverflow", "0025773052.txt" ]
Q: Windows cmd: echo without new line but with CR I would like to write on the same line inside a loop in a windows batch file. For example: setlocal EnableDelayedExpansion set file_number=0 for %%f in (*) do ( set /a file_number+=1 echo working on file number !file_number! something.exe %%f ) setlocal DisableDelayedExpansion This will result in: echo working on file number 1 echo working on file number 2 echo working on file number 3 . . . I would like all of them to be on the same line. I found a hack to remove the new line (e.g. here: Windows batch: echo without new line), but this will produce one long line. Thanks! A: @echo off setlocal enableextensions enabledelayedexpansion for /f %%a in ('copy "%~f0" nul /z') do set "CR=%%a" set "count=0" for %%a in (*) do ( set /a "count+=1" <nul set /p ".=working on file !count! !CR!" ) The first for command executes a copy operation that leaves a carriage return character inside the variable. Now, in the file loop, each line is echoed using a <nul set /p that will output the prompt string without a line feed and without waiting for the input (we are reading from nul). But inside the data echoed, we include the carriage return previously obtained. BUT for it to work, the CR variable needs to be echoed with delayed expansion. Otherwise it will not work. If for some reason you need to disable delayed expansion, this can be done without the CR variable using the for command replaceable parameter @echo off setlocal enableextensions disabledelayedexpansion for /f %%a in ('copy "%~f0" nul /z') do ( for /l %%b in (0 1 1000) do ( <nul set /p ".=This is the line %%b%%a" ) )
[ "stackoverflow", "0053782940.txt" ]
Q: Excel: How do I 'gather' values to display in another cell I have two columns, Column A has a set of a few standard values and column B has all unique values. I'm only just experimenting with more complex ways of compiling data than the beginner level so I'm a bit at a loss. I need to either have a lookup or create a macro that will list only the values in A (once each) but also display which values in B correspond to those in A for example A | B va1|abc va1|bcd Va2|xyz va3|zab will show (in a single cell) the following va1: abc, bcd va2: xyz va3: zab Please help! A: Option Explicit Sub Test() Dim i As Long, j As Long, k As Long k = 1 For i = 1 To Cells(Rows.Count, 1).End(xlUp).Row If Application.CountIf(Range("C:C"), Cells(i, 1).Value) = 0 Then Cells(k, 3).Value = Cells(i, 1).Value For j = 1 To Cells(Rows.Count, 1).End(xlUp).Row If Cells(j, 1).Value = Cells(k, 3).Value And _ InStr(Cells(k, 4).Value, Cells(j, 2).Value) = 0 Then If Cells(k, 4).Value = "" Then Cells(k, 4).Value = Cells(j, 2).Value Else Cells(k, 4).Value = Cells(k, 4).Value & ", " & Cells(j, 2).Value End If End If Next j k = k + 1 End If Next i For i = 1 To Cells(Rows.Count, 3).End(xlUp).Row Cells(i, 3).Value = Cells(i, 3).Value & ": " & Cells(i, 4).Value Cells(i, 4).ClearContents Next i End Sub Edited for single cell
[ "stackoverflow", "0038271984.txt" ]
Q: C# ASP.NET crystal reports on server/hosting I need some help about displaying crystal report on server/hosting, I created account on some free hosting just to check how does my application work when it's UP and not on localhost as allways, and I've found out my crystal reports are not working on web (THEY ARE NOT DISPLAYED, PAGE WHERE I AM CALLING REPORT IS OPENING BUT ITS BLANK - WHITE ) .. Before when I used to test it on localhost I had similar issue, so I copyed aspnet_client folder to my project folder and I solved error on localhost, but what now when its UP on hosting? I guess I have to do something like I did on localhost but I dont know exactly what.. Thank you guys, I will appreciate any kind of help A: I FINALLY SOLVED THIS, AND HERE IS HOW: FIRST OF ALL DO THE FOLLOWING: AFTER YOUR BLANK PAGE LOADS, GO TO INSPECT PAGE AND FIND CONSOLE ERROR, IN MY EXAMPLE I SAW THAT MY APPLICATION IS LOOKING FOR FOLDER WITH NAME 4_6_1069/crystalreportviewer13 etc.. AND WITH SOME OTHER FILES, SO I MANUALLY CREATE THAT FOLDER ON MY SERVER/HOSTING, AND I COPIED FILES FROM EXISTING FOLDERS ON THIS PATH aspnet_client/system_web/FOLDERSTHATINEED to my new created folder "4_6_1069".. and that's it :)
[ "stackoverflow", "0049817921.txt" ]
Q: Can I hide legend name in StackedChart using HighChart? I am using HighChart for displaying graphs and I am showing Stacked chart. My issue is that I don't want to show HIBar name which generally display under graph to indicate the signs displayed in graph. I have attached an image to Describe my query : Here, I have marked what I want to hide with a black circle. What property should I use to hide the legend? A: The circeled area is the legend, so hiding the legend will do the trick, done like this: legend: { enabled: false }, Working example: http://jsfiddle.net/ewolden/k3Lkh13k/ API: https://api.highcharts.com/highcharts/legend.enabled
[ "stackoverflow", "0010668388.txt" ]
Q: Compress image from stream I am storing images in database, before I store them, i am resizing them. However, resizing, doesnt compress the image. Stream is same stream. I want to be able to compress the image as well. How can I compress images which are stored in database as stream and returned to request as follows? public ActionResult ViewImage(int id, string imageType ="image") { ContestImage contestImage = GetContestImage(id); byte[] fileContent; string mimeType; string fileName; if (imageType == "thumb") { fileContent = contestImage.ThumbNail.Image; mimeType = contestImage.ThumbNail.ImageMimeType; fileName = contestImage.ThumbNail.ImageFileName; } else if (imageType == "image") { fileContent = contestImage.Image.Image; mimeType = contestImage.Image.ImageMimeType; fileName = contestImage.Image.ImageFileName; } return File(fileContent, mimeType, fileName); } public class UserImage { public virtual int Id { set; get; } public virtual byte[] Image { set; get; } public virtual string ImageMimeType { set; get; } public virtual string ImageFileName { set; get; } } ContestImage has UserImage object. A: Two main approaches spring to mind: Load the data as an Image and serialize it (to a memory stream) in a compressed file format (e.g. png or jpeg) Serialize the data (to a memory stream) via a compressing stream such as DeflateStream. Once you have the data in a MemoryStream, you can use MemoryStream.ToArray() to convert it back to a straight byte[] buffer to pass to your database.
[ "stackoverflow", "0059636930.txt" ]
Q: imap_dfr to bind_rows from list of lists in R I am trying to use bind_rows in an imap_dfr function. I have lists of lists such that I want to bind together the results from "1", "650" and "1300" (which are all data frames). I am trying with the map_dfr function but cannot seem to get it working. I am also trying to create a new column "model" which contains the list of lists it occured in. x2 <- imap_dfr( shap_values_results[[1]][[1]]$shap_score, shap_values_results[[1]][[650]]$shap_score, shap_values_results[[1]][[1300]]$shap_score, .f = bind_rows, .id = "model" ) I get this message: Error: Argument 1 must have names Where am I going wrong? I would like to create a single data frame with each of the list of lists rows binded together. If I use: x2 <- bind_rows( shap_values_results[[1]][[1]]$shap_score, shap_values_results[[1]][[650]]$shap_score, shap_values_results[[1]][[1300]]$shap_score ) I can get a data frame of the lists binded together but I lack / miss the list "ID" from where that data frame came from. (I am working on filtering the data down to dput() it here.) EDIT: Structure of the list: > str( shap_values_results[[1]][[1]]$shap_score) 'data.frame': 2190 obs. of 30 variables: $ holiday : num -0.306 -0.281 -0.254 -0.248 -0.247 ... $ temp : num -0.0853 -0.025 -0.0735 0.0177 0.0672 ... $ wind : num -0.5213 0.1489 0.605 0.1408 0.0605 ... $ humidity : num 0.11052 0.15571 -0.00248 0.12065 0.17133 ... $ barometer : num -0.0268 -0.0361 -0.0957 -0.0236 -0.0213 ... $ weekday : num 0.0742 0.0918 0.0357 0.0882 0.0921 ... $ weekend : num 0 0 0 0 0 0 0 0 0 0 ... $ workday_on_holiday : num -0.000757 -0.000757 -0.003148 -0.000757 -0.000757 ... $ weekend_on_holiday : num 0 0 0 0 0 0 0 0 0 0 ... $ protocol_active : num 0 0 0 0 0 0 0 0 0 0 ... $ text_fog : num 0.02891 0.0357 0.00851 0.03118 0.02916 ... $ text_light_rain : num 0.0392 0.0362 0.0362 0.0396 0.0394 ... $ text_mostly_cloudy : num -0.00406 -0.00931 -0.00662 -0.02493 -0.01843 ... $ text_passing_clouds : num -0.001616 -0.001324 -0.012845 -0.000541 -0.001381 ... $ text_rain : num 0.00735 -0.00494 -0.01891 -0.00494 -0.00494 ... $ text_scattered_clouds: num -0.1 -0.123 -0.217 -0.128 -0.107 ... $ text_sunny : num 0.000442 0.000909 0.000277 -0.003121 -0.002015 ... $ month_1 : num -0.0176 0.1267 0.0599 0.1313 0.1148 ... $ month_2 : num 0.02293 0.00719 -0.00393 0.09392 0.07848 ... $ month_3 : num -0.023 -0.0329 -0.0335 -0.0163 -0.0073 ... $ month_4 : num -0.1067 -0.1359 -0.1217 -0.126 -0.0669 ... $ month_5 : num -0.0768 -0.1301 -0.2356 -0.1306 -0.0891 ... $ month_6 : num -0.0574 -0.0162 -0.0284 -0.0361 -0.0418 ... $ month_7 : num -0.0787 -0.0724 -0.0537 -0.066 -0.0683 ... $ month_8 : num -0.0587 -0.0948 -0.0845 -0.0947 -0.0894 ... $ month_9 : num 0.0445 0.0603 0.0075 0.0609 0.0482 ... $ month_10 : num 0.0743 0.065 0.0573 0.0654 0.0741 ... $ month_11 : num 0.058 0.0215 0.0164 0.0251 0.0547 ... $ month_12 : num 0.165 0.245 0.102 0.19 0.143 ... $ BIAS0 : num 0.00241 0.00241 0.00241 0.00241 0.00241 ... A: Here, we are extracting the data.frame already from the list and there is no need for the .f = bind_rows in imap_dfr, instead it can be just a placeholder identity (I) after wrapping it in a list out <- imap_dfr(list(`1` = shap_values_results[[1]][[1]]$shap_score, `650` = shap_values_results[[1]][[650]]$shap_score, `1300` = shap_values_results[[1]][[1300]]$shap_score), .f = I, .id = "model" ) If we want the 'model' column to be the index, then place it in a list and set the names of the list with the same values out <- bind_rows(list(`1` = shap_values_results[[1]][[1]]$shap_score, `650` = shap_values_results[[1]][[650]]$shap_score, `1300` = shap_values_results[[1]][[1300]]$shap_score), .id = 'model') In addition to the above, it may be better to do this in a automatic way i.e. not repeating the extraction map_dfr(set_names(shap_values_results[[1]][c(1, 650, 1300)], unique(names(shap_values_results[[1]][c(1, 650, 1300)]))), ~ .x$shap_score, .id = "model")
[ "stackoverflow", "0050778957.txt" ]
Q: What is the proper way of executing multiple queries with one function call in MySQL Connector C++ API? I'm new to MySQL, also their C++ API and I'm having a trouble executing multiple queries at once instead of calling the same function twice, I mean my queries are kinda linked and logically they should be executed at once. I used to do so for example sql::ResultSet* sqlExecute(std::string Query) try { sql::ResultSet *res; res = statement->executeQuery(Query); return res; } catch (sql::SQLException& e) { if (e.getErrorCode()) outc("%c%s: [SQL %c%d%c]%c %s\n", c_gray, my_time("WARN"), c_dark_purple, e.getErrorCode(), c_gray, c_dark_red, e.what()); return 0; } and call it like this (twice) sqlExecute("alter table ###.players AUTO_INCREMENT = 1;"); sqlExecute("insert into ###.players (name, username, password) values('Random Name', 'imrandom', 'this should be random too');"); but when I try to execute them with just one function call separated by ; sqlExecute("alter table ###.players AUTO_INCREMENT = 1;insert into ###.players (name, username, password) values('Random Name', 'imrandom', 'this should be random too');"); I get exception You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'insert into ###.players (name, username, password) values('Random Name', 'imrand' at line 1 In MySQL Workbench, I can execute multiple queries at once. Why not in the API too? A: The ability to execute multiple statements separated by semicolons depends on the CLIENT_MULTI_STATEMENTS connection property being enabled: sql::ConnectOptionsMap options; options["CLIENT_MULTI_STATEMENTS"] = true; sql::mysql::MySQL_Driver *driver = sql::mysql::MySQL_Driver::get_mysql_driver_instance(); sql::Connection *con = driver->connect(options);
[ "boardgames.stackexchange", "0000025627.txt" ]
Q: Does Juragedo always cause a replay? If I SS Juragedo during the battle step, does it always cause a replay? During either player's Battle Step: You can Special Summon this card from your hand, and if you do, gain 1000 LP. You can only use this effect of "Juragedo" once per turn. During either player's turn: You can Tribute this card, then target 1 face-up monster you control; it gains 1000 ATK until the end of the next turn. A: No Juragedo does not always cause a replay. A replay only occurs if the number of monsters on the field changes while an attack is being declared, but before the damage step. Therefore Juragedo can cause a replay, but does not always cause one. If Juragedo is summoned as soon as the Battle Phase starts, then a replay will not occur, but if it is summoned immediately after an attack, then a replay will occur.
[ "stackoverflow", "0010815943.txt" ]
Q: Export an APK library project, and use it in another Android project Today my final project setup has an Android library dependency. That Android library dependency project is located in the same workspace as the final project. I would like to export that library project with its SOURCES and ANDROID RESOURCES, into some archive, jar, apk, apklib, anything that would allow me to add that file as a dependency, and not be forced to include/checkout a project with its sources and resources into the workspace. I know Maven kinda solve this, but that is not my goal, I'm trying to allow simple Eclipse Android project to be able to add the Android library as a dependency. (I don't mind using the apklib Maven produces with a non Maven Android project in Eclipse, but I guess that would be meaningless...) How can this be done? A: OK Guys, As far as I've investigated, there is no way to do that. I have to find a solution for this, or my Cyborg distribution would be hell. I would have to write a script that would do that for me... If something has changed, and ADT would decide to grow some sense, please let me know...
[ "money.stackexchange", "0000029700.txt" ]
Q: ISA trading account options for US citizens living in the UK I am looking for an ISA trading account that can be opened by US citizens that are UK residents. There seems to be a general trend towards brokers in the EU not wanting to do business with US citizens. Interactive Investor for example does not allow US citizens to open accounts. Straight from the support team at interactive investor: "We are unable to open accounts for US citizens. We are not the only broker who has made this decision, but other brokers may be able to offer you an account" I supposed that they are doing this to avoid regulatory headaches, but don't know much about the matter. Does anyone have any recommendations or is it basically impossible? A: This sounds like a FATCA issue. I will attempt to explain, but please confirm with your own research, as I am not a FATCA expert. If a foreign institution has made a policy decision not to accept US customers because of the Foreign Financial Institution (FFI) obligations under FATCA, then that will of course exclude you even if you are resident outside the US. The US government asserts the principle of universal tax jurisdiction over its citizens. The institution may have a publicly available FATCA policy statement or otherwise be covered in a new story, so you can confirm this is what has happened. Failing that, I would follow up and ask for clarification. You may be able to find an institution that accepts US citizens as investors. This requires some research, maybe some legwork. Renunciation of your citizenship is the most certain way to circumvent this issue, if you are prepared to take such a drastic step. Such a step would require thought and planning. Note that there would be an expatriation tax ("exit tax") that deems a disposition of all your assets (mark to market for all your assets) under IRC § 877. A less direct but far less extreme measure would be to use an intermediary, either one that has access or a foreign entity (i.e. non-US entity) that can gain access. A Non-Financial Foreign Entity (NFFE) is itself subject to withholding rules of FATCA, so it must withhold payments to you and any other US persons. But the investing institutions will not become FFIs by paying an NFFE; the obligation rests on the FFI. PWC Australia has a nice little writeup that explains some of the key terms and concepts of FATCA. Of course, the simplest solution is probably to use US institutions, where possible. Non-foreign entities do not have foreign obligations under FATCA. A: I am a US citizen by birth only. I left the US aged 6 weeks old and have never lived there. I am also a UK citizen but TD Waterhouse have just followed their policy and asked me to close my account under FATCA. It is a complete nightmare for dual nationals who have little or no US connection. IG.com seem to allow me to transfer my holdings so long as I steer clear of US investments. Furious with the US and would love to renounce citizenship but will have to pay $2500 or thereabouts to follow the US process. So much for Land of the Free!
[ "stackoverflow", "0009493848.txt" ]
Q: How to pass shipping address value in paypal email? this is first time i'm develope paypal form , i have problem with shipping address how to get shipping address from customer and in email(see attach below) i want to insert into email from paypal ? i don't know how to pass shipping address value. A: There are mainly 10 hidden variables which we've to pass to PayPal for Payment related process mentioned as below (this method is very Basic PayPal Payment option, apart from it PayPal provides few other payment options as well): <input type="hidden" name="business" value="Merchant Account Email Address here"> <input type="hidden" name="notify_url" value="http:// some url for notification purpose"> <input type="hidden" name="currency_code" value="USD"> <input type="hidden" name="lc" value="US"> <input type="hidden" name="item_name" value="Item name here"> <input type="hidden" name="custom" value="PayPal will return this value as it is in the same format, when it is in sending time, like some array values concat with some special character"> <input type="hidden" name="amount" value="Payment Amount here as decimal for ex. 50.00"> <input type="hidden" name="return" value="http:// return url here, after payment to our website"> <input type="hidden" name="type" value="paynow"> <input type="hidden" name="cmd" value="_xclick"> You can just send above hidden variables to PayPal and set required URL as per your demo server website path. Keep in mind to keep developer.paypal.com account logged in while you're checking with PayPal Sandbox (test mode) account. It will be required. Thanks !
[ "stackoverflow", "0039312871.txt" ]
Q: How do I correctly filter my DataSet by GUID using OData? How do I correctly filter my DataSet by GUID? I'm exposing an OData endpoint, and trying to navigate to the URL: http://localhost:5001/mystuf/api/v2/AccountSet?$filter=AccountId%20eq%20guid%2703a0a47b-e3a2-e311-9402-00155d104c22%27 When my OData endpoint tries to filter the DataSet on that GUID, I am getting: "message": "Invalid 'where' condition. An entity member is invoking an invalid property or method.", "type": "System.NotSupportedException" > { "odata.error": { "code": "", "message": { "lang": "en-US", "value": "An error has occurred." }, "innererror": { "message": "Invalid 'where' condition. An entity member is invoking an invalid property or method.", "type": "System.NotSupportedException", "stacktrace": " at Microsoft.Xrm.Sdk.Linq.QueryProvider.ThrowException(Exception exception) at Microsoft.Xrm.Sdk.Linq.QueryProvider.FindValidEntityExpression(Expression exp, String operation) at Microsoft.Xrm.Sdk.Linq.QueryProvider.TranslateWhereCondition(BinaryExpression be, FilterExpressionWrapper parentFilter, Func`2 getFilter, Boolean negate) at Microsoft.Xrm.Sdk.Linq.QueryProvider.TranslateWhere(String parameterName, BinaryExpression be, FilterExpressionWrapper parentFilter, Func`2 getFilter, List`1 linkLookups, Boolean negate) at Microsoft.Xrm.Sdk.Linq.QueryProvider.TranslateWhereBoolean(String parameterName, Expression exp, FilterExpressionWrapper parentFilter, Func`2 getFilter, List`1 linkLookups, BinaryExpression parent, Boolean negate) at Microsoft.Xrm.Sdk.Linq.QueryProvider.TranslateWhere(QueryExpression qe, String parameterName, Expression exp, List`1 linkLookups) at Microsoft.Xrm.Sdk.Linq.QueryProvider.GetQueryExpression(Expression expression, Boolean& throwIfSequenceIsEmpty, Boolean& throwIfSequenceNotSingle, Projection& projection, NavigationSource& source, List`1& linkLookups) at Microsoft.Xrm.Sdk.Linq.QueryProvider.Execute[TElement](Expression expression) at Microsoft.Xrm.Sdk.Linq.QueryProvider.GetEnumerator[TElement](Expression expression) at Microsoft.Xrm.Sdk.Linq.Query`1.GetEnumerator() at Microsoft.Xrm.Sdk.Linq.Query`1.System.Collections.IEnumerable.GetEnumerator() at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty) at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType) at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType) at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value) at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding) at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding) at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__24.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.GetResult() at System.Web.Http.Owin.HttpMessageHandlerAdapter.<BufferResponseContentAsync>d__13.MoveNext()" } } } The start of the CSDL file looks something like this: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <Schema Namespace="Xrm" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://schemas.microsoft.com/ado/2007/05/edm"> <EntityType Name="Account"> <Key> <PropertyRef Name="AccountId" /> </Key> <Property Name="TerritoryCode" Type="Microsoft.Crm.Sdk.Data.Services.OptionSetValue" Nullable="false" /> <Property Name="LastUsedInCampaign" Type="Edm.DateTime" Nullable="true" /> … The controller that is getting triggered is: public IHttpActionResult Get(ODataQueryOptions<Account> options) { var retval = options.ApplyTo(_accountService.GetAccountSet()); return Ok(retval); } And the above Get() method applies the filter to: public IQueryable<Account> GetAccountSet() { return _xrmServiceContext.AccountSet; } How do I correctly filter my DataSet by GUID? Please note that when I return this instead: return _xrmServiceContext.AccountSet.Take(2); Then data is returned correctly to the client (serialization/deserialization correctly works); however, the filter is not applied at all. A: According to updated documentation solution depends on type of AccountId field. If AccountId type is Guid (most probably your case) than comparison with guid literal should be written without guid keyword or putting it into quotes. So valid query should look like this: AccountId eq 03a0a47b-e3a2-e311-9402-00155d104c22 And result url will be this: http://localhost:5001/mystuf/api/v2/AccountSet?$filter=AccountId%20eq%2003a0a47b-e3a2-e311-9402-00155d104c22 But if AccountId type is String and it contains string representation of guid, you should use rules for string literal and put it in single quotes, like this: AccountId eq '03a0a47b-e3a2-e311-9402-00155d104c22' And result url will be this: http://localhost:5001/mystuf/api/v2/AccountSet?$filter=AccountId%20eq%20%2703a0a47b-e3a2-e311-9402-00155d104c22%27 You can just test both url to see which one will work for you :)
[ "stackoverflow", "0044630371.txt" ]
Q: Alertify confirm does not work with Ember js I'm attempting to make a popup box which confirms if you want to delete a document. If I try: if(alertify.confirm("Delete this?')) { this.store.findRecord('document', docId, {backgroundReload: false}).then((doc) => { doc.destroyRecord(); alertify.success('Document successfully deleted!'); } it does not wait for confirmation before running the delete code, because alertify.confirm is non-blocking, as I understand. If I try: deleteFile(docId) { alertify.confirm("Are you sure you want to delete this document?", function (e) { if (e) { this.store.findRecord('document', docId, {backgroundReload: false}).then((doc) => { doc.destroyRecord(); alertify.success('Document successfully deleted!'); }); } else { alertify.error('Something went wrong!'); } }); } it does ask for confirmation, but the delete code doesn't work, as the store is coming up as undefined, so findRecord doesn't work. I've tried injecting the store as a service, but that does not work either. Is there a way to get this confirmation box working? A: You use this in a function, thus referring to the this-context of that function. You could either use fat arrow functions or assign the outer this to a variable. The former would look like this: deleteFile(docId) { alertify.confirm("Are you sure you want to delete this document?", (e) => { if (e) { this.store.findRecord('document', docId, {backgroundReload: false}).then((doc) => { doc.destroyRecord(); alertify.success('Document successfully deleted!'); }); } else { alertify.error('Something went wrong!'); } }); }
[ "stackoverflow", "0015962982.txt" ]
Q: How to set HTML Unicode text to clipboard in VC++? I am a newbie to C++. I want to get the content of the clipboard, which might contain Unicode chars, append a div tag with some content formatted in HTML and set that back to clipboard. I have achieved successfully in getting the content and appending it. But could not set it back to the clipboard as an HTML text. I have achieved setting as simple text. Here is my code: #include <shlwapi.h> #include <iostream> #include <conio.h> #include <stdio.h> using namespace std; wstring getClipboard(){ if (OpenClipboard(NULL)){ HANDLE clip = GetClipboardData(CF_UNICODETEXT); WCHAR * c; c = (WCHAR *)clip; CloseClipboard(); return (WCHAR *)clip; } return L""; } bool setClipboard(wstring textToclipboard) { if (OpenClipboard(NULL)){ EmptyClipboard(); HGLOBAL hClipboardData; size_t size = (textToclipboard.length()+1) * sizeof(WCHAR); hClipboardData = GlobalAlloc(NULL, size); WCHAR* pchData = (WCHAR*)GlobalLock(hClipboardData); memcpy(pchData, textToclipboard.c_str(), size); SetClipboardData(CF_UNICODETEXT, hClipboardData); GlobalUnlock(hClipboardData); CloseClipboard(); return true; } return false; } int main (int argc, char * argv[]) { wstring s = getClipboard(); s += std::wstring(L"some extra text <b>hello</b>"); setClipboard(s); getch(); return 0; } I did try using the code described here and read the doc here. But I couldn't make it work. What I tried could be way off track or completely wrong. Update: The code below is what I tried after the modifications suggested by Cody Gray to the original code presented here: bool CopyHTML2(WCHAR *html ){ wchar_t *buf = new wchar_t [400 + wcslen(html)]; if(!buf) return false; static int cfid = 0; if(!cfid) cfid = RegisterClipboardFormat("HTML Format"); // Create a template string for the HTML header... wcscpy(buf, L"Version:0.9\r\n" L"StartHTML:00000000\r\n" L"EndHTML:00000000\r\n" L"StartFragment:00000000\r\n" L"EndFragment:00000000\r\n" L"<html><body>\r\n" L"<!--StartFragment -->\r\n"); // Append the HTML... wcscat(buf, html); wcscat(buf, L"\r\n"); // Finish up the HTML format... wcscat(buf, L"<!--EndFragment-->\r\n" L"</body>\r\n" L"</html>"); wchar_t *ptr = wcsstr(buf, L"StartHTML"); wsprintfW(ptr+10, L"%08u", wcsstr(buf, L"<html>") - buf); *(ptr+10+8) = L'\r'; ptr = wcsstr(buf, L"EndHTML"); wsprintfW(ptr+8, L"%08u", wcslen(buf)); *(ptr+8+8) = '\r'; ptr = wcsstr(buf, L"StartFragment"); wsprintfW(ptr+14, L"%08u", wcsstr(buf, L"<!--StartFrag") - buf); *(ptr+14+8) = '\r'; ptr = wcsstr(buf, L"EndFragment"); wsprintfW(ptr+12, L"%08u", wcsstr(buf, L"<!--EndFrag") - buf); *(ptr+12+8) = '\r'; // Open the clipboard... if(OpenClipboard(0)) { EmptyClipboard(); HGLOBAL hText = GlobalAlloc(GMEM_MOVEABLE |GMEM_DDESHARE, wcslen(buf)+4); wchar_t *ptr = (wchar_t *)GlobalLock(hText); wcscpy(ptr, buf); GlobalUnlock(hText); SetClipboardData(cfid, hText); CloseClipboard(); GlobalFree(hText); } // Clean up... delete [] buf; return true; } This code compiles successfully, But I get the following error at SetClipboardData : HEAP[Project1.exe]: Heap block at 007A8530 modified at 007A860A past requested size of d2 Project1.exe has triggered a breakpoint. Please guide me on how to proceed. I am using Visual Studio Express 2012 on Windows 8. Thanks. A: This is the function I came up with the help of Jochen Arndt at codeproject.com. Hope this helps somebody. Here is a complete working code, if you are interested in checking this out. It still has one problem. That is when pasted to onenote alone, it pastes gibberish after a anchor tag. It does not happen with Word, PowerPoint or Excel. And it does not have this problem for normal English language texts. If you have a solution for this, please do let me know. The problem seems to be with OneNote. Not with the code. bool setClipboard(LPCWSTR lpszWide){ int nUtf8Size = ::WideCharToMultiByte(CP_UTF8, 0, lpszWide, -1, NULL, 0, NULL, NULL); if (nUtf8Size < 1) return false; const int nDescLen = 105; HGLOBAL hGlobal = ::GlobalAlloc(GMEM_MOVEABLE, nDescLen + nUtf8Size); if (NULL != hGlobal) { bool bErr = false; LPSTR lpszBuf = static_cast<LPSTR>(::GlobalLock(hGlobal)); LPSTR lpszUtf8 = lpszBuf + nDescLen; if (::WideCharToMultiByte(CP_UTF8, 0, lpszWide, -1, lpszUtf8, nUtf8Size, NULL, NULL) <= 0) { bErr = true; } else { LPCSTR lpszStartFrag = strstr(lpszUtf8, "<!--StartFragment-->"); LPCSTR lpszEndFrag = strstr(lpszUtf8, "<!--EndFragment-->"); lpszStartFrag += strlen("<!--StartFragment-->") + 2; int i = _snprintf( lpszBuf, nDescLen, "Version:1.0\r\nStartHTML:%010d\r\nEndHTML:%010d\r\nStartFragment:%010d\r\nEndFragment:%010d\r\n", nDescLen, nDescLen + nUtf8Size - 1, // offset to next char behind string nDescLen + static_cast<int>(lpszStartFrag - lpszUtf8), nDescLen + static_cast<int>(lpszEndFrag - lpszUtf8)); } ::GlobalUnlock(hGlobal); if (bErr) { ::GlobalFree(hGlobal); hGlobal = NULL; } // Get clipboard id for HTML format... static int cfid = 0; cfid = RegisterClipboardFormat("HTML Format"); // Open the clipboard... if(OpenClipboard(0)) { EmptyClipboard(); HGLOBAL hText = GlobalAlloc(GMEM_MOVEABLE |GMEM_DDESHARE, strlen(lpszBuf)+4); char *ptr = (char *)GlobalLock(hText); strcpy(ptr, lpszBuf); GlobalUnlock(hText); ::SetClipboardData(cfid, hText); CloseClipboard(); GlobalFree(hText); } } return NULL != hGlobal; }
[ "stackoverflow", "0026061299.txt" ]
Q: MVC Kendo Grid multiple functions for DataBound event How can I have multiple functions for DataBound in Kendo Grid MVC events.DataBound().Events(events => events.DataBound("AdvancedGrid.onDataBound", "alertMe")); so it will trig both function. A: Through HtmlHelper you can't add more function to event so I look in DOM object found grid and saw that _events -> dataBound is array, so I added run this var grid = $("#MyGrid").data("kendoGrid"); grid.bind("dataBound", alertMe); grid.dataSource.fetch(); and now my dataBound has 2 events
[ "stackoverflow", "0051364564.txt" ]
Q: Is it possible to install a H.264 software codec to Google's native Android WebRTC libraries? According to this post (How to detect Android H.264 hardware acceleration capability) and also personal experience, the latest Android native libraries for WebRTC ('org.webrtc:google-webrtc:1.0.23546') do not support H.264 unless there is a hardware decoder present for it. So far, this only effects me when using the emulator, but I understand that some devices it won't work, so that could to be a large problem. Cisco has their H.264 software decoder available at https://github.com/cisco/openh264 and I'd like to know if there is a way to use that or something else to install software H.264 in a way that will work with WebRTC on devices that don't have hardware decoding. Additionally, I can't seem to find a support matrix for H.264 hardware decoding on devices. A: Can be done using JCodec. Google provides access to create a custom decoder in Java. -- Decoder.decodeFrame is already in YUV format -- Data for Y,U,V can be found at frame.getPlaneData(0/1/2) -- StrideY/U/V is frame.getWidth() >> frame.getColor().compWidth[planeIndex] -- According to the header in "org.jcodec.common.model.Picture" data is shifted by 128. Necessary to adjust by (byte) (a[i] + 128).
[ "stackoverflow", "0044732527.txt" ]
Q: AJAX how to change select values based from database I am trying to change select's values from database but only get one return form Foreachmethod. I don't know the right method for this case. I want a result something like this http://jsfiddle.net/YPsqQ/ , but the data is from database. The problem is how to parse all data to view. Not just one. Maybe some looping on Jquery ? but I don't know how to do that. Here are the codes, I am using Codeigniter by the way. Controller public function prodi_pindah() { if (!$this->login and !$this->admin){ redirect('akademik/logout'); } else { $this->load->model('mahasiswa_model'); $this->mahasiswa_model->prodi_pindah(); } View <input type="text" name="ptasal" id="ptasal" class="addresspicker" /> // this input has jquery Autocomplete , <input type="hidden" name="id_pt_asal" id="id_pt_asal" /> // this input has ID that sent to model, this ID change whenever ptasal change too <select name="id_prodi_asal" id="id_prodi_asal" style=""> <option value="">-- Pilih Program Studi--</option> </select> <script> $(document).ready(function(){ $("#id_prodi_asal").click(function(event){ var formData = { 'id_pt_asal': $('input[name=id_pt_asal]').val() }; $.ajax({ type: 'POST', url: '<?=base_url()?>akademik/prodi_pindah', data: formData, dataType: 'json', encode: true }) .done(function(data) { console.log(data); if (data.hasil_prodi==true) { } if (data.hasil_prodi==false) { } }) event.preventDefault(); }); }); </script> Model public function prodi_pindah() { $id_pt_asal = $this->input->post('id_pt_asal'); $kue_prodi = $this->db->query("SELECT ps.nama_perguruan_tinggi, ps.nama_program_studi, ps.`status`, rjp.nm_jenj_didik, ps.nama_jenjang_pendidikan, ps.id_prodi from ref_prodi ps INNER JOIN ref_jenjang_pendidikan rjp ON ps.id_jenjang_pendidikan=rjp.id_jenj_didik WHERE status = 'A' AND id_perguruan_tinggi = '$id_pt_asal' "); foreach ($kue->result() as $row){ $value = $row->id_prodi; $isi = $row->nama_jenjang_pendidikan.' - '.$row->nama_program_studi; $has = '<option value='.$value.'>'.$isi.'</option>'; } $data['html']="<option value=''>-- Pilih Program Studi--</option>$has"; // I want $has had all result, not just one. Here the problem. $data['hasil_prodi']=TRUE; echo json_encode($data); } A: Ok so you are breaking some MVC rules here which is contributing to your confusion. I'll clarify below. Model: Deals with database logic, one model can be shared by many controllers. View: Where your html is (which could include php variables if you aren't using js). Controller: Where the logic for your php is. e.g. Mapping an array for your view, going to a different page etc. I've changed your code below to put your controller and model code in the correct place. Also your issue was is that you weren't adding the option string onto the previous option string. I've commented where I've changed code. Controller public function prodi_pindah() { if (!$this->login and !$this->admin){ redirect('akademik/logout'); } else { $this->load->model('mahasiswa_model'); $kue = $this->mahasiswa_model->prodi_pindah(); //Set the $has variable first so that we can append to it. $has = ''; foreach ($kue as $row){ $value = $row->id_prodi; $isi = $row->nama_jenjang_pendidikan.' - '.$row->nama_program_studi; // Now correctly appends $has variable $has .= '<option value='.$value.'>'.$isi.'</option>'; } // Now correctly adds $has $data['html']="<option value=''>-- Pilih Program Studi--</option>" . $has; $data['hasil_prodi']=TRUE; echo json_encode($data); } } Model public function prodi_pindah() { $id_pt_asal = $this->input->post('id_pt_asal'); $kue_prodi = $this->db->query("SELECT ps.nama_perguruan_tinggi, ps.nama_program_studi, ps.`status`, rjp.nm_jenj_didik, ps.nama_jenjang_pendidikan, ps.id_prodi from ref_prodi ps INNER JOIN ref_jenjang_pendidikan rjp ON ps.id_jenjang_pendidikan=rjp.id_jenj_didik WHERE status = 'A' AND id_perguruan_tinggi = '$id_pt_asal' ")->result(); return $kue_prodi; }`
[ "stackoverflow", "0047293645.txt" ]
Q: how to read a specific position in the last line using python I have a txt file that is too large and has several similar lines, like this: word1 word2 word3 word4 -553.75 I am interested in the position [4] "the value", that of the last line -553.75 my file text: . . word1 word2 word3 word4 -553.20 . . . word1 word2 word3 word4 -553.25 . . . word1 word2 word3 word4 -553.75 . . . my script : def main(): oTE_list = [] oTE = [] with open("file.txt","r") as f: text = f.readlines() for line in text: if line[0] == 'word1' and line[1] == 'word2' and line[2] == 'word3' and line[3] == 'word4': oTE_list.append(line[4]) # Change Lists To Number Format for idx, item in enumerate(oTE_list): if idx == len(oTE_list) - 1: print(item) if __name__ == '__main__': main() but I do not know why it does not work with me! thank you in advance. A: The line is string not list of word, to convert it to list of word use split and strip before to get rid of \n def main(): oTE_list = [] oTE = [] with open("file.txt","r") as f: text = f.readlines() for line in text: line = line.strip().split() if line[0] == 'FINAL' and line[1] == 'SINGLE' and line[2] == 'POINT' and line[3] == 'ENERGY': oTE_list.append(line[4]) # Change Lists To Number Format for idx, item in enumerate(oTE_list): if idx == len(oTE_list) - 1: print(item) if __name__ == '__main__': main()