instruction
stringlengths
22
34.6k
input
stringclasses
1 value
output
stringlengths
70
4.33k
PHP: How to compare keys in one array with values in another, and return matches? <sep> I have the following two arrays: <code>$array_one = array('colorZero'=>'black', 'colorOne'=>'red', 'colorTwo'=>'green', 'colorThree'=>'blue', 'colorFour'=>'purple', 'colorFive'=>'golden'); $array_two = array('colorOne', 'colorTwo', 'colorThree'); </code> I want an array from <code>$array_one</code> which only contains the key-value pairs whose keys are members of $array_two (either by making a new array or removing the rest of the elements from <code>$array_one</code>) How can I do that? I looked into <code>array_diff</code> and <code>array_intersect</code>, but they compare values with values, and not the values of one array with the keys of the other.
As of PHP 5.1, there is `array_intersect_key` (manual). Just flip the second array from key=>value to value=>key with `array_flip()`, and then compare keys. So to compare OP's arrays, this would do: `$result = array_intersect_key($array_one, array_flip($array_two));`. No need for any looping through the arrays at all.
Can't build Hadoop 2.4.1 with Java8 <sep> The problem is pretty straight-forward. I'm trying to compile Hadoop2.4.1 on windows with the following command : <code>mvn clean package -Pdist,native-win -DskipTests -Dtar </code> With <code>JAVA_HOME=C:\Program Files\Java\jdk1.7.0_51</code>, it works fine. With <code>JAVA_HOME=C:\Program Files\Java\jdk1.8.0_05</code>, it doesn't and fails giving me the following error : <code>[INFO] Apache Hadoop Annotations ......................... FAILURE [4.086s] --- [ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.8 .1:jar (module-javadocs) on project hadoop-annotations: MavenReportException: Er ror while creating archive: [ERROR] Exit code: 1 - C:\hadoop-src\hadoop-common-project\hadoop-annotations\sr c\main\java\org\apache\hadoop\classification\InterfaceStability.java:27: error: unexpected end tag: </ul> [ERROR] * </ul> [ERROR] ^ [ERROR] [ERROR] Command line was: "C:\Program Files\Java\jdk1.8.0_05\jre\..\bin\javadoc. exe" -J-Dhttp.proxySet=true -J-Dhttp.proxyHost=proxy -J-Dhttp.proxyPort=3128 @op tions @packages [ERROR] [ERROR] Refer to the generated Javadoc files in 'C:\hadoop-src\hadoop-common-pro ject\hadoop-annotations\target' dir. [ERROR] -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit ch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please rea d the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionE xception [ERROR] </code> As stated before, I changed nothing else than <code>JAVA_HOME</code>. The error message seems to indicate that the error is proxy related, but I have no idea why. In both case, I have <code>C:\hadoop-src>javac -version javac 1.8.0_05 </code> and <code>C:\hadoop-src>java -version java version "1.8.0_05" Java(TM) SE Runtime Environment (build 1.8.0_05-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode) </code> Would you folks have any clues on what's going on ?
Alternatively to Stuart's suggestion (I had a difficult time finding out where to put the additional parameter): in order to skip Javadoc generation altogether, just run `mvn clean package -Pdist,native-win -DskipTests -Dtar -Dmaven.javadoc.skip=true`.
cannot convert from 'string' to 'System.IFormatProvider' <sep> This code gives me this error: <code>var n = "9/7/2014 8:22:35 AM"; var m = n.ToString("yyyy-MM-dd'T'HH:mm:ssZ"); </code> But this code works as it should and returns the date in the proper format. <code>var n = DateTime.Now; var m = n.ToString("yyyy-MM-dd'T'HH:mm:ssZ"); </code> Anyone know why the first code isn't working and how to get it working?
You need to understand how static typing works. In the first one, the type of `n` is `string`. The type `string` does have a `ToString()` method, but that method either takes no arguments and returns the same string object, or it takes a format provider. Since you provided an argument, the compiler assumes you meant the second version, but the types don't match. Perhaps what you are trying to do is convert a string into a date first, which can be done by parsing it using `DateTime`'s `Parse` or `TryParse` methods: `var n = DateTime.Parse("9/7/2014 8:22:35 AM");`. Here, we convert a `string` to `DateTime`. The type of `n` is `DateTime`. I think it might be a good idea not to use `var` while you're figuring out C#. If you explicitly list the types, you'll gain a greater understanding of what's going on, and the compiler will flag errors earlier. In this case, you'll get the error on the very first line, and it'll be obvious. It will complain about assigning a string to a `DateTime`. No weird stuff about `IFormatProvider`, which is not at all obvious. Your code would look like this: `DateTime n = "9/7/2014 8:22:35 AM"; string m = n.ToString("yyyy-MM-dd'T'HH:mm:ssZ");`. In this example, you'll get an error on line one, and then you can clearly see that you are trying to assign a literal value (the string "9/7/2014 8:22:35 AM") of type `string` to a variable of type `DateTime`, which can't work.
How to use 'WHERE' clause using ssp.class.php DataTables <sep> Okay so i'm trying to display information from my database using jQuery DataTable (DataTables.net). I can get it to work fine displaying the entire table 'notes' but I would like to just display notes that have not been read. So I need to include a WHERE clause somehow but i'm unclear on the best way to go about this. Here is how I currently display the whole table: <code>// DB table to use $table = 'Notes'; // Table's primary key $primaryKey = 'CID'; // Array of database columns which should be read and sent back to DataTables. // The `db` parameter represents the column name in the database, while the `dt` // parameter represents the DataTables column identifier. In this case simple // indexes $columns = array( array( 'db' => 'CID', 'dt' => 0 ), array( 'db' => 'CID', 'dt' => 0, 'formatter' => function( $d, $row ) { return '<a href="profile.php?search='.$d.'" target="_Blank">'.$d."</a>"; } ), array( 'db' => 'Title', 'dt' => 1 ), array( 'db' => 'Name', 'dt' => 2 ), array( 'db' => 'Date', 'dt' => 3, 'formatter' => function( $d, $row ) { return date( 'jS M y', strtotime($d)); } ) ); // SQL server connection information $sql_details = array( 'user' => '*DB_USER*', 'pass' => '*Password*', 'db' => '*DatabaseName*', 'host' => 'localhost' ); require( 'ssp.class.php' ); echo json_encode( SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns ) ); </code> I would need the equivalent of <code>SELECT * FROM Notes WHERE Status ='Unread'</code>
You should change DataTables' default functions to do this! Use this `ssp.class.php` customized class `Link`. Use it like the following example: ```php require( 'ssp.class.php' ); $where = "Status ='Unread'"; echo json_encode( SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns, $where ) ); ``` If you set the `$where` parameter, the custom class will add a WHERE clause to the SELECT statement! Update: In 2015, DataTables added a complex method. The new built-in method can set a WHERE clause in the query!
CVDisplayLink with Swift <sep> I'm trying to create a main render loop for a Swift OS X OpenGL application, but I can't find any examples on the web, and can't figure out the interaction with the Objective C API. Here's code during initialization of my subclass of <code>NSOpenGLView</code>: <code> var udl : Unmanaged<CVDisplayLink>? CVDisplayLinkCreateWithActiveCGDisplays(&udl) var displayLink: CVDisplayLink = udl!.takeRetainedValue() // I guess // The two following lines give errors that the type isn't convertible // to the declared type: let cb: CVDisplayLinkOutputCallback = dlCallback // ERROR: type not convertible let sp: UnsafeMutablePointer<Void> = &self // ERROR: type not convertible CVDisplayLinkSetOutputCallback(displayLink, cb, sp) let cglContext = openGLContext.CGLContextObj let cglPixelFormat = pixelFormat.CGLPixelFormatObj CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, cglContext, cglPixelFormat) CVDisplayLinkStart(displayLink) </code> and here's my callback function. I don't know how to extract the pointer back to my view class from the opaque pointer I passed to <code>CVDisplayLinkSetOutputCallback</code> (or tried to). <code>func dlCallback(displayLink: CVDisplayLink!, inNow: UnsafePointer<CVTimeStamp>, inOutputTime: UnsafePointer<CVTimeStamp>, flagsIn: CVOptionFlags, flagsOut: UnsafeMutablePointer<CVOptionFlags>, context: UnsafeMutablePointer<Void>) -> CVReturn { let that = UnsafeMutablePointer<MyView>(context) // Just a guess, but no that.render() // ERROR: no such method } </code> I'd like to understand how to do this. If I should use some other main render loop instead based on timers, I guess I can do that instead.
```swift // SwiftOpenGLView_Swift_3_0.swift // SwiftOpenGL // Created by Myles La Verne Schultz on 1/11/17. // Copyright 2017 MyKo. All rights reserved. // This file is an update to the previous SwiftOpenGLView used // to display animated content using the CVDisplayLink. This // version uses Swift 3.0 without the need for a bridging // header for the CVDisplayLinkCallback function. An // explanation of the CVTimeStamp is also provided. import Cocoa import OpenGL.GL3 final class SwiftOpenGLView: NSOpenGLView { // A CVDisplayLink for animating. private var displayLink: CVDisplayLink? // The current time, used to produce varying values to change background color private var currentTime = 0.0 required init?(coder: NSCoder) { super.init(coder: coder) let attrs: [NSOpenGLPixelFormatAttribute] = [ UInt32(NSOpenGLPFAAccelerated), UInt32(NSOpenGLPFADoubleBuffer), UInt32(NSOpenGLPFAColorSize), UInt32(32), UInt32(NSOpenGLPFAOpenGLProfile), UInt32(NSOpenGLProfileVersion3_2Core), UInt32(0) ] guard let pixelFormat = NSOpenGLPixelFormat(attributes: attrs) else { Swift.print("pixelFormat could not be constructed") return } self.pixelFormat = pixelFormat guard let context = NSOpenGL
Check that getArguments has some data to be retrieved <sep> <code>Android Studio 0.8.7 </code> I have the following function that sets some argument in the fragment: <code> public static Fragment newInstance(UUID uuid) { Log.d(TAG, "newInstance: " + uuid); Bundle arguments = new Bundle(); arguments.putSerializable(EXTRA_JOB_ID, uuid); DetailFragment fragment = new DetailFragment(); fragment.setArguments(arguments); return fragment; } </code> In my onCreate() I retrieve the arguments using getArguments like this: <code>@Override public void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate()"); super.onCreate(savedInstanceState); /* Get the arguments from the fragment */ UUID uuid = (UUID)getArguments().getSerializable(EXTRA_JOB_ID); . . } </code> However, sometimes there is a situation where I won't be sending any arguments to be retrieved, and my program will crash in that case. Using Intents has the hasExtra method to check this: <code> if(getActivity().getIntent().hasExtra(Intent.EXTRA_TEXT)) { /* There is something to be retrieved */ } </code> I am wondering if there is something similar with getArguments Many thanks in advance,
As an alternative suggestion to the other answers, your `newInstance(...)` method could be designed slightly better. As it stands, it always adds arguments even if your `UUID` parameter is `null`. Try changing it to this... ```java public static Fragment newInstance(UUID uuid) { Log.d(TAG, "newInstance: " + uuid); DetailFragment fragment = new DetailFragment(); if (uuid != null) { Bundle arguments = new Bundle(); arguments.putSerializable(EXTRA_JOB_ID, uuid); fragment.setArguments(arguments); } return fragment; } ``` Then in the `onCreate(...)` method of your `Fragment`, check for arguments before anything else... ```java Bundle arguments = getArguments(); if (arguments != null && arguments.containsKey(EXTRA_JOB_ID)) { UUID uuid = (UUID) arguments.getSerializable(EXTRA_JOB_ID); } ```
What's the difference between principles YAGNI and KISS? <sep> Obviously there are syntactical differences between YAGNI and KISS but I can't see any semantic differences between them. Are they really in essence just the same thing?
Short: YAGNI states you need to cut off the code you don't need right now; KISS is about making the remaining code simple. Here's how it can be visualized: read more here.
Is this slower because of two lookups instead of one? <sep> When I want to make sure that the entry I want to use exists, I usually do this. <code>#include <unordered_map> struct type { int member; }; std::unordered_map<type> map; if (map.find(key) != map.end()) map[key].member = 42; </code> However, I think it performs two lookups for <code>key</code> in the hash map. This caches the lookup. <code>#include <unordered_map> struct type { int member; }; std::unordered_map<type> map; auto find = map.find(key); if (find != map.end()) find->second.member = 42; </code> The first option feels way more expressive. Is it really slower?
It may be slower, it may not (you're now doing an extra write in your "speed up"), but one really shouldn't worry about such minor optimizations when writing code. Write clear, expressive code. Then, if your program really is too slow, run profiling tools on it and find your bottleneck(s). If this code is in fact a real problem, then and only then try your "speed up" and see if it matters.
How to decode a H.264 frame on iOS by hardware decoding? <sep> I have been used ffmpeg to decode every single frame that I received from my ip cam. The brief code looks like this: <code>-(void) decodeFrame:(unsigned char *)frameData frameSize:(int)frameSize{ AVFrame frame; AVPicture picture; AVPacket pkt; AVCodecContext *context; pkt.data = frameData; pat.size = frameSize; avcodec_get_frame_defaults(&frame); avpicture_alloc(&picture, PIX_FMT_RGB24, targetWidth, targetHeight); avcodec_decode_video2(&context, &frame, &got_picture, &pkt); } </code> The code woks fine, but it's software decoding. I want to enhance the decoding performance by hardware decoding. After lots of research, I know it may be achieved by AVFoundation framework. The AVAssetReader class may help, but I can't figure out what's the next.Could anyone points out the following steps for me? Any help would be appreciated.
iOS does not provide any public access directly to the hardware decode engine because hardware is always used to decode H.264 video on iOS. Therefore, session 513 gives you all the information you need to allow frame-by-frame decoding on iOS. In short, per that session: Generate individual network abstraction layer units (NALUs) from your H.264 elementary stream. There is much information on how this is done online. VCL NALUs (IDR and non-IDR) contain your video data and are to be fed into the decoder. Re-package those NALUs according to the "AVCC" format, removing NALU start codes and replacing them with a 4-byte NALU length header. Create a `CMVideoFormatDescriptionRef` from your SPS and PPS NALUs via `CMVideoFormatDescriptionCreateFromH264ParameterSets()`. Package NALU frames as `CMSampleBuffer`s per session 513. Create a `VTDecompressionSessionRef`, and feed `VTDecompressionSessionDecodeFrame()` with the sample buffers. Alternatively, use `AVSampleBufferDisplayLayer`, whose `-enqueueSampleBuffer:` method obviates the need to create your own decoder.
Deserialize POJOs from multiple YAML documents in a single file in Jackson <sep> I have a YAML file that looks something like this: <code>--- name: Sam tags: - Dev - Java ---- name: Bob tags: - PM </code> I'd like to use Jackson to deserialize all documents from the file, but I don't see a way to use a normal <code>ObjectMapper</code> to do it. If I use the <code>YAMLFactory</code> to create a parser for my file I can step through all tokens, so the parser is obviously capable of dealing with multiple documents - but how do I tie them together? Looks like the parser created by my YAMLFactory only parses a single document out of the file. I've also tried creating a YAMLParser directly and using <code>ObjectMapper#readValue(JsonParser, Class)</code>, but the ObjectMapper exhausts the entire YAMLParser to deserialize a single instance.
This is years later, but it's worth pointing out that this is supported. The Jackson semantics are slightly different, probably due to its JSON origins. This can be achieved by using the `MappingIterator` from `ObjectMapper`. ```java YAMLFactory yamlFactory; ObjectMapper mapper; YAMLParser yamlParser = yamlFactory.createParser("file-with-multiple-docs.yaml"); List<ObjectNode> docs = mapper.readValues(yamlParser, new TypeReference<ObjectNode>() {}) .readAll(); ``` Replace `ObjectNode` with your own POJOs if desired.
WPF:Difference between TabControl.ItemTemplate and TabItem.ContentTemplate <sep> I'm confused on this for a long time,these both seem to affect the tabitems' presentation in the tabcontrol. Is it designed for best control of the presentation of the tabcontrol? Or if there is something I dont't understand.
There are some very long answers here for what is actually a very simple question. To avoid confusion: `ItemTemplate` is the template used to format each item in the `ItemsSource` to create the headers (the controls that appear in the tab bar), and `ContentTemplate` is the template used to format each item in the `ItemsSource` to create the content of the tabs (the controls that appear when you click on the header).
How do I calculate total minutes between start and end times? <sep> How do I calculate total minutes between start and end times? The Start/End times columns are nvarchar and I am declaring them as datetime. I'm not sure if that is my first step or not, I am new to SQL and to declaring. The final goal is to take <code>Total Minutes</code>, subtract <code>Lunch</code> and <code>Recess</code> (both are minutes) and then multiply by 5 to get total instructional minutes for the week per school. <code>DECLARE @StartTime datetime, @Endtime datetime SELECT --[School] [GradeLevel] ,[StartTime] ,[EndTime] ,(@Endtime - @StartTime) AS 'TotalMinutes' ,[Lunch] ,[Resess] ,[Passing] FROM [dbo].[StartEndTimes] Current Output: GradeLevel StartTime EndTime TotalMinutes Lunch Resess Passing 2-5 7:50 14:20 NULL 20 10 NULL K-5 7:45 14:20 NULL 20 10 NULL K-5 7:50 14:20 NULL 20 10 NULL </code>
Maybe something like this is what you want? ```sql select (datediff(minute, starttime, endtime) - lunch - recess) * 5 AS TotalInstruct from YourTable ``` If you want to sum it up for all rows then try: ```sql select sum((datediff(minute, starttime, endtime) - lunch - recess) * 5) AS TotalInstruct from YourTable ``` If you want to get the number of hours per school you would have to include the `school` field in the query and use it in the `group by` clause, and then the query becomes this: ```sql select school, sum((datediff(minute, starttime, endtime) - lunch - recess) * 5) AS TotalInstruct from YourTable group by school ``` Sample SQL Fiddle for the above queries.
How To Get The Value Of Header In CSV <sep> In PowerShell I want to pass the name of a header in a CSV file into another function in the PowerShell script. How can I retrieve the value-text of a header name into a variable in CSV? e.g. if I have the following CSV data: <code>ID Name Country -- ---- ------- 1 John United States 2 Beatrice Germany 3 Jouni Finland 4 Marcel France </code> In the above example how can I retrieve the Country column value text as "Country" text into a variable in my script? (Note: I am familiar with the notation $_.Country to retrieve the value of, for example, "Germany" from a row by importing the CSV in Powershell) My specific issue is that currently I have the following function in my script: <code>function GetItemIdFromTitle([string]$LookupTitle, [ref]$LookupId) { $LookupField = $LookupList.Fields["DEPTCATEGORY"] $LookupItem = $LookupList.Items | where {$_['DEPTCATEGORY'] -like "*$LookupTitle*"} $LookupId.Value = $LookupItem.ID } </code> This currently takes a string value -> $LookupTitle and uses that to find an item in a SharePoint list. As you can see in the script I am hard-coding in the column name as "DEPTCATEGORY". This is the column name that will be looked up to in the SharePoint list. Instead of hard-coding the column name I want to pass in the name of the column for the corresponding $LookupTitle value and replace the hard-coded "DEPTCATEGORY". I am calling the above function as follows: <code>#GET THE LOOKUP COLUMN ID GetItemIdFromTitle $_.DEPTCAT ([ref]$LookupIdValue) </code> ( $_.DEPTCAT is the value from the row in the CSV column. ) Can I do something like <code>$myCountryColumnName = $_.Country.Property.Title </code> or <code>$myCategoryColumnName = $_.DEPTCAT.Property.Name </code> to get the column name from the CSV?
Assuming that you have already read in the CSV using `Import-CSV`, you can examine the properties of the resulting object. Similar to this answer, but it maintains column order in the resulting array. Examining the first row/element: `$data = Import-CSV $path` `$data[0].psobject.properties.name` So the second line will return a string array of the properties.
fatal: bad object HEAD <sep> Can somebody help me to solve this problem. I had made a previous post about this but I couldn't solve it through those answers. Please help:) I have tried to run <code>git fsck --full</code> and I get : <code>Checking object directories: 100% (256/256), done. error: HEAD: invalid sha1 pointer 15044de63184bed22f9be9f48fd63a3a7652eea4 error: refs/heads/master does not point to a valid object! notice: No default references dangling blob f4ffb48ece75b45ec593146216a2ecae5a5b2194 dangling blob f37ffd41d80a2d07258d0b8fa7118d236d480fc0 dangling blob f1ff1fa538a538d9085e573f60ad11e8e7f5395e dangling blob f9ff6bdaf08fdbf9001ff44d2aa1a49092c20ad1 dangling blob f97f1a223ef3ca33f55d51ae25d98d3b5b2f9ece </code>
In my case, I edited `\.git/refs/remotes/origin/HEAD`. I couldn't get `git update-ref` to work, but that seems to be the recommended way. So if `git checkout (<branch> | <commit>)` doesn't work, you should try something like `git update-ref HEAD refs/master` or just try editing `\.git/HEAD`.
Include direct link to webpack entry points in application HTML? <sep> My webpack entry point includes a <code>[hash]</code> in the name: <code>entry: "index.js", output: { path: "build/", filename: "index-[hash].js", } </code> How can I link directly to that entry point from my application's HTML? For example, I'd like the HTML that's sent to the client to include: <code><script src="build/index-41d40fe7b20ba1dce81f.js"></script> </code> How can I do this? Is there a plugin which can generate an entry point manifest which my application can read and emit the appropriate file names?
The `html-webpack-plugin` (I'm the author) will generate an `index.html` for you, referencing the correct hashed bundle filename. ```javascript var HtmlWebpackPlugin = require("html-webpack-plugin"); var webpackConfig = { entry: "index.js", output: { path: "build/", filename: "index-[hash].js", }, plugins: [new HtmlWebpackPlugin()] }; ``` This will produce `build/index.html` that includes your bundle with a `<script>` tag.
Organizing Environment Variables Golang <sep> In Node.js I use the nconf module to house environment variables like S3 keys, GCM keys, etc for each of my projects. I haven't been able to find a similar solution in Go. What are the generally accepted tools to help manage environment variables for each Go project? Thanks in advance.
I would strongly recommend using github.com/namsral/flag instead. It's like the built-in flag except you can also supply the parameters via environment variables. For example, suppose you have this code: ```go package main import "fmt" import "github.com/namsral/flag" func main() { var port = 3000 flag.IntVar(&port, "port", port, "Port number") flag.Parse() fmt.Println("You seem to prefer", port) } ``` Then you can supply the values with either a command-line option or an environment variable: ``` :~/dev/GO$ go run dummy.go You seem to prefer 3000 :~/dev/GO$ go run dummy.go -port=1234 You seem to prefer 1234 :~/dev/GO$ PORT=4321 go run dummy.go You seem to prefer 4321 :~/dev/GO$ PORT=4321 go run dummy.go -port=5555 You seem to prefer 5555 ``` This might matter when it's hard to supply command-line arguments. For example, if you use Gin to automatically restart a server, you have no way to supply command-line arguments since Gin is just calling `go run` on the main code without any arguments passed along.
Finding minimal absolute sum of a subarray <sep> There's an array <code>A</code> containing (positive and negative) integers. Find a (contiguous) subarray whose elements' absolute sum is minimal, e.g.: <code>A = [2, -4, 6, -3, 9] |(4) + 6 + (3)| = 1 <- minimal absolute sum </code> I've started by implementing a brute-force algorithm which was <code>O(N^2)</code> or <code>O(N^3)</code>, though it produced correct results. But the task specifies: <code>complexity: - expected worst-case time complexity is O(N*log(N)) - expected worst-case space complexity is O(N) </code> After some searching I thought that maybe Kadane's algorithm can be modified to fit this problem but I failed to do it. My question is - is Kadane's algorithm the right way to go? If not, could you point me in the right direction (or name an algorithm that could help me here)? I don't want a ready-made code, I just need help in finding the right algorithm.
If you compute the partial sums such as `2, 2 + (-4), 2 + (-4) + 6, 2 + (-4) + 6 + (-3)...`, then the sum of any contiguous subarray is the difference of two of the partial sums. So to find the contiguous subarray whose absolute value is minimal, I suggest that you sort the partial sums and then find the two values which are closest together, and use the positions of these two partial sums in the original sequence to find the start and end of the subarray with smallest absolute value. The expensive bit here is the sort, so I think this runs in time `O(n * log(n))`.
How to move files in Google Cloud Storage from one bucket to another bucket by Python <sep> Are there any API function that allow us to move files in Google Cloud Storage from one bucket in another bucket? The scenario is we want Python to move read files in A bucket to B bucket. I knew that gsutil could do that but not sure Python can support that or not. Thanks.
```python from google.cloud import storage import os os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path_to_your_creds.json" def mv_blob(bucket_name, blob_name, new_bucket_name, new_blob_name): """Function for moving files between directories or buckets. It will use GCP's copy function then delete the blob from the old location. Inputs: bucket_name: name of bucket blob_name: str, name of file ex. 'data/some_location/file_name' new_bucket_name: name of bucket (can be same as original if we're just moving around directories) new_blob_name: str, name of file in new directory in target bucket ex. 'data/destination/file_name' """ storage_client = storage.Client() source_bucket = storage_client.get_bucket(bucket_name) source_blob = source_bucket.blob(blob_name) destination_bucket = storage_client.get_bucket(new_bucket_name) # copy to new destination new_blob = source_bucket.copy_blob(source_blob, destination_bucket, new_blob_name) # delete in old destination source_blob.delete() print(f'File moved from {source_blob} to {new_blob.name}') ```
Laravel htaccess <sep> I've setup a new install of Laravel on my local. It appears there are issues with htaccess or Apache settings. I've researched for a number of hours and tried everything I read. OSX Lion 10.7.5 MAMP 3.0.5 PHP 5.5.10 mod_rewrite is being loaded. My development server works with other sites. This is the first time I am trying Laravel 4. I get a 403 Forbidden on the welcome page which is located at website.dev:8888/ Apache gives me this error: Directory index forbidden by Options directive Here is my .htaccess file content: <code><IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> RewriteEngine On # Redirect Trailing Slashes... RewriteRule ^(.*)/$ /$1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule> </code> Here are a few additional actions I've taken: AllowOverride is set to All in httpd.conf Added virtual host code section to httpd-vhosts.conf verified that the hosts file contains a line for the site 127.0.0.1 website.dev I've also tried various lines in the htaccess which I found in articles and I also restarted apache each time I made changes to the conf files. No routes work. When I go to website.dev:8888/public I get a blank page, no error. If I go to a route I created such as website.dev:8888/users I get a 404 not found error. Thank you for your help!
This solution worked fine, the best solution ever for me. Paste this code into your root .htaccess file. That's all. Leave all other files as they are: ``` <IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> RewriteEngine On RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^ ^$1 [N] RewriteCond %{REQUEST_URI} (\.\w+$) [NC] RewriteRule ^(.*)$ public/$1 RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ server.php </IfModule> ```
How to store Django hashed password without the User object? <sep> I have a Django application that allows web visitors to create there own accounts. Once they create an account with a passwords, they should receive and email containing activation code. When a web-visitor creates a new account, they need to receive an activation email containing a unique key. Obviously, I can do all this using Django's built-in authentication system. I've done it before without any problems. However, in this application, I don't want to pollute my Users table with inactive users. I only want activated users to appear in the Users table. So although I will use Django's account system for authenticating activated users, until they become activated, I'm rolling my own system. I'm keeping all the data about not-yet-activated users in a separate Django Model object (called <code>UserActivation</code>). And I will be managing the sending of the activation email myself. The problem I'm having is that I don't want to store the user-submitted password in Plain text. I want to store it in my UserActivation object in a field called "password" in the same hashed-format it would appear in the User table. To put it into the user object, I would have done <code>myUser.set_password("plainTextPassword")</code>. How can I get this same value and stuff it into <code>UserActivation.password</code>? From looking at this doc, it seems that there is a <code>make_password()</code> function that returns the value that I need. But I still need a User object to call that method. How can I conver <code>"plainTextPassword"</code> to hashed password without going through the User object?
The accepted answer was helpful to me; I just wanted to add the `check_password` call (for people like me, who haven't used this functionality before). ```python from django.contrib.auth.hashers import make_password, check_password hashed_pwd = make_password("plain_text") check_password("plain_text", hashed_pwd) # returns True ```
How to check status of URLs from text file using bash shell script <sep> I have to check the status of 200 http URLs and find out which of these are broken links. The links are present in a simple text file (say URL.txt present in my ~ folder). I am using Ubuntu 14.04 and I am a Linux newbie. But I understand the bash shell is very powerful and could help me achieve what I want. My exact requirement would be to read the text file which has the list of URLs and automatically check if the links are working and write the response to a new file with the URLs and their corresponding status (working/broken).
I created a file "checkurls.sh" and placed it in my home directory where the urls.txt file is also located. I gave execute privileges to the file using `chmod +x checkurls.sh`. The contents of checkurls.sh are given below: ```bash #!/bin/bash while read url; do urlstatus=$(curl -o /dev/null --silent --head --write-out '%{http_code}' "$url" ) echo "$url $urlstatus" >> urlstatus.txt done < "$1" ``` Finally, I executed it from the command line using the following: `./checkurls.sh urls.txt`. Voila! It works.
How to Create an Empty SelectList <sep> I have the folloiwng action method: <code>public JsonResult LoadSitesByCustomerName(string customername) { var customerlist = repository.GetSDOrg(customername) .OrderBy(a => a.NAME) .ToList(); var CustomerData; CustomerData = customerlist.Select(m => new SelectListItem() { Text = m.NAME, Value = m.NAME.ToString(), }); return Json(CustomerData, JsonRequestBehavior.AllowGet); } </code> but currently i got the following error on <code>var CustomerData;</code>: <code>implicitly typed local variables must be initialized </code> so i am not sure how i can create an empty SelectList to assign it to the var variable ? Thanks
Use this to create an empty `SelectList`: `new SelectList(Enumerable.Empty<SelectListItem>())`. `Enumerable.Empty<SelectListItem>()` creates an empty sequence which will be passed to the constructor of `SelectList`. This is necessary because `SelectList` has no constructor overloading without parameters.
javascript function wait until another function to finish <sep> I have two javascript functions that are called from android. After long debug sessions finally I realized that the problem is arising from the fact that second function is getting called before first one is finished. I already searched the examples with deferred etc, but they all depends on function calls within another one. <code>function FunctInit(someVarible){ //someVariable is sent from android, cannot call again from getResult //init and fill screen } function getResult(){ //also getResult need to be called from android via button //return some variables } </code> How can I force getResult to wait FuncInit? Is there a way to achieve this via Javascript?
In my opinion, deferreds/promises (as you have mentioned) is the way to go, rather than using timeouts. Here is an example I have just written to demonstrate how you could do it using deferreds/promises. Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks. Hope this helps! ```javascript $(function() { function1().done(function() { // function1 is done, we can now call function2 console.log('function1 is done!'); function2().done(function() { //function2 is done console.log('function2 is done!'); }); }); }); function function1() { var dfrd1 = $.Deferred(); var dfrd2 = $.Deferred(); setTimeout(function() { // doing async stuff console.log('task 1 in function1 is done!'); dfrd1.resolve(); }, 1000); setTimeout(function() { // doing more async stuff console.log('task 2 in function1 is done!'); dfrd2.resolve(); }, 750); return $.when(dfrd1, dfrd2).done(function() { console.log('both tasks in function1 are done'); // Both async tasks are done }).promise(); } function function2() { var dfrd1 = $.Deferred(); setTimeout(function() { // doing async stuff console.log('task 1 in function2 is done!'); dfrd1.resolve(); }, 2000); return dfrd1.promise(); } ```
How to access repository methods for an entity in symfony2? <sep> I am stuck with a problem please help me with it. Here is the scenarario: I have an entity "User" and corresponding repository "UserRepository", inside my entity there are only getter and setter methods. All custom queries I have written to UserRepository. Now inside my UserController I am trying to access repository methods which I am not able to do so. e.g. User entity: <code>class User { ... public function getId() { return $this->id; } public function setId($id) { return $this->id=$id; } public function setProperty($property) { $this->property = $property; } public function getProperty() { return $this->property; } .... } ?> </code> UserRepository: <code>class UserRepository extends EntityRepository { public function findUsersListingById($id) { $queryBuilder = $this->getEntityManager()->createQueryBuilder(); $query = $em->createQuery( "SELECT U FROM UserEntityPathGoesHere WHERE U.id IN (".implode(",", $id).")" ); $users = $query->getResult(); return $users; } public function sayHelloWorld(){ echo ' Hello World'; } } ?> </code> UserController <code>class UserController { ... $users=$this->getDoctrine() ->getRepository('MyUserEntityPath') ->findUsersListingById($ids); //now I have multiple users I want to iterate through each user for associating additional data with each user foreach($users as $user) { $temp = array(); //I am able to access getId method which is defined in User entity $temp['id'] = $user->getId(); //however I am not able to access method from UserRepository, I tried something like below which gives me error call to undefined function sayHelloWorld $temp['status'] = $user->sayHelloWorld(); .... } } </code> .... How can I access repository methods for an entity? Is it possible ? If not then what are the alternatives for the solution?
Everything is possible, however, you should not access the entity's repository from the entity itself because of the separation of concerns. See this Stack Overflow answer for more details. Basically, the whole idea is that you want to have your application organized this way: Controller > Repository > Entities. It should not go in the other direction, otherwise, it creates a mess. If you want to go a bit further into the separation of concerns, you could do the following: Controller > Service > Repository > Entities. Alternative solutions: * Create a Twig extension that accesses a service (which accesses a repository) or a repository. * Create a method in your repository, call the method in your controller, map the data to IDs (keys of an array are the IDs), pass the array to the template, and then pull the data from the array using the entity IDs. * Create a method in your repository, call the method in your controller, inject the data into your entities, and access the data through the entity in your template. There are probably others, but you would know better how your application is organized.
How to remove leading zeros from string using C++? <sep> I want to remove leading zeroes from string like <code>"0000000057"</code>. I did like this but didn't get any result: <code>string AccProcPeriNum = strCustData.substr(pos, 13); string p48Z03 = AccProcPeriNum.substr(3, 10); </code> I want output only 57. Any idea in C++?
Piotr S's answer is good, but there is one case where it will return the wrong answer: the all-zero case (e.g., `000000000000`). To address this, use: `str.erase(0, std::min(str.find_first_not_of('0'), str.size() - 1));` Even when `str.size()` is 0, this will also work.
Android Studio - Run signed apk on emulator <sep> This may sound extremely trivial but as an android newbie I just found myself buried under a ton of hashes tokens keystores and keytools which can be a bit overwhelming. I am trying to make android studio run my application on the emulator signed with my custom keystore and not the debug.keystore Is this an option, or do I just have to generate a signed .apk every time I make changes, then install it via adb and then run it from the emulated device's menu? Also is that a good practice when testing applications or should I avoid it?
After running into problems when using the Android Studio UI to create a signing config, I successfully managed to set it up via the Gradle build file. Open your project's `build.gradle` file. It should contain something like this: ```groovy android { // signingConfigs goes here defaultConfig { // SDK version, version code etc } // Some more stuff } ``` If it isn't already in there, add the following snippet below `android {`: ```groovy signingConfigs { debug { storeFile file(project.property("MyApp.signing")) storePassword project.property("MyApp.signing.password") keyAlias project.property("MyApp.signing.alias") keyPassword project.property("MyApp.signing.password") } } ``` Now, in the same directory where your `build.gradle` file lies, you should have a `gradle.properties` file (if not, create it). We'll now add the properties we used above to the properties file in order to map the values: ```groovy MyApp.signing=RelativeOrAbsolutePathToKeystore MyApp.signing.password=yourPassword MyApp.signing.alias=aliasNameOfYourKeystore ``` An example where the `keystore.jsk` file (generated via Android Studio) lies one directory above the app directory (in which the properties file is): ```groovy MyApp.signing=../myapp.keystore.jsk MyApp.signing.password=helloworkd MyApp.signing.alias=myapp_alias ``` The above configuration would then use the key to sign a debug build (because our `signingConfigs` was made for the debug build). So make sure that in Android Studio, you set your build variant to "debug". If you want to do all this for the release build, switch your build variants to "release" and your `signingConfigs` to `release {...}` instead of `debug {...}` or simply add both if you want to switch between them.
How to reboot android device emulator in Genymotion <sep> How can i test my application after reboot(BOOT COMPLETED) using Genymotion I am using nexus 4 as device <code><receiver android:name="com.template.SampleBootReceiver" android:enabled="true"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> </code>
You can use the command line with `adb reboot`. It should restart your device. To use adb, you need to be inside the adb binary's folder, i.e., `<android SDK>/platform-tools/` or `<genymotion folder>/tools/` if the Android SDK is not installed. You can also add these folders to your path to access it from anywhere.
Change $key of associative array in a foreach loop in php <sep> I have an array like this: <code>array( 'firstName' => 'Joe', 'lastName' => 'Smith' ) </code> I need to loop over every element in my array and in the end, the array should look like this: <code>array( 'FirstName' => 'Joe', 'LastName' => 'Smith' ) </code> Failed idea was: <code> foreach($array as $key => $value) { $key = ucfirst($key); } </code> This obviously will not work, because the array is not passed by reference. However, all these attempts also fail: <code> foreach(&$array as $key => $value) { $key = ucfirst($key); } foreach($array as &$key => $value) { $key = ucfirst($key); } </code> Pretty much at my wits end with this one. I'm using Magento 1.9.0.1 CE, but that's pretty irrelevant for this problem. If you must know, the reason I have to do this is because I have a bunch of object that's I'm returning as an array to be assembled into a SOAP client. The API I'm using requires the keys to begin with a capital letter...however, I don't wish to capitalize the first letter of my object's variable names. Silly, I know, but we all answer to someone, and that someone wants it that way.
unset it first in case it is already in the proper format, otherwise you will remove what you just defined: foreach($array as $key => $value) { unset($array[$key]); $array[ucfirst($key)] = $value; }
Making a Texture2D readable in Unity via code <sep> I have some AssetBundles that I want to convert to .png image files. They are Texture2D assets, but the problem is as they are not Read Enable, when I try to convert them to PNG with a <code>var _bytes = _texture2d.EncodeToPNG(); </code> command, I get the following error message: <blockquote> Texture 'name of a texture' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings. </blockquote> I really can't access the Texture Import Settings, as they come from asset bundles and everything is made with code. Somebody has a workaround for this? Thanks
```csharp public static void SetTextureImporterFormat(Texture2D texture, bool isReadable) { if (texture == null) return; string assetPath = AssetDatabase.GetAssetPath(texture); var tImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (tImporter != null) { tImporter.textureType = TextureImporterType.Advanced; tImporter.isReadable = isReadable; AssetDatabase.ImportAsset(assetPath); AssetDatabase.Refresh(); } } ```
Flask-SQLAlchemy Abstract Base Model <sep> In my Flask-SQLAlchemy App I want to add a few fields (created(by|on), changed(by|on)) to every Model/Table my code right now <code>from .. import db class Brand(db.Model): __tablename__ = 'md_brands' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True, nullable=False) def __repr__(self): return u'<Brand {}>'.format(self.name) </code> I am not sure if it's better to use Mixins or somehow extend the base db.Model (or if even there is a better way to do this). What (and why) is the best way to add such fields (created(by|on), changed(by|on)) to all my models?
```python from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(app) class Base(db.Model): __abstract__ = True created_on = db.Column(db.DateTime, default=db.func.now()) updated_on = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now()) class User(Base): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) ```
corrupted unsorted chunks while calling free() <sep> <code>*** glibc detected *** ./a.out: free(): corrupted unsorted chunks: 0x00000000007646b0 *** *** glibc detected *** ./a.out: malloc(): memory corruption: 0x00000000007635a0 *** </code> I'm getting the above error. But I'm sure that I'm not using the memory after freeing. Why do I get the above error ?
All heaps store certain kinds of metadata inside themselves. When you perform a `malloc` or `free`, the heap will often perform some bookkeeping functions. If it detects something unexpected in the metadata, it will normally crash. Normal heap operations are highly unlikely to cause such problems, so your program is most likely the cause. Since your program has access to all the memory in the process, including the heap metadata, it could have accidentally overwritten some of the metadata. A likely cause is writing beyond the end of an allocated buffer. This write will most probably be allowed and is extremely likely to corrupt the heap metadata. When this is detected by the heap, your program will normally abort.
Generate an integer binary representation using Swift? <sep> How to create a function accepting any type of Int or Uint in swift (and calculating number of bits needs regarding param type)
```swift String has constructors init<T : _SignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default) init<T : _UnsignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default) which can be used here: let num = 100 let str = String(num, radix: 2) print(str) // Output: 1100100 ``` Let me know if you'd like me to elaborate on any of the changes!
Stop Android Studio from wrapping methods and constructors <sep> How can I stop Android Studio from wrapping method lines and constructors? This is how Android Studio currently does it: A class <code>public class Foo { public Foo(Context context, AttributeSet attrs) { super(context, attrs); } } </code> A Method <code>public static void doSomething(Foo foo) { foo.doWork(); } </code> This is how I would like it: A class <code>public class Foo { public Foo(Context context, AttributeSet attrs) { super(context, attrs); } } </code> A Method <code>public static void doSomething(Foo foo) { foo.doWork(); } </code>
Navigate to `Settings >> Editor >> General >> Code Folding`. You will find "One-line methods" checked there. Uncheck it. There are also other settings you can change as needed. I attached a screenshot too. Finally, restart your IDE. Done! Hope this is helpful.
How to define array of objects in Sequelize.js? <sep> How can I define an array of objects field in Sequelize.js model? I need something like this <code>{ "profiles" : [ { "profile_id": 10, "profile_pictures" : ["pic1.jpg","pic2.jpg","pic3.jpg"], "profile_used_id" : 12 }, ... // more profiles ] } </code> I checked the docs, but couldn't find a relevant data type, am I missing something here ?
```javascript var MyModel = sequelize.define('MyModel', { myArrayField: { type: DataTypes.STRING, get: function() { return JSON.parse(this.getDataValue('myArrayField')); }, set: function(val) { return this.setDataValue('myArrayField', JSON.stringify(val)); } } }); ```
Spring Tool Suite 3.6.1 won't update <sep> Updating the Spring Tool Suite in Eclipse Luna, I get the following error since I turned off the option to download updates for Eclipse 3.7: <code>**An error occurred while collecting items to be installed session context was:(profile=DefaultProfile, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=). No repository found containing: osgi.bundle,org.springsource.ide.eclipse.commons.quicksearch,3.6.1.201408250654-RELEASE No repository found containing: osgi.bundle,org.springsource.sts,3.6.1.201408250824-RELEASE No repository found containing: org.eclipse.update.feature,org.springsource.ide.eclipse.commons.quicksearch.feature,3.6.1.201408250654-RELEASE No repository found containing: org.eclipse.update.feature,org.springsource.sts,3.6.1.201408250824-RELEASE No repository found containing: binary,org.springsource.sts.ide.executable.win32.win32.x86_64,3.6.1.201408250824-RELEASE-e43 No repository found containing: org.eclipse.update.feature,org.springsource.sts.package,3.6.1.201408250824-RELEASE-e43 No repository found containing: binary,org.springsource.sts.package_root,3.6.1.201408250824-RELEASE-e43** </code> The version I have installed is: <code>Spring Tool Suite Version: 3.6.0.RELEASE Build Id: 201407101106 Platform: Eclipse Luna (4.4)** </code> Does anyone know how to fix this?
The first bullet point from Martin's answer fixed my issue. I had multiple update sites for SpringSource, including e3.7, e4.3, and e4.4. Steps I took to fix this: Select Window -> Preferences from the menu; expand Install/Update and select Available Software Sites; uncheck update sites for SpringSource, except e4.4, and save. To test the fix: Select Help -> Check for Updates. Hope this helps. Thanks, Martin, for pointing this situation out.
radio group setOnCheckedChangeListener <sep> I have some problem with radio group, I am new to Android development so I don't have much idea to how can handle it.This is form which has some input filed and radio group for choosing gender and save button. but I don't know where can I exactly put my radiogroup setoncheakchangelistener? so it gives me errors. MAIN ACTIVITY : <code>package com.dietandroidproject; import Databasedata.Person; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final RadioGroup genderselected = (RadioGroup) findViewById(R.id.selectgender); genderselected.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup arg0, int selectedId) { selectedId=genderselected.getCheckedRadioButtonId(); RadioButton genderchoosed = (RadioButton) findViewById(selectedId); String gender = genderchoosed.getText().toString(); } }); Button saveinformation = (Button) findViewById(R.id.saveinformation); saveinformation.setOnClickListener(new View.OnClickListener() { EditText weighttext = (EditText) findViewById(R.id.weighttext); EditText heighttext = (EditText) findViewById(R.id.heighttext); EditText usernametext = (EditText) findViewById(R.id.usernametext); EditText agetext = (EditText) findViewById(R.id.agetext); Spinner activitytext = (Spinner) findViewById(R.id.chooseactivity); Button saveinformation = (Button) findViewById(R.id.saveinformation); String pa = activitytext.getSelectedItem().toString(); @Override public void onClick(View v) { int weight = (int) Float.parseFloat(weighttext.getText() .toString()); int height = (int) Float.parseFloat(heighttext.getText() .toString()); String username = usernametext.getText().toString(); int age = (int) Float.parseFloat(agetext.getText().toString()); TextView genderchoosed = (TextView) findViewById(genderselected .getCheckedRadioButtonId()); String gender = genderchoosed.getText().toString(); String pa = activitytext.getSelectedItem().toString(); //BMI========================================================== int Bmivalue = calculateBMI(weight, height); String bmiInterpretation = interpretBMI(Bmivalue); float idealweight = idealweight(weight, height, gender, pa, age); double dailycalories=dailycalories(weight,height,gender,pa,age); //insert data in to db=================================================== Person person = new Person(); person.setUsername(username); person.setHeight(height); person.setWeight(weight); person.setAge(age); person.setGender(gender); person.setPa(pa); person.setBmivalue(Bmivalue); person.setBmiInterpretation(bmiInterpretation); person.setIdealweight(idealweight); person.setDailycalories(dailycalories); Databasedata.DatabaseAdapter dbAdapter = new Databasedata.DatabaseAdapter( MainActivity.this); dbAdapter.insertPerson(person); Toast.makeText(getApplicationContext(), Bmivalue + "and you are" + bmiInterpretation, Toast.LENGTH_LONG).show(); } }); } //BMI FUNCTION=============================================== private int calculateBMI(int weight, int height) { return (int) (weight / (height * height)); }; private String interpretBMI(int Bmivalue) { if (Bmivalue < 18.5) { return "Underweight"; } else if (Bmivalue < 25) { return "Normal"; } else if (Bmivalue < 30) { return "Overweight"; } else { return "Obese"; } } //IDEAL WEIGHT======================================== private float idealweight(int weight, int height, String gender, String pa, int age) { float x = (float) 0.0; int bmi; bmi = idealbmi(age); x = bmi * (height * height); return x; } public int idealbmi(int age) { int bmi = 0; if (age > 17 && age <= 19) { bmi = 21; } if (age > 19 && age <= 24) { bmi = 22; } if (age > 24 && age <= 34) { bmi = 23; } if (age > 34 && age <= 44) { bmi = 24; } if (age > 44 && age <= 54) { bmi = 25; } if (age > 54 && age <= 64) { bmi = 26; } if (age > 64) { bmi = 27; } return bmi; } //DAILY CALORIES=============================================== public double suitablepa(String pa) { double suitablepa = 0; if (pa.equals("Highly active")) { suitablepa = 1.48; } if (pa.equals("Active")) { suitablepa = 1.25; } if (pa.equals("Low activity")) { suitablepa = 1.11; } if (pa.equals("Sedentary")) { suitablepa = 1; } return suitablepa; } private double dailycalories(int weight, int height, String gender, String pa, int age) { double dailycalori = 0; double i; double j; double h; double k; if(gender.equals("femaleselected")){ i=9.36*weight; j=726*height; h=suitablepa(pa)*(i+j); k=6.91*age; dailycalori=354-k+h; }else if(gender.equals("maleselected")){ i=15.91*weight; j=539.6*height; h=suitablepa(pa)*(i+j); k=9.53*age; dailycalori=662-k+h; } return dailycalori; } } </code> XML CODES <code><?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/backgroundmain" android:orientation="vertical" > <RelativeLayout android:id="@+id/personinformation" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1.98" > <EditText android:id="@+id/heighttext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/usernametext" android:layout_below="@+id/usernametext" android:ems="10" android:hint="Enter Your Height" > </EditText> <EditText android:id="@+id/usernametext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:ems="10" android:hint="Enter Username" /> <EditText android:id="@+id/weighttext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/heighttext" android:layout_below="@+id/heighttext" android:ems="10" android:hint="Enter Your Weight" /> <EditText android:id="@+id/agetext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/weighttext" android:layout_below="@+id/weighttext" android:ems="10" android:hint="Enter Your Age" > <requestFocus /> </EditText> </RelativeLayout> <View android:layout_width="250dp" android:layout_height="1dip" android:layout_gravity="center" android:layout_marginTop="20dp" android:background="#aaa" /> <RelativeLayout android:id="@+id/choosegender" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="0.78" > <TextView android:id="@+id/choosefemaleormale" android:layout_width="match_parent" android:layout_height="30dip" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginTop="10dip" android:gravity="center" android:text="Gender : " android:textAlignment="center" android:textColor="#555" android:textSize="19sp" /> <RadioGroup android:id="@+id/selectgender" android:layout_width="220dip" android:layout_height="wrap_content" android:layout_below="@+id/choosefemaleormale" android:layout_centerHorizontal="true" android:orientation="horizontal" > <RadioButton android:id="@+id/femaleselected" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="left" android:layout_weight="1" android:checked="true" android:text="female" android:onClick="onRadioButtonClicked" /> <RadioButton android:id="@+id/maleselected" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="right" android:layout_weight="1" android:text="male" android:onClick="onRadioButtonClicked" /> </RadioGroup> </RelativeLayout> <View android:layout_width="250dp" android:layout_height="1dip" android:layout_gravity="center" android:layout_marginTop="20dp" android:background="#aaa" /> <RelativeLayout android:id="@+id/choosepa" android:layout_width="250dip" android:layout_height="0dp" android:layout_weight="1" android:layout_gravity="center" > <Spinner android:id="@+id/chooseactivity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:entries="@array/activityitems" android:gravity="center" android:prompt="@string/level_of_activity" /> </RelativeLayout> <Button android:layout_width="90dp" android:layout_height="0dp" android:layout_gravity="right" android:layout_marginBottom="10dip" android:layout_marginRight="20dp" android:layout_weight="0.46" android:background="@drawable/recent_foods_depressed" android:hint="save" android:text="save" android:textColor="#fff" android:textSize="20sp" android:textStyle="bold" android:onClick="saveinformation" android:id="@+id/saveinformation"/> </LinearLayout> </code>
```java radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { RadioButton rb = (RadioButton) findViewById(checkedId); Toast.makeText(getApplicationContext(), rb.getText(), Toast.LENGTH_SHORT).show(); } }); ```
python time measure for every function <sep> I just completed writing my first program in python, i have written all my functions in a single module, i just executed it from command line by giving the input files as argument and it worked. But when i gave a big dataset, my program continuously running for some time. Now my next step is to find which function is taking more time in my module. I could get the time taken by whole program, but i need for each function separately. I tried to understand timeit and profile modules in python, but as per my understanding, they were giving the time taken by a particular function. Is there a way to know the time taken by each function in my module as a statistics( all at once )? Thanks in advance.
At the terminal, run `python -m profile -s time file.py` or `python -m cProfile -s time file.py`. The second can be faster and is never worse. This will give something like: ``` Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 39 0.132 0.003 0.139 0.004 :0(load_dynamic) 239 0.097 0.000 0.097 0.000 :0(loads) 541/1 0.083 0.000 3.556 3.556 :0(exec) 30 0.082 0.003 0.082 0.003 :0(statusBar) ... etc ... ``` The left-hand side will contain your functions.
bluetooth keyboard will cause activity destroy and recreate <sep> Bluetooth keyboard will cause activity destroy and recreate if I turn off it or far away from pad(Android) Activity will be recreate how can i avoid this problem
In contrast to the accepted answer, I found that `keyboard|keyboardHidden` was not enough. I was working with a Logitech Bluetooth keyboard (model #JNZYR0021). What did work was this: `<activity ... android:configChanges="orientation|screenSize|keyboard|keyboardHidden|navigation" />` Apparently this Logitech keyboard also changes `navigation`, which is weird because the Android docs say: > The navigation type (trackball/dpad) has changed. (This should never normally happen.) Go figure.
Django Compressor does not minify files <sep> I am trying to let django-compressor working with mezzanine. For first attempt I simply installed django compressor (as should be done for Mezzanine) and changed DEBUG = False but nothing changed in HTML generated from Django. So I followed the docs of django compressor and I modified my settings.py: <code>STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", #"django.contrib.staticfiles.finders.AppDirectoriesFinder", #'django.contrib.staticfiles.finders.DefaultStorageFinder', "compressor.finders.CompressorFinder", ) INSTALLED_APPS = ( "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.redirects", "django.contrib.sessions", "django.contrib.sites", "django.contrib.sitemaps", "django.contrib.staticfiles", "mezzanine.boot", "mezzanine.conf", "mezzanine.core", "mezzanine.generic", "mezzanine.blog", "mezzanine.forms", "mezzanine.pages", "mezzanine.galleries", "mezzanine.twitter", #"mezzanine.accounts", #"mezzanine.mobile", #'debug_toolbar', "compressor", ) OPTIONAL_APPS = ( #"debug_toolbar", "django_extensions", #"compressor", I commented it to follow the django-compressor doc PACKAGE_NAME_FILEBROWSER, PACKAGE_NAME_GRAPPELLI, ) COMPRESS_ENABLED = True COMPRESS_ROOT = STATIC_ROOT </code> These are the packages installed in my environment: <code>Django==1.6.5 Mezzanine==3.1.5 Pillow==2.5.1 bleach==1.4 distribute==0.6.24 django-appconf==0.6 django-compressor==1.4 filebrowser-safe==0.3.5 future==0.9.0 grappelli-safe==0.3.12 html5lib==1.0b3 oauthlib==0.6.3 pytz==2014.4 requests==2.3.0 requests-oauthlib==0.4.1 six==1.7.3 tzlocal==1.0 </code> Here, how I used compressor in templates: <code>{% load pages_tags mezzanine_tags i18n future staticfiles compress %} {% compress css %} <link rel="stylesheet" href="{% static "css/custom/mycss.css" %}"> {% endcompress %} </code> and nothing happened until I launched: <blockquote> python manage.py compress --force </blockquote> So now I have the cache populated and the HTML generated from Django points to the files in CACHE like: <code><link rel="stylesheet" href="/static/CACHE/css/16e8b98f5bd3.css" type="text/css" media="screen"> </code> but the files are not minified, django compressor simply copied them and changed the name. Do you know why the compressor not minify them?
Django compressor will not run on the Django server even with `DEBUG = False`. It also, by default, only merges all your CSS files into one. To do other things like minify, you can apply a filter. Here is what I did in my settings.py: `COMPRESS_ENABLED = True COMPRESS_CSS_FILTERS = ['compressor.filters.css_default.CssAbsoluteFilter', 'compressor.filters.cssmin.CSSMinFilter']` I think this will be helpful for others. Cheers!
Error dialog displayed when opening an excel file generated with EPPlus <sep> I am creating an Excel file using the EPPlus library. When I create file and open up the file, the following pop up message shows: <blockquote> We found a problem with some content in 'ExcelDemo.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, Click Yes </blockquote> I am using following code <code>using (ExcelPackage pck = new ExcelPackage()) { //Create the worksheet ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo"); //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1 ws.Cells[1, 2].Value = "Excel Download"; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx"); Response.BinaryWrite(pck.GetAsByteArray()); } </code> Is there problem in my code or is this an Excel issue?
In my case, the problem was calling `package.Save();` and using `Response.BinaryWrite(package.GetAsByteArray());` at the same time. When you call `package.GetAsByteArray()`, it performs the following operations internally: `this.Workbook.Save(); this._package.Close(); this._package.Save(this._stream);`. So, calling `package.Save()` twice leads to this error when opening in Excel.
JAXB Ignore 'extra' elements from Response XML <sep> I am getting a XML response and it keeps on changing very frequently (nodes keep on increasing or reducing). After each updation in response xml my code breaks as my mapped Java class does not have all fileds. Is there any way to avoid my code breaking if any changes occurs in response XML. Any help will be appreciated. Thanks.
Use `JAXB.unmarshal()` to simply create Java objects from XML. By default, it is very liberal. Quoting from the javadoc: <blockquote>In addition, the unmarshal methods have the following characteristic: Schema validation is not performed on the input XML. The processing will try to continue even if there are errors in the XML, as much as possible. Only as a last resort, this method fails with a `DataBindingException`.</blockquote> So, what `JAXB.unmarshal()` does is it tries to "transfer" as much data from XML to Java as possible. It doesn't care if there is no Java field for an XML element or attribute, and it also doesn't care if there is a Java field for which there is no XML element or attribute. **Example** Let's try to unmarshal the following XML to an instance of `java.awt.Point`: ```xml <p hi="Yo"> <y>123</y> <peach>weor</peach> </p> ``` The Java code: ```java String s = "<p hi=\"Yo\"><y>123</y><peach>weor</peach></p>"; Point p = JAXB.unmarshal(new StringReader(s), Point.class); System.out.println(p); // Prints "java.awt.Point[x=0,y=123]" ``` We told `JAXB.unmarshal()` to parse a `java.awt.Point` instance. The input XML contains an element `<y>` which can be matched with `Point.y`, so an `int` was parsed and set to `Point.y`. No XML data was found for `Point.x`, so it was not touched. There were no matches for the attribute `hi` and the XML element `<peach>`, so they were simply not used for anything. We got absolutely no `Exception` here, and the most that was possible was parsed and transferred from XML to Java.
What is UITableView separatorEffect property for? <sep> New in iOS 8 is a <code>separatorEffect</code> property, to which you are allowed to assign a UIVisualEffect. Has anyone figured out what this is for? I've tried it and I don't see it as having any, uh, visual effect.
I was wondering the exact same thing, so I put a GitHub project together for anyone facing the same issue. The basic idea is that if your `tableView`'s backgroundView consists of a `UIVisualEffectView` with a blur effect, then setting the `separatorEffect` to a Vibrant Effect with the same blur as the `UIVisualEffectView` will produce the effect we see in Notification Center where the separators seem transparent. Something like this: `tableView.separatorEffect = UIVibrancyEffect(forBlurEffect: blurredBackgroundView.blurView.effect as UIBlurEffect)` will produce a table view like this:
Reading System.in for Intellij using Console <sep> I need to open up the console and type in inputs for my an assignment using Intellij. Eclipse has a way of doing this using the <code>Scanner</code> class and reading <code>System.in</code> but running the same code in IntelliJ does not work as I can't type anything into the console. Is there any way to do this? My code is as follows: <code> public class BasicAssertions { @Test public void testAssertions(){ System.out.println("Enter: "); Scanner reader = new Scanner(System.in); int first = reader.nextInt(); int second = reader.nextInt(); String s = reader.next(); String s2 = reader.next(); assertTrue(first<=second); assertFalse(first+second >100); assertNotEquals(s,s2); assertNotNull(s2); } } </code>
Resolved. A `public static void main()` method is required for the correct console to appear; otherwise, running using the default JUnit Test configuration will only result in a console that doesn't receive inputs.
How do I pass parameters to a salt state file? <sep> I want to create a group and user using salt state files, but I do not know the group, gid, user, uid, sshkey until I need to execute the salt state file which I would like to pass in as parameters. I have read about Pillar to create the variable. How do I create pillars before execution? <code>/srv/salt/group.sls</code>: <code>{{ name }}: group.present: - gid: {{ gid }} - system: True </code> Command line: <code>salt 'SaltStack-01' state.sls group name=awesome gid=123456 </code>
If you really want to pass in the data on the command line, like this: ``` {{ pillar['name'] }}: group.present: - gid: {{ pillar['gid'] }} - system: True ``` Then on the command line you can pass in the data like this: ``` salt 'SaltStack-01' state.sls group pillar='{"name": "awesome", "gid": "123456"}' ```
How to use InsertOrReplace in sqlite.net PCL? <sep> I am using the PCL version of sqlite.net from here (https://github.com/oysteinkrog/SQLite.Net-PCL). Here is my simple class. <code> public class LogEntry { [PrimaryKey, AutoIncrement] public int Key { get; set;} public DateTime Date { get; set; } } </code> When a new instance of LogEntry is created, the Key is automatically set to 0. I set the Date to something and then call InsertOrReplace. The record does get saved in my database. The Key field gets the autoincrement value which happens to be 0 since it is the first record. I then create a new instance of LogEntry (Key is automatically initialized to 0) and set the date to something else. I then call InsertOrReplace. Since there is an existing record with a Key of 0 that record gets updated. What is the proper way to deal with this? I considered initializing the Key to -1, but that didn't seem to work either. Does anyone have an example of this working?
If you change the `Key` to a nullable type (int?), it should work. Then SQLite sees null coming in and generates a new ID when needed. ```csharp public class LogEntry { [PrimaryKey, AutoIncrement] public int? Key { get; set; } public DateTime Date { get; set; } } ```
Import JSON Files into Logstash + Elasticsearch + Kibana <sep> So, I have a web platform that prints a JSON file per request containing some log data about that request. I can configure several rules about when should it log stuff, only at certain levels, etc... Now, I've been toying with the Logstash + Elasticsearch + Kibana3 stack, and I'd love to find a way to see those logs in Kibana. My question is, is there a way to make Logstash import these kind of files, or would I have to write a custom input plugin for it? I've searched around and for what I've seen, plugins are written in Ruby, a language I don't have experience with.
Logstash is a very good tool for processing dynamic files. Here is the way to import your JSON file into Elasticsearch using Logstash: **Configuration File:** ``` input { file { path => ["/path/to/json/file"] start_position => "beginning" sincedb_path => "/dev/null" exclude => "*.gz" } } filter { mutate { replace => [ "message", "%{message}" ] gsub => [ 'message','\n',''] } if [message] =~ /^{.*}$/ { json { source => message } } } output { elasticsearch { protocol => "http" codec => json host => "localhost" index => "json" embedded => true } stdout { codec => rubydebug } } ``` **Example of JSON File:** ```json {"foo":"bar", "bar": "foo"} {"hello":"world", "goodnight": "moon"} ``` Note: The JSON needs to be in one line. If you want to parse a multiline JSON file, replace relevant fields in your configuration file: ``` input { file { codec => multiline { pattern => '^{' negate => true what => previous } path => ["/opt/mount/ELK/json/*.json"] start_position => "beginning" sincedb_path => "/dev/null" exclude => "*.gz" } } filter { mutate { replace => [ "message", "%{message}" ] gsub => [ 'message','\n',''] } if [message] =~ /^{.*}$/ { json { source => message } } } ```
Making a mixin of interfaces in Typescript <sep> I have a class with over 80 methods, and each method accepts an object containing some defined interface. <code>class Stuff { /* many more */ getAccount(req: IAccount, callback: ICallback) { return this._call('getAccount', req, callback); } getIds(req: IIDs, callback: ICallback) { return this._call('getIds', req, callback); } /* many more */ } </code> pretty 'boring' stuff, since it's just mapping to the underlaying <code>_call</code> method and making it type safe for each of the methods. But sometimes these <code>req</code> param objects are made up from 2 interfaces or more, and instead of creating another interface for each time there's an "awkward", like this: <code>export interface ILoled extends IAccount { loled: boolean; } export interface IRofloled extends ILoled { rofled: boolean; } class Stuff { getLols(req: ILoled){ } getRofls(req: IRofloled){ } } </code> is there any way I can just put it as an "inline" mixin of interfaces inside the method parameter list? like (which obviously don't work): <code>class Stuff { getMoreStuff(req: <{} extends IAccount, ITime>) { } } </code>
Yes, you can, as of TypeScript 1.6. Called intersection types, use the `&` operator to combine types. ```typescript function extend<T, U>(first: T, second: U): T & U { let result = <T & U> {}; for (let id in first) { result[id] = first[id]; } for (let id in second) { if (!result.hasOwnProperty(id)) { result[id] = second[id]; } } return result; } var x = extend({ a: "hello" }, { b: 42 }); x.a; // works x.b; // works ```
Format datetime.utcnow() time <sep> I have saved a time as <code>presentTime=datetime.datetime.utcnow()</code> It 's output is 2014-08-18 21:11:35.537000. How can this be formatted to : August 18 2014 - 21:11:35 instead?
`datetime.utcnow()` returns a `datetime` object. You can use its `strftime` method to convert it into a string of your desired format: `>>> datetime.datetime.utcnow().strftime('%B %d %Y - %H:%M:%S')` 'August 20 2014 - 13:55:49'
cordova - remove unnecessary permissions <sep> I need to play sounds in my game, so I added org.apache.cordova.media plugin to my application. Now platforms/android/AndroidManifest.xml contains 2 entries I don't need: <code><uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> </code> If I remove those lines, this file regenerated and permissions are added again. What is correct way to remove these permissions? I use apache cordova 3.5.0
Create a file in the root directory of your project and rename it to `remove_permissions.js`. Then put the following code into it: ```javascript var permissionsToRemove = [ "RECORD_AUDIO", "MODIFY_AUDIO_SETTINGS" ]; var fs = require('fs'); var path = require('path'); var rootdir = ""; var manifestFile = path.join(rootdir, "platforms/android/app/src/main/AndroidManifest.xml"); fs.readFile(manifestFile, "utf8", function( err, data ) { if (err) return console.log(err); var result = data; for (var i=0; i<permissionsToRemove.length; i++) { result = result.replace( "<uses-permission android:name=\"android.permission." + permissionsToRemove[i] + "\" />", "" ); } fs.writeFile(manifestFile, result, "utf8", function( err ) { if (err) return console.log(err); }); }); ``` Open `config.xml` and add the following line in the Android part: ```xml <platform name="android"> ... <hook type="after_prepare" src="remove_permissions.js"/> ... </platform> ``` Now rebuild the APK file.
Gmail API - Parse message content (Base64 decoding?) with Javascript <sep> I'm trying to use the Gmail API to get a user's email, grab the message subject and body, and then display it on a webpage. I'll be doing other stuff with it, but this is the part that I am having difficulty with. I am using Angular.js. Here is my API call: <code>function makeApiCall() { gapi.client.load('gmail', 'v1', function() { var request = gapi.client.gmail.users.messages.list({ labelIds: ['INBOX'] }); request.execute(function(resp) { var content = document.getElementById("message-list"); angular.forEach(resp, function(message) { var email = gapi.client.gmail.users.messages.get({'id': message.id}); // var raw = email.payload.parts; // console.log(raw); content.innerHTML += JSON.stringify(email) + "<br>"; }) }); }); } </code> So <code>gapi.client.gmail.users.messages.list</code> returns an array of my messages, with their ID numbers. That is working. The call to <code>gapi.client.gmail.users.messages.get({<specific message ID>})</code> outputs this - <code>{"B":{"method":"gmail.users.messages.get","rpcParams":{},"transport":{"name":"googleapis"}}}</code>. Not sure what that is, but trying to get the message payload (<code>email.payload.parts</code>), results in <code>undefined</code>. So, how can I get the message content? Also, I would assume that if I can get the message contents, I would then have to Base64 decode the contents to get some English out of it. Any suggestions for that would be of great help also. I've found this: https://github.com/kvz/phpjs, but since I'm not sure how to go about getting the message contents so that I can try and decode them, so not sure if that php.js is of an help in that regard.
Regarding the Base64 decoding, you can use `atob(dataToDecode)`. For Gmail, you'll also want to replace some characters: `atob(dataToDecode.replace(/-/g, '+').replace(/_/g, '/') );`. The above function is available to you in JavaScript (see ref). I use it myself to decode the Gmail messages. No need to install extra stuff. As an interesting tangent, if you want to encode your message to Base64, use `btoa`. Now, for accessing your message payload, you can write a function: `var extractField = function(json, fieldName) { return json.payload.headers.filter(function(header) { return header.name === fieldName; })[0].value; };` referenced from my previous SO Question and `var date = extractField(response, "Date");` `var subject = extractField(response, "Subject");` `var part = message.parts.filter(function(part) { return part.mimeType == 'text/html'; });` `var html = atob(part.body.data.replace(/-/g, '+').replace(/_/g, '/'));`
Polymer automatic node finding with dynamic id value <sep> How can I access node that have dynamic id value using Polymer node finding by id? For example <code><template> <div id="{{ id }}"></div> </template> </code> and in js <code>Polymer("my-element", { ready: function() { if (!this.id) { this.id = 'id' + (new Date()).getTime(); } console.log(this.$.id); // this part needs to find my div element } }); </code>
It's true that a JavaScript hash can be accessed using either dot notation (`.`) or array notation (`[]`). If you have a literal name, you can use dot notation (`this.$.some_id`). If you have an indirection, like `this.id = 'some_id'`, then you can use array notation (`this.$[this.id]`) to find the same value. The tricky part is that Polymer only populates the `$` array after first stamping the template, which happens before `ready`. If you had an external binding to `this.id`, `this.$.[this.id]` would work, but since you are setting `this.id` in `ready`, it's too late for the `$` convenience. In this case, you can instead query your shadowRoot directly: `this.shadowRoot.querySelector('#' + this.id)`. Pro tip: at some point a subclass may supply a new template, in which case `this.shadowRoot` will point to the new shadow-root and not the superclass version. For this reason, it's best to install a named div you can query against, e.g., `this.$.id_div.querySelector('#' + this.id')`.
NoClassDefFoundError while running a valid jar (compiled with dependencies) despite having commons-httpclient and httpcomponents dependencies on pom <sep> I'm trying to automate a simple user act by using selenium webdriver from main method (not under test scope) When running the following code from the complier it works! But when running the jar on several cases - facing the following issue (I'm running on Ubuntu, using java 7) "Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/conn/HttpClientConnectionManager" @Log public class MainProgram { <code>public WebDriver driver = new FirefoxDriver(); public static void main(String args[]) { // Injector injector = Guice.createInjector(new WebModule()); System.out.println("Browser will soon be opened"); MainProgram mainProgram = new MainProgram(); mainProgram.run(); } public void run(){ driver.get("http://www.google.co.il"); WebElement lookFor = driver.findElement(By.name("q")); if(!lookFor.isDisplayed()){ driver.close(); log.log(Level.WARNING,"Failed!"); }; driver.close(); } } </code> WebDriver dependencies on pom: <code> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-server</artifactId> <version>2.42.2</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.42.2</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-api</artifactId> <version>2.42.2</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-firefox-driver</artifactId> <version>2.42.2</version> </dependency> Case A when removed -commons-httpclient - received: HttpClientConnectionManager as follows: <!-- <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.4</version> <!-- <scope>test</scope>--> </dependency> Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/conn/HttpClientConnectionManager at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:99) at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:82) at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:77) ------------------------------------------------------------------------------------------------------------------------------------------- Case B removed both commons-httpclient + httpcomponents received HttpClientConnectionManager: <!-- &lt;!&ndash; <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>&ndash;&gt; <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.4</version> &lt;!&ndash; <scope>test</scope>&ndash;&gt; </dependency>--> liron@liron-Latitude-3330:~$ java -jar automatic-tests-4.0-SNAPSHOT-jar-with-dependencies.jar Try Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/conn/HttpClientConnectionManager at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:99) at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:82) --------------------------------------------------------------------------------------------------------------------------------------------- Case C when both were added to pom - same HttpClientConnectionManager liron@liron-Latitude-3330:~$ java -jar automatic-tests-4.0-SNAPSHOT-jar-with-dependencies.jar Browser will soon be opened Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/conn/HttpClientConnectionManager at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:99) at org.openqa.selenium.remote.HttpCommandExecutor.<init>(HttpCommandExecutor.java:82) at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:77) ---------------------------------------------------------------------------------------------------------------------------------------------- </code>
I ran into this same issue last night with my WebDriver project, and after a bit of debugging, I found out that it was missing the following dependency. After adding it, I didn't encounter this exception again. ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.5</version> </dependency> ```
How to permanently disconnect Visual Studio solution from source control <sep> I have a Visual Studio 2012 solution with a few projects in it. Every time i open the solution file i get the message: <blockquote> The mappings for the solution could not be found. The active solution has been temporarily disconnected from source control because the server is unavailable. To attempt to reconnect to source control, close and then re-open the solution when the server is available. If you want to connect this solution to another server, use the Change Source Control dialog. </blockquote> What i want to do is PERMANENTLY remove any mention of source control, but no luck so far. Here is what i have tried so far Deleted the usual suspect files, such as suo, mssccprj.scc, vssver.scc, etc Manually opened every project file (.vbproj, .csproj) and deleted the four lines SccProjectName = "etc" SccAuxPath = "etc" SccLocalPath = "etc" SccProvider = "etc" Ditto for the solution file Noticed that there is a web site project (rather than web application project) in my solution, but being a website project i cannot perform step 2. on it. Checked the dialog "File/Source Control/Advanced/Change Source Control" and noticed that every listed Solution/Projects have NO SERVER, NO BINDING, Status is "Not Controlled" As well as the message described above (has been temporarily disconnected etc), the following 4 lines always get ADDED BACK to the solution file, no matter how many times i've deleted them. <blockquote> SccProjectName = "MyApp" SccAuxPath = "https://some.annoying.domain.com/VaultService" SccLocalPath = "4~89a6b376-099d-49a7-801a-2ba7adb0e268" SccProvider = "SourceGear Vault Visual Studio 2005 Client:{7BE9CE03-56BF-4682-9C06-78C68B134B30}" </blockquote> These 4 lines are within the section that describes the website project. <blockquote> Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "MyApp", "<code>http://localhost/MyApp</code>", "{A5301379-1092-419E-9B03-E37E16E0A8B2}" ProjectSection(WebsiteProperties) = preProject </blockquote> I strongly suspect it is the website project that is screwing it up. But where is the website project holding the source control info? Further info: I have already searched all file contents for the string "some.annoying.domain.com" but came up with nothing of significance (found in OTHER solutions, not this particular solution). The solution appears to have been originally created in VS2010 (where the previous dev obviously used SourceGear's Vault product). ** NB: I could try to change the website proj to a web app proj, and see how it goes, but that's beside the point.
Change the source control plugin to None: `Tools -> Options -> Source Control -> Plug-in Selection: None`. And respond with "Yes" to the question if you want the sources to not be under source control.
Woocommerce, How to edit the "added to cart" message <sep> When click on add to cart button, the Woocommerce shows the message, view cart, I want to edit this message, actually edit all the span, put some icon etc...
```php add_filter( 'wc_add_to_cart_message', 'wc_add_to_cart_message_filter', 10, 2 ); function wc_add_to_cart_message_filter($message, $product_id = null) { $titles[] = get_the_title( $product_id ); $titles = array_filter( $titles ); $added_text = sprintf( _n( '%s has been added to your cart.', '%s have been added to your cart.', sizeof( $titles ), 'woocommerce' ), wc_format_list_of_items( $titles ) ); $message = sprintf( '%s <a href="%s" class="button">%s</a>&nbsp;<a href="%s" class="button">%s</a>', esc_html( $added_text ), esc_url( wc_get_page_permalink( 'checkout' ) ), esc_html__( 'Checkout', 'woocommerce' ), esc_url( wc_get_page_permalink( 'cart' ) ), esc_html__( 'View Cart', 'woocommerce' ) ); return $message; } ```
Iterating through mount points using Python <sep> How do I iterate through the mount points of a Linux system using Python? I know I can do it using df command, but is there an in-built Python function to do this? Also, I'm just writing a Python script to monitor the mount points usage and send email notifications. Would it be better / faster to do this as a normal shell script as compared to a Python script? Thanks.
The Python and cross-platform way: ```python pip install psutil # or add it to your setup.py's install_requires import psutil partitions = psutil.disk_partitions() for p in partitions: print(p.mountpoint, psutil.disk_usage(p.mountpoint).percent) ```
How to convert a timestamp string to local time using javascript? <sep> I have a JSP page in which I am pulling timestamp stored in database as string which has the form <code>Thu Aug 21 2014 22:09:23 GMT+0530 (India Standard Time)</code>. Of Course, I am able to display it as it is in the page, however I was looking for a solution in javascript that would enable me convert this timestamp as per user's local timezone. Is there a way to do this ? Or for such a timestamp it's not possible ? Any help is greatly appreciated, well my question may sound silly as I am still familiarizing myself with javascript. Thanks
I figured it out myself and I am able to accomplish what I needed. Passing the `timestamp` from the database to `var new Date(timestamp)` gets it converted to local time, it takes care of timezone and offsets as well. Thanks for your time, experts! :)
Intersect all possible combinations of list elements <sep> I have a list of vectors: <code>> l <- list(A=c("one", "two", "three", "four"), B=c("one", "two"), C=c("two", "four", "five", "six"), D=c("six", "seven")) > l $A [1] "one" "two" "three" "four" $B [1] "one" "two" $C [1] "two" "four" "five" "six" $D [1] "six" "seven" </code> I would like to calculate the length of the overlap between all possible pairwise combinations of the list elements, i.e. (the format of the result doesn't matter): <code>AintB 2 AintC 2 AintD 0 BintC 1 BintD 0 CintD 1 </code> I know <code>combn(x, 2)</code> can be used to get a matrix of all possible pairwise combinations in a vector and that <code>length(intersect(a, b))</code> would give me the length of the overlap of two vectors, but I can't think of a way to put the two things together. Any help is much appreciated! Thanks.
If I understand correctly, you can look at `crossprod` and `stack`: `crossprod(table(stack(l))) # ind # ind A B C D # A 4 2 2 0 # B 2 2 1 0 # C 2 1 4 1 # D 0 0 1 2 ` You can extend the idea if you want a `data.frame` of just the relevant values as follows: Write a spiffy function `listIntersect <- function(inList) { X <- crossprod(table(stack(inList))) X[lower.tri(X)] <- NA diag(X) <- NA out <- na.omit(data.frame(as.table(X))) out[order(out$ind), ] }` Apply it `listIntersect(l) # ind ind.1 Freq # 5 A B 2 # 9 A C 2 # 13 A D 0 # 10 B C 1 # 14 B D 0 # 15 C D 1 ` Performance seems pretty decent. Expand the `list`: `L <- unlist(replicate(100, l, FALSE), recursive=FALSE) names(L) <- make.unique(names(L)) ` Set up some functions to test: `fun1 <- function(l) listIntersect(l) fun2 <- function(l) apply( combn( l , 2 ) , 2 , function(x) length( intersect( unlist( x[1]) , unlist(x[2]) ) ) ) fun3 <- function(l) { m1 <- combn(names(l),2) val <- sapply(split(m1, col(m1)),function(x) { x1 <- l[[x[1]]]; x2 <- l[[x[2]]]; length(intersect(x1, x2)) }) Ind <- apply(m1,2,paste,collapse="int") data.frame(Ind, val, stringsAsFactors=F) }` Check out the timings: `system.time(F1 <- fun1(L)) # user system elapsed # 0.33 0.00 0.33 system.time(F2 <- fun2(L)) # user system elapsed # 4.32 0.00 4.31 system.time(F3 <- fun3(L)) # user system elapsed # 6.33 0.00 6.33 ` Everyone seems to be sorting the result differently, but the numbers match: `table(F1$Freq) # # 0 1 2 4 # 20000 20000 29900 9900 table(F2) # F2 # 0 1 2 4 # 20000 20000 29900 9900 table(F3$val) # # 0 1 2 4 # 20000 20000 29900 9900 `
How to get locale with region? <sep> I am trying to get the current device locale with the region like "en_us","en_gb". I am calling <code>Locale.getDefault().getLanguage()</code> and it returns only the two letters code <code>en</code>.
A Locale object contains both country code and language code. So you can use the following snippet to format your own code: ``` String cCode = Locale.getDefault().getCountry(); String lCode = Locale.getDefault().getLanguage(); String code = lCode + "_" + cCode; ``` or you can use the `toString()` method on a Locale object to get the data: ``` String code = Locale.getDefault().toString(); ```
Redirecting to error page in Angularjs <sep> I am new to AngularJs. I have a single page app with routes configured having a controller and a view. The view get loaded inside the <code><ng-view></ng-view></code> element of the <code>index.html</code> page. Inside the controller I am making a <code>http</code> call to get the data and binding the data to the <code>$scope</code>. For success scenarios this works fine but if there is an error how do I plug in another view instead of the default view configured inside the angular route. PLease let me know.
To implement a common scenario for processing AJAX errors, you can implement a custom request interceptor and redirect the user to an error page (or login page) according to the error status: ```javascript myApp.factory('httpErrorResponseInterceptor', ['$q', '$location', function($q, $location) { return { response: function(responseData) { return responseData; }, responseError: function(response) { switch (response.status) { case 401: $location.path('/login'); break; case 404: $location.path('/404'); break; default: $location.path('/error'); } return $q.reject(response); } }; }]); // HTTP Interceptor to check auth failures for xhr requests myApp.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('httpErrorResponseInterceptor'); }]); ``` Plunker here
Bit fields portability <sep> I read here that bit fields are not portable. Does that mean that the code below that defines bit fields (code taken from here) could not compile on certain machines? If so, then why? <code>#include <stdio.h> #include <string.h> /* define simple structure */ struct { unsigned int widthValidated; unsigned int heightValidated; } status1; /* define a structure with bit fields */ struct { unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status2; int main( ) { printf( "Memory size occupied by status1 : %d\n", sizeof(status1)); printf( "Memory size occupied by status2 : %d\n", sizeof(status2)); return 0; } </code>
Bit fields are portable, in the sense that they are part of the C language as specified in the standard (C11 section 6.7.2.1). Any compiler that fails to recognize code that uses bitfields is not standard-compliant. There's also nothing really questionable about your example, since all it does is have bitfields present. What they probably mean is that the fields themselves may be packed unpredictably in location and order (allowed by the standard, previous ref. paragraph 11). This means that a struct with, for example, four bitfields of size 4, 12, 13, and 3 does not necessarily take up 32 bits and they won't necessarily be placed within the struct in that order; the compiler can place them where it likes. This means that the struct cannot be treated as an actual component-wise representation of an underlying binary object. In contrast, bitmasks applied manually to integers exist exactly where you put them. If you define masks that mask out the first 4 bits, second 12 bits, etc. of an unsigned integer, the "fields" will actually apply to the bits, in order and in position (assuming you know the endianness, anyway). This makes the representation compiler-independent; i.e., they are portable, but what they do may not necessarily be exactly what a person actually wanting to manipulate individual bits may need.
CSS-Image border glow when hover with individual color <sep> I would like to ask how should I apply different colour glow to an image border when a user hover over? like say that in this JSFiddle file, I have a green thumb and a red thumb. I want each image border to glow according to the colour of the image, or any colour that I specify. How should I achieve that? PS** For example purposes the image are converted to base64 in the JSFiddle. This is how I do in my CSS <code>img{ width: 16px; cursor: pointer; padding: 10px; } img:hover{ border-color: #66afe9; outline: 0; -webkit-box-shadow: inset 5px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6); box-shadow: inset 5px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6); } </code> Thank You
```css img { width: 48px; cursor: pointer; /* padding: 10px; */ /* border: 1px solid #fff; */ margin-right: 20px; } img:hover { -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; -webkit-box-shadow: 0px 0px 30px 0px rgba(0, 255, 0, 0.67); -moz-box-shadow: 0px 0px 30px 0px rgba(0, 255, 0, 0.67); box-shadow: 0px 0px 30px 0px rgba(0, 255, 0, 0.67); } img:last-of-type:hover { -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; -webkit-box-shadow: 0px 0px 30px 0px rgba(232, 0, 0, 0.67); -moz-box-shadow: 0px 0px 30px 0px rgba(232, 0, 0, 0.67); box-shadow: 0px 0px 30px 0px rgba(232, 0, 0, 0.67); } ```