text
stringlengths
64
89.7k
meta
dict
Q: Are arguments of after plugin mandatory? I am writing tiny plugin on Magento\Customer\Controller\Account\Edit:execute(). It's after one. I have just noticed that I am not using any arguments inside my method. /** * Method modify redirection when changing password. * * @param \Magento\Customer\Controller\Account\Edit $subject. * @param \Magento\Framework\View\Result\Page $results * * @return \Magento\Framework\Controller\Result\Redirect */ public function afterExecute(MagentoEdit $subject, $results) { $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); /** @var $resultRedirect \Magento\Framework\Controller\Result\Redirect */ return $resultRedirect->setUrl($this->redirect->getRefererUrl()); } I have tested method with no arguments inserted and it has worked. Is it any mistake or I don't really need arguments in after plugins? A: Syntactically you should still return $result but the reason this works for you is because controller actions are not checked for return values . Plus, you redirect before return value could be reached. It doesn't seem as though there is anything wrong with the way you wrote the plugin. I would just get rid of the type hint and do it more like this sample below. /** * Method modify redirection when changing password. * * @param \Magento\Customer\Controller\Account\Edit $subject. * @param \Magento\Framework\View\Result\Page $results * * @return \Magento\Framework\Controller\Result\Redirect */ public function afterExecute($subject, $result) { $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); /** @var $resultRedirect \Magento\Framework\Controller\Result\Redirect */ $resultRedirect->setUrl($this->redirect->getRefererUrl()); return $result; }
{ "pile_set_name": "StackExchange" }
Q: Rectangles not resizing properly with scale/width change Select 'name' and then 'focus' setting for the attached fiddle http://jsfiddle.net/sjp700/HVkyL/. For some reason the rectangles don't resize with the width change. Any ideas? I'm using a group for rect and text: gEnter = group.enter() .append("g") .attr("class", "grow") .style("fill", "blue") .attr("transform", function (d) { return "translate(" + xRange(d.start) + "," + yRange(d[axes.yAxis]) + ")"; }); A: It seems that the enter/update/exit pattern for elements under a svg:g group is the star of the last two days. See here, for example, for a similar answer by Lars, my comments below the answer (with a link to my blog post on the subject). I believe this is the pattern that you want in your redraw function: ... gEnter.append("rect") .attr("class", "rectband"); group.selectAll(".rectband") .attr("width", function (d) {return xRange(d.width)}) .attr("height", 18) .style("fill", "blue") .style("opacity", .5) // set the element opacity .style("stroke", "black"); // set the line colour; gEnter.append("text") .attr("class", "textband"); group.selectAll(".textband") .style("fill", "black") .text(function (d) {return (d.name);}) .attr("transform", function (d) { return "translate(" + (2) + "," + (13) + ")"; }); ... Please also note that you were using the same CSS class for rectangles and text. Here is the updated FIDDLE.
{ "pile_set_name": "StackExchange" }
Q: Compile Blitz++ with Mingw64 I'm on a Win7 64Bit system and I want to compile the Blitz++ library with mingw64. I am facing some problem, since the readme file of the Blitz++ library states that i have to run ./confiugre which I can't on Win, right? So, who can point me in the right direction? Regards A: Run it from the MSYS shell .MSYS tries to emulate a *Nix shell.You should have installed MSYS with MINGW, if not use the MINGW installer for that.
{ "pile_set_name": "StackExchange" }
Q: Use function in closure I am trying to use a function within a closure but I am receiving an error 'cannot convert value of type () to closure result type Bool'. The following code demonstrates the error. How can I make this work? func test1(){ test2(){ success in self.test1() } } func test2(completionHandler: (Bool) -> Bool){ completionHandler(true) } A: You specify that the test2 closure returns a Bool, so return one: func test1(){ test2 { (success) -> Bool in test1() return success } } Have test2's closure return void if you don't want to return a value from it: func test1(){ test2 { (success) in test1() } } func test2(completionHandler: (Bool) -> Void){ completionHandler(true) }
{ "pile_set_name": "StackExchange" }
Q: Run two pieces of code from different programming language in parallel Is there any way to run a function from python and a function from java in one app in parallel and get the result of each function to do another process? A: There are at least three ways to achieve that. a) You could use java.lang.Runtime (as in Runtime.getRuntime().exec(...)) to launch an external process (from Java side), the external process being your Python script. b) You could do the same as a), just using Python as launcher. c) You could use some Python-Java binding, and from Java side use a separate Thread to run your Python code.
{ "pile_set_name": "StackExchange" }
Q: Disable blackout when open BottomSheetDialogFragment If I can disable activity blackout when BottomSheetDialogFragment showing? A: Only add this line: dialog.window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
{ "pile_set_name": "StackExchange" }
Q: "error: no associated program", CBR files can't be opened I get Error: No associated program error message when trying to open CBR (comic book archive) files. Calibre (3.23) has been associated with this file format in Windows and the error appears whether opening from the library or Windows file explorer. A: You must enable Calibre's internal viewer for the format. Go to "preferences": "behavior": enable CBR and CBZ (one of comic book archive's filename extensions) formats and apply changes: source
{ "pile_set_name": "StackExchange" }
Q: Android: Populate Gallery With Images from SDCard I'm trying to populate a Gallery view with images from a folder in the SDcard. I read the Gallery tutorial on Android Dev seen here: http://developer.android.com/resources/tutorials/views/hello-gallery.html, and can get it working with images from the drawable folder of my project. My question is: how can I get an array of files from the Environment.getExternalStorageDirectory()+File.separator+"MyPictureDirectory folder, and then display them in the Gallery? Thanks! A: Try the following, File file = new File( Environment.getExternalStorageDirectory()+File.separator+"MyPictureDirectory"+File.separator); File imageList[] = file.listFiles(); for(int i=0;i<imageList.length;i++) { //Add images in Gallery from imageList } To set image from file path: File imgFile = new File(imagefilepath); if(imgFile.exists()){ Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); ImageView myImage = (ImageView) findViewById(R.id.imageviewTest); myImage.setImageBitmap(myBitmap); }
{ "pile_set_name": "StackExchange" }
Q: How to pass variable from user interface into controller I have problem when trying to do create Sql statement using netbeans, javFX and MySQL. Here is my main method: public void start(Stage primaryStage) throws Exception { primaryStage.setTitle("Create Product"); Pane myPane = (Pane)FXMLLoader.load(getClass().getResource ("createProduct.fxml")); Scene myScene = new Scene(myPane); primaryStage.setScene(myScene); primaryStage.show(); } public static void main(String[] args) { launch(args); } I design my user interface using javaFX and I store the whole panel as myPane as the code above. And here is my createProduct.fxml. It only contains a text field and a button. <AnchorPane id="AnchorPane" prefHeight="200.0" prefWidth="320.0" xmlns:fx="http://javafx.com/fxml" fx:controller="it2297proj.SampleController"> And this is my event handler class. When button is on click, it will pass the whole panel into CreateProductController. public class SampleController implements Initializable { private SampleController myPane = null; @FXML private void handleButtonAction(ActionEvent event) { System.out.println("You clicked me!"); } @FXML private void createProduct(ActionEvent event){ CreateProductController controller = new CreateProductController(); boolean result = controller.create(myPane); //Error here } And inside my CreateProductController class, I just simply get the text and pass it into an entity. public class CreateProductController { public boolean create(SampleController panel){ String name = panel.getnameTextField.getText(); } } However, there is an error at the event handler class, boolean result = controller.create(myPane); this line. The error message is The type of create(Sample Controller) class is erroneous. I have no idea why because it works fine in eclipse. Any help would be appreciated. Thanks in advance. A: It's unclear which version of JavaFX you're using and what exactly you're trying to do. JavaFX 2.2 makes it really simple to create custom controllers. You can pass parameters into them directly from FXML, or programatically. If you're using version 2.2 you might benefit from reading Creating a Custom Control with FXML. The answer you're looking for might be there, especially in the section regarding FXMLLoaders. This thread might be helpful too.
{ "pile_set_name": "StackExchange" }
Q: Java 8 Convert a stream of set to Map I have written this lambda that is getting values from a map <Code, Message>contained inside an enum MessageKeyRegistry and creating adding to another map with Code as the key and the MessageKeyRegistry as the value. Map<MessageKey, MessageKeyRegistry> keyMap = new HashMap<>(); EnumSet.allOf(MessageKeyRegistry.class) .forEach(messageKeyRegistry -> messageKeyRegistry.getCodeToMessage().keySet() .forEach(code -> keyMap.put(code, messageKeyRegistry))); Now I want to satisfy the immutability concept of functional programming and write a lambda that returns an immutable map directly. A: I have written this lambda that is.. You didn't write just a lambda, but a chain of methods using lambda expressions. one if them is code -> keyMap.put(code, messageKeyRegistry). Back to your question. You start with the iteration correctly (from the EnumSet), the next step is to realize what happens in the forEach methods. Extract codes from the set of keys using them as keys using messageKeyRegistry Using the extractor as a value messageKeyRegistry. This is a job for map, however since the data structure is more complicated (collection in a collection), then flatMap would serve better. Finally, you'd result with something like: Map<MessageKey, MessageKeyRegistry> keyMap = EnumSet.allOf(MessageKeyRegistry.class) .stream() .flatMap(messageKeyRegistry -> messageKeyRegistry.getCodeToMessage().keySet() .stream() .map(code -> new AbstractMap.SimpleEntry<>(code, messageKeyRegistry))) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); However, what you do has a drawback. I see the keys are overridden since there cannot be duplicates which is visible from the original solution, i.e. from this line that iterates at least once which implies the key may be overridden: .forEach(code -> keyMap.put(code, messageKeyRegistry)) So what I suggest is rather group mapping using Collectors.groupingBy resulting in Map<MessageKey, List<MessageKeyRegistry>>: Map<MessageKey, List<MessageKeyRegistry>> keyMap = EnumSet.allOf(MessageKeyRegistry.class) .stream() .flatMap(messageKeyRegistry -> messageKeyRegistry.getCodeToMessage().keySet() .stream() .map(code -> new AbstractMap.SimpleEntry<>(code, messageKeyRegistry))) .collect(Collectors.groupingBy(Entry::getKey)); For immutable map, if you mean a map that is read-only use the Collections.unmodifiableMap() wrapper: Map<MessageKey, List<MessageKeyRegistry>> unmodifiableKeyMap = Collections.unmodifiableMap(keyMap);
{ "pile_set_name": "StackExchange" }
Q: About density of some subsets of infinitely differentiable functions in $C[0,1]$ Let $x_1,...,x_m$ be fixed numbers from $[0,1]$ and let $k_1,..., k_m$ be fixed natural numbers ($\geq 1$). Is the set $$\{f\in C^\infty[0,1]: f^{(k_1)}(x_1)=0,...,f^{(k_m)}(x_m)=0 \}$$a dense subset of the Banach space $C[0,1])$, with the supremum norm? A: Yes, it is dense. Given $f \in C([0,1])$ and $\epsilon > 0$, it is easy to find a continuous function $g$ which is constant on some $\delta$-neighborhood of each $x_i$ and has $\|f-g\| < \epsilon$. (For instance, Now extend $g$ continuously to all of $\mathbb{R}$, say by making it constant on $(-\infty, 0]$ and $[1,\infty)$. Let $\phi$ be a $C^\infty$ bump function with $\int \phi = 1$ and compactly supported inside $(-\delta, \delta)$. Then the convolution $h = g \ast \phi$ is also constant on some neighborhood of each $x_i$, so $h^{(k)}(x_i) = 0$ for all $k \ge 1$, and $h \in C^\infty$, so $h$ is in your set. By choosing the support of $\phi$ as small as needed and using the uniform continuity of $g$, we can get $\|g-h\| < \epsilon$. A: Here is a solution. We prove by induction on $m$. Denote by $P$ the subspace of $C([0,1])$ consisting of the restrictions to $[0,1]$ of the smooth functions $\mathbb{R}\to\mathbb{R}$. Assume first that $x_1,\dotsc, x_m$ are pairwise distinct. Set $$ P_{x_1,\dotsc, x_k}:=\big\{ p\in P;\;\;p^{(k_i)}(x_i)=0,\;i=1,\dotsc, m\big\}. $$ Then $$ P\supset P_{x_1},\supset \cdots \supset P_{x_1,\dotsc, x_m}. $$ Let us show that $P_{x_1,\dotsc, x_m}$ is dense in $P$. The case $m=1$ is dealt with as in my comment. Let us now prove that $P_{x_1,\dotsc, x_m}$ is dense in $P_{x_1,\dotsc, x_{m-1}}$, thus, inductively, in $P$. Define the linear functional $\newcommand{\bR}{\mathbb{R}}$ $$ L: P_{x_1,\dotsc, x_{m-1}}\to \bR,\;\;L(p)= p^{(k_m)}(x_m). $$ The linear functional $L$ is not continuous thus its kernel $\ker L=P_{x_1,\dotsc, x_m}$ is dense in $P_{x_1,\dotsc, x_{m-1}}$. To see that $L$ is not continuous pick a smooth function $f$ with compact support contained in a neighborhood of $x_m$ disjoint form $x_1,\dotsc, x_{m-1}$ and such that $f^{(k_m)}(x_m)=1$. Define $$f_n(x)= n^{-1/2}f\big( x_m+ n(x-x_m)\big).$$ Then the sequence $f_n$ converges uniformly to zero but $$f_n^{(k_m)}(x_m)=n^{k_m-1/2}\to\infty.$$ Suppose now that $x_1,\dotsc, x_m$ are not necessarily distinct. For simplicity assume that $x_1=\cdots=x_m$ and $k_1<\cdots <k_m$. Then define $$ P_{k_1,\dotsc, k_m}:=\big\{ p\in P;\;\;p^{(k_i)}(x_1=0,\;\;i=1,\dotsc, m\big\}. $$ Arguing as above one sees that $P_{k_1,\dotsc, k_i}$ is dense in $P_{k_1,\dotsc, k_{i-1}}$.
{ "pile_set_name": "StackExchange" }
Q: How do I store files or file paths in a java application? I apologize if this is a really beginner question, but I have not worked with Java in several years. In my application, I need to keep up with a list of files (most, if not all, are txt files). I need to be able to add to this list, remove file paths from the list, and eventually read the contents of the files (though not when the files are initially added to the list). What is the best data structure to use to store this list of files? Is it standard to just save the path to the file as a String, or is there a better way? Thanks very much. A: Yes, paths are usually stored as String or File instances. The list can be stored as an ArrayList instance.
{ "pile_set_name": "StackExchange" }
Q: What does it means "[0]" at the end of the array designation? I have these rows of code (source: Google Reference): // log the subjects of the messages in the thread var firstThread = GmailApp.getInboxThreads(0,1)[0]; var firstThread1 = GmailApp.getInboxThreads(0,1); var messages = firstThread.getMessages(); for (var i = 0; i < messages.length; i++) { Logger.log(messages[i].getSubject()); } Why removing the [0] I'll get an Array (firstThread1), and with [0] I'll get an Object (firstThread)? Thank you A: Using [0] you get the first element of the array and that's why you get an Object. If you don't use it, you get the array itself.
{ "pile_set_name": "StackExchange" }
Q: Limit CPU load or set process prority It's not the first time I get a too much cpu load warning from my hosting. The code is just some random php script with mysql queries, nothing fancy. (THe tables are nothing extraordinary, a few hundred lines maximum and I always limit them if requested. I don't mind if it runs for 0.15 second instead of 0.05, so is there a way I can control process priority or limit cpu load? Thanks! A: If this is a dameon or program that runs for long time add sleep()/usleep(). A small sleep will reduce your CPU usage dramatically. Following code will consume a lot of cpu while(...){ //do stuff } Because you are not giving room for CPU to do other task here. change it to while(...){ //do stuff sleep(1); } This will greatly decrease your CPU usage. 1 second for CPU is a lot of time to do other task. To sleep that extra 0.1 second (0.15 - 0.05) use usleep(). usleep(100000); A: In principle, on Unixish system (Linux, BSD, etc.), you could use the proc_nice() function to change the process priority, like this: proc_nice( 20 ); // now this process has very low priority However, there are a couple of major caveats here that make it less useful in practice: It isn't supported on Windows. You're only allowed to increase the niceness, not to decrease it (not even back to its original value). The niceness persists until the PHP process exits, which could be a problem if you're running PHP as a FastCGI process, or, even worse, as a webserver extension. Because of the above issues, proc_nice() might be disabled for security reasons even on systems that could technically support it. What you could try to do, if your webhost allows it, is to start a background process for the long-running task, so that your webserver can get back to serving requests while it's running. You can even use the nice shell command to lower the priority of the background process, like this: exec( "nice nohup php -f slow_script.php < /dev/null > output.txt 2>&1 &" ); Once the slow script has finished, you can get its output by downloading output.txt.
{ "pile_set_name": "StackExchange" }
Q: The following sections have been defined but have not been rendered for the layout page This is an ASP.NET MVC 3 exception message. What it says? What should I do? OK, I have this code: @{ Layout = "~/_Layout.cshtml"; Page.Title = "Home"; } @section meta{ <meta name="keywords" content="" /> <meta name="description" content="" /> } <h2>Html Content Here</h2> @section footer { <script src="http://code.jquery.com/jquery-latest.min.js" charset="utf-8"></script> <script type="text/javascript"> $(document).ready(function() { }); </script> } A: Your layout page isn't actually rendering the sections footer and meta In your _Layout.cshtml, put in @RenderSection("meta") where you want the meta section rendered. You can also do @RenderSection("meta", false) to indicate that the section is optional. A: The error message implies that your _Layout.cshtml does not include @RenderSection statements for the @sections that you have in your view. Check your Layout and let us know. See this page for more information. A: I faced a similar problem where the layout template indeed has the @RenderSection(...) but inside an if-else statement. So when the page executes the statement that doesn't contain the @RenderSection it will throw that exception. If that is your case, then your solution is a little more complicated, either: make sure you have @RenderSection outside of the statements or repeat @RenderSection in both if-else statements, or use different partial views, or redesign the layout. That could be your main problem!
{ "pile_set_name": "StackExchange" }
Q: How to backup and restore mysql database in rails 3 Is it possible to do the following: 1. Hot database backup of mysql database from Rails 3 application 2. Incremental database backup of mysql database from Rails 3 application 3. Cold database backup of mysql database from Rails 3 application 4. Restore any of the above databases ( Hot, incremental and cold) through Rails 3 application. Please let me know how to achieve this? Thanks, Sudhir C.N. A: Setup some cronjobs. I like to use Whenever for writing them. I run this bash script once per day: #!/bin/bash BACKUP_FILENAME="APPNAME_production_`date +%s`.gz" mysqldump -ce -h MYSQL.HOST.COM -u USERNAME -pPASSWORD APPNAME_production | gzip | uuencode $BACKUP_FILENAME | mail -s "daily backup for `date`" [email protected] echo -e "\n====\n== Backed up APPNAME_production to $BACKUP_FILENAME on `date` \n====\n" And output it to cron.log. This may require some tweaking on your end, but it works great once you get it. E-mails the backup to you once per day as a gzipped file, my database is fairly large and file is under 2000kb right now. It's not the safest technique, so if you're really concerned that someone might get into your e-mail and get access to the backups (which should have sensitive information encrypted anyways), then you'll have to find another solution. To restore: gzip -d APPNAME_production_timestamp.gz mysql -u USERNAME -pPASSWORD APPNAME_production < APPNAME_production_timestamp.sql or something similar... I don't need to restore often so I don't know this one off the top of my head, but a quick google search should turn up something if this doesn't work.
{ "pile_set_name": "StackExchange" }
Q: Questions about review testing While reviewing, I sometimes get test-results. Flagging them typically will show the following: This was only a test, designed to make sure you were paying attention. The post has already been removed, but if it hadn't your response would have helped to ensure that it was. Thanks! I just had it happen in "First Posts", but recall seeing it with some of the other review types as well, and sometimes multiple times within the same reviewing session. I assume they are meant to prevent review-abuse by users harvesting badges who just click the same review action repeatedly. I'm just curious about a few things: I assume some type of review options are better suited for these tests than others. I cannot see it work on "Suggested Edits", for example. Is this the case? What happens if I accidentally would miss-click? Will I be punished in any way? Does the fact I keep seeing these tests every now and then imply I might have marked some answers wrongly, or do they show for absolutely everyone? (Note: I'm not trying to figure out how to sidestep the system. Just curious). Edit: Another question, actually. What reply does one get when missing it's a honeypot answer? I don't think I ever encountered one of those occasions, but that could be because I just caught the honeypot questions. Is there a "Whoops, you screwed the pooch on that one" message, too? A: I assume some type of review options are better suited for these tests than others. I cannot see it work on "Suggested Edits", for example. Is this the case? Yes, Shog mentions the honeypot is right now present for Low Quality Posts and First posts review queue Will I be punished in any way? As of now, the failures are logged, but no actions are taken. I wouldn't be surprised if this was changed later. There are automated review suspensions in place now, so if you fail too many review audits you'll be automatically banned from reviewing Does the fact I keep seeing these tests every now and then imply I might have marked some answers wrongly, or do they show for absolutely everyone? I haven't run into these often(they get swooshed before I can even look) but I do believe this is shown for all, to keep the reviewers on their toes and to reduce robo-reviewers
{ "pile_set_name": "StackExchange" }
Q: Rails 4: best way to reference table constants I have two tables: posts and post_types (each post is associated with a post_type_id). The post types are pre-defined in seeds.rb like this: PostType.create!([ { :id => 1, :name => 'Question' }, { :id => 2, :name => 'Answer' }, { :id => 3, :name => 'Note' } ]) What is the best way to reference the constants in controllers? For example, I currently hard code the post_type_id in my posts#create action: def create @post = current_user.posts.new( :post_type_id => 3, :title => post_params[:title], :body => post_params[:body]) end A: Don't reference the IDs in your code. There's no guarantee they'll always be the same. The way I usually handle this is to create a code column which is a "slugified" version of the item's name. So, in your case, you'd have a code column on PostType, and the code for "Question" would be question. (To use an example with spaces, "Other post type" would become other_post_type.) Then, in your controller, you can do PostType.find_by(code: "question") or, if you want to get fancy, you can implement a helper like post_type :question or something like that. Oh, and if you don't want to do a DB call every time you need to reference the post type id, you can always do something like # app/models/post_type.rb class PostType < ActiveRecord::Base QUESTION = find_by(code: "question") ANSWER = find_by(code: "answer") NOTE = find_by(code: "note") end Then in the controller you could do PostType::QUESTION. Actually, I like that way better than the other things I suggested. And just to tie the whole thing up: def create @post = current_user.posts.new( post_type: PostType::NOTE, title: post_params[:title], body: post_params[:body] ) end
{ "pile_set_name": "StackExchange" }
Q: Autoconf for Visual C++ I want to build XZ Utils with MSVC++, but xz utils uses a Gnu Autoconf Script. Is there a way to import a whole autoconfed project into MSVC++, then build it? If not, is there a way to run the Gnu Autoconf script for MSVC++, then after that, just take all the source files, as well as config.h, then build it? A: As far as I know, not really. You could try installing MSYS and seeing what the support for cl.exe is like in the configure script: ./configure CC=c:/path/to/cl.exe CXX=c:/path/to/cl.exe Last time I checked, the support was rather immature, but it could be worth a shot. On the other hand, since xz-utils is written in straight C, what does it matter which compiler you use? Build it with MinGW and link against it with visual studio.
{ "pile_set_name": "StackExchange" }
Q: When you increase the temperature such that change in Gibb's free energy becomes zero, does Keq = 1 at that temperature? $$\Delta G = \Delta H - T \Delta S$$ say for example, both $\Delta H$ and $\Delta S$ are positive. So assuming $\Delta H$ and $\Delta S$ do not change or change minimally with temperature, if you increase the temperature until $\Delta G = 0$, is the equilibrium that you reach an equilibrium in which reactants and products are in standard conditions i.e. $K_\mathrm{eq} = 1$? A: Yes and no. $K = 1$ is true, and it follows directly from the equation $\Delta G^\circ = -RT \ln K$. However, there is no reason for it to be "an equilibrium in which reactants and products are in standard conditions". $K = 1$ does not necessarily mean that the concentrations (or activities if you prefer) of all reactants and products are also equal to $1~\mathrm{mol~dm^{-3}}$ (or $1$, in the case of activities). Remember that $K$ is a fraction. For the reaction: $$\nu_{r1}\ce{R1} + \nu_{r2}\ce{R2}\cdots \longrightarrow \nu_{p1}\ce{P1} + \nu_{p2}\ce{P2} \cdots$$ we have: $$K = \frac{[\ce{P1}]^{\nu_{p1}}[\ce{P2}]^{\nu_{p2}}\cdots}{[\ce{R_1}]^{\nu_{r1}}[\ce{R_2}]^{\nu_{r2}}\cdots}$$ Just like how the fractions $\displaystyle \frac{2}{2}$, $\displaystyle \frac{4}{4}$, or $\displaystyle \frac{4000\hbar\pi e}{4000\hbar\pi e}$ are all equal to $1$, the individual concentrations $[\ce{P1}], [\ce{P2}], [\ce{R1}], [\ce{R2}]\cdots$ might not be equal to $1~\mathrm{mol~dm^{-3}}$, but the result will still be $1$.
{ "pile_set_name": "StackExchange" }
Q: What is the power specification for SATA? We are designing a product which needs to provide data and power to an SSD connected using SATA. However, we cannot find a specification of the power requirements for a SATA connector. How much power should a power supply behind a SATA power connector provide at a minimum? I have acccess to the SATA specification. However, we did not find a specification of a minimum power supply. It only mentions the 1.5 A rating of the individual pins. It seems to define how to deliver power, but not how much. I found an answer on power connector pins and the wikipedia entry on SATA power connectors. However, it seems to me that the 1.5 A specified there is the minimum the connector should support. That is, the connector should not melt if I put 1.5 A per pin through it. I don't think it means the SATA device connected to it can expect 1.5 A per pin to be supplied. A: As @bitshift says, you'll likely need to get the actual spec to be sure. 1.5A may well be a real supply requirement, though. The cables used are actually rated to 4.5A per supply rail. The connectors contain 3.3V, 5V, and 12V rails. A regular (magnetic 3.5") hard drive can dissipate almost 10W. This energy is probably split across the three available power rails. Since I have no idea what the split may be, the worst case numbers look something like this : All 10W @ 3.3V - 3.33A All 10W @ 5V - 2A All 10W @ 12V - 0.83A The actual spec could help you understand how the load is allowed to be spread over the three supplies and what the effective ratings needed are. If you don't care about it being SATA compliant, you could assume the load is lower by a factor of 2 or so since you're only using SSDs.
{ "pile_set_name": "StackExchange" }
Q: User defined function to R library function like avg() I created a user defined function in R for checking whether a given number is prime or not. How can I make that user defined function as library function like avg or sd? A: library(numbers) isPrime(561) # [1] FALSE
{ "pile_set_name": "StackExchange" }
Q: jQuery sortable drag and drop - cloning and other issues I'd like to begin with saying what I'm trying to do. I'm currently working on a menu generator (idk how to name it exactly), something like placing widgets in WordPress but for creating menu on a website. I've tried to do it using jQuery and Sortable (I've tried Draggable and LiveQuery too but that's not what I'm looking for) but I have some problems: the user should be given the possibility of hiding the content of the item but the button hiding/unhiding it blocks after copying the item the source item should be cloned and not moved (but using a placeholder - I couldn't find draggable with a placeholder) without being removed from list (I have a temporary solution with adding the source item on the end of list but that isn't what I want to achieve) the item has to be moved from one column to another (i.e. from #column1 to #column2, not #column1 -> #column1 [same with #column2] and not #column2 -> #column1) Here's the code: JavaScript: $(function(){ $('.dragbox').each(function(){ $(this).find('.dragbox-content').css('display', 'none'); }); $('.dragbox') .each(function(){ $(this).hover(function(){ $(this).find('h2').addClass('collapse'); }, function(){ $(this).find('h2').removeClass('collapse'); }) .find('h2').hover(function(){ $(this).find('.configure').css('visibility', 'visible'); }, function(){ $(this).find('.configure').css('visibility', 'hidden'); }) .click(function(){ $(this).siblings('.dragbox-content').toggle(); }) .end() .find('.configure').css('visibility', 'hidden'); }); $('.column').sortable({ connectWith: '.column', handle: 'h2', cursor: 'move', placeholder: 'placeholder', forcePlaceholderSize: true, opacity: 0.4, stop: function(event, ui){ if (ui.target == event.target) alert("Error!"); $(ui.item).find('h2').click(); $(ui.item).clone().appendTo(event.target); $(event.target).each(function(){ $(this).find('.dragbox-content').css('display', 'none'); }); }, remove: function(event, ui) { if (ui.target == event.target) alert("Error!"); } }); }); and HTML: <h3>Drag n Drop - menu test</h3> <div class="column" id="column1"> <div class="dragbox" id="item1" > <h2>category</h2> <div class="dragbox-content" > Name: <input type="text"/> </div> </div> <div class="dragbox" id="item2" > <h2>button</h2> <div class="dragbox-content" > Text: <input type="text"/><br /> Link: <input type="text"/> </div> </div> <div class="dragbox" id="item3" > <h2>html code</h2> <div class="dragbox-content" > <textarea></textarea> </div> </div> </div> <div class="column" style="width: 49%;" id="column2" > </div> I know it may look chaotic so there's an example of what I mean: http://hun7er.pl/poligon/dragndrop/ The code is based on that tutorial: http://webdeveloperplus.com/jquery/collpasible-drag-drop-panels/ As you can probably see only content of the target item can be hidden/unhidden and sometimes while trying to hide/unhide the item can be accidentally cloned. I've searched for a solution here, on stackoverflow, and in some other places (Google search) but nearly all solutions concern Draggable or LiveQuery and I have no idea how to use a placeholder there (as I mentioned I couldn't find any tutorial/thread/post with draggable&placeholder). I've thought about using regexp to change item id (it stays the same for all cloned items) but idk how to get item id and changind it using Firebug doesn't seem to help. Sorry if there was a similar thread but I couldn't find any (the only one I can see now has no solution). Thanks in advance for any help A: To answer what I think is your most pressing question, here is an example of the jQueryUI sortable using a placeholder. However, I think what you might be after is actually the helper property, which is used to define an element to be displayed while dragging. Regarding your explicit questions (I've prepended a classifier to help identify what I perceive to be the problem) ... Event Binding Problems: the user should be given the possibility of hiding the content of the item but the button hiding/unhiding it blocks after copying the item. To address this problem you'll need to use event delegation, ideally scoping the event delegation to your columns for performance reasons. jQuery has a .delegate method which allow you to achieve this. Here's some sample code based on your markup: $('.column').delegate('.dragbox h2', 'hover', function() { $(this).toggleClass('collapse'); }); $('.column').delegate('.dragbox', 'click', function() { $(this).find('.dragbox-content').toggle(); }); What this allows you to do is not worry about re-binding events when you generate your elements, as per the description in the jQuery docs on .delegate: "Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements." Cloning : the source item should be cloned and not moved (but using a placeholder - I couldn't find draggable with a placeholder) without being removed from list (I have a temporary solution with adding the source item on the end of list but that isn't what I want to achieve) In order to properly clone the item I might suggest changing your interface paradigm so you have a button that instructs the user with a call to action like "Click to Add" or something like that. It would be better to have a button that drove adding instead of worrying about drag drop. You can still do .sortable within column2 but having a button would simplify the add interaction. Drop Restrictions : the item has to be moved from one column to another (i.e. from #column1 to #column2, not #column1 -> #column1 [same with #column2] and not #column2 -> #column1) If you go with a button paradigm for the adding then you can avoid needing to worry about these restrictions. Also, take a look at the receive function as it might provide more ability to restrict and revert should you not want to go with the button paradigm.
{ "pile_set_name": "StackExchange" }
Q: How do I make fancybox use its larger icons How can I make fancybox 2 use its larger icons versions? this ones ([email protected], [email protected]) This sucks I have to write something so this page will allow me to post my question. A: Those 2x icons were created for devices with retina display support. If you analyze the fancybox CSS file, at the end you will find these lines : /*Retina graphics!*/ @media only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min--moz-device-pixel-ratio: 1.5), only screen and (min-device-pixel-ratio: 1.5){ #fancybox-loading, .fancybox-close, .fancybox-prev span, .fancybox-next span { background-image: url([email protected]); background-size: 44px 152px; /*The size of the normal image, half the size of the hi-res image*/ } #fancybox-loading div { background-image: url([email protected]); background-size: 24px 24px; /*The size of the normal image, half the size of the hi-res image*/ } } If you wan to use them in a none-retina-display support device or browser, I guess you may need to hack the CSS file and change the regular icon's dimensions and sprites to match those in the media queries
{ "pile_set_name": "StackExchange" }
Q: How do we handle "Basic" issues/misunderstandings? We have an ongling problem, where some site visitors demonstrate a basic lack of understanding of basic Christianity. The example that inspired this question would be: show where god claims to be just. Then show where god has justified wicked people then you can make that claim The fact that God is just is something I think most Christians take for granted, because it's so obviously stated multiple times in the Bible--as evidenced by the various answers to my followup question. So... that's the proper way to handle these questions? Lets ignore for a moment the possibility that the user asking for proof that God claims to be just, might have been trolling (I don't think we know if he was or not). Lets give him the benefit of the doubt, and assume he really didn't know that about Christianity. How do we address this issue? Clearly I chose to address it by asking a question to clear the air. But as @DJClayworth rightly points out, that is not an expert-level question. What's a guy to do? A: I hate the fact that we have to have these questions. However, it seems that we're getting more and more people debating the very core foundations of Christianity (such as God being just, Mary being a Virgin at the birth of Jesus, sin being evil, etc.) However, unlike other SE sites, we can't simply presume that the basics and fundamentals are understood. For example, when dealing with StackOverflow, you can presume that everyone there understands that you can't store a fractional number in an integer value without precision loss. On SuperUser, it's safe to presume that if you unplug a network cable, you'll lose connectivity. Here, though, we can't even assume that everyone is on board with the idea that God is perfect (for example). These extremely basic questions have to be hashed out. It seems that we'll have to go through the process of knocking out all these basic questions until we can build a firm foundation on which we can begin to answer the expert questions. When you have to debate the definition of English words, we clearly are at a place that needs a firm foundation. As we gain that foundation, we can start weeding out the simple answers as duplicates of past answers and we can start pointing arguments within comments to the simple questions that address those confusions. My hope is that, as this site matures, these silly little debates will fade away so that we can focus on more expert level questions. But until then, I think these child's school questions are foundational and essential--purely because of the nature of the topic. A: I'm going to pull the quote I use in my profile sig out: "This is a question and answer site. Not a "complex question, insightful answer that grows you as a person site." People should be able to ask simple questions with simple answers, that just may so happen to be spoon-fed. A lot of people just want to get good answers. Not be empowered. – Owen Sep 19 '08 at 21:23" (paraphrasing just a bit to fit this site's purpose) Ever since early SO days (and I've been around before there was such a thing as SU and SF, never mind a whole army of Stack Exchange sites), I've been arguing for a broad level of acceptance for questions with regard to level of complexity. Why? Traffic. The more questions we have that come up high in google results, the more traffic/exposure we get. The more exposure we get, the more we grow and the better we can serve our userbase. Even if something can possibly be considered a "general reference" question, we should definitely keep it. I agree that a flood of entry-level questions can definitely damage an SE site, but we've already fairly well established that we have a thriving expert community here. It certainly wouldn't hurt to have simpler questions that can expand into a solid platform for explaining perhaps more fundamental concepts of Christianity, as well as spur thought and discussion among our users. And to me, it feels like just a touch of snobbery to say "Your question is too dumb for us to answer. Just go away and google it." (and I'm pretty sure i'm one of few who would phrase it that tolerably :P) Surely we can tone that down?
{ "pile_set_name": "StackExchange" }
Q: Find file name using wildcard in C I need to find the name of a file using * in a C program. There is exactly 1 file in the specific folder that has the extension .UBX. I can do this in terminal but it doesn't work in C. Can anyone give me example code to do this? //There is exactly 1 file that ends in .UBX #define FILE_TO_SEND "/home/root/logs/*.UBX" fd = open(FILE_TO_SEND, O_RDONLY); A: This should do the trick: #include <glob.h> #include <stdlib.h> #include <fcntl.h> #define FILE_TO_SEND "/home/root/logs/*.UBX" int main (void) { glob_t globbuf; glob(FILE_TO_SEND, 0, NULL, &globbuf); if (globbuf.gl_pathc > 0) { int fd = open(globbuf.gl_pathv[0], O_RDONLY); // ... } globfree(&globbuf); return 0; }
{ "pile_set_name": "StackExchange" }
Q: how to process action listener method before processing client listener in adf Is there a way to process client listener after processing action listener in ADF ? Following is my code snippet: <af:commandLink text="Click Me" id="myLink" partialSubmit="true" actionListener="#{pageFlowScope.myBean.changeSelection}"> <af:clientListener method="showMyTable" type="action"/> </af:commandLink> <af:outputText value="#{pageFlowScope.myBean.selectedValue}" id="ot1" partialTriggers="myLink" /> My use case is: When I click on the command link, I have to change the display value of the output text and then have to show some other components using javascript (client listener). Here my issue is: when I click on the command link, first the client listener is being processed. After processing the client listener, output text component is refreshing through action listener. My requirement is to process action listener first, so that my output text component will be refreshed first. Then to process client listener to show other components. A: There is no way to make it work this way, since clientListener will work BEFORE by design. However, you can achieve your goal just by launching your javascript request from actionListener directly. Do something like this in the actionListener's method: FacesContext fctx = FacesContext.getCurrentInstance(); ExtendedRenderKitService service = Service.getRenderKitService(fctx, ExtendedRenderKitService.class); service.addScript(fctx, "showMyTable();");
{ "pile_set_name": "StackExchange" }
Q: missing after argument list jersey jsonp I'm using jersey to generate jsonp that will activate a jQuery callback to populate an autocomplete. However, the generated jsonp is syntactically incorrect as it causes a javascript error with the message: 'SyntaxError: missing ) after argument list' And my browser is right. This is the jsonp that is returned from the server: jQuery18204124785447421858_1369727990195("[{\"firstname\":\"Carl\",\"lastname\":\"xxxxxx\",\"nihii\":\"140xxxxxx\"},{\"firstname\":\"Bram\",\"lastname\":\"xxxxxxxxx\",\"nihii\":\"102xxxxx\"},{\"firstname\":\"Carl\",\"lastname\":\"Mxxxxxx\",\"nihii\":\"1403xxxxxx\"},{\"firstname\":\"Max\",\"lastname\":\"Dexxxxx\",\"nihii\":\"1000xxxxx\"}]" Which indeed has a missing closing parenthese. This is the code at the server side: @Path("/yxxxxxxx") @Produces("application/x-javascript") public class YellowPagesService implements InitializingBean{ private YPWSClient ypwsClient; @GET public JSONWithPadding getClichedMessage(@QueryParam("callback") String callback, @QueryParam("name_startsWith") String name_startsWith) { List<Person> persons = new ArrayList<Person>(); if(name_startsWith != null && !name_startsWith.equals("")){ List<Contact> result = ypwsClient.getPersonsStartsWith(name_startsWith).getContact(); for(Contact c : result){ if(c.getFirstName() != null){ Person p = new Person(c.getFirstName(), c.getLastName(), c.getIdentifier()); persons.add(p); } } } JSONWithPadding jsonWithPadding = new JSONWithPadding(new GenericEntity<List<Person>>(persons){}, callback); return jsonWithPadding; } I am using Jersey 1.12 but I cannot find this issue anywhere logged and I did not find users with the exact same problem, which make me doubt about the cause of this issue. I've tried Genson but to no avail. Somebody has a clue? Thanks a lot! Cheers A: Try upgrading to Genson 0.97, jax-rs integration code was closing outputstreams (when it shouldn't) thus the missing closing paranthesis.
{ "pile_set_name": "StackExchange" }
Q: how do I get my button to have a sprite without setting a width or using text indent? I'm thinking this can be done with some sort of inline-block magic? maybe? idk.. but basically, the text and the sprite should be inline. right now, they are not: http://jsfiddle.net/DerNalia/qvZkK/2/ html: <a href="" class="action_button" rel="facebox" style=""> <span class="button_sprite_x"></span> Delete </a> A: Will your layout allow you to float it? .action_button span.button_sprite_x, .action_button span.button_sprite_plus, .action_button span.button_sprite_duplicate, .action_button span.button_sprite_star{ width: 20px; height: 20px; display: block; float: left; /* Added float */ } http://jsfiddle.net/qvZkK/3/ UPDATE: Ah, but you probably want the sprite to be within the a element's background. A combination of display: inline-block and float: left does that. .action_button { display: inline-block; /* Add display: inline-block to .action_button */ } .action_button span.button_sprite_x, .action_button span.button_sprite_plus, .action_button span.button_sprite_duplicate, .action_button span.button_sprite_star{ display: inline-block; /* And add display: inline-block here, also */ float: left; /* Added float */ } http://jsfiddle.net/qvZkK/4/
{ "pile_set_name": "StackExchange" }
Q: How to analyze AWS S3 costs? Into "Cost Explorer Monthly costs by service" report I saw $300 for S3 for certain month. But when I tried to drill-down into the bill for this month, I saw just $4 for the "Simple Storage Service". So I'm not sure I understand how I can investigate S3 cost. TIA, Vitaly A: Use the AWS Cost Explorer. Log into your account then use this link, or navigate to "my billing dashboard". It's a bit odd to get into. You have to click "Cost Explorer" on the top left of the menu bar, then click "launch cost explorer" on the right so it opens a window, then you click "cost explorer" top left again. Really weird. Once it actually loads up you can choose to filter by server (right hand side), then you can sort by usage type (in the middle above the graph). Details appear under the graph. It takes some playing around to get good at it. To decode the screenshot below: USW2 = US West 2 Requests GDA is S3 Glacier Deep Archive Requests Timed Storage is storage You can see in July there were a lot of uploads to Glacier Deep Archive, which increased the bill.
{ "pile_set_name": "StackExchange" }
Q: Distributing Webpage Widgets that need to Access an Authorized API I have developed an API that uses JWT to authorize client requests. Seasoned developers can get a JWT using a login API over HTTPS and use that JWT to make subsequent authorized API calls. That all works fine. Now I've got some interest from less-seasoned developers who are primarily front-end oriented (HTML/CSS/Javascript developers). Ideally for this class of individual, they'd like to be instructed to "drop this script tag in your HTML, set it up like this, and magic will ensue." Without having them also deploy some kind of proxy server on some random port (e.g. like 9090) on their back-end (which is the where my brain went when I thought about this independently), is there a canonical strategy that would allow this sort of thing without that developer having to put their JWT in their client side code, and therefore break the authorization / authentication model of the API (since in that case anyone could masquerade as that user by, e.g., simply looking at Chrome developer tools network and/or source tabs). Obviously my back-end proxy concept is not perfect, and could be abused, but at least I could revoke a maliciously behaving JWT under some kind of abuse scenario and communicate to the affected authorized developer to come up with a resolution. Setting up a proxy service is a lot of effort for some people though. I guess I could ultimately set one up for each developer who wants this sort of thing if they were willing to pay for it, but I am left wondering "is there a better way?". What say you? A: I don't think you can prevent malicious users from accessing any API endpoints that the widget can access, unless you have them authenticate themselves in the widget before they can use it. Assuming authentication is a no-go, maybe the Principle of Least Privilege is the answer. It's hard to say without knowing how interactive the widget is, but some examples: If the widget doesn't need write access, give it read-only access. Give the widget access to only the data/endpoints it needs. If the widget is only displaying digested data (e.g. fetching raw data but rendering a chart), have the API digest the data first instead of sending the raw data to the client (e.g. render the chart on the server). This would make the raw data more difficult to retrieve.
{ "pile_set_name": "StackExchange" }
Q: updating alarm from pending intent in android I am working on an Alarm Clock project and i want to edit my already set Alarm. when I edit alarm then alarm time is updated but values that I send by using putExtra() are not changing. I am using PendingIntent.FLAG_ONE_SHOT flag. But when I set flag PendingIntent.FLAG_UPDATE_CURRENT all putExtra() values are also change but now problem is that, when i click on stop button and finish() the current activity it calls again. means when I go to finish the activity it calls again on button click while I am finishing current activity. please help me. Thanks in advance. A: My prefered way to update a PendingIntent in AlarmManager is to Cancel it and re-set it do not forget to cancel : 1) AlarmManager.cancel(pendingIntent) with a pendingIntent that match your pending intent (same class , same action ... but do not care about extra see IntentFilter) 2) pendingIntent.cancel(); 3) pendingIntent = new PendingIntent() ... and do other settings 4) AlarmManager.set(... to provide new PendingIntent
{ "pile_set_name": "StackExchange" }
Q: How can I add a CSS class to the body tag based on the current path alias? Is it possible in Drupal 8, to add a CSS class to the <body> tag based on the current path alias? A: In your theme, you can add the following code in template_preprocess_html: $current_path = \Drupal::service('path.current')->getPath(); $path_alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path); $path_alias = ltrim($path_alias, '/'); $variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($path_alias);
{ "pile_set_name": "StackExchange" }
Q: Extensions of $\mathbb{Z}_p$ by $\mathbb{Z}$ (Hilton & Stammbach III.1.2) Question is to compute $E(\mathbb{Z}_p,\mathbb{Z})$ i.e., equivalence classes of extensions of $\mathbb{Z}_p$ by $\mathbb{Z}$ By an extension of $A$ by $B$ i mean an $R$ module $E$ such that $B\rightarrow E\rightarrow A$ is an exact sequence. I say $B\rightarrow E_1\rightarrow A$ and $B\rightarrow E_2\rightarrow A$ are equivalent if there exists a homomorphism $\zeta : E_1\rightarrow E_2$ such that the following diagram commutes \begin{matrix} B&\to&E_1&\to&A\\ \|&&\;\;\downarrow f&&\|\\ B&\to&E_2&\to&A \end{matrix} Now First question is to show that : $$\mathbb{Z}\xrightarrow {\mu} \mathbb{Z}\xrightarrow{\epsilon} \mathbb{Z}_3 ~\text{and }~ \mathbb{Z}\xrightarrow {\mu'} \mathbb{Z}\xrightarrow{\epsilon'} \mathbb{Z}_3 $$ where $\mu=\mu'$ is multiplication by $3$, $\epsilon(1)=1 (\mod 3)$ and $\epsilon'(1)=2 (\mod 3)$ are not equivalent. Second Question is (use above idea) to compute $E(\mathbb{Z}_p,\mathbb{Z})$... I have solved first exercise and with that i realized that there are atleast $p-1$ non equivalent extensions with $\mu$ being multiplication by $p$ and $\epsilon_i=i\mod p$ for $1\leq i\leq p-1$. And then I have split extension $$\mathbb{Z}\rightarrow \mathbb{Z}\oplus \mathbb{Z}/p\mathbb{Z}\rightarrow \mathbb{Z}/p\mathbb{Z}$$ So i have $p$ extensions now.. I am not able to prove there are no other extensions which are not equivalent to any of this.. Please help me to see this.... If any one can make that commutative diagram using latex i will be so thankful.. I tried to google for drawing commutative diagrams but i am not able to do as of now.. Thank you. This is an exercise in Hilton & Stammbach's A Course in Homological algebra chapter $3$, Exercise $1.2$ A: Suppose $\def\ZZ{\mathbb Z}0\to\ZZ\xrightarrow{f}E\xrightarrow{g}\ZZ_p\to0$ is a non-split extension. If $E$ has non-zero torsion, then that torsion clearly does not intersect the image of $f$, and therefore is mapped injectively into $\ZZ_p$. You can easily construct, then, a map $\ZZ_p\to E$ which is a section to $g$: this contradicts non-splitness. It follows that $E$ is torsion free. As Jyrki observes, $E$ is either cyclic or a direct sum of two cyclic groups. It it were a direct sum of two cyclic groups, its quotient by the image of $f$ would be infinite. It follows that $E$ is isomorphic to $\ZZ$. Now there are exactly $p-1$ surjective homomorphisms from $\ZZ$ to $\ZZ_p$, etc.
{ "pile_set_name": "StackExchange" }
Q: using linq to orderBy in list of lists I have the following model: public class Person { public int Id {get; set; } public string Name {get; set; } public List <Car> Cars {get; set; } } public class Car { public int Id {get; set; } public string Make {get; set; } public string Color {get; set; } } var persons = new List<Person>(){.....} I want to query the persons list and order it by Person.Name and Car.Make. I want the person list to be sorted by Person.Name, and the individual person car list to be sorted by Car.Make var entities = Persons .Include(h => h.Cars) .Where(h => h.Id == 1).OrderBy(h => h.Name).ToList(); Order by Person.Name works fine, but I need to order by Car.Make also. since I can't use orderBy within .Include(h => h.Cars), so I decided to order it using a foreach, entities.ForEach(h => { h.Cars.OrderBy(t => t.Make); }); this didn't work. How do I make it work? A: Regarding OrderBy() The OrderBy() method returns a collection of items as opposed to ordering in-place, so you would need to set your Cars to that specific value: entities.ForEach(h => { // This will order your cars for this person by Make h.Cars = h.Cars.OrderBy(t => t.Make).ToList(); }); You could potentially handle this within a single call with a Select() statement as well to avoid iterating through the list once more with a ForEach() call: var entities = Persons.Include(h => h.Cars) .Where(h => h.Id == 1) .OrderBy(h => h.Name) // .ToList() (Use this if calling directly from EF) .Select(p => new Person(){ Id = p.Id, Name = p.Name, Cars = p.Cars.OrderBy(c => c.Name).ToList() });
{ "pile_set_name": "StackExchange" }
Q: NoMethodError on method added to Date class I added two methods to the Date class and placed it in lib/core_ext, as follows: class Date def self.new_from_hash(hash) Date.new flatten_date_array hash end private def self.flatten_date_array(hash) %w(1 2 3).map { |e| hash["date(#{e}i)"].to_i } end end then created a test require 'test_helper' class DateTest < ActiveSupport::TestCase test 'the truth' do assert true end test 'can create regular Date' do date = Date.new assert date.acts_like_date? end test 'date from hash acts like date' do hash = ['1i' => 2015, '2i'=> 'February', '3i' => 14] date = Date.new_from_hash hash assert date.acts_like_date? end end Now I am getting an error that: Minitest::UnexpectedError: NoMethodError: undefined method 'flatten_date_array' for Date:Class Did I define my method incorrectly or something? I've even tried moving flatten_date_array method inside new_from_hash and still got the error. I tried creating a test in MiniTest also and got the same error. A: private doesn't work for class methods, and use self. class Date def self.new_from_hash(hash) self.new self.flatten_date_array hash end def self.flatten_date_array(hash) %w(1 2 3).map { |e| hash["date(#{e}i)"].to_i } end end
{ "pile_set_name": "StackExchange" }
Q: How can DateTimeFormatInfo.CurrentInfo be null I have the following code in my C# application. DateTimeFormatInfo.CurrentInfo.DayNames ReSharper 7.1.1 is highlighting the fact that the DateTimeFormatInfo.CurrentInfo could cause a null reference exception. Under what circumstances would this occur? Or is this just a mistake on ReSharper's part believing that any object whose property you access should be null checked? A: ReSharper is most probably just doing lexical analysis here and nothing deeper. Since DateTimeFormatInfo is a class, a variable of this type can be null. Which means that the instance returned by DateTimeFormatInfo.CurrentInfo can be a null reference. That's the error you are getting. Resharper doesn't understand that the method was coded such that it will not return a null reference, so it gives a warning. Don't take the messages from Resharper as scripture...
{ "pile_set_name": "StackExchange" }
Q: C: Confusion Regarding The Use of Pointers I'm in the middle of reading a C programming book. I'm currently reading and practising using Xcode with pointers. I am wondering why this line of code is only printing the first character H of a literal character array string and not the full string "Hello" char *myCharPointer = "Hello"; printf("The value of myCharPointer is %c \n \n", *myCharPointer); I was under the impression that a string literal returns the address of the first character within that array, which then, I thought would automatically print the reset of the characters sequentially. The reason behind this thought process was a preceding example that demonstrated a similar string being passed to a char pointer within a function, then the address of that char pointer being passed into a strcpy() function for all the characters to be read. I also tried changing the format specifier to %s, but the program crashed. I'm also a little confused why this: int myIntArray[10]; int *myIntArrayPointer; myIntArrayPointer = myIntArray; And not: int myIntArray[10]; int *myIntArrayPointer; myIntArrayPointer = &myIntArray; I know that myIntArray is not defined as yet, but its just an example A: I am wondering why this line of code is only printing the first character H of a literal character array string and not the full string "Hello" First, the pointer char* is defined as pointing to a character. In the case of your example, that is H in Hello. With a string, you are defining data in contiguous memory. For instance, char [H][e][l][l][o][\0] index [0][1][2][3][4][5] The pointer is used simply as a way of iterating over each character in memory. This means myCharPointer = H(0), ++myCharPointer = e(1), etc. When you print the string, you would do the following: printf("The value of myCharPointer is %s \n \n", myCharPointer); I know that myIntArray is not defined as yet, but its just an example An integer pointer and an integer array are essentially the same thing in the context of assignment. A pointer can iterate through a block of memory and therefore your straight assignment myIntArrayPointer = myIntArray is correct. As a side note: If you have a regular character char myChar = 'a'; you can get its address in memory with the &. For instance, char* myCharPointer = &myChar; -> myCharPointer now points to myChar. To get the value at the address, simply use the dereferencing operator *myCharPointer which would be 'a'.
{ "pile_set_name": "StackExchange" }
Q: setDuration only affects one CALayer when animating multiple CALayers I'm trying to animate a change in position for numerous CALayers simultaneously. Implicit animations seems to work fine, but if I try to explicitly specify a value for the duration properties of each CALayer, only one is animated while the other is changed successfully but without any animation. Here is the code I am working with: CGPoint initialPt = CGPointMake(160.0, 10); CGPoint pt2 = CGPointMake(160.0, 185.0); CGPoint pt3 = CGPointMake(160.0, 270.0); CABasicAnimation *firstAnim = [CABasicAnimation animationWithKeyPath:@"postion"]; [firstAnim setFromValue:[NSValue valueWithCGPoint:initialPt]]; [firstAnim setToValue:[NSValue valueWithCGPoint:pt2]]; [firstAnim setDuration:1.0]; [layer1 setPosition:p2]; [layer1 addAnimation:firstAnim forKey:@"Slide"]; CABasicAnimation *secondAnim = [CABasicAnimation animationWithKeyPath:@"position"]; [secondAnim setFromValue:[NSValue valueWithCGPoint:initialPt]]; [secondAnim setToValue:[NSValue valueWithCGPoint:pt3]]; [secondAnim setDuration:1.0]; [layer2 setPosition:p3]; [layer2 addAnimation:secondAnim forKey:@"Slide2"]; I've already tried using CATransaction as well but nothing changed. If I comment out the setDuration method, both layers animate the position change without issue, except that they are at a fixed duration. It seems that for some reason setting the animation explicitly muddles things up but I'm lost as to why. Any help would be much appreciated! Thanks. A: The problem is you type the wrong word! CABasicAnimation *firstAnim = [CABasicAnimation animationWithKeyPath:@"postion"]; change the 'postion' to 'position' should be CABasicAnimation *firstAnim = [CABasicAnimation animationWithKeyPath:@"position"]; change the 'postion' to 'position' 'postion' to position
{ "pile_set_name": "StackExchange" }
Q: struggle to run python script with crontab I am currently working on some python scripts that involve sending emails to recipients with information I scrape from the web or by API. The first script, magic_sea.py scrapes magicseaweed for wave heights in certain locations. The second one uses an API to get weather data. Both scripts run as they should when I type in the command and a second later I recieve the inteded email. python3 <script.py> But only the first one runs when I put them in the crontab like this * * * * * /usr/bin/python3.5 /path/to/script.py >> crontab_log.txt * * * * * /usr/bin/python3.5 /path/to/second_script.py >> crontab_log.txt I am using the shebang #!/usr/bin/python3.5 in both scripts looking at the crontab_log.txt file, they both seem to run fine. But I only recieve emails from the first scripts. A: Your method of logging: * * * * * /usr/bin/python3.5 /path/to/script.py >> crontab_log.txt * * * * * /usr/bin/python3.5 /path/to/second_script.py >> crontab_log.txt only sends stdout to the log file, not errors. You can fix that by using 2>&1 to send stderr to stdout like this: * * * * * /usr/bin/python3.5 /path/to/script.py >> crontab_log.txt 2>&1 * * * * * /usr/bin/python3.5 /path/to/second_script.py >> crontab_log.txt 2>&1 That should allow you to identify and correct any errors. If you still don't see what you need, add logging all through script 2 to see what is happening while it is being executed by cron.
{ "pile_set_name": "StackExchange" }
Q: How should I set the classpath for gradle 4.5 in android studio I'm using android studio 3.1 and I just configured gradle-wrapper.properties to use gradle-4.5 and it downlowded the file succesfully. : distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip how should I configure classpath in dependencies of build.gradle file? it was like this when I was using an older version of Gradle: dependencies { classpath 'com.android.tools.build:gradle:3.1.0-alpha09' } I changed it to : dependencies { classpath 'com.android.tools.build:gradle:4.5' } but it didnt work A: Don't confuse gradle with android plugin for gradle. It is the android plugin for gradle and 4.5 doesn't exist. dependencies { classpath 'com.android.tools.build:gradle:4.5' } It is gradle, and it is enough to use gradle 4.5 distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip
{ "pile_set_name": "StackExchange" }
Q: Unity 2D display "flash effect" above tiles I want to apply a brighten effect above my scene. My scene contains tiles, and I want to perform white flash for a few frames by code. I have already tried this code: private Tilemap tm; ... tm = GetComponent<Tilemap>(); tm.color = new Color(0.5f,1.0f,1.0f,1.0f); This code darkens the scene by a certain color amount, but I wish to brighten it. A: Your code is not working because in Unity if you render an image (in your case tile) the original color of the image is when its color is white (255,255,255,255). It means that if you change the color of an image it will add this color to this image. For instance, if you set the color of an image to red, the image colors will become more similar to red than the original image. As I see it you have 2 ways to perform the white flash: A) Add another image of a white rectangle that covers all the screen and set it's alpha color to a low number (the lower the number the lighter flash effect). In the editor disable this object's renderer and when you want to perform a flash effect enable this object from the code (You can improve this with animations or code to get a smooth flash animation). B) Install the package "2D Light". This is an experimental package that allow you to render 2d light. This package contains a lot of components that allow you to stimulate light.
{ "pile_set_name": "StackExchange" }
Q: The presentation matrix $A$ of an $R$-module is the same as deleting a column of zeros of $A$ This is a proposition from Artin's Algebra (1st edition, Proposition 5.12): The presentation matrix $A$ of an $R$-module is the same as deleting a column of zeros of $A$. He proves it by stating that a column of zeros corresponds to the trivial relation which can be deleted. I am quite confused. 1) To talk about relation, we must first have a set of elements in $V$, the relation here refers to what set of elements in $V$? My guess is the generating set of $V$, but in his theorem he is talking about a general module $V$ which might not have a generating set. 2) Even though we confine ourselves to finitely generated $R$-module $V$, does $A$ always correspond to a complete relation of some generating set in $V$? I do not see why this must be true if we are only given an isomorphism between $R^m/AR^n$ and $V$. A: In the proposition, $V$ is a fixed finitely-generated module and $A$ is a presentation matrix for $V$. As explained in the above paragraphs, this means that $V \cong R^m /AR^n$. The generators are the images under the above isomorphism of the (cosets of the) $m$ standard basis vectors in $R^m$. Also note that any module always has a generating set, namely, take the whole module as a generating set. Yes, $A$ gives you a complete set of relations. Any relation in $V$ corresponds, under the above isomorphism, to an element of $R^m$ (a relation vector) that belongs in $AR^n$. This means precisely that the relation vector is a linear combination of columns of $A$.
{ "pile_set_name": "StackExchange" }
Q: String message divide 10 character by character I want to divide the following message by 10 character. I want to append every part into StringBuilder object. 04421,1,13,S,312|4000004130,1;4000000491,1;4000005240,1;4000005789,2;4000004978,2;4000004934,2;4000004936,1;4000000569,2;4000005400,1;4000000;4000004934,2; I have done the following solution : if(getMsgOtherPart(message) != null){ System.out.println("part message::"+getMsgOtherPart(message)); String newMessage = getMsgOtherPart(message) ; int len = newMessage.length(); System.out.println("len::"+len); int firstIndex = 0; int limit = 10; int lastIndex = 10; int count = 0; StringBuilder sb = new StringBuilder(); String completeMessage = null; for(int i = 0; i <= len;i++){ count++; if( count == limit && lastIndex < len){ sb.append(getSmsUniqueHeader()); sb.append(newMessage.substring(firstIndex,lastIndex)); sb.append("#"); sb.append("\n"); firstIndex = lastIndex; lastIndex = firstIndex + limit; count = 0; } else if(count < limit && i == len) { System.out.println("lastIndex:: "+lastIndex); sb.append(getSmsUniqueHeader()); sb.append(newMessage.substring(lastIndex-10)); sb.append("#"); } } completeMessage = sb.toString(); System.out.println("message::\n"+completeMessage); } I am getting output: message:: $04421,1,13# $,S,312|400# $0004130,1;# $4000000491# $;400000540# $0,1;400000# $0;40000000# $63,1;40000# $00076,1;40# $00000776,2# $;400000078# $8,2;400000# ------------ $0;# Please let me know to optimize my solution. A: I had done this kind of thing in one of my project and here is the function i used, which return the List but you can modify it and use StringBuilder. public List<String> splitStringEqually(String txtStr, int subStringSize) { List<String> splittedStringList = new ArrayList<String>(); for (int start = 0; start < txtStr.length(); start += subStringSize) { splittedStringList.add(txtStr.substring(start, Math.min(txtStr.length(), start + subStringSize))); } return splittedStringList; }
{ "pile_set_name": "StackExchange" }
Q: Best practise for PostgreSQL backup I'm writing a script for backing up PostgreSQL each night and I'm happy with doing a full database dump. I'm curious about how I should backing up though. Is it wise for me to first do a VACUUM and then a full dump? Does this reduce the size of the backed up file? (I will be compressing the file into a tar so I don't know if it even matters) Since the script will be backing up nightly, is there something like too much VACUUMing? Or should I leave VACUUM to another script that runs say once a month? A: VACUUM only affects the size of physical backups (pg_basebackup, etc), not logical backups (dumps). You don't need to. There's no such thing as too much VACUUM. It's harmless. You shouldn't need manual VACUUM though, just make sure autovacuum is enabled and set to run enough. I strongly advise that you use point-in-time recovery as well as logical backups though. See the manual. There are helper tools like pgbarman and WAL-E for this.
{ "pile_set_name": "StackExchange" }
Q: Laravel Database Queue, "Killed" after a few seconds i got a problem in my Laravel Project, i'm trying to transcode a video file with FFMPEG about 450MB in size and due to this taking a long time i'm using Queues in Laravel to do this. Due to the configuration of my production environment i have to use database queues the problem is that the queued job gets killed after about 60 seconds each time anytime i use the command php artisan queue:work in my Vagrant box. The Vagrant box has 4GB of Ram available, 2D and 3D acceleration enabled and the memory_peak_usage() command never lists anything above 20MB during this whole process. I checked the php_sapi_name() and it's cli as expected so it shouldn't have any limits at all when it comes to execution time, regardless i went to the cli php.ini file and removed any limits again to be certain. Tried rebooting Vagrant, getting Killed after a few seconds anyways. So i decided to try creating a Laravel Command for the transcoding process, i hardcoded the filepaths and stuff and lo and behold it's working without being Killed... Am i missing something about Queues? I'm just running php artisan queue:work i'm not specifing a timeout of any sort, why is my queue getting killed? Thank you in advance for your help. A: The default timeout for jobs is 60 seconds, as you've found out. The timeout is specified with the --timeout[=TIMEOUT] property, and disabling the timeout entirely is done with --timeout=0. php artisan queue:work --timeout=0
{ "pile_set_name": "StackExchange" }
Q: Countably generated sigma-algebras This question asks whether every family $\mathcal A\subseteq\mathcal P(X)$ is contained in a countably generated $\sigma$-algebra. (The OP stipulates that $\mathcal A$ is itself a $\sigma$-algebra, but that clearly doesn't matter.) The answers provide counterexamples with either $|\mathcal A|\gt2^{\aleph_0}$ or $|X|=2^{2^{\aleph_0}}.$ I would like to see a counterexample with $|\mathcal A|\le2^{\aleph_0}$ and $|X|\le2^{\aleph_0}.$ Question. Is there a family $\mathcal A\subset\mathcal P(\mathbb R)$ such that $|\mathcal A|\le2^{\aleph_0}$ and $\mathcal A$ is not contained in any countably generated $\sigma$-algebra? A: Claim: Under CH, there is no such family. Proof: Recall that $\mathcal{P}(\omega_1) \otimes \mathcal{P}(\omega_1) = \mathcal{P}(\omega_1 \times \omega_1)$ (a result of B. V. Rao, On discrete Borel spaces and projective sets, Bull Amer. Math. Soc. 75 (1969), 614–617). Given $\{A_i : i < \omega_1\} \in [\omega_1]^{\omega_1}$, choose $\{(X_n, Y_n): n < \omega\}$, $X_n, Y_n \subseteq \omega_1$, such that the sigma algebra generated by $\{X_n \times Y_n : n < \omega \}$ contains $\{(i, x): i < \omega_1, x \in A_i\}$. It follows that the sigma algebra generated by $\{Y_n : n < \omega\}$ contains each $A_i$. In the other direction, Arnold W. Miller, Generic Souslin sets, Pacific J. Math. 97 (1981), 171–181 showed that it is consistent that there is no countable family $\cal{F} \subseteq \mathcal{P}(\mathbb{R})$ such that the sigma algebra generated by $\mathcal{F}$ contains all analytic sets. So the existence of such a family is independent of ZFC.
{ "pile_set_name": "StackExchange" }
Q: Typed default arguments in destructuring parameters One of my favorite features of es6 is the ability to use destructuring parameters. For example: function example1({ bar = -1, transform = Math.abs } = {}) { transform(bar); } However, the typescript compiler generates an error when an explicit type needs to be assigned to one of the arguments (e.g. to give it greater flexibility than would be inferred by the default): type Formatter = { (n: number): (number | string) }; function example2({ bar = -1, transform: Formatter = Math.abs } = {}) { // ERROR: cannot find name 'transform' return transform(bar) + ' is the value'; } The only way around this I've found is to explicitly type the whole set of parameters - which seems overly complex when the remaining parameter types can be inferred: type Formatter = { (n: number): (number | string) }; type ExampleOpts = { bar?: number, transform?: Formatter }; function example3({ bar = -1, transform= Math.abs }: ExampleOpts = {}) { return transform(bar) + ' is the value'; } Thoughts? Is there are syntax that accomplishes #3 with the simplicity of #2 that I'm missing? A: type Formatter = { (n: number): (number | string) }; function example2({ bar = -1, transform = Math.abs as Formatter } = {}) { // ERROR: cannot find name 'transform' return transform(bar) + ' is the value'; } When using default parameters, you are aiming for type inference. If there's no type definition or you'd like to provide your own, simply cast it with the 'variable as type' syntax! :)
{ "pile_set_name": "StackExchange" }
Q: c#, html-agility-pack get text which is not inside tags This is my HTML: <a class="bla"></a> 25 oct 2012 How can I get only 25 oct 2012. The text is not inside any tags. I am using the c# htmlagilitypack library. A: Basically, you can use text() to reference text nodes in XPath. Try to pass the following XPath to HtmlAgilityPack's SelectNodes() or SelectSingleNode() method : //a[@class='bla']/following-sibling::text()[1] brief explanation : //a[@class='bla'] : find <a> element, anywhere in the HTML document, that have class attribute equals "bla"... /following-sibling::text()[1] : then from such <a> return the nearest text node that follows
{ "pile_set_name": "StackExchange" }
Q: Draw a border around shapes in the canvas with JavaFx I have drawn a straight line in a canvas and filled with a solid color. I want to border this straight line with a black colored border. A: You can use two fillRect with different size and color example: final Canvas canvas = new Canvas(250,250); GraphicsContext gc = canvas.getGraphicsContext2D(); gc.setFill(Color.BLUE); gc.fillRect(0,0,100,20); gc.setFill(Color.RED); gc.fillRect(1,1,98,18);
{ "pile_set_name": "StackExchange" }
Q: Same Values unable to be inserted in SAP table I have made two keys in the table in SAP, mandt and subject values of subject have to be repetitive. But I'm unable to insert same values. Error being shown is that 'an entry already exists with the same key. This error persists even after I remove subject as the key. This may be a silly question, but I'm new to world of SAP. A: The fact that those values are keys is the issue. You must use any other field that make them non-unique. I don't know your case but you can use another field, a sequence or a guid value. Hope it helps.
{ "pile_set_name": "StackExchange" }
Q: How to find out matching number and string in a text file using C# I am trying to read a string from a TEXT File inside the quotation ' ', which is a filepath. If the line contains "SSiJobPage:" and if it's matches the number next to it. Like If the line contains 'SSiJobPage: 8', then got to the line where 'SSiJobFileRef: 8' and get the file path next to it which is 'C:\folderName\012M032.filename.p1.pdf'. Also it will run until find all the 'SSiJobPage:' How can I do that in C#? Thanks so much in advance!! >%SSiJobFileRef: 2 'C:\folderName\210C001-3.filename.p1.pdf' 2 -1 0 0.00000 >%SSiJobFileRef: 3 'C:\folderName\210C001-3.filename.p2.pdf' 3 -1 0 0.00000 >%SSiJobFileRef: 4 'C:\folderName\210C001-3.filename.p3.pdf' 4 -1 0 0.00000 >%SSiJobFileRef: 5 'C:\folderName\210C001-3.filename.p4.pdf' 5 -1 0 0.00000 >%SSiJobFileRef: 6 'C:\folderName\210C001-3.filename.p5.pdf' 6 -1 0 0.00000 >%SSiJobFileRef: 7 'C:\folderName\210C001-3.filename.p6.pdf' 7 -1 0 0.00000 >%SSiJobFileRef: 8 'C:\folderName\012M032.filename.p1.pdf' 8 -1 0 0.00000 >%SSiJobFileRef: 9 'C:\folderName\002M052.filename.p1.pdf' 9 -1 0 0.00000 >%SSiJobFileRef: 10 'C:\folderName\012M042.filename.p1.pdf' 10 -1 0 0.00000 >%SSiJobFileRef: 11 'C:\folderName\002W000.filename.p1.pdf' 11 -1 0 0.00000 >%SSiJobFileRef: 12 'C:\folderName\012B000.filename.p1.pdf' 12 -1 0 0.00000 >%SSiJobFileRef: 13 'C:\folderName\002W100.filename.p1.pdf' 13 -1 0 0.00000 > >%SSiJobPage: 8 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 9 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 10 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 2 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 3 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 11 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 12 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 4 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 5 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 13 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 14 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 6 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 7 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 15 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 16 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 17 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 8 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 21 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 10 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 >%SSiJobPage: 18 1 0.00000 0.00000 1.00000 1.00000 3 0.00000 0.00000 '' 0 A: Maybe something like so: public class SSiJob { public int id { get; set; } public string path { get; set; } public bool matched { get; set; } } List<SSiJob> jobs = new List<SSiJob>(); using (StreamReader sr = new StreamReader(@"D:\CYA\Test2.txt")) { string stringy; while ((stringy = sr.ReadLine()) != null) { string[] words = stringy.TrimStart().Split(' '); if (words[0] == ">%SSiJobFileRef:") { jobs.Add(new SSiJob { id = Convert.ToInt32(words[1]), path = words[2] }); } else if (words[0] == ">%SSiJobPage:") { var check = jobs.Where(a => a.id == Convert.ToInt32(words[1])).FirstOrDefault(); if(check != null) { check.matched= true; } } } jobs.RemoveAll(a => a.matched == false); }
{ "pile_set_name": "StackExchange" }
Q: How to write from stdin to a pipe in C I have a program being called by the arguments: pipeline -f outfile2 < infile > outfile1 It is supposed to mimick the functionality of the bash script: (rev | sort | uniq -c | tee outfile2| wc) < infile > outfile1 I understand how to get the piping set up, but I do not understand how to get the initial read. I've captured the outfile2 filename to a variable, but I think I can keep the outer two and the operating system will pick them up as stdin and stdout respectively. How would I programatically read the stdin into a pipe in my parent process? UPDATE follows: The following code does nothing to modify the output files with the command line argument: pipeline -f outfile2 outfile1 obviously with real file names. main: char *fp; int c; /* parse command line arguments */ parse_argv(argc, argv); if (pipe(pipeOne) == -1){ /* Create the pipe */ perror("pipe one"); error(-1); } if (pipeOne[1] != 1){ dup2(pipeOne[1], stdout); exit(-1); } while ((c = getc(stdin)) != EOF){ if ((write(pipeOne[1], c, 1)) < 1) { perror("Write to pipe failed."); exit(-1); } } wc_child(); /* begin reading file to pipe */ if (close(pipeOne[0]) == -1){ /* Close unused read end */ perror("closing pipes"); exit(-1); } close (pipeOne[1]); wc_child: void wc_child(){ int numread; switch (fork()) { /* Create a child process */ case -1: perror("fork for rev_child"); case 0: /* Child */ /*if (close(pipeOne[1]) == -1) /* Close unused write end */ /*perror("closing pipes");*/ if (close(pipeOne[1]) == -1){ /* Close unused write end */ perror("closing pipes"); exit(-1); } dup2(pipeOne[0], stdin); /* dup2(pipeFive[0], stdin);*/ /* Not sure how to set up stdout since it will be going to a file.*/ for(;;){ execlp("wc","wc"); } break; default: /* Parent */ return 0; } return -1; /*return -1 because it never should reach this code. If it does that indicates a problem*/ } A: You could #include <unistd.h> and then read straight from the file descriptor STDIN_FILENO. dup2(pipeOne[0], stdin); should probably also use STDIN_FILENO, as stdin is a FILE * and not a descriptor. I don't think you really want to do any of that, though. Instead of reading from stdin, you should be hooking stdout up to the write end of a pipe (and the next stage of the pipeline to the read end) and then execing to begin the first stage of your pipeline. The invoked subprocess will then read from stdin, transform the input and write to stdout, filling the pipe with data.
{ "pile_set_name": "StackExchange" }
Q: Relational Database: When do we need to add more entities? We had a discussion today related to W3 lecture case study about how many entities we need for each situation. And I have some confusion as below: Case 1) An employee is assigned to be a member of a team. A team with more than 5 members will have a team leader. The members of the team elect the team leader. List the entity(s) which you can identify in the above statement? In this cases, if we don't create 2 entities for above requirement, we need to add two more attributes for each employee which can lead to anomaly issues later. Therefore, we need to have 2 entities as below: EMPLOYEE (PK is employeeId) (0-M)----------------(0-1) TEAM (PK teamId&employeeId) -> 2 entities Case 2) The company also introduced a mentoring program, whereby a new employee will be paired with someone who has been in the company longer." How many entity/ies do you need to model the mentoring program? The Answer from Lecturer is 1. With that, we have to add 2 more attributes for each Employee, mentorRole (Mentor or Mentee) and pairNo (to distinguish between different pairs and to know who mentors whom), doesn't it? My question is why can't we create a new Entity named MENTORING which will be similar to TEAM in Q1? And why we can only do that if this is a many-many relationship? EMPLOYEE (PK is employeeId) (0-M)----------------(0-1) TEAM (PK is pairNo&employeeId) -> 2 entities Thank you in advance A: First of all, about terminology: I use entity to mean an individual person, thing or event. You and I are two distinct entities, but since we're both members of StackOverflow, we're part of the same entity set. Entity sets are contrasted with value sets in the ER model, while the relational model has no such distinction. While you're right about the number of entity sets, there's some issues with your implementation. TEAM's PK shouldn't be teamId, employeeId, it should be only teamId. The EMPLOYEE table should have a teamId foreign key (not part of the PK) to indicate team membership. The employeeId column in the TEAM table could be used to represent the team leader and is dependent on the teamId (since each team can have only one leader at most). With only one entity set, we would probably represent team membership and leadership as: EMPLOYEE(employeeId PK, team, leader) where team is some team name or number which has to be the same for team members, and leader is a true/false column to indicate whether the employee in that row is the leader of his/her team. A problem with this model is that we can't ensure that a team has only one leader. Again, there's some issues with the implementation. I don't see the need to identify pairs apart from the employees involved, and having a mentorRole (mentor or mentee) indicates that the association will be recorded for both mentor and mentee. This is redundant and creates an opportunity for inconsistency. If the goal was to represent a one-to-one relationship, there are better ways. I suggest a separate table MENTORING(menteeEmployeeId PK, mentorEmployeeId UQ) (or possibly a unique but nullable mentorEmployeeId in the EMPLOYEE table, depending on how your DBMS handles nulls in unique indexes). The difference between the two cases is that teams can have any number of members and one leader, which is most effectively implemented by identifying teams separately from employees, whereas mentorship is a simpler association that is sufficiently identified by either of the two people involved (provided you consistently use the same role as identifier). You could create a separate entity set for mentoring, with relationships to the employees involved - it might look like my MENTORING table but with an additional surrogate key as PK, but there's no need for the extra identifier. And why we can only do that if this is a many-many relationship? What do you mean? Your examples don't contain a many-to-many relationship and we don't create additional entity sets for many-to-many relationships. If you're thinking of so-called "bridge" tables, you've got some concepts mixed up. Entity sets aren't tables. An entity set is a set of values, a table represents a relation over one or more sets of values. In Chen's original method, all relationships were represented in separate tables. It's just that we've gotten used to denormalizing simple one-to-one and one-to-many relationships into the same tables as entity attributes, but we can't do the same for many-to-many binary relationships or ternary and higher relationships in general.
{ "pile_set_name": "StackExchange" }
Q: mvc2 migration issue i migrate my mvc1 project to mvc2. my jquery json result function does not work anymore. have any idea ? aspx $.getJSON('Customer/GetWarningList/0', function(jsonResult) { $.each(jsonResult, function(i, val) { $('#LastUpdates').prepend(jsonResult[i].Url); }); }); controller public JsonResult GetWarningList(string id) { List<WarningList> OldBck = new List<WarningList>(); return this.Json(OldBck); } A: There has been a change to JsonResult in MVC 2 and therefore it will no longer work with HTTP GET to avoid Json hijacking. So you have two options a. return your results via HTTP Post or b. the JsonRequestBehavior property to JsonRequestBehavior.AllowGet There is an interesting article on how to modify here. or (more elegant) c. return Json(data, JsonRequestBehavior.AllowGet);
{ "pile_set_name": "StackExchange" }
Q: Avoid recompiling package after rename one table How to make package (pkg_test) not decompile while rename an internal table (rename table test_table to test_table_new) online to the table that is inside the package (pkg_test). In addition to this, there is a webservices that consults the package constantly and has it blocked while consuming it. One of the solutions was to use the command "alter package pkg_test compile" but the problem is that the webservices has already taken the package (pkg_test) and does not allow the action. A: Well, the right way I can think of is: don't do that. If you renamed a table that is used by a package, the package becomes invalid and you can't use it until you fix the error. Why do you rename the table? What benefit does it do? If possible, move code - that uses the TEST_TABLE - into dynamic SQL. Doing so, package won't be invalidated, but you still won't be able to use code that references the renamed table. Here's an example: Create sample table and a package (nothing fancy): SQL> create table test (datum date); Table created. SQL> insert into test values (sysdate); 1 row created. SQL> create or replace package pkg_test as 2 function f_right_now return date; 3 function f_max_datum return date; 4 end; 5 / Package created. SQL> create or replace package body pkg_test as 2 function f_right_now return date is 3 begin 4 return sysdate; 5 end; 6 7 function f_max_datum return date is 8 retval date; 9 begin 10 select max(datum) 11 into retval 12 from test; 13 return retval; 14 end; 15 end; 16 / Package body created. SQL> Let's see it work: SQL> select pkg_test.f_right_now, pkg_test.f_max_datum from dual; F_RIGHT_NO F_MAX_DATU ---------- ---------- 2018-10-01 2018-10-01 SQL> select object_type, status from user_objects where object_name = 'PKG_TEST'; OBJECT_TYPE STATUS ------------------- ------- PACKAGE VALID PACKAGE BODY VALID So far, so good. Now, rename the table and check package status again: SQL> rename test to test_new; Table renamed. SQL> select object_type, status from user_objects where object_name = 'PKG_TEST'; OBJECT_TYPE STATUS ------------------- ------- PACKAGE VALID PACKAGE BODY INVALID SQL> select pkg_test.f_right_now, pkg_test.f_max_datum from dual; select pkg_test.f_right_now, pkg_test.f_max_datum from dual * ERROR at line 1: ORA-04063: package body "SCOTT.PKG_TEST" has errors SQL> As expected - package body is now invalid and you can't use it. So, let's switch to dynamic SQL: SQL> create or replace package body pkg_test as 2 function f_right_now return date is 3 begin 4 return sysdate; 5 end; 6 7 function f_max_datum return date is 8 retval date; 9 begin 10 execute immediate 'select max(datum) from test' into retval; 11 return retval; 12 end; 13 end; 14 / Package body created. SQL> See? Oracle doesn't complain although table TEST doesn't exist any more. Package status is VALID: SQL> select object_type, status from user_objects where object_name = 'PKG_TEST'; OBJECT_TYPE STATUS ------------------- ------- PACKAGE VALID PACKAGE BODY VALID but you can't use the "invalid" function (while the "correct" one still works): SQL> select pkg_test.f_right_now, pkg_test.f_max_datum from dual; select pkg_test.f_right_now, pkg_test.f_max_datum from dual * ERROR at line 1: ORA-00942: table or view does not exist ORA-06512: at "SCOTT.PKG_TEST", line 10 SQL> select pkg_test.f_right_now from dual; F_RIGHT_NO ---------- 2018-10-01 SQL> SQL> select pkg_test.f_right_now, pkg_test.f_max_datum from dual; select pkg_test.f_right_now, pkg_test.f_max_datum from dual * ERROR at line 1: ORA-00942: table or view does not exist ORA-06512: at "SCOTT.PKG_TEST", line 10 SQL> One more rename? Sure, why not? SQL> rename test_new to test_littlefoot; Table renamed. SQL> select object_type, status from user_objects where object_name = 'PKG_TEST'; OBJECT_TYPE STATUS ------------------- ------- PACKAGE VALID PACKAGE BODY VALID SQL> select pkg_test.f_right_now from dual; F_RIGHT_NO ---------- 2018-10-01 SQL> select pkg_test.f_max_datum from dual; select pkg_test.f_max_datum from dual * ERROR at line 1: ORA-00942: table or view does not exist ORA-06512: at "SCOTT.PKG_TEST", line 10 Therefore, see it dynamic SQL works for you. In my opinion (once again) - don't rename tables "just because", you should have a valid reason to do that.
{ "pile_set_name": "StackExchange" }
Q: addstr causes getstr to return on signal I have a reworked python curses code with two 'threads' basically. They are not real threads - one main subwidow processing function, and the second, a different subwindow processing function, executing on the timer. And I ran into an interesting effect: The main window code is waiting for the user's input using getstr(). At the same time a timer interrupt would come and the interrupt code would output something in a different subwidow. The output from a timer function will cause getstr() to return with empty input. What can be causing this effect? Is there any way to avoid this effect other than checking the return string? Sample code to reproduce the problem: #!/usr/bin/env python # Simple code to show timer updates import curses import os, signal, sys, time, traceback import math UPDATE_INTERVAL = 2 test_bed_windows = [] global_count = 0 def signal_handler(signum, frame): global test_bed_windows global global_count if (signum == signal.SIGALRM): # Update all the test bed windows # restart the timer. signal.alarm(UPDATE_INTERVAL) global_count += 1 for tb_window in test_bed_windows: tb_window.addstr(1, 1, "Upd: {0}.{1}".format(global_count, test_bed_windows.index(tb_window))) tb_window.refresh() else: print("unexpected signal: {0}".format(signam)) pass def main(stdscr): # window setup screen_y, screen_x = stdscr.getmaxyx() stdscr.box() # print version version_str = " Timer Demo v:0 " stdscr.addstr(0, screen_x - len(version_str) - 1, version_str) stdscr.refresh() window = stdscr.subwin(screen_y-2,screen_x-2,1,1) for i in range(3): subwin = window.derwin(3,12,1,2 + (15*i)) test_bed_windows.append(subwin) subwin.box() subwin.refresh() signal.signal(signal.SIGALRM, signal_handler) signal.alarm(UPDATE_INTERVAL) # Output the prompt and wait for the input: window.addstr(12, 1, "Enter Q/q to exit\n") window.refresh() the_prompt = "Enter here> " while True: window.addstr(the_prompt) window.refresh() curses.echo() selection = window.getstr() curses.noecho() if selection == '': continue elif selection.upper() == 'Q': break else: window.addstr("Entered: {0}".format(selection)) window.refresh() if __name__ == '__main__': curses.wrapper(main) A: I suspect it's not the writing to the subwindow that's causing the getstr() to return an empty string, but rather the alarm signal itself. (Writing to a window from within an signal handler may not be well defined either, but that's a separate issue.) The C library Curses, which Python's curses module is often built on top of, will return from most of its blocking input calls when any signal (other than a few it handles internally) comes in. In C there's a defined API for the situation (the function returns -1 and sets errno to EINTER). The Python module says it will raise an exception if a curses function returns with an error. I'm not sure why it is not doing so in this case. Edit: A possible solution is to use a more programmer-friendly console UI library than curses. Urwid appears (in my brief browsing of the manual) to support event-driven UI updates (including updates on a timer) while simultaneously handling keyboard input. It may be easier to learn that than to deal with the sketchy and poorly documented interactions between signals and curses. Edit: from the man page for the getch(): The behavior of getch and friends in the presence of handled signals is unspecified in the SVr4 and XSI Curses documentation. Under historical curses implementations, it varied depending on whether the operating system's implementation of handled signal receipt interrupts a read(2) call in progress or not, and also (in some implementations) depending on whether an input timeout or non-blocking mode has been set. Programmers concerned about portability should be prepared for either of two cases: (a) signal receipt does not interrupt getch; (b) signal receipt interrupts getch and causes it to return ERR with errno set to EINTR. Under the ncurses implementation, handled signals never interrupt getch. I have tried using getch instead of getstr and it does return -1 on a signal. That (negative return value) would solve this problem if it was implemented by getstr. So now the option are (1) writing your own getstr with error handling or (2) using Urwid. Could this be a bug for Python library?
{ "pile_set_name": "StackExchange" }
Q: How to use fastScrollEnabled in RecyclerView? I am new to RecyclerView and I want to implement the fast scroll feature in RecyclerView like google contact application and search on the internet and i found that now Android provide officially New fastScrollEnabled boolean flag for RecyclerView. So my question is can someone provide the sample implementation of it. Here is the official document from google https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0 A: With Support Library 26, we can easily enable fast scrolling for RecyclerView. Let’s get to it! Let’s go over each property one by one : fastScrollEnabled : boolean value to enable the fast scrolling. Setting this as true will require that we provide the following four properties. fastScrollHorizontalThumbDrawable : A StateListDrawable that will be used to draw the thumb which will be draggable across the horizontal axis. fastScrollHorizontalTrackDrawable : A StateListDrawable that will be used to draw the line that will represent the scrollbar on horizontal axis. fastScrollVerticalThumbDrawable : A StateListDrawable that will be used to draw the thumb which will be draggable on vertical axis. fastScrollVerticalTrackDrawable : A StateListDrawable that will be used to draw the line that will represent the scrollbar on vertical axis. add in build.gradle dependencies { .... compile 'com.android.support:design:26.0.1' compile 'com.android.support:recyclerview-v7:26.0.1' .... } Since Support Library 26 has now been moved to Google’s maven repository, let’s include that in our project level build.gradle allprojects { repositories { jcenter() maven { url "https://maven.google.com" } } } activity_main.xml <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="wrap_content" app:fastScrollEnabled="true" app:fastScrollHorizontalThumbDrawable="@drawable/thumb_drawable" app:fastScrollHorizontalTrackDrawable="@drawable/line_drawable" app:fastScrollVerticalThumbDrawable="@drawable/thumb_drawable" app:fastScrollVerticalTrackDrawable="@drawable/line_drawable"> </android.support.v7.widget.RecyclerView> add below four xml file in your drawable folder, line_drawable.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/line"/> <item android:drawable="@drawable/line"/> </selector> line.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@android:color/darker_gray" /> <padding android:top="10dp" android:left="10dp" android:right="10dp" android:bottom="10dp"/> </shape> thumb_drawable.xml <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/thumb"/> <item android:drawable="@drawable/thumb"/> </selector> thumb.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <corners android:topLeftRadius="44dp" android:topRightRadius="44dp" android:bottomLeftRadius="44dp" /> <padding android:paddingLeft="22dp" android:paddingRight="22dp" /> <solid android:color="@color/colorPrimaryDark" /> </shape> A: Add the attributes to the RecyclerView tag in your layout file: <android.support.v7.widget.RecyclerView xmlns:app="http://schemas.android.com/apk/res-auto" ... app:fastScrollEnabled="true" app:fastScrollHorizontalThumbDrawable="@drawable/fast_scroll_thumb" app:fastScrollHorizontalTrackDrawable="@drawable/fast_scroll_track" app:fastScrollVerticalThumbDrawable="@drawable/fast_scroll_thumb" app:fastScrollVerticalTrackDrawable="@drawable/fast_scroll_track" /> Make two drawables. The "track" drawable can be any drawable, but the "thumb" drawable must be a state list drawable. Example drawable/fast_scroll_track.xml file: <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#80ffffff" /> </shape> Example drawable/fast_scroll_thumb.xml file: <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true"> <shape android:shape="rectangle"> <solid android:color="#ff0" /> </shape> </item> <item> <shape android:shape="rectangle"> <solid android:color="#fff" /> </shape> </item> </selector> A: As you know that, RecyclerView supports “fast scroller” in Support Library 26.0.0. Note: Keep in mind it’s XML-only though.
{ "pile_set_name": "StackExchange" }
Q: Haskell stack with global ghc Is it possible to use stack with an already installed ghc without stack installing a local copy of ghc or cabal? A: Yes. If the ghc in PATH is of right version for the selected snapshot, stack will happily use it. % ghc --version The Glorious Glasgow Haskell Compilation System, version 7.8.4 % stack --resolver=lts-2.22 install packdeps Run from outside a project, using implicit global project config Using resolver: lts-2.22 specified on command line packdeps-0.4.1: unregistering packdeps-0.4.2: download ... % stack --resolver=nightly-2015-12-25 install packdeps Run from outside a project, using implicit global project config Using resolver: nightly-2015-12-25 specified on command line Compiler version mismatched, found ghc-7.8.4 (x86_64), but expected minor version match with ghc-7.10.3 (x86_64) (based on resolver setting in /Users/phadej/.stack/global/stack.yaml). Try running "stack setup" to install the correct GHC into /Users/phadej/.stack/programs/x86_64-osx/ You can also skip ghc check --skip-ghc-check: % stack --resolver=nightly-2015-12-25 --skip-ghc-check install packdeps Run from outside a project, using implicit global project config Using resolver: nightly-2015-12-25 specified on command line split-0.2.2: configure ... but that might be a bad idea
{ "pile_set_name": "StackExchange" }
Q: parser for c++ headers to extract functions with standard linux tools? Is there something like this? I need to extract C++ functions from header files with all the parameters they use. It would be nice if i can use standard Linux programs A: You can use understand 4 C++ which is a front end tool that browse your source code and generate metrics for your source code. It also has a powerful API that allows you to write your own static analysis tools. So far understand works on windows, and a bunch of other linux based OS's. Though I've only used the windows based API. It is found at: http://scitools.com/
{ "pile_set_name": "StackExchange" }
Q: Generate alphanumeric 8-character strings in UNIX shell I mean sequentially generate all combinations of 8 alphanumeric characters. Like what you would use for bruteforcing an 8-digit password. A: I did not test this thoroughly, but it should be a start. #!/bin/sh declare -A aa=( [0]=1 [1]=2 [2]=3 [3]=4 [4]=5 [5]=6 [6]=7 [7]=8 [8]=9 [9]=A [A]=B [B]=C [C]=D [D]=E [E]=F [F]=G [G]=H [H]=I [I]=J [J]=K [K]=L [L]=M [M]=N [N]=O [O]=P [P]=Q [Q]=R [R]=S [S]=T [T]=U [U]=V [V]=W [W]=X [X]=Y [Y]=Z [Z]=a [a]=b [b]=c [c]=d [d]=e [e]=f [f]=g [g]=h [h]=i [i]=j [j]=k [k]=l [l]=m [m]=n [n]=o [o]=p [p]=q [q]=r [r]=s [s]=t [t]=u [u]=v [v]=w [w]=x [x]=y [y]=z [z]=0 ) bb=(0 0 0 0 0 0 0 0) while : do IFS= read ff <<< "${bb[*]}" echo $ff place=7 while : do bb[place]=${aa[${bb[place]}]} if [ ${bb[place]} = 0 ] then (( place-- )) else break fi done done
{ "pile_set_name": "StackExchange" }
Q: Magento 1.7.2 - How to include CMS pages in topmenu? I have created 2 CMS pages in magento 1.7.2 Lets say the cms page "About Us" which is the URL http://localhost/magento/index.php/about-company/?___store=default and the page "Customer Service" which is the URL http://localhost/magento/index.php/customer-service/?___store=default In my HEADER.PHTML the line getChildHtml('topMenu') ?> shows the topmenu. the problem is that the 'topMenu' contains only the categories created by Catalog->Manage Categories What is the appropriate way to include the 2 cms pages ("About Us" and "Customer Service") in the 'topMenu' ? Thank you for your help ! A: Create a static block for cms pages from admin and write the below format code <ul> <li><a href="{{store direct_url="about-company"}}">About Company</a></li> <li><a href="{{store direct_url="customer-service"}}">Customer Service</a></li> </ul> Call this block in topmenu.phtml (/template/page/html/topmenu.phtml) page <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('cms_pages')->toHtml();?>
{ "pile_set_name": "StackExchange" }
Q: How to install FFMPEG in PHP to encode video I want to know how this FFMPEG to integrate in php. I want to encode video. I got this link earlier to refer http://youtubeclone.wordpress.com/2007/05/26/how-to-convertencode-files-to-flv-using-ffmpeg-php/ but dont know where to point this $ffmpegPath = "/path/to/ffmpeg"; $flvtool2Path = "/path/to/flvtool2"; here we have to give the path "/path/to/ffmpeg", "/path/to/flvtool2". I am little bit confused what to do or how to integrate ffmpeg, flvtool2 in php A: exec("ffmpeg -i /tmp/orig.mov /tmp/output.mp4"); You don't need those $ffmpegPath variables on a properly configured system. Rather than employing pseudo security, you should escape input and output filenames using escapeshellarg(). Conversion options are available in the ffmpeg manual or man page. Google will know more about your flvtool2.
{ "pile_set_name": "StackExchange" }
Q: Simple encryptio/decryption doesn't seems to work, help me find what i am doing wrong Trying to make a simple encryption/decryption to use it in a simple communication protocol. It seems I can't make my decrypt method to work or maybe is the encryption method, the output text is not the original one. What am I doing wrong? String s1 = encrypt("Hello World!"); String s2 = decrypt(s1); public static String encrypt(String decStr) { byte[] key = new byte[]{ 92, -33, 70, 90, 42, -22, -76, 38, 37, 109, 26, -113, 125, 105, 66, 81, 17, 22, 21, -30, 87, -124, -85, 58, 40, -116, -100, 28, 37, 127, 51, 36 }; byte[] encBytes = decStr.getBytes(); int n = encBytes.length + 5; int k = key[encBytes.length % key.length] & 255; for (int i = 0; i < encBytes.length; i++) { encBytes[i] ^= key[(n + i) % key.length]; encBytes[i] ^= key[(k + i) % key.length]; } return new BigInteger(encBytes).toString(36); } public static String decrypt(String encStr) { byte[] key = new byte[]{ 92, -33, 70, 90, 42, -22, -76, 38, 37, 109, 26, -113, 125, 105, 66, 81, 17, 22, 21, -30, 87, -124, -85, 58, 40, -116, -100, 28, 37, 127, 51, 36 }; byte[] encBytes = new BigInteger(encStr, 36).toByteArray(); byte[] decBytes = Arrays.copyOfRange(encBytes, 1, encBytes.length); int n = decBytes.length + 5; int k = key[decBytes.length % key.length] & 255; for (int i = 0; i < decBytes.length; i++) { decBytes[i] ^= key[(n + i) % key.length]; decBytes[i] ^= key[(k + i) % key.length]; } return new String(decBytes); } A: byte[] decBytes = Arrays.copyOfRange(encBytes, 1, encBytes.length); You are starting from the second character. Change the 1 to a 0 byte[] decBytes = Arrays.copyOfRange(encBytes, 0, encBytes.length); Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case (byte)0 is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from. https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOfRange(byte[],%20int,%20int) Also, you are creating a new byte array and then immediately copying it into a second array but never use the original. It seems there is no need to perform this copy in the first place Test: Hello World! zxj9kxukhtsdmoll41 Hello World!
{ "pile_set_name": "StackExchange" }
Q: Name of fastening metal pieces holding the cardboard back to a picture frame? What do you call those thin metal pieces that fold to fasten the cardboard back on a picture frame? A: Points Thin metal tabs used to hold the mat, mount board and/or glazing inside of wood picture frames. Some points are stiff while others are flexible to allow access into the frame. https://www.framedestination.com/media/wysiwyg/points_1.jpg A: If you're asking about something like this: then they are clips. This image is from a page advertising "Wood picture frame spring clips" from webpictureframes.com. Other designs are available, including those which fit into a slot in the frame. This type isn't very adjustable for different thicknesses of cardboard but they are still clips (as are the hanging clips also shown here): (Image from dataliteframes.co.uk)
{ "pile_set_name": "StackExchange" }
Q: PHP if variable definitely is either value or value then I want to do a quick check to see if a user has access to view the page and so I have the function which simply returns the users access level when called and made that into a variable but would like to know how to write the if statement... This is what I have so far: if($uac_check == "Owner" OR "Admin") { echo "You have Access"; } else { echo "No access for you!"; } Is anyone able to help please? A: You'll need to test the value of $uac_check again. if($uac_check == "Owner" or $uac_check == "Admin") { Boolean operators like or and and need a boolean value on both sides of them. When you have an expression like $uac_check == "Owner", it evaluates to a true or false value, also known as a "boolean" value. You have $uac_check on the other side. Most variables will evaluate to true when cast as a boolean value unless they are empty, null or 0. That's likely to give you results you don't expect. Note that I re-wrote the OR operator as or. Both are valid, and so is || . One last note - you can make tests more specific to avoid "misunderstandings" in PHP. PHP is very lax about types, so it will tell you that "1" == 1 and 0 == false are true, when the 1 character and the number 1 are not the same thing, nor are 0 and false equal. You can avoid mistakes like this by using the === operator, which checks both value and type. This can be very important, especially with certain functions that can return 0 and false with two very different meanings. It's called the identical operator. You can read more about comparisons in the PHP manual on the Comparison Operators page. A: I think you want ternary operator. $access = ($uac_check == "Owner" || $uac_check == "Admin") ? 'You have Access' : 'No access for you!'; echo $access;
{ "pile_set_name": "StackExchange" }
Q: How does this litle program work? I tried to check QA exercices about C++ and one question drove me crazy !! typedef struct { unsigned int i : 1; } myStruct; int main() { myStruct s; s.i = 1; s.i++; cout << s.i; return 0; } The question said what is the ouput : 0/1/2/3/-1/Seg Error ? I did check 2 which is a wrong answer :D , so why does the program shows 0 ? A: You need to familiarize yourself with bitfields. By default int has size of 32 bits(4 bytes). But using the given notation, you can specify how many bits are used for the variable. So when you increment the value from 1, it overflows and returns to zero.
{ "pile_set_name": "StackExchange" }
Q: heroku dependencies fail I'm trying for the first time to deploy an app to heroku and I'm getting the following error. The list of gems on heroku includes this version of the bson gem, and my gemfile includes source 'http://rubygems.org' at the top. Can anyone suggest why the gem is not being found? -----> Heroku receiving push -----> Ruby/Rails app detected -----> Detected Rails is not set to serve static_assets Installing rails3_serve_static_assets... done -----> Configure Rails 3 to disable x-sendfile Installing rails3_disable_x_sendfile... done -----> Configure Rails to log to stdout Installing rails_log_stdout... done -----> Gemfile detected, running Bundler version 1.0.7 Unresolved dependencies detected; Installing... Using --without development:test Fetching source index for http://rubygems.org/ Could not find bson-1.4.1 in any of the sources FAILED: http://devcenter.heroku.com/articles/bundler ! Heroku push rejected, failed to install gems via Bundler A: Looks like the 1.4.1 version of BSON for Ruby was yanked - nothing to do with Heroku. http://rubygems.org/gems/bson/versions
{ "pile_set_name": "StackExchange" }
Q: Reference custom column created in SELECT I would like to reference column short hand names created above to greatly simplify a DATE_DIFF line for readability, but am unsure if this is allowed. Is something like below code possible? Notice that the inputs to the DATE_DIFF were initiated in the 2 preceding lines. SELECT DISTINCT Stuff , DATE_FORMAT(FROM_UNIXTIME(date1), '%Y-%d-%m') as Date_Start , DATE_FORMAT(FROM_UNIXTIME(date2), '%Y-%d-%m') as Date_End , DATE_DIFF( 'day' , Date_Start , Date_End) + 1 as Date_Delta , `<-- HERE More_Stuff FROM T1 LEFT JOIN T2 ON Stuff = More_Stuff LEFT JOIN T3 ON More_Stuff = Other_Stuff I am hoping to avoid nesting the full query for Date_Start & Date_End inside the DATE_DIFF or using yet another Join. If this is something that cannot be done, then the question can be converted to What is best practice for something like this and why? A: You would either be looking at: SELECT Stuff , Date_Start , Date_End , DATE_DIFF( 'day' , Date_Start , Date_End) + 1 as Date_Delta , More_Stuff FROM ( SELECT DISTINCT Stuff , DATE_FORMAT(FROM_UNIXTIME(date1), '%Y-%d-%m') as Date_Start , DATE_FORMAT(FROM_UNIXTIME(date2), '%Y-%d-%m') as Date_End , DATE_DIFF( 'day' , Date_Start , Date_End) + 1 as Date_Delta , More_Stuff FROM T1 LEFT JOIN T2 ON Stuff = More_Stuff LEFT JOIN T3 ON More_Stuff = Other_Stuff ) as Q Or: SELECT DISTINCT Stuff , DATE_FORMAT(FROM_UNIXTIME(date1), '%Y-%d-%m') as Date_Start , DATE_FORMAT(FROM_UNIXTIME(date2), '%Y-%d-%m') as Date_End , DATE_DIFF( 'day' , DATE_FORMAT(FROM_UNIXTIME(date1), '%Y-%d-%m') , DATE_FORMAT(FROM_UNIXTIME(date2), '%Y-%d-%m')) + 1 as Date_Delta , More_Stuff FROM T1 LEFT JOIN T2 ON Stuff = More_Stuff LEFT JOIN T3 ON More_Stuff = Other_Stuff To use a field in the SELECT part, it must exist in the FROM part.
{ "pile_set_name": "StackExchange" }
Q: Adding a view when a spinner item is selected I have a spinner. If selected item is (e.g) 1, then add EditText with button. I used switch method to check item_name. What you recommend in adding edittext with button? Is it a good way to create new layout? How can i add layout to screen? A: Inside your initial layout create a container layout to inflate with your desired generated views. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> </LinearLayout> </RelativeLayout> Then create the separate layouts (your_layout) that you want to generate upon spinner selection. When that happens, use a layout inflator to replace the container with the layout you want. LayoutInflater inflater = LayoutInflater.from(context); View layout = inflater.inflate(R.layout.your_layout, null, false); View container = inflater.inflate(R.id.container, null, false); container.addView(layout);
{ "pile_set_name": "StackExchange" }
Q: Open activity "B" from tabspec TA1 of tabhost and on backpressed of activity "B" tabhost should be set to "TA1" tabspec I am having four tabspec in tabhost TA1,TA2,TA3,TA4 in which i set current tab as TA2, I set four different activities for four tabspec A1, A2, A3 and A4 respectively, Activity A1 is set to TA1 and so on,then Activity A1 Open new activity B1, when i pressed back button from activity B1 the tab should be set to TA1 not to default TA2, How can i achieve above task in tab host, I tried to store current index of tab into shared preferences and onResume i read int value of current tab from shared preferences, but this way i was not able to achieve above task, Please let me know if anyone knows the best solution. A: Hi Friends i resolved my issue by passing value through intent to main tab activity, here below is sample code,Set this code lines to child activity of tab that means if i relate to above question child activity is "B1", Intent homeIntent = new Intent(SelectFetchee.this, Home.class); homeIntent.putExtra("tabvalue", "2"); startActivity(homeIntent); Then in main activity that have tabhost in which i collect the string String crntTab = getIntent().getStringExtra("tabvalue"); if (crntTab == null) { tabHost.setCurrentTab(2); } else if (crntTab.toString().equals("4")) { tabHost.setCurrentTab(4); } else if (crntTab.toString().equals("2")) { tabHost.setCurrentTab(2); } else if (crntTab.toString().equals("3")) { tabHost.setCurrentTab(3); } else if (crntTab.toString().equals("0")) { tabHost.setCurrentTab(0); } else if (crntTab.toString().equals("1")) { tabHost.setCurrentTab(1); }
{ "pile_set_name": "StackExchange" }
Q: Intercepting RDTSC instruction in KVM I am trying to debug a rootkit in a virtual environment. From reversing I know that it uses super simple CPU timing checks, that look something like this (source pafish): static inline unsigned long long rdtsc_diff_vmexit() { unsigned long long ret, ret2; unsigned eax, edx; __asm__ volatile("rdtsc" : "=a" (eax), "=d" (edx)); ret = ((unsigned long long)eax) | (((unsigned long long)edx) << 32); /* vm exit forced here. it uses: eax = 0; cpuid; */ __asm__ volatile("cpuid" : /* no output */ : "a"(0x00)); /**/ __asm__ volatile("rdtsc" : "=a" (eax), "=d" (edx)); ret2 = ((unsigned long long)eax) | (((unsigned long long)edx) << 32); return ret2 - ret; } int cpu_rdtsc() { int i; unsigned long long avg = 0; for (i = 0; i < 10; i++) { avg = avg + rdtsc_diff(); Sleep(500); } avg = avg / 10; return (avg < 750 && avg > 0) ? FALSE : TRUE; } It's calling rdtsc instruction with cpuid in between. The issue is that this simple check will detect presence of KVM. I want to overcome that. As it was stated in this question (and mailing list), I cloned Linux kernel source (5.4.0 stable) and edited these files accordingly: arch/x86/kvm/vmx/vmx.c (around 2300, setup_vmcs_config): min = CPU_BASED_HLT_EXITING | #ifdef CONFIG_X86_64 CPU_BASED_CR8_LOAD_EXITING | CPU_BASED_CR8_STORE_EXITING | #endif CPU_BASED_CR3_LOAD_EXITING | CPU_BASED_CR3_STORE_EXITING | CPU_BASED_UNCOND_IO_EXITING | CPU_BASED_MOV_DR_EXITING | CPU_BASED_USE_TSC_OFFSETTING | CPU_BASED_MWAIT_EXITING | CPU_BASED_MONITOR_EXITING | CPU_BASED_INVLPG_EXITING | CPU_BASED_RDPMC_EXITING | CPU_BASED_RDTSC_EXITING; // <- added this opt = CPU_BASED_TPR_SHADOW | CPU_BASED_USE_MSR_BITMAPS | CPU_BASED_ACTIVATE_SECONDARY_CONTROLS; if (adjust_vmx_controls(min, opt, MSR_IA32_VMX_PROCBASED_CTLS, &_cpu_based_exec_control) < 0) return -EIO; arch/x86/kvm/vmx/vmx.c (around 5500): static int (*kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = { [EXIT_REASON_EXCEPTION_NMI] = handle_exception_nmi, [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt, [EXIT_REASON_TRIPLE_FAULT] = handle_triple_fault, [EXIT_REASON_NMI_WINDOW] = handle_nmi_window, [EXIT_REASON_IO_INSTRUCTION] = handle_io, [EXIT_REASON_CR_ACCESS] = handle_cr, [EXIT_REASON_DR_ACCESS] = handle_dr, [EXIT_REASON_CPUID] = kvm_emulate_cpuid, [EXIT_REASON_MSR_READ] = kvm_emulate_rdmsr, [EXIT_REASON_MSR_WRITE] = kvm_emulate_wrmsr, [EXIT_REASON_INTERRUPT_WINDOW] = handle_interrupt_window, [EXIT_REASON_HLT] = kvm_emulate_halt, [EXIT_REASON_INVD] = handle_invd, [EXIT_REASON_INVLPG] = handle_invlpg, [EXIT_REASON_RDPMC] = handle_rdpmc, [EXIT_REASON_VMCALL] = handle_vmcall, [EXIT_REASON_VMCLEAR] = handle_vmx_instruction, [EXIT_REASON_VMLAUNCH] = handle_vmx_instruction, [EXIT_REASON_VMPTRLD] = handle_vmx_instruction, [EXIT_REASON_VMPTRST] = handle_vmx_instruction, [EXIT_REASON_VMREAD] = handle_vmx_instruction, [EXIT_REASON_VMRESUME] = handle_vmx_instruction, [EXIT_REASON_VMWRITE] = handle_vmx_instruction, [EXIT_REASON_VMOFF] = handle_vmx_instruction, [EXIT_REASON_VMON] = handle_vmx_instruction, [EXIT_REASON_TPR_BELOW_THRESHOLD] = handle_tpr_below_threshold, [EXIT_REASON_APIC_ACCESS] = handle_apic_access, [EXIT_REASON_APIC_WRITE] = handle_apic_write, [EXIT_REASON_EOI_INDUCED] = handle_apic_eoi_induced, [EXIT_REASON_WBINVD] = handle_wbinvd, [EXIT_REASON_XSETBV] = handle_xsetbv, [EXIT_REASON_TASK_SWITCH] = handle_task_switch, [EXIT_REASON_MCE_DURING_VMENTRY] = handle_machine_check, [EXIT_REASON_GDTR_IDTR] = handle_desc, [EXIT_REASON_LDTR_TR] = handle_desc, [EXIT_REASON_EPT_VIOLATION] = handle_ept_violation, [EXIT_REASON_EPT_MISCONFIG] = handle_ept_misconfig, [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause, [EXIT_REASON_MWAIT_INSTRUCTION] = handle_mwait, [EXIT_REASON_MONITOR_TRAP_FLAG] = handle_monitor_trap, [EXIT_REASON_MONITOR_INSTRUCTION] = handle_monitor, [EXIT_REASON_INVEPT] = handle_vmx_instruction, [EXIT_REASON_INVVPID] = handle_vmx_instruction, [EXIT_REASON_RDRAND] = handle_invalid_op, [EXIT_REASON_RDSEED] = handle_invalid_op, [EXIT_REASON_PML_FULL] = handle_pml_full, [EXIT_REASON_INVPCID] = handle_invpcid, [EXIT_REASON_VMFUNC] = handle_vmx_instruction, [EXIT_REASON_PREEMPTION_TIMER] = handle_preemption_timer, [EXIT_REASON_ENCLS] = handle_encls, [EXIT_REASON_RDTSC] = handle_rdtsc, // <- added exit handler }; and finally defined the exit handler itself right above it (just to test if the handling works): static int handle_rdtsc(struct kvm_vcpu *vcpu) { printk("[vmkernel] handling fake rdtsc from cpl %i\n", vmx_get_cpl(vcpu)); uint64_t data; data = 123; vcpu->arch.regs[VCPU_REGS_RAX] = data & -1u; vcpu->arch.regs[VCPU_REGS_RDX] = (data >> 32) & -1u; skip_emulated_instruction(vcpu); return 1; } And as I was afraid, after building the kernel, running the VM and inspecting dmesg, I can't see anything. Also the measured difference is completely the same and unchanged. What else do I need to edit in order for the handler to be actually called and used? I am building the kernel with all options set to default (run make menuconfig -> save). Of course I also checked that the kernel is booted and that Qemu is using KVM for the VM. Any ideas would be appreciated. Thanks. A: Well... The code above that I posted works, but only on Intel CPUs. Sadly I did not notice that. To make it work on AMD CPU, I needed to modify arch/x86/kvm/svm/svm.c: static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = { [SVM_EXIT_READ_CR0] = cr_interception, [SVM_EXIT_READ_CR3] = cr_interception, [SVM_EXIT_READ_CR4] = cr_interception, [SVM_EXIT_READ_CR8] = cr_interception, [SVM_EXIT_CR0_SEL_WRITE] = cr_interception, [SVM_EXIT_WRITE_CR0] = cr_interception, [SVM_EXIT_WRITE_CR3] = cr_interception, [SVM_EXIT_WRITE_CR4] = cr_interception, [SVM_EXIT_WRITE_CR8] = cr8_write_interception, [SVM_EXIT_READ_DR0] = dr_interception, [SVM_EXIT_READ_DR1] = dr_interception, [SVM_EXIT_READ_DR2] = dr_interception, [SVM_EXIT_READ_DR3] = dr_interception, [SVM_EXIT_READ_DR4] = dr_interception, [SVM_EXIT_READ_DR5] = dr_interception, [SVM_EXIT_READ_DR6] = dr_interception, [SVM_EXIT_READ_DR7] = dr_interception, [SVM_EXIT_WRITE_DR0] = dr_interception, [SVM_EXIT_WRITE_DR1] = dr_interception, [SVM_EXIT_WRITE_DR2] = dr_interception, [SVM_EXIT_WRITE_DR3] = dr_interception, [SVM_EXIT_WRITE_DR4] = dr_interception, [SVM_EXIT_WRITE_DR5] = dr_interception, [SVM_EXIT_WRITE_DR6] = dr_interception, [SVM_EXIT_WRITE_DR7] = dr_interception, [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception, [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception, [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception, [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception, [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception, [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception, [SVM_EXIT_EXCP_BASE + GP_VECTOR] = gp_interception, [SVM_EXIT_INTR] = intr_interception, [SVM_EXIT_NMI] = nmi_interception, [SVM_EXIT_SMI] = nop_on_interception, [SVM_EXIT_INIT] = nop_on_interception, [SVM_EXIT_VINTR] = interrupt_window_interception, [SVM_EXIT_RDPMC] = rdpmc_interception, [SVM_EXIT_CPUID] = cpuid_interception, [SVM_EXIT_IRET] = iret_interception, [SVM_EXIT_INVD] = emulate_on_interception, [SVM_EXIT_PAUSE] = pause_interception, [SVM_EXIT_HLT] = halt_interception, [SVM_EXIT_INVLPG] = invlpg_interception, [SVM_EXIT_INVLPGA] = invlpga_interception, [SVM_EXIT_IOIO] = io_interception, [SVM_EXIT_MSR] = msr_interception, [SVM_EXIT_TASK_SWITCH] = task_switch_interception, [SVM_EXIT_SHUTDOWN] = shutdown_interception, [SVM_EXIT_VMRUN] = vmrun_interception, [SVM_EXIT_VMMCALL] = vmmcall_interception, [SVM_EXIT_VMLOAD] = vmload_interception, [SVM_EXIT_VMSAVE] = vmsave_interception, [SVM_EXIT_STGI] = stgi_interception, [SVM_EXIT_CLGI] = clgi_interception, [SVM_EXIT_SKINIT] = skinit_interception, [SVM_EXIT_WBINVD] = wbinvd_interception, [SVM_EXIT_MONITOR] = monitor_interception, [SVM_EXIT_MWAIT] = mwait_interception, [SVM_EXIT_XSETBV] = xsetbv_interception, [SVM_EXIT_RDPRU] = rdpru_interception, [SVM_EXIT_NPF] = npf_interception, [SVM_EXIT_RSM] = rsm_interception, [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception, [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception, [SVM_EXIT_RDTSC] = handle_rdtsc_interception, // added handler }; in init_vmcb: set_intercept(svm, INTERCEPT_WBINVD); set_intercept(svm, INTERCEPT_XSETBV); set_intercept(svm, INTERCEPT_RDPRU); set_intercept(svm, INTERCEPT_RSM); set_intercept(svm, INTERCEPT_RDTSC); // added if (!kvm_mwait_in_guest(svm->vcpu.kvm)) { set_intercept(svm, INTERCEPT_MONITOR); set_intercept(svm, INTERCEPT_MWAIT); } then defining the handler itself again: static int handle_rdtsc_interception(struct vcpu_svm *svm) { printk("[vmkernel] handling fake rdtsc (AMD) from cpl %i\n", svm_get_cpl(&svm->vcpu)); svm->vcpu.arch.regs[VCPU_REGS_RAX] = last_tick & -1u; svm->vcpu.arch.regs[VCPU_REGS_RDX] = (last_tick >> 32) & -1u; skip_emulated_instruction(&svm->vcpu); return 1; }
{ "pile_set_name": "StackExchange" }
Q: Adding each new value of a String 'temp' value to ArrayList without overwriting previous 'temp' My input is coming from a socket using DataInputSteam and because I can have several different String values all being assigned to same clientDayOfWeek string, I cannot figure out how to save all the string values coming in into the same ArrayList without replacing the last value. I'd also like no duplicates if possible. Socket socket = null; DataInputStream dataInputStream = null; dataInputStream = new DataInputStream( socket.getInputStream()); String clientDayOfWeek = dataInputStream.readUTF(); ArrayList<String> ar = new ArrayList<String>(); String temp = clientDayOfWeek; ar.add(temp); System.out.print("Items in list: "+ ar); A: Thanks Prasaanth, that's what I was doing wrong. I needed my ArrayList<String> ar = new ArrayList<String>(); to be global and simplified the rest as follows inside my method. dataInputStream = new DataInputStream( socket.getInputStream()); ar.add(dataInputStream.readUTF()); System.out.print("ar: "+ar);
{ "pile_set_name": "StackExchange" }
Q: Folder and file are not getting created by Java code under Linux, but it works for Windows I have a few questions about Java's io.file class Linux: does the file seperator operator '//' work or do we need to use '\'? In red hat there is no drive partion name so how to give the Linux equivalent of the Windows path 'c://TempFolder//Images//'? A: You can use the static field File.separator or, better, use the nio Paths class like this: File f = Paths.get( "dir1", "dir2", "dir3" ).toFile(); To get something to refer to the absolute path, start the String arguments with a File.separator, which you might get also with nio with this method: http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html#getSeparator%28%29 A: Under Windows: File file = new File("C:\\TempFolder\\Images"); File file = new File("C:/TempFolder/Images"); // Because Windows soemtimes is nice. Under Linux: File file = new File("/TempFolder/Images"); The reason having two backslashes (\\), is that in strings a backslash must be escaped: \t being a tab character etcetera. There are no drive letters in Linux, if that was your question. For temporary files you might use File.createTemporaryFile or createTemporaryDirectory. Directories on other computers may also be used without drive letters, but with UNC paths: Windows: \\Server\Directory\Directory "\\\\Server\\Directory\\Directory" Linux: //Server/Directory/Directory
{ "pile_set_name": "StackExchange" }
Q: System calls, AWK, and Bringing in external inputs awk '{ TEMPVAR="/usr/bin"; printf("%s", system("ls $TEMPVAR")); }' empty In this example I'm trying to bring in the variable TEMPVAR into the system call. How would I do this? What I'm aiming to do: I'm trying to use date -d $0 +%s in a system call that occurs every line of a file. However, I'm struggling with how to get that $0 value into the system call. A: awk can access environment variables using the ENVIRON special array. However, while you can assign values to elements of that array, it is not passed in the environment of the commands executed by awk's system, | getline or print |. That ENVIRON array is only intended for awk to get the value of the environment variables it is passed. You can do: system("ls " var), but beware that the string that is passed to awk's system() (or print | or | getline) is actually passed as an argument to sh -c, so it is interpreted as shell code. For instance, if the awk var variable contains foo;rm -rf /, it will not tell ls to list the file called "foo;rm -rf /" but instead to list the file called foo and then the rm command will be run. So, you may need to escape all the characters special to the shell in that var variable. This could be done for instance with: awk ' function escape(s) { gsub(/'\''/, "&\\\\&&", s) return "'\''" s "'\''" } { cmd = "date -d " escape($0) " +%s" cmd | getline seconds close(cmd) print seconds }' While that means running one shell and one date command per line, you might as well do the reading of the file with the shell itself: while IFS= read <&3 -r line; do date -d "$line" +%s done 3< the-file
{ "pile_set_name": "StackExchange" }
Q: Fragment not attached to activity when using resource file I have an activity that loaded a string array directly into it private String[] questions = {"Q1", "Q2", "Q3"}; private String[] answers= {"A1", "A2", "A3"}; I wanted to change it to load from a resource file Resource File named Questions <string-array name="questions"> <item>Q1</item> <item>Q2</item> <item>Q3</item> </string-array> <string-array name="answers"> <item>A1</item> <item>A2</item> <item>A3</item> </string-array> Changed the string array to private String[] questions = getResources().getStringArray(R.array.questions); private String[] answers= getResources().getStringArray(R.array.answers); When I changed it to pull the string array from my resource file it gives me java.lang.IllegalStateException: My_Fragment{38ad4cd} not attached to Activity A: What's going on? What your actual code does is that it tries to access the resources when the Fragment is instantiated, which is wrong because the resources won't be available unless your Fragment is attached to some Activity. Plus The call getResources() is just a shortcut to getActivity().getResources(). My guess is that its implementation looks like this: if(isAttached()) { return getActivity().getResources(); } else { throw new RuntimeException("Fragment is not attached..."); } Solution Move this initialization: private String[] questions = getResources().getStringArray(R.array.questions); private String[] answers = getResources().getStringArray(R.array.answers); To your onCreateView method: private String[] questions; private String[] answers; public void onCreateView(...){ // ... questions = getResources().getStringArray(R.array.questions); answers = getResources().getStringArray(R.array.answers); // ... } Note You're safe to move this initialization anywhere in between onAttach and onDetach callbacks. Check the fragment life-cycle to get a clear idea. Similar question but with an activity App crashing when fetching from string ressources.
{ "pile_set_name": "StackExchange" }
Q: How to structure data to easily build HTML tables in Flask I am trying to create HTML tables from data stored in a table. My data is read from a table and converted into a dict of lists, e.g.: x = {'date':[u'2012-06-28', u'2012-06-29', u'2012-06-30'], 'users': [405, 368, 119]} My goal is to create an HTML table with the following structure for an arbitrary list length: <table> <thead> <th>Date</th> <th>Users</th> </thead> <tbody> <tr> <td>2012-06-28</td> <td>405</td> </tr> <tr> <td>2012-06-29</td> <td>368</td> </tr> <tr> <td>2012-06-30</td> <td>119</td> </tr> </tbody> </table> I have tried doing this two incorrect ways in my Flask template: <tbody> {% for line in x %} <tr> <td>{{ x.date|tojson|safe }}</td> <td>{{ x.users }}</td> </tr> {% endfor %} </tbody> Which prints the entire list into each column. And: {% for date in x.date %} <tr><td>{{ date|tojson|safe }}</td></tr> {% endfor %} {% for users in x.users %} <tr><td>{{ users }}</td></tr> {% endfor %} Which simply prints everything into the first column. These experiments and many other dead ends lead me to believe that there is no simple way to build the table as I would like given my current data structure. Given this, I have two questions: 1) How would I go about building the table using my current data structure? 2) What is the standard or ideal way to structure data for this use case? Thanks in advance. A: Like you said, you could either change your data structure, or change your template code. Here is one way to keep the current structure: {% for row_index in range(x['date']|count) %} <tr> <td>{{ x['date'][row_index]|tojson|safe }}</td> <td>{{ x['users'][row_index] }}</td> </tr> {% endfor %} Or you could restructure your data in python: x = zip(x['date'], x['users']) And then use this template: {% for row in x %} <tr> <td>{{ row[0]|tojson|safe }}</td> <td>{{ row[1] }}</td> </tr> {% endfor %} You can also structure the data so that the template does not depend on the order of the cells: from itertools import izip x = [dict(date=d, user=u) for d, u in izip(x['date'], x['users'])] Then you can access your data like this: {% for row in x %} <tr> <td>{{ row['date']|tojson|safe }}</td> <td>{{ row['user'] }}</td> </tr> {% endfor %} A: You might use Flask-Table or for something more complex even leverage Flask-Admin.
{ "pile_set_name": "StackExchange" }
Q: Can IRA save me money? Basically, wife and I made low income in 2016, I have an inherited IRA now, and want to know if I should take a $9k chunk of it for 2016 (I have one day left to decide). If I do, it will be taxed at 10% because we're in that bracket--but I'll lose another ~14% in Premium Tax Credit for my Healthcare Marketplace-selected health insurance, so 24% tax. We don't plan on staying in this super-low tax bracket for 2017 and beyond. If I take a $9k distribution now, can I offset my 2016 income with a $9k traditional IRA? Not a Roth IRA (because then I'd be paying the 24%), but a regular IRA. As I understand it, regular IRA contributions reduce your MAGI used for figuring the Premium Tax Credit. The $9k would go into the IRA before April (I don't have to rush to open it). I'd then pay tax on that IRA when I withdrew the funds at retirement, when, I assume, I will be again in a low(ish) tax bracket (15% I'd guess?). Upside: I may reduce taxes on $9k and save $810. Downside: Won't reunite with this money for 20+ years, so don't have added flexibility that I currently have with this inherited IRA. I don't need the $9k as cash, I don't think, and hope to never have to be in the position to cash out early and take the 10% tax penalty. Am I thinking right? A: TL; DR version: What you propose to do might not save you taxes, and may well be illegal. Since you mention your wife, I assume that the Inherited IRA has been inherited from someone other than your spouse; your mother, maybe, who passed away in Fall 2015 as mentioned in your other question (cf. the comment by Ben Miller above)? If so, you must take (at least) the Required Minimum Distribution (RMD) from the Inherited IRA each year and pay taxes on the distribution. What the RMD is depends on how old the Owner of the IRA was when the Owner passed away, but in most cases, it works out to be the RMD for you, the Beneficiary, considered to be a Single Person (see Publication 590b, available on the IRS web site for details). So, Have you taken the (at least) the RMD amount for 2016 from this Inherited IRA? If not, you will owe a 50% penalty of the difference between the amount withdrawn and the RMD amount. No, it is not a typo; the penalty (it is called an excise tax) is indeed 50%. Assuming that the total amount that you have taken as a Distribution from the Inherited IRA during 2016 is the RMD for 2016 plus possibly some extra amount $X, then that amount is included in your taxable income for that year. You cannot rollover any part of the total amount distributed into your own IRA and thereby avoid taxation on the money. Note that it does not matter whether you will be rolling over the money into an existing IRA in your name or will be establishing a new rollover IRA account in your name with the money: the prohibition applies to both ways of handling the matter. If you wish, you can roll over up to $X (the amount over and above the RMD) into a new Inherited IRA account titled exactly the same as the existing Inherited IRA account with a different custodian. If you choose to do so, then the amount that you roll over into the new Inherited IRA account will not included in your taxable income for 2016. To my mind, there is no point to doing such a rollover unless you are unhappy with the current custodian of your Inherited IRA, but the option is included for completeness. Note that the RMD amount cannot be rolled over in this fashion; only the excess over the RMD. If you don't really need to spend the money distributed from your Inherited IRA for your household expenses (your opening statement that your income for 2016 is low might make this unlikely), and (i) you and/or your spouse received compensation (earned income such as wages, salary, self-employment income, commissions for sales, nontaxable combat pay for US Military Personnel, etc) in 2016, and (ii) you were not 70.5 years of age by December 2016, then you and your wife can make contributions to existing IRAs in your names or establish new IRAs in your names. The amount that can be contributed for each IRA is limited to the smaller of $5500 ($6500 for people over 50) and that person's compensation for 2016, but if a joint tax return is filed for 2016, then both can make contributions to their IRAs as long as the sum of the amounts contributed to the IRAs does not exceed the total compensation reported on the joint return. The deadline for making such IRA contributions is the due date for your 2016 Federal income tax return. Since your income for 2016 is less than $98K, you can deduct the entire IRA contribution even if you or your wife are covered by an employer plan such as a 401(k) plan. Thus, your taxable income will be reduced by the IRA contributions (up to a maximum of $11K (or $12 K or $13K depending on ages)) and this can offset the increase in taxable income due to the distribution from the Inherited IRA. Since money is fungible, isn't this last bullet point achieving the same result as rolling over the entire $9.6K (including the RMD) into an IRA in your name, the very thing that the first bullet point above says cannot be done? The answer is that it really isn't the same result and differs from what you wanted to do in several different ways. First, the $9.6K is being put into IRAs for two different people (you and your wife) and not just you alone. Should there, God forbid, be an end to the marriage, that part of your inheritance is gone. Second, you might not even be entitled to make contributions to IRAs (no compensation, or over 70.5 years old in 2016) which would make the whole thing moot. Third, the amount that can be contributed to an IRA is limited to $5500/$6500 for each person. While this does not affect the present case, if the distribution had been $15K instead of $9.6K, not all of that money could be contributed to IRAs for you and your wife. Finally, the contribution to a Traditional IRA might be non-deductible for income tax purposes because the Adjusted Gross Income is too high; once again, not an issue for you for 2016 but something to keep in mind for future years. In contrast, rollovers from one IRA into another IRA (both titled the same) can be in any amount, and they can be done at any time regardless of whether there is compensation for that year or not or what the Adjusted Gross Income is or whether there is coverage by a 401(k) plan. There are no tax consequences to rollovers unless the rollover is from a Traditional IRA to a Roth IRA in which case, the distribution is included in taxable income for that year. What is prohibited is taking the entire amount of the $9.6K distribution from an Inherited IRA and rolling it over into your existing IRA (or establishing a Rollover IRA in your name with that $9.6K); ditto for some money going into your IRA and some into your wife's IRA. I expect that any IRA custodian will likely refuse to allow you to carry out such a rollover transaction but will be glad to accept 2016 contributions (in amounts of up to $5500/$6500) from you into existing IRAs or open a new IRA for you. The custodian will not ask whether you have compensation for 2016 or not (but will check your age!); it is your responsibility to ensure that you do not contribute more than the compensation etc. Incidentally, subject to the $5500/6500 maximum limit, you can (if you choose to do so) contribute the entire amount of your compensation to an IRA, not just the take-home pay amount (which will be smaller than your compensation because of withholding for Social Security and Medicare tax, State and Federal income tax, etc).
{ "pile_set_name": "StackExchange" }
Q: Bootstrapping all inbound requests via API gateway This may seem like an interesting/odd request but I was wondering if there's a way API gateway could be taught to respond to all requests as to act as a bootstrap/route manager for an API layer? Basically all requests ie. /getUser, /getLocation, /getManager could be written as one API Gateway endpoint rule? Here's the idea...all GET requests no matter the path on the API get routed to a Lambda function which parses the request and envokes the proper delegate function. Similar rules would be setup for POST, DELETE and PUT. So basically the API gateway would only have 4-5 registered points that all map to the same Lambda function. I'm conducting some early research into different patterns/approaches to gateway usage and was wondering if it would be possible to factor something such as this. There's advantages and disadvantages to this but I just want to know if it could be scripted this way. Thanks. A: You can use request path parameters with API Gateway. You could create several endpoints like these ones: GET /{param1} GET /{param1}/{param2} GET /{param1}/{param2}/{param3} These endpoints should match whatever url that has up to 3 path parameters. They can be configured to call the same Lambda. In the integration request configuration, we could use something like this for the mapping template (we could add data from the body, query string and header too ...): { "endpoint": { "path": "/$input.params('param1')/$input.params('param2')/$input.params('param3')", "method": "$context.httpMethod" } } Then in the lambda event, we would be able to know the HTTP method and the resource path and execute the appropriate portion of code. An advantage would be to use more often the same lambda and improve its average performance. Indeed, if you make successive calls to a lambda, chances are that AWS re-use the same container to execute it and you don't need time to "warm it up". Using the same lambda more often should reduce the proportion of "warm up" depending on the frequency of executions. A disadvantage is to loose the "microservice" aspect of using Lambda because all your application would be embed in only one Lambda. Another disadvantage of course is that you will have to code routing rules and execute them in the Lambda.
{ "pile_set_name": "StackExchange" }
Q: How to make all org-files under a folder added in agenda-list automatically? I am using org-mode to write notes and org-agenda to organize all notes, especially to search some info. by keyword or tag. C-c a m can search some files by tag inputed, C-c a s by keyword ,those functions from org-agenda are well to utilize, however, I need to add org-file into the agenda-list by hand. I added some codes into .emacs, such as (setq org-agenda-files (list "path/folder/*.org")) or (setq org-agenda-files (file-expand-wildcards "path/folder/*.org")) but, both failed to add files under the folder specified into agenda-list automatically, so I can't search keyword or tag among those org-files, unless that I open a org-file and type C-c [ to add it into agenda-list. How can I make all org-files under a folder automatically added in agenda? A: Just naming the directory should be enough. For example this works for me very well: (setq org-agenda-files '("~/org")) Also take a look at org-agenda-text-search-extra-files; it lets you add extra files included only in text searches. A typical value might be, (setq org-agenda-text-search-extra-files '(agenda-archives "~/org/subdir/textfile1.txt" "~/org/subdir/textfile1.txt")) Caveat: If you add a file to the directory after you have started Emacs, it will not be included. Edit: (2018) To include all files with a certain extension in the extra files list you can try the following function I wrote sometime back (a more recent version might be available here). ;; recursively find .org files in provided directory ;; modified from an Emacs Lisp Intro example (defun sa-find-org-file-recursively (&optional directory filext) "Return .org and .org_archive files recursively from DIRECTORY. If FILEXT is provided, return files with extension FILEXT instead." (interactive "DDirectory: ") (let* (org-file-list (case-fold-search t) ; filesystems are case sensitive (file-name-regex "^[^.#].*") ; exclude dot, autosave, and backupfiles (filext (or filext "org$\\\|org_archive")) (fileregex (format "%s\\.\\(%s$\\)" file-name-regex filext)) (cur-dir-list (directory-files directory t file-name-regex))) ;; loop over directory listing (dolist (file-or-dir cur-dir-list org-file-list) ; returns org-file-list (cond ((file-regular-p file-or-dir) ; regular files (if (string-match fileregex file-or-dir) ; org files (add-to-list 'org-file-list file-or-dir))) ((file-directory-p file-or-dir) (dolist (org-file (sa-find-org-file-recursively file-or-dir filext) org-file-list) ; add files found to result (add-to-list 'org-file-list org-file))))))) You can use it like this: (setq org-agenda-text-search-extra-files (append (sa-find-org-file-recursively "~/org/dir1/" "txt") (sa-find-org-file-recursively "~/org/dir2/" "tex"))) Edit: (2019) As mentioned in the answer by @mingwei-zhang and the comment by @xiaobing, find-lisp-find-files from find-lisp and directory-files-recursively also provides this functionality. However, please note in these cases the file name argument is a (greedy) regex. So something like (directory-files-recursively "~/my-dir" "org") will give you all Org files including backup files (*.org~). To include only *.org files, you may use (directory-files-recursively "~/my-dir" "org$"). A: There is a simpler way of doing recursive search of org files (courtesy @xiaobing): (setq org-agenda-files (directory-files-recursively "~/org/" "\\.org$")) For Emacs <25, you can use find-lisp-find-files: (load-library "find-lisp") (setq org-agenda-files (find-lisp-find-files "FOLDERNAME" "\.org$"))
{ "pile_set_name": "StackExchange" }
Q: How to disable symbolic preprocessing in NMinimize without performance loss? I want to find a global minimum of a function which is defined only numerically and cannot be evaluated with symbolic arguments. For example, this could be a minimum of a compiled function. numfun = Compile[{{x1,_Real}, {x2,_Real}, {x3,_Real}, {x4,_Real}, {x5,_Real}, {x6,_Real}, {x7,_Real}, {x8,_Real}, {x9,_Real}, {x10,_Real}}, Sqrt[(x1-1.0)^2+(x2-2.0)^2+(x3-3.0)^2+(x4-4.0)^2+(x5-5.0)^2 +(x6-6.0)^2+(x7-7.0)^2+(x8-8.0)^2+(x9-9.0)^2+(x10-10.0)^2]]; If I use NMinimize directly, it attempts to substitute symbolic arguments into my function. The following code generates a lot of warning messages: First@RepeatedTiming@NMinimize[numfun[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10], {x1,x2,x3,x4,x5,x6,x7,x8,x9,x10}] CompiledFunction::cfsa: Argument x1 at position 1 should be a machine-size real number. 0.056 If I use standard wrapping trick to prevent symbolic input ClearAll[numfunWrapper]; numfunWrapper[x1_Real,x2_Real,x3_Real,x4_Real,x5_Real, x6_Real,x7_Real,x8_Real,x9_Real,x10_Real]:=numfun[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10]; then the performance is degraded by two orders of magnitude. First@RepeatedTiming@NMinimize[numfunWrapper[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10], {x1,x2,x3,x4,x5,x6,x7,x8,x9,x10}] 1.904 Is there a way prevent NMinimize from using symbolic arguments/preprocessing without such performance penalty? It seems that for a compiled function one can just disable warning messages, but are there any NMinimize options which can disable symbolic preprocessing like Method -> {Automatic, "SymbolicProcessing" -> 0} in the NIntegrate function? A: As I mentioned in the comments RuntimeOptions is your friend here: numfun = Compile[{{x1, _Real}, {x2, _Real}, {x3, _Real}, {x4, _Real}, {x5, _Real}, {x6, _Real}, {x7, _Real}, {x8, _Real}, {x9, _Real}, {x10, _Real}}, Sqrt[(x1 - 1.0)^2 + (x2 - 2.0)^2 + (x3 - 3.0)^2 + (x4 - 4.0)^2 + (x5 - 5.0)^2 + (x6 - 6.0)^2 + (x7 - 7.0)^2 + (x8 - 8.0)^2 + (x9 - 9.0)^2 + (x10 - 10.0)^2], RuntimeOptions -> {"EvaluateSymbolically" -> False} ]; NMinimize[ numfun[x1, x2, x3, x4, x5, x6, x7, x8, x9, x10], {x1, x2, x3, x4, x5, x6, x7, x8, x9, x10} ] // AbsoluteTiming {2.48474, {1.46191*10^-7, {x1 -> 1., x2 -> 2., x3 -> 3., x4 -> 4., x5 -> 5., x6 -> 6., x7 -> 7., x8 -> 8., x9 -> 9., x10 -> 10.}}} ClearAll[numfunWrapper]; numfunWrapper[x1_Real, x2_Real, x3_Real, x4_Real, x5_Real, x6_Real, x7_Real, x8_Real, x9_Real, x10_Real] := numfun[x1, x2, x3, x4, x5, x6, x7, x8, x9, x10]; NMinimize[ numfunWrapper[x1, x2, x3, x4, x5, x6, x7, x8, x9, x10], {x1, x2, x3, x4, x5, x6, x7, x8, x9, x10} ] // AbsoluteTiming {3.98258, {1.46191*10^-7, {x1 -> 1., x2 -> 2., x3 -> 3., x4 -> 4., x5 -> 5., x6 -> 6., x7 -> 7., x8 -> 8., x9 -> 9., x10 -> 10.}}} Of course for this case you'll be even better off with the direct symbolic processing done: numfun2 = Compile[{{x1, _Real}, {x2, _Real}, {x3, _Real}, {x4, _Real}, {x5, _Real}, {x6, _Real}, {x7, _Real}, {x8, _Real}, {x9, _Real}, {x10, _Real}}, Sqrt[(x1 - 1.0)^2 + (x2 - 2.0)^2 + (x3 - 3.0)^2 + (x4 - 4.0)^2 + (x5 - 5.0)^2 + (x6 - 6.0)^2 + (x7 - 7.0)^2 + (x8 - 8.0)^2 + (x9 - 9.0)^2 + (x10 - 10.0)^2] ]; NMinimize[ numfun2[x1, x2, x3, x4, x5, x6, x7, x8, x9, x10], {x1, x2, x3, x4, x5, x6, x7, x8, x9, x10} ] // Quiet // AbsoluteTiming {0.010106, {3.20225*10^-6, {x1 -> 1., x2 -> 2., x3 -> 3., x4 -> 4., x5 -> 5., x6 -> 6., x7 -> 7., x8 -> 8., x9 -> 9., x10 -> 10.}}} Which corresponds to inserting the symbolic form directly: NMinimize[ Sqrt[(x1 - 1.0)^2 + (x2 - 2.0)^2 + (x3 - 3.0)^2 + (x4 - 4.0)^2 + (x5 - 5.0)^2 + (x6 - 6.0)^2 + (x7 - 7.0)^2 + (x8 - 8.0)^2 + (x9 - 9.0)^2 + (x10 - 10.0)^2], {x1, x2, x3, x4, x5, x6, x7, x8, x9, x10} ] // AbsoluteTiming {0.00434, {3.20225*10^-6, {x1 -> 1., x2 -> 2., x3 -> 3., x4 -> 4., x5 -> 5., x6 -> 6., x7 -> 7., x8 -> 8., x9 -> 9., x10 -> 10.}}}
{ "pile_set_name": "StackExchange" }
Q: How to change the height of textarea with content? I am trying to change the height of the textarea as per the content height. I see that the event handler doesn't change the height since it is getting overwritten by the bootstrap style. Please help! class PostForm extends React.Component { constructor(props){ super(props); this.state = {titleHeight: '30', storyHeight: 1}; this.handleKeyUp = this.handleKeyUp.bind(this); } handleKeyUp(event){ this.setState({titleHeight: document.getElementById('post_title').scrollHeight}); this.setState({storyHeight: document.getElementById('post_story').scrollHeight}); } render () { var csrfToken = $('meta[name=csrf-token]').attr('content'); return ( <form action='create' method='post' acceptCharset='UTF-8' className= "form-group"> <input type='hidden' name='_method' value='patch'/> <input type='hidden' name='utf8' value='✓' /> <input type='hidden' name='authenticity_token' value={csrfToken} /> <textarea id="post_title" name="post[title]" className="form-control boldText" style={formStyle.textArea} height={this.state.titleHeight} onKeyUp={this.handleKeyUp} placeholder="Title"/> <textarea id="post_story" name="post[story]" className="form-control" style={formStyle.textArea} height={this.state.storyHeight} onKeyUp={this.handleKeyUp} placeholder="Start telling the story"/> <input name="commit" type="submit" value="Post" className="btn" style={formStyle.button}/> </form> ); } } const formStyle = { textArea: { border: 5, boxShadow: 'none', margin: 5, overflow: 'hidden', resize: 'none', ariaHidden: 'true', }, button: { backgroundColor: 'black', color: 'white', width: 70, marginLeft: 18, marginRight: 5, }, } A: The textarea HTML component has no attribute height but an attribute rows that you can use for that purpose (e.g. <textarea rows={Math.round(this.state.storyHeight)} ... />). No CSS style will override what you pass in the style attribute, it works the opposite way. But there is no height in your formStyle definition anyway. A: You can do what you want with ref attribute export default class Textarea extends Component { componentDidMount () { if (this.multilineTextarea) { this.multilineTextarea.style.height = 'auto'; } } changeTextarea = () => { this.multilineTextarea.style.height = 'auto'; this.multilineTextarea.style.height = this.multilineTextarea.scrollHeight + 'px'; } render () { return ( <textarea onChange={this.changeTextarea} ref={ref => this.multilineTextarea = ref} /> ); } } Also here is working DEMO
{ "pile_set_name": "StackExchange" }
Q: Javascript: script reference with no children not working I was trying to make a jQuery templates example work on a SharePoint web part. I narrowed my problem down to the following: This WORKS: <script type="text/javascript" src="/_layouts/ServerComponents/jquery-latest.min.js" ></script> <script type="text/javascript" src="/_layouts/ServerComponents/jquery.tmpl.min.js" ></script> but this DOESN'T: <script type="text/javascript" src="/_layouts/ServerComponents/jquery-latest.min.js" /> <script type="text/javascript" src="/_layouts/ServerComponents/jquery.tmpl.min.js" /> Why? Thanks! A: Because script is not a self-closing tag. You always need the closing tag. See the specification: Start tag: required, End tag: required
{ "pile_set_name": "StackExchange" }
Q: Textarea height: 100% Here's my fiddle: http://jsfiddle.net/e6kCH/15/ It may sound stupid, but I can't find a way to make the text area height equal to 100%. It works for the width, but not for height. I want the text area to resize depending of the window size...like it works in my fiddle for the width... Any ideas? A: Height of an element is relative to its parent. Thus, if you want to make expand your element into the whole height of the viewport, you need to apply your CSS to html and body as well (the parent elements): html, body { height: 100%; } #textbox { width: 100%; height: 100%; } Alternative solution with CSS3: If you can use CSS3, you can use Viewport percentage units and directly scale your textbox to 100 % height (and 100% width) of the viewport (jsfiddle here) body { margin: 0; } #textbox { width: 100vw; height: 100vh; }
{ "pile_set_name": "StackExchange" }
Q: How can I change the size of the markers inside the legend? I'm trying to plot multiple plots in just one. I need to have small markers inside the plot, but in the legend it would be more convenient to have bigger markers. I'm trying to change LegendMarkerSize, but it only changes the shape of the whole legend (without changing the size of the points). Here's an example of my struggle: I have: ListPlot[{Prime[Range[25]], Sqrt[Range[40]]}, PlotMarkers -> {Automatic, 3}, PlotLegends -> PointLegend[{"Primes", "Roots"}, LegendMarkerSize -> 3, LegendFunction -> None, LegendLabel -> "Legend"]] And changing only LegendMarkerSize from 3 to (say) 23, I get: ListPlot[{Prime[Range[25]], Sqrt[Range[40]]}, PlotMarkers -> {Automatic, 3}, PlotLegends -> PointLegend[{"Primes", "Roots"}, LegendMarkerSize -> 23, LegendFunction -> None, LegendLabel -> "Legend"]] As you can see, only the text have shifted. How can I increase the size of the markers inside the legend without modifying the size of the markers in the plot on itself? Thank you very much. A: Update: To have the legend markers match the markers in plot, you can add the option LegendMarkers -> ChartElementData["SimpleMarkers"][[All,1]] in SwatchLegend: ListPlot[{Prime[Range[25]], Sqrt[Range[40]],Log@Range[40]}, PlotMarkers -> {Automatic, 9}, PlotLegends -> SwatchLegend[{"Primes", "Roots", "Logs"}, LegendMarkerSize -> 15, LegendMarkers -> ChartElementData["SimpleMarkers"][[All,1]], LegendLabel -> Style["Legend", 20]]] Original answer: You can use SwatchLegend with options LegendMarkers -> "Bubble" and LegendMarkerSize -> 15: ListPlot[{Prime[Range[25]], Sqrt[Range[40]]}, PlotMarkers -> {Automatic, 3}, PlotLegends -> SwatchLegend[{"Primes", "Roots"}, LegendMarkerSize -> 15, LegendMarkers -> "Bubble", LegendLabel -> Style["Legend", 20]]]
{ "pile_set_name": "StackExchange" }
Q: How to send parameters on declare WebSocket HTML5 I want to send params in the first connect to socket server. I'm looking for a sending method like: var wsUrl = 'ws://localhost:9300', wsHandle = new WebSocket(wsUrl, [myParam]); or like: var wsUrl = 'ws://localhost:9300', wsHandle = new WebSocket(wsUrl, { myKey: myParam }); Anyone help me with some keywords? Thanks for your answers. A: I'm assuming you mean you want to send something upon connecting? var socket; function OpenSocket() { if (window.hasOwnProperty("WebSocket")) { // webkit-browser socket = new WebSocket("ws://localhost:12345/"); } else if (window.hasOwnProperty("MozWebSocket")) { // firefox socket = new MozWebSocket("ws://localhost:12345/"); } else { // browser doesnt support websockets alert("Your browser doesn't support WebSocket."); return; } socket.onopen = function() { // the socket is ready, send something //socket.send("Testing websocket data flow..."); }; }
{ "pile_set_name": "StackExchange" }
Q: How to make a console application wait for the "Enter" key, but automatically continue after time? I created a console application in delphi 7, which is supposed to show messages after you press the enter button: begin writeln ('Press ENTER to continue'); readln; writeln ('blablabla'); writeln ('blablabla'); end; The thing is that the user can press any button to continue and that's the problem. I want only the program to continue if the user press the enter button of his keyboard. Except, I need it to automatically continue after a period of time, such as 5 seconds, without user input. How do I make a console application which waits a period of time for the user to press the Enter key, but automatically continues if the user doesn't? A: You may try this code (adapted from our SynCommons.pas unit, within our mORMot framework): procedure ConsoleWaitForEnterKey(TimeOut: integer); function KeyPressed(ExpectedKey: Word):Boolean; var lpNumberOfEvents: DWORD; lpBuffer: TInputRecord; lpNumberOfEventsRead : DWORD; nStdHandle: THandle; begin result := false; nStdHandle := GetStdHandle(STD_INPUT_HANDLE); lpNumberOfEvents := 0; GetNumberOfConsoleInputEvents(nStdHandle,lpNumberOfEvents); if lpNumberOfEvents<>0 then begin PeekConsoleInput(nStdHandle,lpBuffer,1,lpNumberOfEventsRead); if lpNumberOfEventsRead<>0 then if lpBuffer.EventType=KEY_EVENT then if lpBuffer.Event.KeyEvent.bKeyDown and ((ExpectedKey=0) or (lpBuffer.Event.KeyEvent.wVirtualKeyCode=ExpectedKey)) then result := true else FlushConsoleInputBuffer(nStdHandle) else FlushConsoleInputBuffer(nStdHandle); end; end; var Stop: cardinal; begin Stop := GetTickCount+TimeOut*1000; while (not KeyPressed(VK_RETURN)) and (GetTickCount<Stop) do Sleep(50); // check every 50 ms end; Note that the version embedded in mORMot does allow to call the TThread.Synchronize() method and also handle a GDI message loop, if necessary. This procedure just fits your need, I hope. A: I have done things similar to this a few times before: First declare a few global variables: var hIn: THandle; hTimer: THandle; threadID: cardinal; TimeoutAt: TDateTime; WaitingForReturn: boolean = false; TimerThreadTerminated: boolean = false; Second, add functions function TimerThread(Parameter: pointer): integer; var IR: TInputRecord; amt: cardinal; begin result := 0; IR.EventType := KEY_EVENT; IR.Event.KeyEvent.bKeyDown := true; IR.Event.KeyEvent.wVirtualKeyCode := VK_RETURN; while not TimerThreadTerminated do begin if WaitingForReturn and (Now >= TimeoutAt) then WriteConsoleInput(hIn, IR, 1, amt); sleep(500); end; end; procedure StartTimerThread; begin hTimer := BeginThread(nil, 0, TimerThread, nil, 0, threadID); end; procedure EndTimerThread; begin TimerThreadTerminated := true; WaitForSingleObject(hTimer, 1000); CloseHandle(hTimer); end; procedure TimeoutWait(const Time: cardinal); var IR: TInputRecord; nEvents: cardinal; begin TimeOutAt := IncSecond(Now, Time); WaitingForReturn := true; while ReadConsoleInput(hIn, IR, 1, nEvents) do if (IR.EventType = KEY_EVENT) and (TKeyEventRecord(IR.Event).wVirtualKeyCode = VK_RETURN) and (TKeyEventRecord(IR.Event).bKeyDown) then begin WaitingForReturn := false; break; end; end; Now you can use TimeoutWait to wait for Return, but no longer than a given number of seconds. But you have to set hIn and call StartTimerThread before you make use of this function: begin hIn := GetStdHandle(STD_INPUT_HANDLE); StartTimerThread; Writeln('A'); TimeoutWait(5); Writeln('B'); TimeoutWait(5); Writeln('C'); TimeoutWait(5); EndTimerThread; end. You can get rid of StartTimerThread, especially if you start one thread per call, but it might be more tricky to call TimeoutWait several times in a row then. A: The unit Console unit Console; interface procedure WaitAnyKeyPressed(const TextMessage: string = ''); overload; inline; procedure WaitAnyKeyPressed(TimeDelay: Cardinal; const TextMessage: string = ''); overload; inline; procedure WaitForKeyPressed(KeyCode: Word; const TextMessage: string = ''); overload; inline; procedure WaitForKeyPressed(KeyCode: Word; TimeDelay: Cardinal; const TextMessage: string = ''); overload; implementation uses System.SysUtils, WinAPI.Windows; procedure WaitAnyKeyPressed(const TextMessage: string); begin WaitForKeyPressed(0, 0, TextMessage) end; procedure WaitAnyKeyPressed(TimeDelay: Cardinal; const TextMessage: string); begin WaitForKeyPressed(0, TimeDelay, TextMessage) end; procedure WaitForKeyPressed(KeyCode: Word; const TextMessage: string); begin WaitForKeyPressed(KeyCode, 0, TextMessage) end; type TTimer = record Started: TLargeInteger; Frequency: Cardinal; end; var IsElapsed: function(const Timer: TTimer; Interval: Cardinal): Boolean; StartTimer: procedure(var Timer: TTimer); procedure WaitForKeyPressed(KeyCode: Word; TimeDelay: Cardinal; const TextMessage: string); var Handle: THandle; Buffer: TInputRecord; Counter: Cardinal; Timer: TTimer; begin Handle := GetStdHandle(STD_INPUT_HANDLE); if Handle = 0 then RaiseLastOSError; if not (TextMessage = '') then Write(TextMessage); if not (TimeDelay = 0) then StartTimer(Timer); while True do begin Sleep(0); if not GetNumberOfConsoleInputEvents(Handle, Counter) then RaiseLastOSError; if not (Counter = 0) then begin if not ReadConsoleInput(Handle, Buffer, 1, Counter) then RaiseLastOSError; if (Buffer.EventType = KEY_EVENT) and Buffer.Event.KeyEvent.bKeyDown then if (KeyCode = 0) or (KeyCode = Buffer.Event.KeyEvent.wVirtualKeyCode) then Break end; if not (TimeDelay = 0) and IsElapsed(Timer, TimeDelay) then Break end end; function HardwareIsElapsed(const Timer: TTimer; Interval: Cardinal): Boolean; var Passed: TLargeInteger; begin QueryPerformanceCounter(Passed); Result := (Passed - Timer.Started) div Timer.Frequency > Interval end; procedure HardwareStartTimer(var Timer: TTimer); var Frequency: TLargeInteger; begin QueryPerformanceCounter(Timer.Started); QueryPerformanceFrequency(Frequency); Timer.Frequency := Frequency div 1000 end; function SoftwareIsElapsed(const Timer: TTimer; Interval: Cardinal): Boolean; begin Result := (GetCurrentTime - Cardinal(Timer.Started)) > Interval end; procedure SoftwareStartTimer(var Timer: TTimer); begin PCardinal(@Timer.Started)^ := GetCurrentTime end; initialization if QueryPerformanceCounter(PLargeInteger(@@IsElapsed)^) and QueryPerformanceFrequency(PLargeInteger(@@IsElapsed)^) then begin StartTimer := HardwareStartTimer; IsElapsed := HardwareIsElapsed end else begin StartTimer := SoftwareStartTimer; IsElapsed := SoftwareIsElapsed end end. The Test or Sample program program Test; {$APPTYPE CONSOLE} {$R *.res} uses WinAPI.Windows, Console in 'Console.pas'; begin Console.WaitAnyKeyPressed('Press any key to continue ...'); WriteLn; Console.WaitAnyKeyPressed(5000, 'I''ll wait 5 seconds until You press any key to continue ...'); WriteLn; Console.WaitForKeyPressed(VK_SPACE, 'Press [Space] key to continue ...'); WriteLn; Console.WaitForKeyPressed(VK_ESCAPE, 5000, 'I''ll wait 5 seconds until You press [Esc] key to continue ...'); WriteLn end.
{ "pile_set_name": "StackExchange" }
Q: Reading an RDS file within a zip file without extracting to disk Is there a reason I can't read a RDS file from within a zip file directly, without having to unzip it to a temp file on disk first? Let's say this is the zip file: saveRDS(cars, "cars.rds") saveRDS(iris, "iris.rds") write.csv(iris, "iris.csv") zip("datasets.zip", c("cars.rds", "iris.rds", "iris.csv")) file.remove("cars.rds", "iris.rds", "iris.csv") For the csv file, I could read it directly like this: iris2 <- read.csv(unz("datasets.zip", "iris.csv")) However, I don't understand why I can't use unz() directly with readRDS(): iris3 <- readRDS(unz("datasets.zip", "iris.rds")) This gives me the error: Error: unknown input format I'd also like to understand why this happens. I'm aware that I could do the following, as in this question: path <- unzip("datasets.zip", "iris.rds") iris4 <- readRDS(path) file.remove(path) This doesn't seem as efficient, though, and I need to do it frequently for a really large number of files, so I/O inefficiencies matter. Is there any workaround to read the rds file without extracting it to disk? A: This was a little tricky to track down until I read the body of readRDS(). What it seems you need to do is Open a connection to the .zip archive and the file inside it with unz() Apply GZIP decompression to this connection using gzcon() And finally pass this decompressed connection to readRDS(). Here's an example to illustrate using the following serialised matrix mat inside a zip archive matrix.zip mat <- matrix(1:9, ncol = 3) saveRDS(mat, "matrix.rds") zip("matrix.zip", "matrix.rds") Open a connection to matrix.zip con <- unz("matrix.zip", filename = "matrix.rds") Now, using gzcon(), apply GZIP decompression to this connection con2 <- gzcon(con) Finally, read from the connection mat2 <- readRDS(con2) In full we have con <- unz("matrix.zip", filename = "matrix.rds") con2 <- gzcon(con) mat2 <- readRDS(con2) close(con2) This gives > con <- unz("matrix.zip", filename = "matrix.rds") > con2 <- gzcon(con) > mat2 <- readRDS(con2) > close(con2) > mat2 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 > all.equal(mat, mat2) [1] TRUE Why? Why you have to go through this convoluted extra step is (I think) described in ?readRDS: Compression is handled by the connection opened when file is a file name, so is only possible when file is a connection if handled by the connection. So e.g. url connections will need to be wrapped in a call to gzcon. And if you look at the internals of readRDS() we see: > readRDS function (file, refhook = NULL) { if (is.character(file)) { con <- gzfile(file, "rb") on.exit(close(con)) } else if (inherits(file, "connection")) con <- file else stop("bad 'file' argument") .Internal(unserializeFromConn(con, refhook)) } <bytecode: 0x2841998> <environment: namespace:base> If file is a character string for the file name, the object is decompressed using gzile() to create the connection to the .rds we want to read. Notice that if you pass a connection as file, as you want to do, at no point has R decompressed the connection. file is just assigned to con and then passed to the internal function unserializeFromConn. Hence wrapping gzcon() around the connection created by unz works. Basically, when unserializeFromConn reads from a connection it expects it to be decompressed but that decompression only happen automagically when you pass readRDS() a filename, not a connection.
{ "pile_set_name": "StackExchange" }
Q: With BreezeJs how do you handle updating cache for user1 after user2 has made changes? Trying to find the proper solution for breezejs, if user1/device1 has a cached list of projects and user2/device2 updates one of those records, user1 still sees stale data unless they manually refresh. What are the solutions to make sure User1 gets the new upated data? Is there something I can do on save of entity to remove it from everyone's cache? Is the cache based per user? A: The Breeze EntityManager cache is a client side cache, so each user/device/application will have its own data. There is no simple way to keep these caches in sync except by requerying. Optimistic concurrency, providing you are using it, does guarantee that you do not update newer data with older data, but the stale data issue is still very real. We along with several other Breeze users have investigated using SignalR with Breeze to let Breeze know when and what to refresh, but right now these solutions are all custom. Please add your vote to the Breeze User Voice ( https://breezejs.uservoice.com/forums/173093-1-breezejs-feature-suggestions) on this topic if you want to see either examples or tighter integration between Breeze & SignalR.
{ "pile_set_name": "StackExchange" }
Q: Help defining a parameterizable function I need a parametrizable function $f$ with domain and codomain $[0..1]$ and parameter $k$ in $[0,1]$ such that: $f(0)=1, f(1)=0$ it is concave when $k=0$ it is equivalent to $(1-x)$, when $k=1$ it is equivalent to a step function (that is, $f$ in $[0..1)$ is $1, f(1)=0$). The parameter $k$ should allow smooth morphing between the linear $(1-x)$ function and the step function. Step 3, case $k=1$ can be relaxed.... A: If we swap the rules and say $g(0) = 0$, $g(1) = 1$, then $$ g_k(x) = x^\frac{1}{1-k} $$ works pretty well. It's linear for $k = 0$, and grows to look like $x^2$, $x^3$, etc. as $k$ gets close to one. We can then "fix" this (to make the values at $0$ and $1$ be what you asked, rather than my swapped values) by defining $$ f_k(x) = 1 - g_k(x) $$ which flips the $y$ directions to make it match your goals.
{ "pile_set_name": "StackExchange" }
Q: How to acess Image on a server I am working on a Web application, I have its two Modules,both modules are separate solutions(ie projects): 1: Application 2: SiteSetup Sitesetup module is a separate project, I am saving images for logo and banner in this project,the database of both modules is same and i am storing image name in database and file is physically saving on disk, I want to display the stored Logo and banner in my Application,How can i achieve this? Regards A: store image path relative to web application root and use "~/images/logo.png" syntax, then correctly resolve it in web application. use Path.Combine(webAppPath,"images") to get directory for the ~/images.
{ "pile_set_name": "StackExchange" }
Q: What is development by inspection (DBI) and how is it done? While reading this answer I noticed the DBI concept. If I understand correctly, the idea is to develop a film while being able to see the progress (and apply the fixer once you're happy with the result). Is that what it means? If so: I assume you can't use the same chemicals you'd use normally, right? (I'm more interested in B/W, if it makes a difference) A green filter is mentioned; is there a reason why green is used? Any other relevant skills or knowledge needed to do DBI? A: apply the fixer once you're happy with the result I actually use stop bath. I assume you can't use the same chemicals you'd use normally, right? I followed Jeno Dulovits on this, basically using D23 diluted in half. Rodinal works quite good too, especially for the old emulsions. I know people using HC-110. See Antec saying "High sulfite developers such as D-76 or D-23 are less efficient than developers like FG-7, Rodinal or HC-110. Any panchromatic or infrared sensitive films may be treated." is there a reason why green is used? Green light helps to estimate the contrast better. A short introduction is here. You may also want to search APUG forums. A: Development by inspection is obsolete. It was used in the distant past (in other words, before about 1930) when films or plates were much less sensitive in general and almost completely insensitive to red. If attempted today, with fast panchromatic films, you will fog the film, no matter which safelight is used. Development by time and temperature is standard and recommended. It takes lots of experience to develop by inspection, and as I said today's fast panchromatic films do not permit it. They will fog. Kodak and other manufacturers used to make orthochromatic (non-red sensitive) films and plates, which were offered until about 1980 (though a few special-purpose ortho films are still produced for copying, where red sensitivity is of no value). A good example of the old discontinued films is Kodak Super Speed Ortho Portrait film. This film could be handled under a Kodak Series 2 safelight (deep red). This was not for development by inspection, but rather for ease of loading into film holders. Ortho films were preferred for male portraiture and for ease of handling, since a dark red safelight could be used. Ortho press films were also used where red sensitivity was not important. These films have been discontinued for decades. At one time, when photographers coated their own plates and exposed them while they were still wet (wet plates had to be exposed very soon after coating) development by inspection was standard: The sensitivity of the plates was less consistent than with modern materials, and adjustments were sometimes necessary. But dry plates were introduced by the 1870s, and shortly thereafter wet plates were abandoned. All of these materials were insensitive to red, of course. This article is informative. The article by Michael Smith referenced above applies to large sheet film (8x10, 11x14, etc.) and does not apply to miniature or roll films. The best answer is, forget about it. It will not produce any miracles.
{ "pile_set_name": "StackExchange" }
Q: Limiting mySQL data as 5 column 2 entries per column 1 entry Hey there, I'm new to mySQL, so my poor knowledge of the languages might be precluding me from searching for the result I need. I am building a simple application in CodeIgniter that will access the Twitter API and return a table of status updates for a certain number of various users. I would like to limit this to showing 5 updates per user. Imagine I have the following database, which is essentially a reduced version of my actual db. person picture update john pic 1 lorem ipsum john pic 1 lorem ipsum john pic 1 lorem ipsum john pic 1 lorem ipsum john pic 1 lorem ipsum jim pic 2 lorem ipsum jim pic 2 lorem ipsum jim pic 2 lorem ipsum jim pic 2 lorem ipsum jim pic 2 lorem ipsum joe pic 3 lorem ipsum joe pic 3 lorem ipsum joe pic 3 lorem ipsum joe pic 3 lorem ipsum joe pic 3 lorem ipsum steve pic 4 lorem ipsum steve pic 4 lorem ipsum steve pic 4 lorem ipsum steve pic 4 lorem ipsum What I would like to do is to limit the number of updates per person on its way into the database using an SQL query. I'm using INSERT IGNORE for my query, as each time the page is refreshed, I don't want duplicate entries inserted, but simply adding a LIMIT 5 limits 5 for the entirety of users. I would simply like to LIMIT 5 per user. Is there any simple way to do this? REPLACE INTO? UPDATE? Sub-queries? Thanks so much for any help you could give. A: The easiest approach might be with a trigger on INSERT. This would let the application logic only deals with sending INSERTS when needed. On mySQL side, the trigger logic would delete all but 4 most recent (or whatever criteria you desire) records prior to inserting the new record. It could be something like that: (note: untested + concerns about LIMIT clasue in the nested query, could find alternative trick if need be.) This snippet assumes that an id field would be available. Such field not shown in the OP's write-up but would make much sense, as such a PK makes CRUD operations so much easier (rather than spelling out composite keys, here would be all 3 fields...). The trigger could be made AFTER INSERT instead, and this would avoid the possibility of deleting some record unnecessarily if the new record was a duplicate). CREATE TRIGGER LimitTweetUpdates BEFORE INSERT ON myTweeterTable FOR EACH ROW BEGIN DELETE FROM myTweeterTable WHERE person = NEW.person AND id NOT IN (SELECT id FROM myTweeterTable WHERE person = NEW.person ORDER BY id DESC LIMIT 5) END;
{ "pile_set_name": "StackExchange" }
Q: Jenkins can't find defined function? I wrote this to test the idea I saw on JENKINS-44085 def generateStage(String job, String targetVersion, String rootVersion, Integer sleepTime=0) { return { stage("Deploying: ${job}") { sleep sleepTime println "Job: $job" } } } def deployProcs(targetVersion, rootVersion) { script { int sleepTime = 0 def procs = ["proc-proc", "proc-proc-high"] def parallelStagesMap = procs.collectEntries { ["${it}" : generateStage(it, targetVersion, rootVersion, sleepTime)] sleepTime += 5 } timestamps { parallel parallelStagesMap } } } node('linux') { deployProcs(10, 10) } But I get java.lang.NoSuchMethodError: No such DSL method 'generateStage' found among steps. What am I missing? A: You are calling deployProcs(10, 10) where both parameters are type of Integer. The same integer parameters are used when calling generateStage, which parameters are typed String targetVersion and String rootVersion. A fix is to either, call deployProcs('10', '10') or change def generateStage(String job, Integer targetVersion, Integer rootVersion, Integer sleepTime=0), or remove types from generateStage function parameters.
{ "pile_set_name": "StackExchange" }
Q: golang: winapi call with struct parameter I'm trying to call WinHttpGetIEProxyConfigForCurrentUser function to get the automatically detected IE proxy settings. It accepts an inout struct parameter according to documentation. I'm using following code: func GetProxySettings() { winhttp, _ := syscall.LoadLibrary("winhttp.dll") getIEProxy, _ := syscall.GetProcAddress(winhttp, "WinHttpGetIEProxyConfigForCurrentUser") settings := new(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG) var nargs uintptr = 1 ret, _, callErr := syscall.Syscall(uintptr(getIEProxy), nargs, uintptr(unsafe.Pointer(&settings)), 0, 0) fmt.Println(ret, callErr) if settings != nil { fmt.Println(settings.fAutoDetect) fmt.Println(settings.lpszAutoConfigUrl) fmt.Println(settings.lpszProxy) fmt.Println(settings.lpszProxyBypass) } } type WINHTTP_CURRENT_USER_IE_PROXY_CONFIG struct { fAutoDetect bool lpszAutoConfigUrl string lpszProxy string lpszProxyBypass string } It looks like the call is successful, settings is not nil, but as soon as I access it I get panic. Here's the output: 1 The operation completed successfully. panic: runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x0 addr=0x1 pc=0x4d2bb4] A: You need to pass a pointer to your allocated struct, which you already created with the new function. Remove the extra & from the syscall; uintptr(unsafe.Pointer(settings)) You also need to have a struct that has the same layout as the C struct expected by the syscall. The struct definition looks like: typedef struct { BOOL fAutoDetect; LPWSTR lpszAutoConfigUrl; LPWSTR lpszProxy; LPWSTR lpszProxyBypass; } WINHTTP_CURRENT_USER_IE_PROXY_CONFIG; Which should translate to type WINHTTP_CURRENT_USER_IE_PROXY_CONFIG struct { fAutoDetect bool lpszAutoConfigUrl *uint16 lpszProxy *uint16 lpszProxyBypass *uint16 } Each of those LPWSTR fields is going to be a null-terminated, 16bit/char string. For windows you can generally use the syscall UTF16 functions, but here we first need to convert the *uint16 to a []uint16 slice, then decode that slice to a utf8 string. There function that the syscall pakcage uses to do this isn't exported, but we can easily copy that: // utf16PtrToString is like UTF16ToString, but takes *uint16 // as a parameter instead of []uint16. // max is how many times p can be advanced looking for the null terminator. // If max is hit, the string is truncated at that point. func utf16PtrToString(p *uint16, max int) string { if p == nil { return "" } // Find NUL terminator. end := unsafe.Pointer(p) n := 0 for *(*uint16)(end) != 0 && n < max { end = unsafe.Pointer(uintptr(end) + unsafe.Sizeof(*p)) n++ } s := (*[(1 << 30) - 1]uint16)(unsafe.Pointer(p))[:n:n] return string(utf16.Decode(s)) } Or use the exported version that was recently added to golang.org/x/sys/windows, windows.UTF16PtrToString.
{ "pile_set_name": "StackExchange" }
Q: Class-only generic constraints in Swift I'm trying to mark a variable of a generic type as weak: class X<T> { weak var t: T? } If I don't put in any constraints for T I get the error weak cannot be applied to non-class type 'T'. If I would only use use this with NSObject derived classes this would work: class X<T: NSObject> { weak var t: T? } But I also want to be able to use pure Swift classes. For protocols it is possible to require that the implementor is of class type by using the class keyword: protocol ClassType: class { } With the ClassType protocol I can now mark the variable as weak: class X<T: ClassType> { weak var t: T? } But I cannot add the class keyword directly to the generic parameter: class X<T: class> { // Compile error weak var t: T? } I can make the protocol solution work for all NSObject derived classes with an extension: extension NSObject: ClassType { } But for pure Swift classes there is no common superclass that I could add this extension to. Is there a way to make this work without adding the ClassType protocol to each class I want to use the X class with? E.g. some special qualifier for the generic parameter like class X<T:ThisIsAClass>? A: You want AnyObject, which the Swift docs describe as: The protocol to which all classes implicitly conform. class X<T: AnyObject> { weak var t: T? } class C { } let x = X<C>() // works fine x.t = C() // error: type 'Int' does not conform to protocol ‘AnyObject’ // (because Int is a struct) let y = X<Int>()
{ "pile_set_name": "StackExchange" }
Q: JavaScript Object.create and IE8 I'm doing software development for SharePoint 2013. Part of this involves overriding SharePoint's file previewer (filepreview.debug.js becomes myfilepreview.debug.js). We've run into problems, however, with IE8. Everything works just fine in IE9. The error thrown in IE8 causes an error on any site you visit within the site collection that our custom feature is activated on: "Object does not support this property or method" After doing some research on this error, it would appear that IE8 simply does not support Object.create. This Mozilla Developer post seems to support this theory. I was more pressed to believe this when the issue was solved by adding this polyfill code before the line that was throwing the error: if (typeof Object.create !== 'function') { Object.create = function (o) { function F() { } F.prototype = o; return new F(); }; } I guess that would make sense that it works because it mimics the functionality of Object.create which supposedly isn't supported in IE8. However, this was confusing because SharePoint's file previewer javascript works just fine. Their javascript also uses Object.create. Even weirder, the section of code that was throwing the error in our javascript wasn't even our code -- it's SharePoint's. The entire javascript code up to then is actually the same as SharePoint's as well, except for a few lines. Here's the default, up to the line in question: function $_global_filepreview() { RegisterSod("mediaplayer.js", "_layouts/15/mediaplayer.js"); RegisterSod("sp.publishing.resources.resx", "/_layouts/15/ScriptResx.ashx?name=sp.publishing.resources&culture=" + STSHtmlEncode(Strings.STS.L_CurrentUICulture_Name)); RegisterSodDep("mediaplayer.js", "sp.publishing.resources.resx"); previewBase = (function() { ULS7RK: ; var filePreviewUniqueId = 0; return { init: function(ctxT, listItem, extension) { this.fpId = ++filePreviewUniqueId; this.fpDomId = "FilePreviewID-" + String(this.fpId); this.fpCtx = ctxT; this.fpExtension = extension; this.fpListItem = listItem; }, getHtml: function() { ULS7RK: ; return ['<div class="js-filePreview-containingElement" id=', StAttrQuote(this.fpDomId), '>', this.getInnerHtml(), '</div>'].join(""); }, getDomId: function() { ULS7RK: ; return this.fpDomId; }, getContainingElement: function() { ULS7RK: ; var containingElement = document.getElementById(this.fpDomId); Sys.Debug.assert(m$.isElement(containingElement), "Containing element has not been rendered yet."); return containingElement; }, canRender: function() { ULS7RK: ; return true; }, getLoadingIndicatorHtml: function(customStyle) { if (m$.isUndefined(customStyle)) { customStyle = ""; } return ['<div class="js-filePreview-loading-image" style="width:', this.getWidth(), 'px; height:', this.getHeight(), 'px; line-height:', this.getHeight(), 'px; text-align:center; vertical-align:middle; display: inline-block; ' + customStyle + '">', '<img src="', "/_layouts/15/images/gears_anv4.gif", '" />', '</div>'].join(""); }, hideLoadingIndicator: function() { ULS7RK: ; var containingElement = document.getElementById(this.fpDomId); ((m$(containingElement)).find("div.js-filePreview-loading-image")).css({ display: "none" }); }, getInnerHtml: function() { ULS7RK: ; return ""; }, getWidth: function() { ULS7RK: ; return null; }, getHeight: function() { ULS7RK: ; return null; }, onPostRender: function() { }, onVisible: function() { }, onHidden: function() { } }; })(); //**This is where the "fix" was added originally** blankPreview = Object.create(previewBase); <--- error is thrown here The only difference between the SharePoint javscript (above) and ours (up to this point) is we've removed these following two lines from the beginning, though adding them back still doesn't solve the issue: RegisterSod("sp.publishing.resources.resx", "/_layouts/15/ScriptResx.ashx?name=sp.publishing.resources&culture=" + STSHtmlEncode(Strings.STS.L_CurrentUICulture_Name)); RegisterSodDep("mediaplayer.js", "sp.publishing.resources.resx"); So my question is: Why am I getting this error that Object.create isn't supported in IE8 while other uses of the same exact function in the default javascript work without issue? EDIT: A user on another forum suggested I try registering my script via sod. I added this to my code without effect: RegisterSod("MyFilepreview.debug.js", "_layouts/15/MyFilepreview.debug.js"); A: Try debugging in IE and put breakpoints in SharePoint's default JavaScript file. Are you sure the instances of Object.create in the default JavaScript are actually being hit? A: They aren't using Object.create with proper arguments. They use Object.create({name:value}) when it should be Object.create({name:{value:value}}). So they probably defined their own Object.create and their code is used after yours so you already have your Object.create set when their code runs and they probably test for existence just like you do and assume it's their version that is there when in fact it's yours. So check for a definition of Object.create in their code and check the order in which scripts are executed.
{ "pile_set_name": "StackExchange" }
Q: nodejs s3 bucket upload script reusable Hey guys Im trying to upload a file to s3 I am successfully able to do it with the following code. However I would like to make it a little more reusable. I would like to be able to use a function like this. singleFileUpload(fieldName, bucketName, newfileName); So that I an use the same function on multiple pages without defining it over and over again. I also want it to be able to return any upload errors in a try catch block. Is this possible? Heres the code I have so far that works. var AWS = require("aws-sdk"); var multer = require("multer"); multerS3 = require("multer-s3"); var fs = require("fs"); AWS.config.credentials = { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: "eu-west-1" }; AWS.config.region = "eu-west-1"; var s3 = new AWS.S3(); var newFileName = "coolNewFileName"; const fileFilter = (req, file, cb) => { var ext = file.originalname.split(".")[1]; console.log("ext", ext); if (ext == "jpg" || ext == "mp4" || ext == "wmv") { cb(null, true); } else { cb(new Error("invalid file format"), false); } }; var upload = multer({ fileFilter, storage: multerS3({ s3, bucket: process.env.BUCKET_NAME, acl: "public-read", metadata: function(req, file, cb) { cb(null, { fieldName: "testing_meta_data!" }); }, key: function(req, file, cb) { console.log(file); let fileExtension = file.originalname.split(".")[1]; cb(null, newFileName + "." + fileExtension); } }) }); var singleUpload = upload.single("image"); singleUpload(req, res, function(err) { if (err) { data.error = true; data.message = err.message; console.log(data); res.json(data); } else { // res.json({ imageurl: req.file.location }); data.fileUploadLocation = req.file.location; console.log(data.fileUploadLocation); } }); Any help here would be fantastic thank you. A: This is how its done place the following code in a separate file. aws file contains an include for aws and the s3 configuration. Like so: var AWS = require("aws-sdk"); AWS.config.credentials = { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: "eu-west-1" }; AWS.config.region = "eu-west-1"; var s3 = new AWS.S3(); module.exports = { AWS, s3 }; var AWS = require("../AWS").AWS; var s3 = require("../AWS").s3; var multer = require("multer"); var multerS3 = require("multer-s3"); than I include the following code like so: let singleFileUpload = require("../upload"); Lastly I build the function in the upload/index.js file like so: function singleFileUpload(req, res, newFileName, bucketName, fieldName) { var fileFilter = (req, file, cb) => { var ext = file.originalname.split(".").slice(-1); console.log("ext", ext); if (ext == "jpg" || ext == "mp4" || ext == "wmv") { cb(null, true); } else { cb(new Error("invalid file format"), false); } }; var upload = multer({ fileFilter, storage: multerS3({ s3, bucket: bucketName, acl: "public-read", metadata: function(req, file, cb) { cb(null, { test: "testing_meta_data!" }); }, key: function(req, file, cb) { console.log(file); let fileExtension = file.originalname.split(".")[1]; cb(null, newFileName + "." + fileExtension); } }) }); var singleUpload = upload.single(fieldName); singleUpload(req, res, error => { if (error) { throw error; } else { console.log("it worked"); } }); } module.exports = singleFileUpload; I than run the function like so: var newFileName = "Testing"; var fieldName = "image"; singleFileUpload( req, res, newFileName, process.env.BUCKET_NAME, fieldName );
{ "pile_set_name": "StackExchange" }
Q: Jquery.load(html) not working my JSfiddle is here http://jsfiddle.net/hhimanshu/VAAKf/3/ When i click on search, it doesn't do anything, but when i put alert, I get alert. Please let me know what might be going wrong? Thank you A: I have two jquery functions, when I made this jQuery function at top, the alert started to work // loading search page $(function(){ $("#search").click(function(){ alert("hi"); }); }); // animating slideshow on landing page $(function(){ $('#slides').slides({ preload: true, pagination: true, preloadImage: '../static/img/loading.gif', play: 2000, pause: 1000, hoverPause: true }); $('.slides_control').css({ "height": "600px", "margin-right": "400px" }); $('.pagination').hide('') }); How did that work? I have no idea. Do i need to order the calls?
{ "pile_set_name": "StackExchange" }
Q: Is it possible to allow calling in Kid's Corner? Sometimes people ask me for my phone to call someone if their own phone is out of battery or if they don't have it on them. Just giving my phone to someone in Kid's Corner mode would be the most useful thing in Kid's Corner for me, but it seems like I can't allow calling in Kid's Corner? A: No, calling (ie. the phone app) can't be added to Kids Corner in Windows Phone 8. When setting up Kids Corner, you can add Games, Music, Videos and App you've download from the Windows Phone Store but not many of the built-in apps as the FAQ on Kids Corner mentions... Because they can be used to make changes to your Start screen or phone settings, Hubs and many built-in apps (such as Messaging, Calendar, and Wallet) can't be added to Kid's Corner.
{ "pile_set_name": "StackExchange" }