text
stringlengths
64
89.7k
meta
dict
Q: Finding coordinate vector of $f(t) = \cos(t+a)$ relative to the basis $\{\sin(t+2\pi), \cos(t+2\pi)\}$ Ok so, $$\cos(t+a) = \cos(t)\cos(a) - \sin(t)\sin(a) $$ $$= \cos(t+2\pi) \cos(a) - \sin(t+2\pi)\sin(a) $$ Would this mean that the coordinate vector is $(1,-1)$? Or should i find the coordinates in a different form? A: You basically need to find the coefficients of the linear combination $sin(t+2\pi) + cos(t+2\pi) = cos(t+a)$. Your trigonometric identity is a good path. In this case, I believe it means that the coordinate vector is $cos(a)$, $sin(a)$ as these are the coefficients in front of the basis components.
{ "pile_set_name": "StackExchange" }
Q: prove or disprove: if $E$ in $\mathbb R$ is a Null set, than its closure is also a null set. prove or disprove: if $E$ in $\mathbb R$ is a Null set, than its closure is also a null set. I think its true. I have no sense of direction on how to start. Thanks in advance for any response. A: Hint: Countable subsets of $\Bbb R$ are null sets. Do you know of a countable subset of $\Bbb R$ whose closure is the whole of $\Bbb R$ (i.e. the subset is dense in $\Bbb R$)?
{ "pile_set_name": "StackExchange" }
Q: iOS - Should I be calling "weakSelf" in this block? Okay so I might have not fully grasped WHEN I should use weakSelf in blocks. I know that it is done to prevent retain cycles and what not, but I heard there are some exceptions to this rule. In the following code, I check to see if an API call failed due to the login session expiring, and then I attempt to re-authenticate the user and retry the API request that failed because of this issue by calling [self sendTask:request successCallback:success errorCallback:errorCallback]; in the re-authentication method's success block: /*! * @brief sends a request as an NSHTTPURLResponse. This method is private. * @param request The request to send. * @param success A block to be called if the request is successful. * @param error A block to be called if the request fails. */ -(void)sendTask:(NSURLRequest*)request successCallback:(void (^)(NSDictionary*))success errorCallback:(void (^)(NSString*))errorCallback { NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { [self parseResponse:response data:data successCallback:success errorCallback:^(NSString *error) { //if login session expired and getting "not authenticated" error (status 401) NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response; if (httpResp.statusCode == 401) { NSLog(@"NOT AUTHENTICATED THO"); AuthenticationHelper* auth = [AuthenticationHelper sharedInstance]; NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults]; //attempt to re-authenticate the user [AuthenticationHelper loginUser:[defaults stringForKey:@"username"] password:[defaults stringForKey:@"password"] successCallback:^(User* u) { auth.loggedInUser = u; NSLog(@"RE-AUTHENTICATION BUG FIX SUCCEEDED"); //attempt to re-try the request that failed due to [self sendTask:request successCallback:success errorCallback:errorCallback]; } errorCallback:^(NSString *error) { NSLog(@"RE-AUTHENTICATION BUG FIX FAILED"); }]; } else { errorCallback(error); } }]; }]; [task resume]; } Is this bad practice in that it can lead to a retain cycle? If so, why? Should I instead be using [weakSelf sendTask:request successCallback:success errorCallback:errorCallback]; assuming that I do MyAPIInterface *__weak weakSelf = self; beforehand? A: In this example there would not be a retain cycle because self isn't holding a reference to the block. When the block completes, it will release its hold on self, and if that was the last reference, the instance will be deallocated, just as you would expect.
{ "pile_set_name": "StackExchange" }
Q: Custom view not getting drawn in GridLayout I've got a custom view that I'm trying to fill a GridLayout with. The custom view consists of a TextView inside of a circle. The problem I'm having is that the onDraw() method of my custom view never gets called so I always end up with a blank screen. When I populate my GridLayout with just regular TextViews it works just fine so I'm guessing the problem lies somewhere with my custom View. My onCreate: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sample_collection); gl = (GridLayout) findViewById(R.id.grid_sample_collection); gl.setColumnCount(9); gl.setRowCount(9); LayoutInflater inflater = LayoutInflater.from(this); for(int i=0;i<gl.getRowCount();i++){ for(int j=0;j<gl.getColumnCount();j++){ SampleCollectionView sampleCollectionView = new SampleCollectionView(this); sampleCollectionView.setLabelText(i + "." + j); gl.addView(sampleCollectionView); //Adding the TextViews shown below works just fine //TextView t = new TextView(this); //t.setText(i + "." + j); //t.setTextSize(30f); //t.setPadding(30, 30, 30, 30); //gl.addView(t); } } int childCount = gl.getChildCount(); for (int i= 0; i < childCount; i++){ final SampleCollectionView sampleCollectionView = (SampleCollectionView) gl.getChildAt(i); //final TextView text = (TextView) gl.getChildAt(i); sampleCollectionView.setOnClickListener(new View.OnClickListener(){ public void onClick(View view){ Log.d("OnClickListener: ", "Clicked text: " + sampleCollectionView.getLabelText()); } }); } } My custom view: public SampleCollectionView(Context context){ super(context); init(); } public SampleCollectionView(Context context, AttributeSet attrs) { super(context, attrs); //get the attributes specified in attrs.xml using the name we included TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SampleCollectionView, 0, 0); try { //get the text and colors specified using the names in attrs.xml circleText = a.getString(R.styleable.SampleCollectionView_circleLabel); //0 is default circleCol = a.getInteger(R.styleable.SampleCollectionView_circleColor, 0); circleBorderCol = a.getInteger(R.styleable.SampleCollectionView_circleBorderColor, 0); labelCol = a.getInteger(R.styleable.SampleCollectionView_labelColor, 0); } finally { a.recycle(); init(); } } public void init(){ mPaint = new Paint(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int viewWidthHalf = this.getMeasuredWidth()/2; int viewHeightHalf = this.getMeasuredHeight()/2; int radius = 0; if(viewWidthHalf>viewHeightHalf) radius=viewHeightHalf-10; else radius=viewWidthHalf-10; mPaint.setStyle(Paint.Style.FILL_AND_STROKE); mPaint.setAntiAlias(true); mPaint.setColor(circleCol); canvas.drawCircle(viewWidthHalf, viewHeightHalf, radius, mPaint); mPaint.setTextAlign(Paint.Align.CENTER); mPaint.setTextSize(20); canvas.drawText(circleText, viewWidthHalf, viewHeightHalf, mPaint); } EDIT: After some testing I found out that the height and weight of my custom views were 0. After using setMinimumHeight and setMinimumWidth they are actually getting drawn and are responding to clicks. The only problem now is that for some reason, all of the custom views are completely invisible... EDIT 2: Turns out the views weren't visible because I wasn't setting the View's properties like circleCol properly, which caused them to be set to their default value (0). A: I managed to figure out what was going wrong. I created my custom Views without specifying a height/width. Naturally, this led to them getting a height and width of 0, with the GridLayout getting the same constraints as it was set to wrap_content. After giving my views a proper height and width with the setMinimumHeight and setMinimumWidth methods I ran into another issue: The views weren't visible. They were being drawn as the onClickListener was responding to taps on various parts of the screen but I couldn't see them. The cause of this was the same thing that was responsible for the height and width being 0: The custom View's color properties weren't set properly. I was attempting to do this via XML but for some reason it couldn't retrieve the values of the properties I had specified in my XML file. Because the properties weren't specified, they reverted to their default values which resulted in no color being specified and no string getting supplied to the label. I fixed this by programmatically setting the properties.
{ "pile_set_name": "StackExchange" }
Q: Crosh Shell as default New Tab page I run crouton on my chromebook and use the Crosh shell pretty frequently. Is there any way to specify Crosh as the default New Tab on a Chromebook? I already attempted using the Crosh extension location as the New Tab URL (chrome-extension://pnhechapfaindjhompbnflcldabbghjo/html/crosh.html) but no luck. A: Do you have your own extension? If not create it, with a manifest.json file like this: { "manifest_version": 2, "name": "Crosh Newtab", "version": "1", "chrome_url_overrides" : { "newtab": "main.html" } } Create main.js and add it to main.html. In main.js, open Crosh and close the current window, like this: chrome.tabs.create({ url: "chrome-extension://pnhechapfaindjhompbnflcldabbghjo/html/crosh.html" }, function() { window.close() })
{ "pile_set_name": "StackExchange" }
Q: sliding window scenario - taking partitions offline Is there a way in MS SQL Server 2005 to take a partition / file groups / files offline? I have a lot of data in certain tables and would like to use the sliding window Scenario: http://msdn.microsoft.com/en-us/library/ms345146%28SQL.90%29.aspx#sql2k5parti_topic24 Instead of keeping all the data in the first partition, I would like to take the partition (or files or file group if possible) offline and make it unavailable for my queries. A: The best description of the sliding window scenario I have ever seen is over here: http://blogs.msdn.com/b/hanspo/archive/2009/08/21/inside-of-table-and-index-partitioning-in-microsoft-sql-server.aspx The article title is "Microsoft SQL Server Inside Out. Inside of Table and Index Partitioning in Microsoft SQL Server". I do not see the reason to retell this article here. Just go, read and exercise with example by your hands. And one more very good example is here: http://sqlserverpedia.com/wiki/Example_of_Creating_Partitioned_Tables These two articles should be enough to get your table partitioned even you deal with partitioning at very first time. Good luck.
{ "pile_set_name": "StackExchange" }
Q: Error in main() for function call from a derived class C++ //Newton-Raphson Method: #include <iostream> #include <cmath> using namespace std; class ClassNewton { public: double NewtonRaphson(double x0, double epsilon, double f(double), double df(double)); virtual double f(double) = 0; virtual double df(double) = 0; }; double ClassNewton::NewtonRaphson(double x0, double epsilon, double f(double), double df(double)){ double xold = x0; double diff; double xnew; do { xnew = xold - (f(xold)/df(xold)); xold = xnew; } while (abs(diff) > epsilon); return xnew; } class derivedClass:public ClassNewton{ public: double f(double x){ double function = (x * x) + (2 * x) + 2; return function; } double df(double x){ double derivative = (2 * x) + 2; return derivative; } }; int main() { derivedClass n; double root; double x0 = 1.0; double epsilon = 0.00001; root = n.NewtonRaphson(x0, epsilon, f(root), df(root)); cout << "The root of the function is " << root << endl; return 0; } I checked the code up to the main function using an empty main and it could get compiled with no errors. However, when I integrate the main, I get the following error: NewtonRaphson.cc: In function ‘int main()’: NewtonRaphson.cc:52:44: error: ‘f’ was not declared in this scope NewtonRaphson.cc:52:54: error: ‘df’ was not declared in this scope NewtonRaphson.cc:53:47: error: expected ‘;’ before ‘)’ token I would appreciate some explanations, I suspect I am using the virtual functions in a wrong way. A: First of all in this statement cout << "The root of the function is ", root); ^^^^ ^^^ there is invalid expression. As for other errors then you have to use an object name that to call non-static member functions of a class. For example n.f(root) or n.df(root) Take into account that this declaration double NewtonRaphson(double x0, double epsilon, double f(double), double df(double)); is invalid because you are going to use as arguments non-static member functions f and df while the corresponding parameters are declared as non-member functions. There is no need to define these two parameters of the function because you could simply call these member functions within the body of NewtonRaphson.
{ "pile_set_name": "StackExchange" }
Q: how to define an array without a defined length of it The question is: get a score of 10 peoples; then you need to ask each one with a score higher than 80 if he would want to continue studying 'y' for yes and 'n' for no. Next you need to get their location in the array so if person number 5 array[5]=90 and answers 'y' it will make a new array with newarray[1]=[5(his location)] My question is how to define the newarray without knowing its length(how many 'y' there would be). EDIT: import java.util.Scanner; public class p44_52 { static Scanner reader = new Scanner(System.in); static void input(int []a) { for(int i=0; i<a.length;i++){ System.out.println("Write an score of a student"); a[i]= reader.nextInt(); } } static void output(int []b) { for (int i =0; i<b.length;i++) { System.out.println("serial number of who choose to continue and score above 80 "+ b[i]); } } public static void main(String[]args){ char c = 'g'; int count =0; int []score = new int[10]; kelet(score); for(int i=0; i<score.length;i++) { if(score[i]>80) { System.out.println("Studnet number "+i+ " Do you want to continue?"); c = reader.next().charAt(0); if(c == 'y'){ //Here i want to make the new array(length isn't known) for their locationnumbers } } } } } A: You can create a temporary array with the same size as the full list (because you know that's the largest it could need to be) and populate it with as many students as choose to continue. There will probably be fewer elements actually in the temporary array than it can hold because some students won't continue, so then you can create a new array that's the right size (now that you know it) and use System.arraycopy() to copy all of the elements into the right-size array. It's not the most efficient way to do it, but it's not terrible (it just uses one extra array allocation and copy operation) and it's certainly good enough for homework. And it doesn't use anything other than arrays. In general, this is a technique you'll use from time to time as you write programs: if there's something you can't do until you've done some operation, then look for a way to break the operation into multiple steps so you can rearrange steps in an order that is possible but still yields the same result. Better still is to find a different data structure that meets your needs (as ArrayList will, since its capacity can be grown at runtime), but there will be times when you can't just drop in a different data structure, and this approach of breaking the problem down and rearranging steps can be useful then.
{ "pile_set_name": "StackExchange" }
Q: How to be more logical? (less bugs/errors) I have been programming for 6 years and I am in high school (I prefer not to disclose my age). I have dabbled in many different languages. Just to list a few: Java, PHP, C++, Python, Autohotkey, Mathematica and many more. I have a very good understanding of the basics of general programming. The only problem is I still create bugs all the time. I think too often. Do you have any hints besides continuing to program that will help me become a better programmer and make less errors? A: Keep your methods small. When methods grow too big, extract units of logic to new methods. Name your classes, methods, and variables things that make sense. Never feel undue pressure to abbreviate any of these. Use GoF design patterns whenever they make sense. [Here's a good beginner's book.] Cover your code with automated unit tests. This will force you to modularize your code and give you confidence when refactoring. Read Code Complete 2.
{ "pile_set_name": "StackExchange" }
Q: Pandas row to json I have a dataframe in pandas and my goal is to write each row of the dataframe as a new json file. I'm a bit stuck right now. My intuition was to iterate over the rows of the dataframe (using df.iterrows) and use json.dumps to dump the file but to no avail. Any thoughts? A: Pandas DataFrames have a to_json method that will do it for you: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html If you want each row in its own file you can iterate over the index (and use the index to help name them): for i in df.index: df.loc[i].to_json("row{}.json".format(i)) A: Looping over indices is very inefficient. A faster technique: df['json'] = df.apply(lambda x: x.to_json(), axis=1)
{ "pile_set_name": "StackExchange" }
Q: how to insert in map (3 inputs) in java I have an input that is given below. How can I insert these inputs in a map, HashMap preferrably. {1,"abc","a"} {200,"xyz","b"} {1,"ab","c"} {12,"fgh","d"} Integer being the key and remaining are values. A: add integer value in hasmap as key and other 2 values in list and then add this list to hashmap as key value Map<String, String> map = new HashMap<Interger, Object>(); List<String> maplist1=new ArrayList<String> maplist1.add("abc"); maplist1.add("a"); map.put(1, maplist1) // otherwise clear maplist List<String> maplist2=new ArrayList<String> maplist2.add("xyz"); maplist2.add("b"); map.put(200, maplist2)
{ "pile_set_name": "StackExchange" }
Q: A good place to learn about Game Programming with Mathematical Vectors? I am looking for a place in the web where I can turn my current game development process into a vector based approach. I am sorry If this question has been asked once. According to my google search analysis, few places I've found pretty interesting are Tony Pa's tutorials and Metanet. But, due to limited explanations, I found it little bit tough to implement. I could try out the same examples as provided there, but when I have to use it in my games, I am STUCK. I want to know about the dot products and cross product stuff, Its uses and detecting collisions and predicting collisions with these mathematical techniques. Please, write down some links and a brief description of the link. Thank you A: Here you go: http://blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-1/ This is the first entry in a series of (4) blog posts about linear algebra pertaining to game development. It'll explain about dot products, cross products and transformations using matrices.
{ "pile_set_name": "StackExchange" }
Q: ASP.Net NavigateUrl to remote server Is there a way to open a PDF file from a remote server directory inside a gridview using NavigateUrl? I'm able to retrieve the file number from the textbox and generate the link, but when you click on the link nothing happens. Could my NavigateUrl be formatted wrong due it being on a remote server and trying to open in a web browser? My code below. Thanks in advance. <asp:TemplateField> <ItemTemplate> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("Name", "file:\\fileserver\pdf\{0}") %>' Target="_blank" Text='<%# Eval("Name", "{0:d}") %>'></asp:HyperLink> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Name" DataFormatString="{0:d}" HeaderText="FILE NUMBER" /> <asp:BoundField DataField="CreationTime" DataFormatString="{0:d}" HeaderText="DATE ADDED" /> <asp:BoundField DataField="Length" DataFormatString="{0:#,### bytes}" HeaderText="FILE SIZE" /> A: You will need to have the file accessible via http:// and not file:// in order for the the link to work properly. Once that is set, use the Server.MapPath() method to generate the URL based on the path to your file.
{ "pile_set_name": "StackExchange" }
Q: Error 415 when call POST API using Fetch in ReactJS I want to call an API for register from method in React. Below is my javascript code : fetch('http://localhost:5001/api/Account', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email: "[email protected]", name: "Hugh Daniel", password: "1234" }) }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); And this is my controller [HttpPost] public ResponseModel RegisterByEmail([FromBody]UserModel user) { return _accountService.RegisterEmail(user); } But I always get these errors I tried to add mode: 'no-cors' in my javascript code, but it makes Content-Type set to plain. The API is working if I tested it using Postman like this A: You need to combat CORS first of all. You can't make API requests against a different domain:port than the one from which it was served by development server. Are you using Webpack in your project? If yes, the easiest way is to set up API proxy by the Webpack configuration. See the doc. Something like this: // webpack.config.js devServer: { port: 3030, proxy: { '/api': { target: `http://localhost:5001`, secure: false } } } Now you have to remove host:port from fetch address param and also I would add Accept header to the request settings: fetch('/api/Account', { method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, // ... } )
{ "pile_set_name": "StackExchange" }
Q: regex: match all characteres between 2 words, returns strange output in this text: "IPAddress":"10.0.0.18","PolicerID":"","IPAddress":"","PolicerID":"" I want to catch all ips, in this example are 10.0.0.18 and emptystring I tried to use this regex: (?<="IPAddress":")(.*?)(?=") which returns me 10.0.0.18 and ", it took the first " from PolicerID instead of the last " in IPAddress. Can you please help me? Thanks A: You can keep it simple and just use a capturing group: >>> str = r'"IPAddress":"10.0.0.18","PolicerID":"","IPAddress":"","PolicerID":""' >>> print re.findall(r'"IPAddress":"([^"]*)', str) ['10.0.0.18', ''] >>> However if you have to use lookbehind assertion then use this regex: (?<="IPAddress":")([^"]*) ([^"]*) is a negated pattern to match 0 or more of any character that is not a double quote. RegEx Demo
{ "pile_set_name": "StackExchange" }
Q: Sum of all possible angles. If $$\tan\left(\frac{\pi}{12}-x\right) , \tan\left(\frac{\pi}{12}\right) , \tan \left(\frac{\pi}{12} +x\right)$$ in order are three consecutive terms of a GP then what is sum of all possible values of $x$. I am not getting any start, can anybody provide me a hint? A: Use :$$\Big(\tan\frac{\pi}{2}\Big)^2=\tan\Big(\frac{\pi}{12}-x\Big)\tan\Big(\frac{\pi}{12}+x\Big) \tag1$$ (Condition for G.P) And : $$\tan (A\pm B) = \frac{\tan A \pm \tan B}{1\mp \tan A\tan B}$$ Let $\tan \dfrac{\pi}{12} =c$ Put in $(1)$ $$c^2=\frac {c+\tan x}{1-c\tan x} \cdot \frac{c-\tan x}{1+c\tan x} \implies c^2-c^4\tan^2 x =c^2-\tan^2 x \implies \tan x =0$$ Sum of solutions in a bounded interval will be sum all angles in the form $k\pi ~;~ k \in \mathbb Z$
{ "pile_set_name": "StackExchange" }
Q: PHP UFT8 Encoding Internet Explorer Problems I am facing the following problem: Currently, I am creating a web application using the Yii2 framework for PHP running on an apache server. My web application is fully functional on Gooogle Chrome but on Internet Explorer I am facing the problem, that UTF8 econded turkish special characters are not displayed nor readable for drop down menus. The menus remain empty once a selection containing special characters is made. I have created dynamical dropdown menus which read values from a MySQL database table. In this table, values in columns are saved in the turkish language containing special characters and collation is set to utf-8. The header charsets of the PHP framework and also metadata of the webpage are all set to utf-8 but Internet Explorer seems to struggle with the encoding. My code for the dropdown menus is the following: <div class="feedback-view"> <?php $form = ActiveForm::begin(); ?> <p><?php $sql = 'SELECT * FROM tbl_feedback'; $feedbacks = app\models\Feedback::findBySql($sql)->all(); $list = yii\helpers\ArrayHelper::map($feedbacks, 'name', 'name'); echo $form->field($model, 'name')->dropDownList($list, [ 'style'=>'width:300px', 'prompt'=>'--Name select--', 'class' => 'form-field', 'onchange'=>'$.get("'.Yii::$app- >request->baseUrl.'" + "/index.php?r=feedback/test&name=" + $(this).val(), function(data){ $("#feedback_id").html(data); } );' ]); ?> <input type="submit" value="submit"> </p> <?php ActiveForm::end(); ?> Any hints or recommendations / tips would be highly appreciated as I am really stuck with this problem. Thank you in advance. A: The solution was using http://php.net/manual/de/book.mysqli.php this package and formatting utf8. Before I was using a different package designed for SQL which did not work for the character encoding containing the special letters.
{ "pile_set_name": "StackExchange" }
Q: Is it permissible to run post-hoc tests after a non-significant ANOVA? We ran a 3-way ANOVA getting a non-significant result, but in doing so we saw that one condition looked like it had a strong effect. We tried a Bonferroni-corrected t-test of just that group, and it turned out significant. Is it valid to consider this? Is there some other correction needed to deal with the fact that we tested that group only after we saw that it "looked" like an effect? (And does the answer to this sort of question depend on between vs. within factors? We have a mix. I ask this because SPSS doesn't seem to give the option for post hoc tests under the GLM procedure except for between-factor effects. Not the best way to learn, but it's a clue, nonetheless.) A: It depends on what you plan to do with the result. If you want to form a conclusion regarding a null hypothesis and have a specifiable rate of false positives (i.e. you want a Neyman-Pearson hypothesis test) then no, you can't do it. Spuriously 'significant' results turn up all the time and any result that looks significant will quite likely turn out to be statistically significant even when it is not real. Neyman-Pearson analysis allows you to test PREDEFINED hypotheses with PREDETERMINED analyses. If you want to use your data to help form hypotheses to test with new experiments (i.e. use a Fisherian approach) then yes, go ahead and test! The fact that you cannot reliably test an hypothesis that is formed on the basis of seeing a dataset using that same dataset does not mean that the dataset cannot point to something worthy of a follow-up experiment.
{ "pile_set_name": "StackExchange" }
Q: Replacing the Wordpress password validation I have a custom application with thousands of users who already have a password stored. I would like to set up a self hosted wordpress site to accompany that application and to use the usernames and encrypted passwords that already exist in that database. Is there a way to configure Wordpress to not use the normal list of users, but instead to validate usernames and passwords against another database on another server? We have a team of developers so if there was a way to write code to hook into the login process this would be acceptable. Does anyone have experience with this, or have any suggestions of where to look? A: Actually you can bypass login mechanism of wordpress by login user automatically (after they succesfuly passed with credentials from another website for example) with this function: wp_set_auth_cookie($user_id); for example with this you do login admin (user with id = 1) wp_set_auth_cookie(1); //after this admin is logged in so you can create user in wordpress with specified user privileges and then as user log with another credentials you can log him as this "placeholder" user. A: Investigating the filter authenticate, we can find that it is called inside the function wp_authenticate, which is a pluggable function. That means that it can be replaced by one of our own making. This is the original function, plus a marked entry point: function wp_authenticate($username, $password) { $username = sanitize_user($username); $password = trim($password); $user = apply_filters('authenticate', null, $username, $password); /* ENTRY POINT */ if ( $user == null ) { // TODO what should the error message be? (Or would these even happen?) // Only needed if all authentication handlers fail to return anything. $user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.')); } $ignore_codes = array('empty_username', 'empty_password'); if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) { do_action('wp_login_failed', $username); } return $user; } The test was done creating a wp_authenticate function inside a Must Use plugin. On that entry point, I put the following: global $wpdb; $table = $wpdb->prefix . 'my_users'; $parent = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE name='$username'" ) ); if( $username == $parent->name && $password == $parent->password ) $user = get_user_by( 'id', $parent->id ); The table wp_my_users is a simple test table, password is even plain text. The matter is how build the $user object completely based on a custom table. Or if it is feasible or advisable... Because in this test the ID of the users is the same, so we are giving back (get_user_by) to WordPress a user from its own table wp_users, but with credentials checked in a custom table wp_my_users. Notes: This answer doesn't goes beyond the analysis and hacking of the function wp_authenticate. No consideration is done about security, password management nor the wp_usermeta table. For reference, this is the content of $user: user | WP_User Object ( [data] => stdClass Object ( [ID] => 1 [user_login] => rod [user_pass] => $P$BQ8qnb3iYPRzisxYHUKq5X/GCQqhoz1 [user_nicename] => rod [user_email] => [email protected] [user_url] => [user_registered] => 2012-09-21 14:39:01 [user_activation_key] => [user_status] => 0 [display_name] => rod ) [ID] => 1 [caps] => Array ( [administrator] => 1 ) [cap_key] => wp_capabilities [roles] => Array ( [0] => administrator ) [allcaps] => Array ( [switch_themes] => 1 [edit_themes] => 1 [activate_plugins] => 1 [edit_plugins] => 1 [edit_users] => 1 [edit_files] => 1 [manage_options] => 1 [moderate_comments] => 1 [manage_categories] => 1 [manage_links] => 1 [upload_files] => 1 [import] => 1 [unfiltered_html] => 1 [edit_posts] => 1 [edit_others_posts] => 1 [edit_published_posts] => 1 [publish_posts] => 1 [edit_pages] => 1 [read] => 1 [level_10] => 1 [level_9] => 1 [level_8] => 1 [level_7] => 1 [level_6] => 1 [level_5] => 1 [level_4] => 1 [level_3] => 1 [level_2] => 1 [level_1] => 1 [level_0] => 1 [edit_others_pages] => 1 [edit_published_pages] => 1 [publish_pages] => 1 [delete_pages] => 1 [delete_others_pages] => 1 [delete_published_pages] => 1 [delete_posts] => 1 [delete_others_posts] => 1 [delete_published_posts] => 1 [delete_private_posts] => 1 [edit_private_posts] => 1 [read_private_posts] => 1 [delete_private_pages] => 1 [edit_private_pages] => 1 [read_private_pages] => 1 [delete_users] => 1 [create_users] => 1 [unfiltered_upload] => 1 [edit_dashboard] => 1 [update_plugins] => 1 [delete_plugins] => 1 [install_plugins] => 1 [update_themes] => 1 [install_themes] => 1 [update_core] => 1 [list_users] => 1 [remove_users] => 1 [add_users] => 1 [promote_users] => 1 [edit_theme_options] => 1 [delete_themes] => 1 [export] => 1 [administrator] => 1 ) [filter] => )
{ "pile_set_name": "StackExchange" }
Q: Pasting code from gist to OneNote 2013 places extra newlines. How to solve? Pasting code from github gists inserts extra newline to OneNote. //-------------------------------------------------- // constexpr and Constant Expressions   const int flies = 20; // OK const int limit = flies+1; // OK int staff_size = 27; // NOT a constant expression (no const) const int sz = get_size(); // Not a constant expression, get_size() not known until runtime I want it to look like this: //-------------------------------------------------- // constexpr and Constant Expressions   const int flies = 20; // OK const int limit = flies+1; // OK int staff_size = 27; // NOT a constant expression (no const) const int sz = get_size(); // Not a constant expression, get_size() not known until runtime Manually deleting newlines is not an option. How can I do this? A: One of the solutions is to do as follows: Copy the code from the gist and paste it to Microsoft Word first, then copy from there and paste it to OneNote. Also works for code from Visual Studio.
{ "pile_set_name": "StackExchange" }
Q: WooCommerce: change button class without overwrite template files I want to change the button classes of WooCommerce with the classes from Bootstrap. At the moment I've done that by overwriting the existing templates files. In many cases, the button classes are the only changes. Is there any hook to do this for all buttons instead of overwriting the template files? I couldn't find anything A: I don't know about a hook for this (there could be one), and I don't know about the Bootstrap classes. But if you want to avoid overwriting template files you could achieve it with some JavaScript. Add this code to the functions.php and it will change the class names accordingly. But the functions.php file will be overwritten with every theme update. So the proper way would be to create a child theme. add_action( 'wp_head', 'change_button_class' ); function change_button_class() { ?> <script type="text/javascript"> jQuery(document).ready(function($){ $('.button-1').addClass('button-2').removeClass('button-1'); }); </script> <?php } Update Added script tag
{ "pile_set_name": "StackExchange" }
Q: Regex - Select content by `contains` condition? Looking at this string : [app/default-viewcomponent.ts] I need to select the whole string only if it contains . (at least one) This is what I've managed to do and it works (partially): (\[(.(?=.*\.[^\]]+)).*\]) () - becuase I need to extract the group content (.(?=.*\.[^\]]+)) positive lookahead - get all chars which has a future dot .*\] - after the dot there can be more content which is closed with ]. Looking at this image , there is a match : But if I move the dot to last char before ] , there's no match : Question: I think I know what the problem is , it's becuase the regex don't match a situation where the dot is right before the ]. How can I fix my regex , Also - is there's a better/simpler way of doing it ? REGEX101 A: You can solve the problem with no lookarounds, use 2 negated character classes: \[[^\].]*\.[^\]]*\] See the regex demo Note that this way you only match [...] if the dot is inside the brackets. Your original regex matches [...] if a dot is after the closing bracket, too, due to the . pattern used in the lookahead and . matches any char but a line break char. Details \[ - a literal [ [^\].]* - zero or more chars other than ] and . \. - a dot [^\]]* - zero or more chars other than ] \] - a literal ] (need no escaping, but just escaped for consistency). A: It is the + in there causing the problem, because burried in your regex is the condition Any character that is NOT in this class: []], one or more repetitions Changing that + to a * (any number of repetitions) fixes the problem. New regex: (\[(.(?=.*\.[^\]]*)).*\]) Tested against [app/default-viewcomponentts.] [app/default-viewcomponent.ts] [app/default-viewcomponent.ts.]
{ "pile_set_name": "StackExchange" }
Q: Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class View I am trying to instantiate an object of type Application outside of where I wrote my static main method and I am getting this exception. public class Main { public static void main(String[] args) { new View(args); } } import javafx.application.Application; public class View extends Application { public View(String... args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { } } The stack trace: Exception in Application constructor Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class View at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:907) at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$152(LauncherImpl.java:182) at com.sun.javafx.application.LauncherImpl$$Lambda$2/1867083167.run(Unknown Source) at java.lang.Thread.run(Thread.java:745) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:422) at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$158(LauncherImpl.java:819) at com.sun.javafx.application.LauncherImpl$$Lambda$46/1861073381.run(Unknown Source) at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326) at com.sun.javafx.application.PlatformImpl$$Lambda$48/1540794519.run(Unknown Source) at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295) at com.sun.javafx.application.PlatformImpl$$Lambda$50/1604144171.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(PlatformImpl.java:294) at com.sun.javafx.application.PlatformImpl$$Lambda$49/718368050.run(Unknown Source) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101) at com.sun.glass.ui.win.WinApplication$$Lambda$38/1823101961.run(Unknown Source) ... 1 more Caused by: java.lang.IllegalStateException: Application launch must not be called more than once at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:162) at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:143) at javafx.application.Application.launch(Application.java:252) at View.<init>(View.java:33) ... 18 more A: Not sure what are you trying to do, but invoking launch(args) in your constructor looks wrong. From javadocs (https://docs.oracle.com/javase/8/javafx/api/javafx/application/Application.html#launch-java.lang.String...-): The launch method does not return until the application has exited, either via a call to Platform.exit or all of the application windows have been closed. Even if it worked, it would hang in your constructor. If you need to do it outside main() method, use some static instantiator.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to get early/static binding using function pointers in c++? If yes then how? In C++, one way to get late/dynamic binding is to use function pointers we can also use virtual functions. But don't know about the early/static binding. A: You can't get static binding with a pointer. Technically it's not even "bound" -- it's just the address of some function that you then need to call at runtime. For static binding, the compiler would need to know the address of the function in advance to put it directly in the output machine code, but the value of a pointer is not (usually) known until runtime. If the compiler can guarantee that a pointer value is invariant, or if it can narrow down the value of a pointer at a particular point in execution, then it could possibly optimize things and bind the call statically: void foo() { cerr << "foo!" << endl; } int main(int argc, char **argv) { void (*f)() = &foo; f(); // can statically bind here... but why use a pointer? } But this is a toy example. If the compiler can figure out that your pointer always points to the same function, then one has to wonder why you're using a pointer. A: Here's a toy ... extern void verbose() ; extern void terse() ; const bool debug1 = false; extern bool debug2; void toy() { void (*f)() = debug1 ? verbose : terse ; (*f)(); f = debug2 ? verbose : terse ; (*f)(); return; } ... and here's how the implementers of Intel 11 C++ for Linux interpret it (comments removed): # mark_begin; .globl _Z3toyv _Z3toyv: ..B1.1: # Preds ..B1.0 call _Z5tersev #7.3 ..B1.2: # Preds ..B1.1 movzbl debug2, %eax #8.7 movl $_Z7verbosev, %edx #8.3 movl $_Z5tersev, %ecx #8.3 cmpl $0, %eax #8.3 cmovne %edx, %ecx #8.3 call *%ecx #9.3 ..B1.3: # Preds ..B1.2 ret #10.3 .align 16,0x90 # mark_end; The first call depends on debug1, which is a known-at-compile-time constant. Intel breezes through the ternary operator and reduces it to "call terse" in #7.3. The second call depends on debug2, which is extern, in some other compilation unit. Intel, figuring that given the hapless state of the human condition, any bool is more likely to be false than true, moves the address of terse into ecx and verbose into edx, compares the runtime value of debug2 to zero, and if it's not zero, moves edx to ecx, then calls whatever is in ecx. Note that if you know a priori that debug2 is in fact going to be biased towards truth and that this code is in a critical loop, there may be a compiler-dependent optimization possibility.
{ "pile_set_name": "StackExchange" }
Q: DatagramPacket to string Trying to convert a received DatagramPacket to string, but I have a small problem. Not sure what's the best way to go about it. The data I'll be receiving is mostly of unknown length, hence I have some buffer[1024] set on my receiving side. The problem is, suppose I sent string "abc" and the do the following on my receiver side... buffer = new byte[1024]; packet = new DatagramPacket(buffer, buffer.length); socket.receive(packet); buffer = packet.getData(); System.out.println("Received: "+new String(buffer)); I get the following output: abc[][][][]][][][]..... all the way to the buffer length. I'm guessing all the junk/null at the end should've been ignored, so I must be doing something wrong." I know the buffer.length is the problem because if I change it to 3 (for this example), my out comes out just fine. Thanks. A: new String(buffer, 0, packet.getLength())
{ "pile_set_name": "StackExchange" }
Q: python __getattr__ and __name__ I'm using "new style" classes in Python 2.6 and am having trouble with __getattr__ in a subclass. If the subclass implements like such... def __getattr__(self, name): if self.__folderDict.has_key(name): if name == 'created': return doSomethingSpecial(self.__folderDict[name]) return self.__folderDict[name] else: raise AttributeError() It's not clear to me why my attribute exception gets thrown for a reference to __name__ ? My understand is that __getattr__ should not even get called and that __name__ should be fullfilled by __getattribute__ since I'm using new style? Here's a more complete example... class Base(object): @staticmethod def printMsg(msg, var): print msg + str(var) return def printName(self): Base.printMsg('#', self.__name__) return class Derived(Base): def __getattr__(self, name): if self.__testDict.has_key(name): return self.__testDict[name] else: raise AttributeError() __testDict = {'userid': 4098} d = Derived() print d.userid d.printName() The result is... 4098 Traceback (most recent call last): File "D:/.../Scratch/scratch01.py", line 24, in <module> d.printName() File "D:/.../Scratch/scratch01.py", line 17, in __getattr__ raise AttributeError() AttributeError A: __name__ is predefined for class objects, not instances, and you don't define __name__ anywhere before trying to read it. So _getattr__ is called (since __name__ can't be found via normal lookup) and results in an exception. I suspect that what you actually want is: ... def printName(self): Base.printMsg('#', self.__class__.__name__) return ...
{ "pile_set_name": "StackExchange" }
Q: Replace anything between paragraph tags if it is a html tag I need to remove empty paragraphs from a string which is being pasted into a html textarea. I have this as a regular expression to do that. var reg = /\<p( [a-zA-Z]*=((\"[^\"]*\")|(\'[^\']*\')))*\>\<\/p\>/g; and it works okay. But, some of the data being pasted contains paragraphs that look like this. <p><b></b></p> So the regular expression does not work - as the paragraph, although it contains no actual text, does contain html tags. Can anyone tell me please now to modify my regular expression so that it will not only replace paragraphs with no content with an empty string, but will also replace paragraphs where the only content is html tags. At the moment text like this. <p style="margin:0px;"></p> <p>Fred</p> <p style="margin-left:10px;"></p> <p><b></b></p> <p>Jim</p> is being modified so it then becomes <p>Fred></p> <p><b></b></p> <p>Jim</p> I need it to become <p>Fred</p> <p>Jim</p> A: You can try this: <p[^>]*>(?:\s*<(\w+)>\s*<\/\1>\s*|\s*)<\/p> and replace by empty Regex Demo const regex = /<p[^>]*>(?:\s*<(\w+)>\s*<\/\1>\s*|\s*)<\/p>/g; const str = `<p style="margin:0px;"></p> <p>Fred</p> <p style="margin-left:10px;"></p> <p><b></b></p> <p>Jim</p>`; const subst = ``; const result = str.replace(regex, subst); console.log(result);
{ "pile_set_name": "StackExchange" }
Q: Como ocultar a mensagem em bootstrap? Observem a imagem Quando eu abro o formulário modal ele já aparece a faixa de mensagem de validação, eu gostaria que ele somente aparecesse quando a validação fosse ativada. É esse trecho de código; <div class="alert alert-danger" role="alert"> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="false"></span> <span id="erroMsgUJ"></span> <span id="erroMsgPeriodoInicio"></span> </div> A: É só vc já começar ele com display:none, para isso vc pode usar a classe nativa .hidden do Bootstrap 3 como vc pode consultar aqui: https://getbootstrap.com/docs/3.3/css/#helper-classes-show-hide // Classes .show { display: block !important; } .hidden { display: none !important; } Então sua div de alert ficaria inicialmente assim, depois vc retira o .hidden e coloca o .show pelo JS já usando essas classes nativas do BS3 <div class="alert alert-danger hidden" role="alert">
{ "pile_set_name": "StackExchange" }
Q: Prove or Disprove: If $A$ and $ B$ are $n \times n$ orthogonally diagonalizable matrices, then $A + B$ is orthogonally diagonalizable. So I know the properties that $A^T = A$ if its orthogonally diagonalizable and also $A=PDP^T$, But cant quite use them to prove or disprove. Would appreciate any help. A: If $A^T=A$ and $B^T=B$, then $(A+B)^T=A^T+B^T=A+B$.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to perform a rudimentary asymmetric key encryption algorithm by hand? I have at least three, distinct motivations for having a simple way to use asymmetric key encryption by hand or without modern computers. First, I was recently demonstrating to a 12-year-old how encryption works. I created some basic cyphers and had him figure them out. (I recommend this; it's quite fun.) Wanting to up the ante, I looked for ways to send messages back and forth using public-private key encryption, and I failed with flying colors. Second reason for wanting this is that it would really help me understand how asymmetric encryption works. At the moment, I can't figure out a way to do solve this on my own, and I feel that betrays my lack of understanding in the subject. Finally, (this one may be a stretch) I'm writing a fantasy story, and I'd like to do something unique with the form of exchange. One thought was to have a memorized key that the owner held, which she would use to sign her (paper) payment of 30 units for a loaf of bread, or whatever, combining her key with the shopkeeper's public key. (UPDATE: Note that this gets into digital signatures, rather than asymmetric key encryption. I'm hoping they are related, but if they're not, forget it.) Any ideas how to accomplish this? If it's simply not feasible, I would appreciate an explanation as to why. There are two similar questions on this site, but neither of them address asymmetric key encryption, unless I'm more misinformed than I thought: Is there a secure cryptosystem that can be performed mentally? What is the most secure hand cipher? A: Yes, you can perform rudimentary asymmetric encryption or signing by hand, but no it won't be secure. Textbook RSA with small enough numbers is easy to do by hand. Diffie-Hellman to exchange a symmetric key is even easier. However, the kinds of numbers for which this is feasible are far from those needed for real security. There are a lot of other asymmetric systems, but those tend to use even more complicated (to humans) math. Generally asymmetric encryption on a computer is something like an order of magnitude slower than symmetric and like the question you linked shows even secure symmetric encryption is barely doable, maybe, by hand.
{ "pile_set_name": "StackExchange" }
Q: Python Sqlite3 advanced grouping I hope this question has not been asked before. I have a csv file containing below columns and info and I can upload this to sqlite3 database with the exact same column names Company Type Qty Price ABC r 5 $$$ ABC h 9 $$$ ABC s 10 $$$ DER a 3 $$$ DER z 6 $$$ GGG q 12 $$$ GGG w 20 $$$ but, how do I get the below result on a csv file? Basically, grouping by the company name and still showing Type, Qty and Price, and at the end of lines showing the total qty for each company. Company Type Qty Price Total Qty ABC r 5 $$$ h 9 $$$ s 10 $$$ 24 DER a 3 $$$ z 6 $$$ 9 GGG q 12 $$$ w 20 $$$ 32 I have been trying with GROUP BY, but no luck. Any help is much appreciated Thank you A: I would do this using a combination of SQL and itertools.groupby. For example, something like: results = cxn.execute("SELECT * FROM orders ORDER BY Company") for company, orders_iter in itertools.groupby(results, key=lambda r: r[0]): orders = list(orders_iter) total_qty = sum(order[2] for order in orders) ... print out orders ... Someone with more SQL-foo than I have might be able to come up with a query which would produce exactly the results that you want… But that's probably unnecessary, especially given that, with some minor modifications (calculating the total while iterating over the orders), the Python code would only need O(n) time and O(1) memory.
{ "pile_set_name": "StackExchange" }
Q: Apps with 2 admob accounts on 1 developer account I have 1 developer account, and about 10 apps, all of which use my admob account. I am creating a new app with a friend and I plan to use his admob ads for this app. Can this be done? Do I risk both accounts by doing this? A: Yes you can do this, there is no such restrict that you can only use your own ADMOB account for your applications.
{ "pile_set_name": "StackExchange" }
Q: Create large instance from my micro instance (AWS) I have a micro instance with Ubuntu 11.10 as the OS. I would like to create a Large/Small instance based on my micro instance. Is that OK to create an image from the micro instance and to use it to launch the Large/Small instances? And will it be OK to create the image while the instance is still running? Thank you! A: Is that OK to create an image from the micro instance and to use it to launch the Large/Small instances? Yes It's alright. We do it. Servers running for years. No problem. (: And will it be OK to create the image while the instance is still running? Yes. I always take caution to stop processes, delete unrequired, temp files, log files just to avoid these stuffs go into image. But anyways, it does not matter a-lot. Your system will halt/reboot once, I guess, while creating the AMI.
{ "pile_set_name": "StackExchange" }
Q: Sitecore instance needs DLL from other project...? Alright guys and gals, this one is really weird: when rebuilding the Lucene indexes for my Web database, my Sitecore instance (6.4.1) is taking a dirt nap. Looking at log files, everything is peachy until the index rebuild starts, and then the log is filled with MEGABYTES of the following stack trace repeated over and over: ManagedPoolThread #6 15:57:06 ERROR Failed to sort items Exception: System.IO.FileNotFoundException Message: Could not load file or assembly 'file:///[OTHER PROJECT LIBRARY].dll' or one of its dependencies. The system cannot find the file specified. Source: mscorlib at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark) at System.Reflection.Assembly.LoadFrom(String assemblyFile) at Sitecore.Reflection.ReflectionUtil.LoadAssembly(String name) at Sitecore.Reflection.ReflectionUtil.CreateObject(String assembly, String className, Object[] parameters) at Sitecore.Reflection.ReflectionUtil.CreateObject(String typeName, Object[] parameters) at Sitecore.Data.Comparers.ComparerFactory.GetComparer(String sortingId, Database database) at Sitecore.Data.Comparers.ComparerFactory.GetComparer(Item item) at Sitecore.Configuration.Factory.GetItemComparer(Item item) at Sitecore.Data.Managers.ItemProvider.Sort(ItemList items, Item owner) (the [OTHER PROJECT LIBRARY].dll was shortened for privacy, but it's a full path to this project's sitecore/website/bin directory) The really, really weird thing is that this DLL isn't referenced in any way, shape, or form in both the solution or the entire filetree (both the project and website folders). But here's the punchline: this DLL isn't even from the same project, it's from a different project I have on my workstation (which is running in its own Sitecore instance alongside this project). How could this happen? Project A is trying to reference a DLL from Project B, and this DLL isn't referenced in any way. I've even checked the EventQueue tables in my databases... I'm really starting to lose my mind here. A: Looking at the attached stacktrace you can see that the problem is that Sitecore tries to find a proper comparer while sorting some items. It looks like one of your items has the "Type" field set to the class name from some external library. Maybe someone pasted some wrong class name from the clipboard and hasn't noticed it? Try to execute this query to find the name and the id of the Item with wrong field value set and the value of field: SELECT ii.Name, ii.ID, f.Value FROM [Sitecore_Master].[dbo].[SharedFields] f, [Sitecore_Master].[dbo].[Items] i, [Sitecore_Web].[dbo].[Items] ii WHERE f.FieldId = i.ID AND i.Name = 'Type' AND ii.ID = f.ItemId AND f.Value LIKE '%[OTHER ASSSEMBLY NAME WITHOUT DLL].%' Change the name of the database to your database and use the name of the assembly that appears in the logs. You can also try this query with other databases and without AND i.Name = 'Type' line. The other way is to override the ItemProvider class as follows: namespace My.Namespace { public class MyItemProvider : Sitecore.Data.Managers.ItemProvider { protected override void Sort(Sitecore.Collections.ItemList items, Sitecore.Data.Items.Item owner) { try { base.Sort(items, owner); } catch (System.Exception exc) { Sitecore.Diagnostics.Log.Error("Exception while sorting children of " + owner.Paths.FullPath, exc, this); } } } } and change in your sitecore.config file: <itemManager defaultProvider="default"> <providers> <clear/> <add name="default" type="My.Namespace.MyItemProvider, My.Assembly"/> </providers> </itemManager> You should now see in logs which item is causing problems.
{ "pile_set_name": "StackExchange" }
Q: How can I call methods within a nested class using new()? Right now, I have a nested class as so: class Outer{ public: class Inner{ public: void display(){ cout << "You are in inner class" << endl; } }; void display(){ cout << "You are in outer class" << endl; } }; I have to create an instance of each class Outer and Inner so I can invoke each of their display() methods. I have to use new in order to invoke them as part of my requirement. I can invoke the Outer class fine and point to its method as so: Outer *pOuter = new Outer(); pOuter->display(); But, I'm having troubles doing the same to the Inner class. I've tried: Outer:Inner *pInner = new Outer:Inner(); pInner->display(); but, that doesn't work. So I'm wondering what I can do to invoke the inner method while using new? A: Use the fully qualified path: Outer::Inner* p = new Outer::Inner; p->display(); delete p; Without pointers: Outer::Inner o; o.display(); Or mark the function static and call as: Outer::Inner::display(); That being said, as-is this is better suited for a (Outer) namespace instead of a class.
{ "pile_set_name": "StackExchange" }
Q: How is the array works while in a loop? i'am learning C,and after learning the array,i want to try something,but here comes the confusion. i try to print a-z but there are something more("{|") been printed.and i am confused with it. int count; char ph[26]; char x; for(count = 0, x= 'a'; count < 26 , ph[count] = x; count++ , x++) printf("%c",ph[count]); I expect the output to be a-z, but the actual output is a-|. Thank you and I realize that what matters is the comma operator. A: The problem is that the stopping conditional expression count < 26, ph[count] = x has the value x, i.e. count probably runs past 25. This is how the expression separator operator , behaves. If this means that you end up with an out of bounds read of ph (which you do on ASCII encoded platforms), the behaviour of your code is undefined. The way you have written the loop is unnecessarily obfuscating, but if you want to stick to a similar way then writing count < 26 && ph[count] = x is the fix. Finally note that ASCII is not the only encoding supported by C, so even when you do get the program working on your platform, you have not written it in portable C. A: This for loop for(count = 0, x= 'a'; count < 26 , ph[count] = x; count++ , x++) printf("%c",ph[count]); is incorrect. In the condition of the loop count < 26 , ph[count] = x there is used the comma operator. The value of the operator is the value of its second operand that is the value of the assignment ph[count] = x. The first operand count < 26 is just ignored. As a result the loop has undefined behavior. Rewrite the loop the following way for(count = 0; count < 26; count++ ) printf( "%c", ph[count] = 'a' + count );
{ "pile_set_name": "StackExchange" }
Q: Magento 2: "Empty option" for programmatically populated select attribute I have a product attribute dropdown select box that I populate via a source model. The population works fine, but I want the first option in the list to be "Select one...". I've used the following code: $options[] = array( 'label' => 'Select one...', 'value' => '', ); But the result is as follows: With the rendered HTML: <select> <option value="">Select one...</option> <option data-title="Select one..." value="">Select one...</option> What am I doing wrong? A: @awarche's answer works: You'll need to add a caption to your UI component field config: <item name="caption" xsi:type="string" translate="true">Select one...</item> I don't think an empty "Please select..." value belongs in a source model.
{ "pile_set_name": "StackExchange" }
Q: Where to put X11 drivers configuration in Ubuntu Lucid? Since hal is removed from Lucid, where now can I put all those little configuration tweaks for mouse and other input devices? In particular, I want to configure ThinkPad trackpad to enable scrolling with middle button. In hal, it was done with <match key="info.product" string="TPPS/2 IBM TrackPoint"> <merge key="input.x11_options.EmulateWheel" type="string">true</merge> <merge key="input.x11_options.EmulateWheelButton" type="string">2</merge> <merge key="input.x11_options.ZAxisMapping" type="string">4 5</merge> <merge key="input.x11_options.XAxisMapping" type="string">6 7</merge> <merge key="input.x11_options.Emulate3Buttons" type="string">true</merge> <merge key="input.x11_options.EmulateWheelTimeout" type="string">200</merge> </match> A: I've managed to find the right place. It's /usr/lib/X11/xorg.conf.d/. There's already some configuration files that can be used as examples but surprisingly man xorg.conf have good enough documentation about all new Match keywords. The example from the post can be translated to the following snippet (in a file /usr/lib/X11/xorg.conf.d/20-trackpoint.conf) Section "InputClass" Identifier "Trackpoint" MatchProduct "TPPS/2 IBM TrackPoint" MatchDevicePath "/dev/input/event*" Option "EmulateWheel" "true" Option "EmulateWheelButton" "2" Option "ZAxisMapping" "4 5" Option "XAxisMapping" "6 7" Option "Emulate3Buttons" "true" Option "EmulateWheelTimeout" "200" Option EndSection Note: for Ubuntu 10.10 you should place your config files in /usr/share/X11/xorg.conf/ instead.
{ "pile_set_name": "StackExchange" }
Q: How to retrieve name and icon of WIndows Store App I need to retrieve Windows Store App the way like Task Manager does. Is it possible? I was trying to use Query API and packaging API, reading manifest, but I need to read resources from resources.pri file to get desired info. Where I can find API which helps me to get Display Name and Icon of Store App? PS My app is not Windows Store App, written in C++ A: List from desktop WPF app all installed WinRT/Metro applications Windows.Management.Deployment.PackageManager class has method to get all packages and then perform XML deseralization of manifest files to get the info. Use shlwapi.dll with DLL interop to extract more data using method SHLoadIndirectString
{ "pile_set_name": "StackExchange" }
Q: Is there any way to bind drop down field options to specific input type in yii2 I have a form which consists of media type drop down. <?= $form->field($model, 'media_type')->dropDownList( [ 'text' => 'Text', 'image' => 'Image', 'url' => 'Url', 'audio' => 'Audio', 'video' => 'Video', ], [ 'options' => ['prompt' => 'Select Media Type'] ] ) ?> I wants to change value field when changing media type in yii2 form. For example, if we select text option then we need to show tinymce editor. Or if we select image then we need to show file input field. File input field <?php echo $form->field ( $model, 'value' )->fileInput (); if ($model->value != ""){ echo Html::a('Click here to view image', $model->value, ['target' => '_blank']); } ?> Tiny mce editor <?= $form->field($model, 'value')->textarea(['rows' => 6])->widget(letyii\tinymce\Tinymce::className(), [ 'options' => [ 'class' => '', ], 'configs' => [ 'plugins' => 'advlist autolink link lists charmap preview code colorpicker', 'height' => 300, 'selector' => 'textarea', 'forced_root_block' => '', ], ]); ?> Is there anyway to achieve this will be very helpful Thanks A: Add some JavaScript that listens to the change of the dropdown and show/hide your elements based on the selected value. I wrote a small example. You'll have to change the IDs to match your elements and maybe make some other small changes, but something like this should work. <?php $this->registerJs(" $(function() { $('#your-form-media-type-id').on('change', function() { var value = this.value switch (value) { case 'text': $('#your-mce-div').show(); $('#your-image-input-div').hide(); break; case 'image': $('#your-image-input-div').show(); $('#your-mce-div').hide(); break; } }); }); ");
{ "pile_set_name": "StackExchange" }
Q: R: reducing set to fixed size Suppose I have the following data: library(data.table); set.seed(55) dat <- data.table(id=1:50, x=sample(100:200,50,replace=TRUE), y=sample(500:600,50,replace=TRUE), z=sample(900:1000,50,replace=TRUE)) > head(dat) id x y z 1: 1 155 583 912 2: 2 122 574 945 3: 3 103 524 963 4: 4 179 587 993 5: 5 156 592 915 6: 6 107 545 996 from which I pick one row at random, say row number 5. 5: 5 156 592 915 My goal is now to find those n_min=10 other rows that are most similar, according to a ranking of variables, say x, y, z. That is, I would like to take the first variable, see how many rows are within a particular interval and keep adding variables until one is reached that would reduce my n below n_min. For example, in the example above, x and y jointly reduce the set to 16 rows, but adding z would reduce n below n_min. x_possible <- (156-round(sd(dat$x))):(156+round(sd(dat$x))) y_possible <- (592-round(sd(dat$y))):(592+round(sd(dat$y))) z_possible <- (915-round(sd(dat$z))):(915+round(sd(dat$z))) > nrow(dat[x%in%x_possible]) [1] 32 > nrow(dat[x%in%x_possible & y%in%y_possible]) [1] 16 > nrow(dat[x%in%x_possible & y%in%y_possible & z%in%z_possible]) [1] 6 Such tasks are completely new to me and I didn't even know which terms to use to start looking. I wonder whether there is an efficient way of automatizing this such that I could throw in another dat and get the relevant rows out. A: Here's a way to use non-equi joins. There's probably a more efficient way to assign the sd results to the data.table but this is what I have: library(data.table) set.seed(55) dat <- data.table(id=1:50, x=sample(100:200,50,replace=TRUE), y=sample(500:600,50,replace=TRUE), z=sample(900:1000,50,replace=TRUE)) n_min <- 10 col_name <- names(dat)[-1] sds <- dat[, lapply(.SD, sd), .SDcols = col_name] dat[dat[, .(id,x, y, z, x_sd_min = x - sds[['x']], x_sd_plus = x + sds[['x']])] , on = .(x > x_sd_min, x < x_sd_plus) , j = .(id, i.id , y_inrange = between(y, i.y - sds[['y']], i.y + sds[['y']], incbounds = F) , z_inrange = between(z, i.z - sds[['z']], i.z + sds[['z']], incbounds = F)) , allow.cartesian = T , nomatch = 0L ][, .(x = .N, x_y = sum(y_inrange), x_y_z = sum(y_inrange & z_inrange)), keyby = id ][, .(id, x, x_y, x_y_z, threshold_breaker = c('x','y','z')[max.col(.SD[, -1] > n_min, ties.method = 'last')])] id x x_y x_y_z threshold_breaker 1: 1 31 17 6 y 2: 2 24 15 12 z 3: 3 17 8 5 x 4: 4 28 14 5 y 5: 5 32 16 6 y 6: 6 19 13 6 y 7: 7 20 4 2 x 8: 8 29 14 4 y 9: 9 29 18 11 z 10: 10 19 11 7 y 11: 11 22 11 6 y 12: 12 19 10 7 x 13: 13 30 20 13 z 14: 14 29 17 11 z 15: 15 26 11 5 y 16: 16 29 12 7 y 17: 17 32 15 5 y 18: 18 21 7 2 x 19: 19 33 15 12 z 20: 20 27 20 10 y 21: 21 27 13 5 y 22: 22 26 13 8 y 23: 23 24 12 4 y 24: 24 23 15 10 y 25: 25 16 11 6 y 26: 26 32 11 4 y 27: 27 27 20 12 z 28: 28 23 11 7 y 29: 29 27 17 10 y 30: 30 28 12 3 y 31: 31 27 16 11 z 32: 32 30 16 8 y 33: 33 19 9 6 x 34: 34 17 9 8 x 35: 35 24 13 7 y 36: 36 30 14 5 y 37: 37 32 17 6 y 38: 38 22 11 4 y 39: 39 26 13 7 y 40: 40 28 14 7 y 41: 41 19 13 8 y 42: 42 19 9 6 x 43: 43 19 11 3 y 44: 44 26 13 3 y 45: 45 27 10 6 x 46: 46 25 12 7 y 47: 47 25 10 6 x 48: 48 16 8 2 x 49: 49 29 10 6 x 50: 50 33 16 7 y id x x_y x_y_z threshold_breaker # Mostly original, here for reference col_name <- names(dat)[-1] dat[, paste0(col_name, '_sd') := lapply(.SD, sd), .SDcols = col_name] dat[, paste0(col_name, '_sd_min') := .SD - mget(paste0(col_name, '_sd')), .SDcols = col_name] dat[, paste0(col_name, '_sd_plus') := .SD + mget(paste0(col_name, '_sd')), .SDcols = col_name] dat dat[dat , on = .(x > x_sd_min, x < x_sd_plus , y > y_sd_min, y < y_sd_plus , z > z_sd_min, z < z_sd_plus ) , j = .(id, i.id, x.x, x.y, x.z) , allow.cartesian = T , nomatch = 0L][id == 5, ] id i.id x.x x.y x.z 1: 5 1 156 592 915 2: 5 5 156 592 915 3: 5 16 156 592 915 4: 5 24 156 592 915 5: 5 29 156 592 915 6: 5 37 156 592 915 I need more details about fixed sized but you can probably get a maximum number of subset using this way.
{ "pile_set_name": "StackExchange" }
Q: Semi-responsive build chopped off viewed on iPad I have not a link to share at this point but was wondering if anyone had come across the same problem as myself. I have made a responsive website, the client requested that the site should be responsive from 1080px in width down to 960px in width, this was easy to build and works on the Desktop but on the ipad in portrait the website is chopped off, in landscape however its perfect. I'm thinking its something to do with the initial width being used on render.. I've tried: <meta name = "viewport" content = "width=device-width; initial-scale = 1; maximum-scale=1; user-scalable = no;" /> and <meta name="viewport" content="width=device-width, initial-scale=0.7"> as a "fix" maybe I should set a fixed width for ipad? A: Leave your meta with initial-scale = 1; Then go in you media queries and find if you are checking for ipad dimensions @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) Please bare in mind that you need extra media queries for ipad3/4
{ "pile_set_name": "StackExchange" }
Q: Category Database Design I'm new to database design and I need some help to solve a problem. Sorry if this question has already been answered, i've been searching without success. This is a simplified scenario of whats going on: It's an ITEM database and each item can belong to one, two, three... or 5 level category structure (hierarchy), examples are: `Product | Category1 | Category 2 | Category 3 | Category 4 | Category 5 ClassicLens Clothing Men Accesories Summer Old Lens Clothing Men Accesories Phone 2G Cell Phones Locked 2G Pulp Fiction Movie DVD Lets say I have three tables ITEM, CATEGORY and CATEGORY_HIERARCHY with the following schemas: ITEM ----------- Id_Item (PK), Id_Category_Hierarchy (FK) Name CATEGORY_HIERARCHY ------------ Id_Category_Hierarchy (PK), Id_Category1 (IX) (FK), Id_Category2 (IX) (FK), Id_Category3 (IX) (FK), Id_Category4 (IX) (FK), Id_Category5 (IX) (FK) CATEGORY ------------ Id_Category (PK), Name As you can see, I force with the Unique Index that only one combination of category1, category2, ... category 5 can exist. This approach can work but I bet there is a better solution for this scenario. ¿What do you think? Any help/comments will be appreciated! I can't group all kind of categories in different tables because this would be endless. Edit: I forgot to mention the database is Access + VBA, would a recursive solution work? I guess SQL Queries will be more complex. A: I would probably go with something that is more like this: Product ---------- ProductId Name Categories ---------- CategoryId Name ParentCategory --Recursive Key ProductCategories ----------------- ProductId CategoryId Any time you find yourself adding something like columnName_{some number} over and over it's probably time to break that set of columns into it's own table. I can almost guarantee that at some point you will get a request to go from a max of 5 categories to something larger. Using the table structure above will allow you to do this without making any significant changes.
{ "pile_set_name": "StackExchange" }
Q: KDE: how do i find and switch current global keyboard layout from CLI? I'm on KDE and I need to find out and to be able to switch current global keyboard layout in a script. I've made a research on setxkbmap - but in this case it's of no help. A: Found a solution: setxkbmap -print | grep xkb_symbols | awk '{print $4}' | awk -F"+" '{print $2}' to find out current layout. The following allows to set it: setxkbmap -layout us setxkbmap -layout ru and this toggles it: if [ `setxkbmap -print | grep xkb_symbols | awk '{print $4}' | awk -F"+" '{print $2}'` = us ] ;then echo "EN"; echo "changing to RU..."; setxkbmap ru ; else echo "RU"; echo "Changing to US..."; setxkbmap us ; fi If You use gxneur -- it can't cope with all this, but standard Kubuntu layout indicator works fine.
{ "pile_set_name": "StackExchange" }
Q: How can I create a platform on my stairs strong enough to support a ladder? I live in a two-story condo and need to reach a spot on the wall high above my staircase to do some handy work. A ladder is the only way I can do this (I am stating this explicitly in order to avoid responses of Well, tell us exactly what you are doing so we can possibly find an alternative). A scaffold for a staircase would be nice, but there's no place around here that rents them out for a reasonable price. I came across an idea on YouTube to set a ladder up against a wall and then lay a board across the staircase and one of the rungs on the ladder, but there's no way I can transport a board of such length in my sedan. As I am sorta forced to find a way to do this on my own, I came upon the dangerous idea of creating a platform by stacking a few cinder blocks on a lower step and putting a sheet of plywood across the blocks and a higher step. I have a rail that will serve as backing for the plywood. Conceptually, it seems like a sound idea, but I am coming to you guys for alternatives that might help me avoid breaking a part of my body. Update: Since I am in dire need of a super quick solution and couldn't find a PiViT per Tester's recommendation, I picked up a Werner 22' multi-use ladder from Lowe's. Tester gets the mark for best answer since his answer addresses my question. Even though I haven't tried it, I know it would work. A: If you're using an extension ladder, they sell Ladder leveling feet. I also stumbled across this product The PiViT Ladder tool, though you'd need two for a step ladder. A: I know this is an old thread, but in case there are any new readers using it as a resource... We've released a new tool to address this need. It's a small, compact platform for using ladders on stairs, with adjustable height to fit any staircase. I hope this helps someone down the road. You can find it online (www.ladder-aide.com), or in paint and home improvement stores.
{ "pile_set_name": "StackExchange" }
Q: What's the best way to store lettuce in the refrigerator? What is the best way to store lettuce in the fridge? Should I store it in an airtight container, or an open bag? Should I wash and cut it first? Should it be stored wet, or patted dry? A: It depends on what type of lettuce it is -- part of the issue is that if the lettuce is touching plastic, it will rot quicker, so I wrap it in paper towels, then bag it (but not sealed), and keep it in my crisper. For whole heads of lettuce (iceburg, butter, red leaf, etc), I just wrap the whole thing in dry paper towels, then shove it back into the bag from the grocery store or farmer's market. I then pull off leaves as I need it, and re-wrap it. It stores for well over a week this way. For mescalin mixes, arugula, or other individual leaves, I'll wash them, dry them, then unroll enough paper towels to spread the leaves on, then roll up the whole thing, and bag the roll (again, not sealed), and keep it in my crisper. I can probably get a week out of it this way. (all times assume you're not buying from a store where it's been sitting on the shelf too long before you buy it; I get my lettuce when I can from the local farmer's market) So, to answer the specific questions: keep the bag open; you don't want moisture to condense inside the bag, as it'll make the lettuce rot faster. I get better storage time with heads of letuce keeping them whole. If you're going to be eating it all within 2-3 days, it probably doesn't matter, and for loose lettuce, I find it more convenient to wash it as I re-pack it anyway. You never want to store lettuce wet ... you might be able to store it completely submerged, but damp will lead to it rotting faster. A: I have just found the transcript of a Good Eats episode about lettuce storage. It's close to Joe's answer but they say the lettuce should be kept in an air tight bag with air sucked out. In short they say: washed heads kept intact for delicate lettuce, cut is ok if hearty heads spinned dry wrapped in paper towel stored in air tight bag with the air sucked out See senes 9-10-11 of http://www.goodeatsfanpage.com/Season1/Salad/SaladTranscript.htm
{ "pile_set_name": "StackExchange" }
Q: Looking for low-mid phone with good battery & screen I need a new phone to replace a Moto G7 Power that I dropped in a lake. I would buy it again but I can't find it anywhere for near its original price (I saw one on eBay for £250, double its original price). I'd like to find a similar phone for a similar price of £100-£200. Requirements in order of how important they are to me: Good battery life. Moti G7 Power had 5000mAh which admittedly is overkill, but the more the better (>=4000mAh would be nice) decent screen: Moto G7 Power had a 720p 19:9 display which was probably it's weakest point, a 1080p screen would be nice but I'll compromise on the screen if necessary. Relatively stock android: so not Samsung, I want a pretty standard version like that of Motorola phones. Android 9 is my OS of choice because it's relatively recent but also still has the old-school navigation buttons that i can't live without. USB-C: is very cool Decently fast processor, basically anything will do to be honest, and enough graphics power to play 1080p60 YouTube smoothly (probably not even necessary to specify) Thanks for any and all suggestions in advance! A: Might I suggest the Moto G7 Power? Despite what the question indicates, I was able to find several sites where it is being offered for less than £200, including eBay. Here is a refurbished one for only 143. Here is a completely new one from about 125. The Motorola store in the US is definitely still selling it for $179 (£134). If you have a friend in the US they can mail it to you. Careful of possible international version differences. Alternately, you can go for the G8 Power Lite, which is being sold for £130 on Motorola's UK site. You'll see improvements in almost everything over the G7 Power, except that 4K video recording may not be possible, and it has an unusual processor, something that might affect battery life. You could even get the regular G8 Power for under 200 on Amazon if you are willing to go for a used, like-new device. Lenovo UK is also selling them new for 200 (limited time discount coupon). This will be an improvement in all aspects over your previous device, except that a higher resolution may decrease battery life. It would come with Android 10, unfortunately.
{ "pile_set_name": "StackExchange" }
Q: capybara regex xpath not working I have the following hmtl code. li id is increasing sequentially, and I want to generate regex so as to use in xpath but is not working: irb#1(main):044:0* find(:xpath, "//li[@id = 'divPictureAndPrices_productListItem1']") => #<Capybara::Node::Element tag="li" path="/html/body/div[2]/div[7]/div[2]/div/div[3]/ol/li[2]"> irb#1(main):045:0> irb#1(main):017:0* all(:xpath, "//li[matches(@id, '^divPictureAndPrices_productListItem\d{0,2}$')]") Selenium::WebDriver::Error::InvalidSelectorError: invalid selector: Unable to locate an element with the xpath expression //li[matches(@id, '^divPictureAndPrices_productListItemd{0,2}$')] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//li[matches(@id, '^divPictureAndPrices_productListItemd{0,2}$')]' is not a valid XPath expression. (Session info: chrome=48.0.2564.116) (Driver info: chromedriver=2.20.353124 (035346203162d32c80f1dce587c8154a1efa0c3b),platform=Mac OS X 10.11.3 x86_64) from /Library/Ruby/Gems/2.0.0/gems/selenium-webdriver-2.52.0/lib/selenium/webdriver/remote/response.rb:70:in `assert_ok' from /Library/Ruby/Gems/2.0.0/gems/selenium-webdriver-2.52.0/lib/selenium/webdriver/remote/response.rb:34:in `initialize' from /Library/Ruby/Gems/2.0.0/gems/selenium-webdriver-2.52.0/lib/selenium/webdriver/remote/http/common.rb:78:in `new' from /Library/Ruby/Gems/2.0.0/gems/selenium-webdriver-2.52.0/lib/selenium/webdriver/remote/http/common.rb:78:in `create_response' from /Library/Ruby/Gems/2.0.0/gems/selenium-webdriver-2.52.0/lib/selenium/webdriver/remote/http/default.rb:90:in `request' from /Library/Ruby/Gems/2.0.0/gems/selenium-webdriver-2.52.0/lib/selenium/webdriver/remote/http/common.rb:59:in `call' from /Library/Ruby/Gems/2.0.0/gems/selenium-webdriver-2.52.0/lib/selenium/webdriver/remote/bridge.rb:645:in `raw_execute' from /Library/Ruby/Gems/2.0.0/gems/selenium-webdriver-2.52.0/lib/selenium/webdriver/remote/bridge.rb:623:in `execute' from /Library/Ruby/Gems/2.0.0/gems/selenium-webdriver-2.52.0/lib/selenium/webdriver/remote/bridge.rb:602:in `find_elements_by' from /Library/Ruby/Gems/2.0.0/gems/selenium-webdriver-2.52.0/lib/selenium/webdriver/common/search_context.rb:84:in `find_elements' from /Library/Ruby/Gems/2.0.0/gems/capybara-2.6.2/lib/capybara/selenium/driver.rb:69:in `find_xpath' from /Library/Ruby/Gems/2.0.0/gems/capybara-2.6.2/lib/capybara/node/base.rb:107:in `find_xpath' from /Library/Ruby/Gems/2.0.0/gems/capybara-2.6.2/lib/capybara/query.rb:110:in `block in resolve_for' from /Library/Ruby/Gems/2.0.0/gems/capybara-2.6.2/lib/capybara/node/base.rb:80:in `synchronize' from /Library/Ruby/Gems/2.0.0/gems/capybara-2.6.2/lib/capybara/query.rb:106:in `resolve_for' from /Library/Ruby/Gems/2.0.0/gems/capybara-2.6.2/lib/capybara/node/finders.rb:182:in `block in all' from /Library/Ruby/Gems/2.0.0/gems/capybara-2.6.2/lib/capybara/node/base.rb:84:in `synchronize' from /Library/Ruby/Gems/2.0.0/gems/capybara-2.6.2/lib/capybara/node/finders.rb:181:in `all' from /Library/Ruby/Gems/2.0.0/gems/capybara-2.6.2/lib/capybara/session.rb:686:in `block (2 levels) in <class:Session>' from /Library/Ruby/Gems/2.0.0/gems/capybara-2.6.2/lib/capybara/dsl.rb:51:in `block (2 levels) in <module:DSL>' from (irb#1):17irb#1(main):018:0> this is also not working: find(:xpath, "//li[matches(@id, '^divPictureAndPrices_productListItem\d{0,2}$')]") please help me on solving problem? A: matches is supported only in xpath2.0. if your xpath processor is 1.0 compliant only, then you must use contains.
{ "pile_set_name": "StackExchange" }
Q: Iterating over a column in Pandas DataFrame with groupby conditions I have a dataset in a pandas DataFrame. Data are sorted by ["Customer_Id","Campaign"]. My goal though is to add another step to the groupby function. For each campaign there is batches, new batches is represented by the New_rank == 1. I would like to add a column = "Occurence" that gives me an numbered "batch" for per Customer_Id & campaign. Desired output like this in this case: Any ideas would be greatly appreciated! A: Use cumsum: df['Occurence'] = df.groupby(['CustomerId','Campaign'])['New_rank'].cumsum() Output: CustomerId Campaign New_rank Occurence 0 1 1 1 1 1 1 1 0 1 2 1 1 1 2 3 1 2 1 1 4 1 2 1 2 5 2 1 1 1 6 2 1 0 1 7 2 1 0 1 8 2 2 1 1 9 2 3 1 1 10 2 3 0 1
{ "pile_set_name": "StackExchange" }
Q: Regex to match a string that contains at least 3 dashes / hyphens I have an email body. It contains several lines of text. I need to extract the first occurrence of a string that: comes after a specific text contains at least 3 dashes The shape of the dashed string is unknown. It may contain letters and numbers of any number, i.e.: AA3A-123-NNN-D or 12-OOO-12455-AS For example: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec imperdiet porta libero ac imperdiet. Nam enim nisl: aliquam ut feugiat vitae Specific text after which I need to search: Etiam rhoncus AAFA-12X-DDDD-12 metus risus More text: foo Target language is C#. I've tried doing something like ([A-Za-z0-9]{5}-[A-Za-z0-9]{4}-[A-Za-z0-9]{3}-[A-Za-z0-9]{5}) but as you can see here I need to set the shape of the string which is not always known. A: You can use a lazy quantifier with [\s\S]: (?:Specific\ text\ after\ which\ I\ need\ to\ search:) [\s\S]+?\K (\b\w+-\w+-\w+-\w+\b) The \b is a word boundary, \K deletes everything to the left from the match. See a demo on regex101.com.
{ "pile_set_name": "StackExchange" }
Q: What do $#, $1 and $2 mean? My question is about a bash-programme, which is in this big book about programming a raspberry pi (bash, Python, C). There is a sample programme to show how the if works in bash, but no matter how many times a read through the description of the programme, it just doesn't seem to explain properly what it does (I know it's too much to ask if I want a thorough bash tutorial in a 1000 pages book, and that's why I'm here) So here is the code: #!/bin/bash if test $# -ne 2; then echo "You have to pass 2 arguments to the command" #argument / parameter, whatever you prefer exit 1 else echo "Argument 1: $1, argument 2: $2" fi I understand, that the -ne 2 means: not equal to 2, so it checks if the $# is equal to 2, but I don't understand what it does (the $#). -> First question In the else it prints the $1 and $2, but I thought that $variablename would print the value of that variable. How can an integer be a variable? -> second question And yes, I google'ed and didn't find anything of use (maybe didn't search enough?), which is exactly why I'm here. I would appreciate any kind of help, be it a link to read it myself, or a short explanation. Thanks in advance :) A: The $# refers to the number of parameters received at run time, not a specific parameter. $1 gets replaced by whatever was in location 1 on the command line when the script was executed.
{ "pile_set_name": "StackExchange" }
Q: How to know when my app has been killed? I need to know when the user kills my app (Force stop). I've been reading the android lifecycle, which has the onStop() and onDestroy() functions, these are related to each activity the user ends on my app, but not when the user forces stop or kills my app. Is there any way to know when the user kills the app? A: I have found one way to do this..... Make one service like this public class OnClearFromRecentService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("ClearFromRecentService", "Service Started"); return START_NOT_STICKY; } @Override public void onDestroy() { super.onDestroy(); Log.d("ClearFromRecentService", "Service Destroyed"); } @Override public void onTaskRemoved(Intent rootIntent) { Log.e("ClearFromRecentService", "END"); //Code here stopSelf(); } } Register this service in Manifest.xml like this <service android:name="com.example.OnClearFromRecentService" android:stopWithTask="false" /> Then start this service on your splash activity startService(new Intent(getBaseContext(), OnClearFromRecentService.class)); And now whenever you will clear your app from android recent Then this method onTaskRemoved() will execute. NOTE: In Android O+ this solution only works when the app is full-time in foreground. After more than 1 minute with the app in background, the OnClearFromRecentService (and all other Services running) will be automatically force-killed by the system so the onTaskRemoved() will not be executed. A: there's no way to determine when a process is killed. From How to detect if android app is force stopped or uninstalled? When a user or the system force stops your application, the entire process is simply killed. There is no callback made to inform you that this has happened. When the user uninstalls the app, at first the process is killed, then your apk file and data directory are deleted, along with the records in Package Manager that tell other apps which intent filters you've registered for. A: Create a Application class onCreate() Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created. onLowMemory() This is called when the overall system is running low on memory, and actively running processes should trim their memory usage. onTerminate() This method is for use in emulated process environments. Even if you are application Killed or force stop, again Android will start your Application class
{ "pile_set_name": "StackExchange" }
Q: How to quickly mark resolution having conflicts during rebase? this is a part of my git status # Unmerged paths: # (use "git reset HEAD <file>..." to unstage) # (use "git add/rm <file>..." as appropriate to mark resolution) # # deleted by us: ../../src/generic/asdfgsdfgsfg.java # deleted by us: ../../src/generic/bsdfgsdf.java # deleted by us: ../../src/generic/cdghdfgh.java # deleted by us: ../../src/generic/dghkghjk.java # deleted by us: ../../src/generic/eghkghjk.java # deleted by us: ../../src/generic/fsdfgsdfg.java # deleted by us: ../../src/generic/gsdfgsd.java # deleted by us: ../../src/generic/hdsfgsdfg.java # deleted by us: ../../src/generic/isdgsdfg.java # deleted by us: ../../src/generic/jdsfgsd.java # deleted by us: ../../src/generic/ksdf.java # deleted by us: ../../src/generic/lnsfgnsg.java # How can I easily and quickly make git rm on each of this file, knowing that in folder ../../src/generic/ there are a lot of other files, which I don't want to remove. A: There's this really great pair of aliases I picked up from the git wiki a while back (it's currently down along with kernel.org): edit-unmerged = \ "!f() { git ls-files --unmerged | cut -f2 | sort -u ; }; vim ` add-unmerged = \ "!f() { git ls-files --unmerged | cut -f2 | sort -u ; }; git add `f`" This could be reimplemented in terms of git status --porcelain, which didn't exist when the tip was written, which would make it easier to rewrite edit-unmerged to avoid including deletion conflicts, since usually you want to delete/keep those, not edit them. But add-unmerged fits your use case exactly! Something like this (untested): add-unmerged = \ "!f() { git status --porcelain | grep '^[ADU][ADU]' | cut -d" " -f2 }; git add `f`" edit-unmerged = \ "!f() { git status --porcelain | grep '^UU' | cut -d" " -f2 }; git add `f`" with tweaking on the second pattern until it includes only the types of conflicts you like to edit. You definitely want UU; you might also want AU/UA, and maybe even AA. A for added, D for deleted, U for unmerged (modified).
{ "pile_set_name": "StackExchange" }
Q: Javascript solution for user being inside or outside a rectangle I was checking Stackoverflow and many other pages to find a Javascript (or JQuery) solution that tells me if a user (with its current GPS location) is inside or outside a predefined rectangle on a map. There are many solutions for circles and squares but I can't find a solution for rectangles. Furthermore the rectangle must not be parallel to f.e. the equator. It can have any possible angle to it. Which parameter of the rectangle are required to make the inside/outside calculation? Anyone knows a Javascript solution to solve this problem? A: To know if a point is inside a rectangle in a 2D plan you need: the position of one point of the rectangle: X0, Y0; the angle the rectangle is making with the horizontal axis: a; the length of the first side: L1; the length of the second side: L2. See this drawing. A point (X,Y) is inside the rectangle when: 0 >= (X-X0)*cos(a) - (Y-Y0)*sin(a) >= L1 0 >= (X-X0)*sin(a) + (Y-Y0)*cos(a) >= L2 Or in javascript: function isInRectangle(x, y, x0, y0, a, l1, l2) { var v1 = (x-x0)*Math.cos(a) - (y-y0)*Math.sin(a); var v2 = (x-x0)*Math.sin(a) + (y-y0)*Math.cos(a); return v1 >= 0 && v1 <= l1 && v2 >= 0 && v2 <= l2; } To use it: var p = {x: /*user longitude*/, y: /*user latitude*/}; var p0 = {x: /*rect longitude*/, y: /*rect latitude*/}; var a = /*angle of the rect in rad*/; var l1 = /*length of one side of the rectangle*/ var l2 = /*length of the second size*/ isInRectangle(p.x, p.y, p0.x, p0.y, a, l1, l2); // => return true if inside, false otherwise
{ "pile_set_name": "StackExchange" }
Q: Where is my Collatz conjecture proof wrong? I am amateur and don't have very good understanding of mathematical proving. My proof is so simple i don't believe noone thought of this before. But I am so blinded by the hope it is correct, that I can't find any errors in it. Here are all the conclusions I made in the process: You can always make smaller odd number from even, so we only need to prove that every odd number works. Out of the two ways (3n+1 and n/2) only the n/2 can be used to create n ≡ 0 (mod 3) from n-1, where n-1 ≡ 0 (mod 3) has to hold true n ≡ 0 (mod 3) always creates n ≡ 1 (mod 3) (EDIT: every odd n ≡ 0 (mod 3)) therefore once we abandon n ≡ 0 (mod 3), we can never find any other n ≡ 0 (mod 3) later in the sequence in other words we can't compose any n ≡ 0 (mod 3) from smaller number But, we can "compose" any n !≡ 0 (mod 3) (sorry, if I invented the notation. !≡ means the remainder after division is not 0) from smaller number. reverse Collatz Example: 5 => 10 => either 3 or 20 The only way to reverse n ≡ 2 (mod 3) is n*2, after which every n-1 ≡ 1 (mod 3) n-1 ≡ 1 (mod 3) can be reversed in both ways, but the (n-1)/3 yielding n-2 will always be smaller then n If n !≡ 0 (mod 3) can be "composed" from smaller number, we need only to prove the Collatz conjecture works for the smaller number. which can be either n !≡ 0 (mod 3) and can be "compsed" from smaller number again or be n ≡ 0 (mod 3) So the only thing I have to prove now is that the Collatz conjecture works for every odd n ≡ 0 (mod 3) But since every odd n ≡ 0 (mod 3) will yield n+1 ≡ 1 (mod 3) and I already concluded that once we abandon n ≡ 0 (mod 3), no later number will be n ≡ 0 (mod 3), the Collatz conjecture works also for n ≡ 0 (mod 3) I've already looked at this for two days and can't find any errors and it drives me crazy. Is it cyclic or something? Am I depending on my own proves that also depend on my own proves? Did I make algebraic mistake? Hopefully, some of you will be willing to help. P. S. Please be mindful of my experience and don't use very mathematical language if not neccessary. I've tried to search for this and didn't understand many papers on this matter. EXPLANATIONS: "be composed of" means "is preceded by" EDIT: don't overlook EDIT in point 3 made the points ordered so we can reference them more easily. added explanations A: EDIT after OP edited the question. Your reasoning fails after point $6$ (included). Indeed, you talk about a certain number in the chain being "smaller" or "bigger" than another, and then mistakenly apply this rule to multiple elements of the chain (for instance in your point $6c$). This is not strong enough, as $n/2$ might be followed by $3(n/2)+1$, which is always bigger than your original $n$. And then the same behaviour might happen again, etc. So you have not proved that every $n ≡ 1\ ( mod \ 3)$ eventually becomes smaller than $n$. Nor have you proved that there does not exist a cycle other than $4\to2\to1\to4$, a problem that your reasoning did not address.
{ "pile_set_name": "StackExchange" }
Q: FYI - the Stack Exchange iOS app has soft launched Look for an official launch blog post next week if no show stoppers are found, however, you can download the Stack Exchange app now from the App Store. MSE: Was the iOS App Officially Launched Get the app - https://itunes.apple.com/us/app/stack-exchange/id871299723?mt=8 A: The blog post has all the details. Get some! http://blog.stackoverflow.com/2014/05/stack-exchange-for-iphone-is-here/
{ "pile_set_name": "StackExchange" }
Q: Symfony 2 Variable Entity Naming I feel like this shouldn't be to hard, but try as I might, I keep getting errors. What I'm wanting to do, is to have a single "add" function that will handle the basic functionality of adding records to any / all tables. Basically, the post data will contain the table name, as well as the fields / values to be inserted. The controller itself, confirms the user has access to do these things, and then verifies the fields are valid, before creating a new instance of the entity, that's where things go haywire: $entityName = 'Products'; $row = new $entityName(); //doesn't work $row new Products(); //works I haven't found a way or any examples of creating a new entity using the Entity Manager, or else that might work, because i've created functions using EM to do queries, updates, and deletes, but I just can't get this to work with the add functions. A: 1. Your problem is almost certainly namespacing (see below). Try this instead: $entityName = 'My\Bundle\Entity\Products'; $row = new $entityName(); Should work. ;)   2. If you want to create new instances using an EntityManager, try this: $entityName = 'My\Bundle\Entity\Products'; $row = $em->getClassMetadata($entityName)->newInstance(); ...assuming $em is your EntityManager. :-)   3. To "prove" that your problem is namespacing, try this in a plain .php file that you run from the command line: namespace Foo; class Test {} $class1 = 'Foo\Test'; $class2 = 'Test'; $x = new Test(); // Will work $y = new $class1(); // Will work $z = new $class2(); // Will trigger "Class 'Test' not found" fatal error
{ "pile_set_name": "StackExchange" }
Q: Broken RenderPartial After Upgrade To ASP.NET MVC2 I upgraded a MVC1 project to MVC2, now all my calls to RenderPartial are throwing System.ArgumentNullException: Value cannot be null. However this does works: <% Html.RenderPartial("~/Views/Shared/LogOnUserControl.ascx"); %> And this does not (works in MVC1): <% Html.RenderPartial("LogOnUserControl"); %> Did the behavior of RenderPartial change? A: Bleh.... found the problem, my project was referencing MVCContrib 1.0, downloaded the latest build and referenced that instead fixed the issue.
{ "pile_set_name": "StackExchange" }
Q: Process data before express renders page Using node and express, I'm trying to process some information before the response renders the page, but I'm not having any luck doing so. Any suggestions? app.get("/Category", function (request, response) { if (request.query.Id) { // get all the posts by categoryId ForumPost.find({categoryId: request.query.Id}, function (err, posts) { if (err) throw err; var usernames = {}; for (i = 0; i < posts.length; i++) { User.findById(posts[i].userId, function (err, user) { if (err) throw err; var username = user.username; usernames[i] = username; }); } response.render("Category", { message: posts, userList: usernames }); }); } }); A: You probably want to query the DB only once, using a single find with all the user ids passed in as single $in filter, and then make sure you form your response in the callback handler that mongoose wants you to pass in as second argument to the find function: // build the list of all ids you need var ids = posts.map(p => mongoose.Types.ObjectId(p.userId)); // let's remove duplicates, too ids = ids.filter((id,pos) => ids.indexOf(id)===pos); // find all these users in a single query: User.find({ '_id': { $in: ids} }, (err, users) => { // handle the query result if (err) { // do something error related here return ... } // no error: get the usernames and send the response var usernames = users.map(user => user.username); response.render("Category", { message: posts, userList: usernames }); }); This uses modern arrow functions, but if you're on an old version of Node (pre-6) those are easily replaced with classic function signatures ((a,b,...) => c is equivalent to function(a,b,...) { return c }. Technically they're (function(a,b,...) { return c; }).bind(this) but that's not a relevant distinction in the code above).
{ "pile_set_name": "StackExchange" }
Q: Calculation of the EFIE integral I need help computing the following integral: $$ \int_{}\frac{(1+jk|\vec{r}-\vec{r}^\prime|)e^{-jk|\vec{r}-\vec{r}^\prime|}}{|\vec{r}-\vec{r}^\prime|}d\vec{r}^\prime $$ in this integral $\vec{r}$ and $\vec{r}^\prime$ are the position vectors that correspond to the observation point and source point, respectively. This integral comes from the Electric-Field Integral Equation (EFIE) kernel. A: A classic paper for evaluation of the integrals commonly present in computational electromagnetics (EM) is: D. R. Wilton, S. M. Rao, A. W. Glisson, D. H. Schaubert, O. M. Al-Bundak, and C. M. Butler, "Potential integrals for uniform and linear source distributions of polygonal and polyhedral domains," IEEE Trans. Antennas Propag., vol. AP-32, no. 3, pp. 276-281, Mar. 1984. The challenge to evaluate the EFIE integrals is the required singularity treatment. If both $\mathbf{r}$ and $\mathbf{r}^\prime$ belong to the same patch in the discretized geometry, one cannot use just quadrature-based integration. The idea is to subtract a singularity and integrate it analytically and the rest (already without a singularity), numerically. So, say you need to calculate the integral ($R=|\mathbf{r}-\mathbf{r'}|$): $$ \int\limits_S\frac{e^{-jkR}}{R}ds'=\underbrace{\int\limits_S\frac{e^{-jkR}-1}{R}ds'}_{I_1}+\underbrace{\int\limits_S\frac{1}{R}ds'}_{I_2} $$ Here, $S$ is the source patch and $\mathbf{r}$ is fixed. Now, integral $I_1$ does not have a singularity and can be evaluated using, say, 2-D Gaussian quadrature (use barycentric coordinates and apply Gaussian quadrature over $\xi$, $\eta$ with a proper Jacobian) Integral $I_2$ can be found analytically. The formula for a planar polygon $S$ is given in the referenced paper. You still might want to use this technique of singularity subtraction even when observation and source patches are different, but relatively close together. Such singularity treatment will decrease the error coming from numerical integration and reduce the number of quadrature points required to achieve the accuracy for nearby interactions. I assume, that right now you've discretized your EFIE using pulse-basis functions and you are testing your EFIE using pulses as well. That might be good enough for certain scenarios, but I will point out that the use of proper basis functions and testing procedure might be important later in your development process. Note: there are other techniques to tackle the singularity in this Green's function, including special quadrature rules, but I personally prefer this approach.
{ "pile_set_name": "StackExchange" }
Q: How to populate empty columns with unique values in SQL Server? I have a table which have a row containing user emails and I want to add a constraint to make this row unique. The problem is that there are some (around 200) columns with empty values. I need to generate dummy values and insert them to the empty columns. How can I do it? Thanks A: Description You can use the T-SQL function newid() newid() Creates a unique value of type uniqueidentifier. Sample UPDATE MyTable set Column = newid() where Column is null More Information MSDN - NEWID (Transact-SQL) A: If you use SQL Server 2008 - consider unique index by email which filters out null values, smth like that: CREATE UNIQUE INDEX [UX.Email, not null] on dbo.YourTable(email) WHERE email is not null OR For versions of SQL Server prior to 2008 you can use the value of your primary key identity of row, if you have one update yourtable set email = id where email is null If you have no such a key, at least you can use NEWID() function instead of id
{ "pile_set_name": "StackExchange" }
Q: JS, How to select all rows data of serverside DataTable I have 2 pages of serverside Datatable and I want to select all rows data from all pages And this code var table = $('#table').DataTable({ "processing": true, "serverSide": true, /* Some code */ }) var data = table.rows().data() console.log(data) returns the data of selected page only ( in this case the data of 1st page ) So, is it possible to select all data from all pages for serverside DataTables ? A: No, you can't. If you use remote paging, the client doesn't know anything about other pages records yet. According to documentation to select all records for local paging. You could use table.rows().select() In same way, if you want to deselect them just try like this. table.rows().deselect();
{ "pile_set_name": "StackExchange" }
Q: Configure Blaze and start Bokeh server from Pyramid web-application I have a Pyramid web-application on which the customer would like the ability to plot large data sets interactively. The application currently displays a sub-set of the customer's selected data with zoom, pan, hover, etc. capabilities using D3. However, in the case the user needs to see the full set with the same functionality, I would like to use the Bokeh server and use down-sampling. Where I am running into trouble is that the down-sampling function can only be used with plots employing a ServerDataSource. Ideally, the Bokeh server would be running constantly and I could push the customer's selected data to it and then use it as the source for the down-sampled plot. However, as far as I can tell, Blaze doesn't allow me to push data to an existing server. Instead, I thought when the user requested the plot, I could use one of Pyramid's views to modify the Blaze configuration file and then start the Bokeh server. @view_config(route_name='startBokehServer', renderer = 'json',permission='view') def startBokehServer_view(request): r""" Configures blaze_config.py file to create a dict containing customer's select reversal data Starts Bokeh server using modified blaze_config.py file at http://localhost:5006 """ bokeh_server.run() Once the data was stored on the server, another view would plot the curve with the Bokeh server as the data source. @view_config(route_name='fetchPlotDataRev', renderer = 'json',permission='view') def fetchPlotDataRev_view(request): r""" Plots full reversal data using Bokeh's down-sampling method. """ from bokeh.plotting import output_server, figure, show from bokeh.models import HoverTool, Range1d from bokeh.transforms import line_downsample output_server("Full Reversal Curve(s)") c=bokeh_client('http://localhost:5006') d=bokeh_data(c) rev=d.rev source=line_downsample.source() source.from_blaze(rev,local=True) TOOLS="pan,wheel_zoom,box_zoom,reset,hover" p = figure(title="Reversal with tooltip", tools=TOOLS) p1=p.scatter(x='time',y='aa_cd',color='#0000ff',source=source) p1.select(dict(type=HoverTool)).tooltips=[("(x,y)", "($x, $y)"),] p2=p.scatter(x='time',y='aa_cv',color='#ff0000',source=source) p2.select(dict(type=HoverTool)).tooltips=[("(x,y)", "($x, $y)"),] xmin=float(rev.time.min()) xmax=float(rev.time.max()) ymin=float(rev.aa_cv.min()) ymax=float(rev.aa_cd.max()) p.x_range=Range1d(start=xmin,end=xmax) p.y_range=Range1d(start=ymin,end=ymax) show(p) Finally, a signal from the JavaScript that the Bokeh server window has been closed posts a request to another view that would stop the server. @view_config(route_name='stopBokehServer', renderer = 'json',permission='view') def stopBokehServer_view(request): r""" Stops Bokeh server. """ bokeh_server.start.stop() However, the application exits with status 2 when trying to serve /startBokehServer. The traceback is included below. usage: pserve [-h] [--ip IP] [--port PORT] [--url-prefix URL_PREFIX] [-D BLAZE_CONFIG] [-m] [--script SCRIPT] [--backend BACKEND] [--redis-port REDIS_PORT] [--start-redis] [--no-start-redis] [--ws-conn-string WS_CONN_STRING] [-d] [--dev] [--filter-logs] [-j] [-s] [--robust-reload] [-v] pserve: error: unrecognized arguments: development.ini /home/katmeg/mat-cruncher/PyramidAnalysis 2015-04-09 12:20:53,730 ERROR [waitress][Dummy-11] Exception when serving /startBokehServer Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/waitress-0.8.9-py2.7.egg/waitress/channel.py", line 337, in service task.service() File "/usr/local/lib/python2.7/dist-packages/waitress-0.8.9-py2.7.egg/waitress/task.py", line 173, in service self.execute() File "/usr/local/lib/python2.7/dist-packages/waitress-0.8.9-py2.7.egg/waitress/task.py", line 392, in execute app_iter = self.channel.server.application(env, start_response) File "/usr/local/lib/python2.7/dist-packages/pyramid-1.5.1-py2.7.egg/pyramid/router.py", line 242, in __call__ response = self.invoke_subrequest(request, use_tweens=True) File "/usr/local/lib/python2.7/dist-packages/pyramid-1.5.1-py2.7.egg/pyramid/router.py", line 217, in invoke_subrequest response = handle_request(request) File "/usr/local/lib/python2.7/dist-packages/pyramid_debugtoolbar-2.3-py2.7.egg/pyramid_debugtoolbar/toolbar.py", line 178, in toolbar_tween response = _handler(request) File "/usr/local/lib/python2.7/dist-packages/pyramid_debugtoolbar-2.3-py2.7.egg/pyramid_debugtoolbar/panels/performance.py", line 57, in resource_timer_handler result = handler(request) File "/usr/local/lib/python2.7/dist-packages/pyramid-1.5.1-py2.7.egg/pyramid/tweens.py", line 21, in excview_tween response = handler(request) File "/usr/local/lib/python2.7/dist-packages/pyramid-1.5.1-py2.7.egg/pyramid/router.py", line 163, in handle_request response = view_callable(context, request) File "/usr/local/lib/python2.7/dist-packages/pyramid-1.5.1-py2.7.egg/pyramid/config/views.py", line 245, in _secured_view return view(context, request) File "/usr/local/lib/python2.7/dist-packages/pyramid-1.5.1-py2.7.egg/pyramid/config/views.py", line 355, in rendered_view result = view(context, request) File "/usr/local/lib/python2.7/dist-packages/pyramid-1.5.1-py2.7.egg/pyramid/config/views.py", line 501, in _requestonly_view response = view(request) File "/home/katmeg/mat-cruncher/PyramidAnalysis/pyramidanalysis/views.py", line 649, in startBokehServer_view bokeh_server.run() File "/home/katmeg/pyrEnv/local/lib/python2.7/site-packages/bokeh/server/__init__.py", line 134, in run args = parser.parse_args(sys.argv[1:]) File "/usr/lib/python2.7/argparse.py", line 1691, in parse_args self.error(msg % ' '.join(argv)) File "/usr/lib/python2.7/argparse.py", line 2347, in error self.exit(2, _('%s: error: %s\n') % (self.prog, message)) File "/usr/lib/python2.7/argparse.py", line 2335, in exit _sys.exit(status) SystemExit: 2 Note: The plots work as I intend them to when I run the bokeh-server executable from the command line and then create and serve them from a separate Python script. So my questions are as follows: Can I push data to an already running Bokeh server and then use it as a data source for down-sampling? And if not, how can I start/stop the Bokeh server as requested within the Pyramid application? Thanks in advance for any help! A: Here is how the application dynamically configures the Server data source, starts the Bokeh server, and plots the requested data on the the Bokeh server for the customer to navigate. The data to be plotted is passed to the startBokehServer view where it is written to a temporary text file. The Bokeh server is then started using Python's subprocess and a configuration file that reads the text file and configures the data such that it can be read by Blaze. views.py @view_config(route_name='startBokehServer',renderer = 'json',permission='view') def startBokehServer_view(request): # plotDataRev is dictionary containing data requested from web page with open('pyramidanalysis/temp/reversal_data.txt','wb') as handle: pickle.dump(plotDataRev,handle) bokeh_pid=str(subprocess.Popen(['/bokeh-server','-D','blaze_config.py'],stdout=subprocess.PIPE).pid) request.session['bokehPID']=bokeh_pid blaze_config.py import pandas as pd import pickle with open('pyramidanalysis/temp/reversal_data.txt','rb') as handle: b=pickle.loads(handle.read()) data=dict() keys=b.keys() for key in keys: data[key]=pd.DataFrame(b[key]) The server page is then displayed in an iFrame on the web-page and closing the frame or the main window initiates another view that terminates the Bokeh server and deletes the temporary text file.
{ "pile_set_name": "StackExchange" }
Q: Play Framework use Joined Table in Query (ExpressionList) So I have two tables: Users and AlertHistory. I have joined AlertHistory to User, so that if I do: List<User> users = new Model.Finder(Integer.class, User.class).setMaxRows(9).findList(); List<AlertHistory> ahc = users.get(3).getAlertHistoryCollection(); I will get the list of Users, and each user will have a collection of AlertHistory objects. What I would like to do with the Finder, is return the list of Users where the AlertHistory is NOT NULL. I've tried various version of: new Model.Finder(Integer.class, User.class).where().isNotNull("alertHistoryCollection").setMaxRows(9).findList(); but to no avail. A: The problem here was that the relationships I had defined weren't correct. In User.java: @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user") private List<AlertHistory> alertHistoryList = new ArrayList<>(); and in AlertHistory.java: @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name = "user_id") Once I got the relationship annotated and typed correctly, it started working as expected, so that if the User has associated AlertHistory's, they will populate, and if not, the collection will be empty. .isNotNull() now works as expected.
{ "pile_set_name": "StackExchange" }
Q: React.js store multiple datepicker dates against id's in state I have a problem where I am generating datepickers on the fly based on a number of props passed down. The props passed down from the parent component are charges of a particular product. So say there a 6 charges, then we create an input field containing the charge and then for each one a corresponding datepicker needs to be displayed. The image below hopefully displays this better than i could explain it! (Picture paints a thousand words they say!!) So my problem is this, if the user updates all of the dates in the datepickers (to the right) then how do I save each date to the particular id? I would obviously store them in state, but how do i save each one? I cant just have values in state pre-set as the number of datepickers and charges can be different each time. Sometimes there may be 1, sometimes there may be 10. The code I have for this component is as follows: export class Charges extends Component { constructor(props) { super(props); this.state = { currentItem: 0, newDate: '' fields: [] } this.handleChange = this.handleChange.bind(this); } ****** EDIT ********* handleDateChange = (e) => { const date = e.target.value; const chargeId = e.target.name; console.log(date); this.setState({ fields: [ ...this.state.fields, [chargeId]: date ] }, () => console.log(this.state.fields)) } ********** render() { const {charges, chargeTypes} = this.props; if (charges.length === 0) { return null; } return <Form> <h3>Charges</h3> {charges.map(charge => { console.log(charge); const chargeType = chargeTypes.find(type => type.code === charge.type) || {}; return <Grid> <Grid.Row columns={2}> <Grid.Column> <Form.Input key={charge.id} label={chargeType.description || charge.type} value={Number(charge.amount).toFixed(2)} readOnly width={6} /> </Grid.Column> <Grid.Column> <DateInput name={charge.id} selected={this.state.newDate} onChange={this.handleChange} value={charge.effectiveDate} /> </Grid.Column> </Grid.Row> </Grid> })} <Divider hidden /> <br /> </Form> } } As you can see, I will just overwrite previous' state value if the user was to update more than one datepicker? I have viewed the following article, but its not really what i want: Multiple DatePickers React How can i achieve the functionality I want? I hope I have made this clear? If there are any questions please don't hesitate to ask! * Edited Answer * I have now updated the handleDateChangeMethod to store the data in an array (as this is what I want) however, it only gives me the chargeId and not the date mapped to it! See screenshot below: Is there anyway to save like this in the state array [chargeId: date] A: You can set a unique prop in the state for each datepicker by its name attribute using computed property handleChange = (e, date) => { const value = moment(date); const chargeId = e.target.name; console.log(chargeId); this.setState({[chargeId]: value}, () => console.log(this.state[chargeId])); } Read more about this approach in React's website: https://reactjs.org/docs/forms.html#handling-multiple-inputs
{ "pile_set_name": "StackExchange" }
Q: itextsharp auto font size and Linebreak only on Spaces I have a itextsharp Table, with a strict height and width of the Cells. I then get a string that can differ in word count and work length. How can i set the Font size automaticaly to go as big as possible, and only allow breaks after a word has ended, just like in WPF's Viewboxes. currently i am working with this: Cell.AddElement(new Paragraph(text, new Font(Font.FontFamily.COURIER, Convert.ToInt32(FZ), 1)){Alignment = Element.ALIGN_CENTER}); Cell.VerticalAlignment = Element.ALIGN_MIDDLE; Cell.HorizontalAlignment = Element.ALIGN_MIDDLE; Cell.Padding = 4; Cell.FixedHeight = Utilities.MillimetersToPoints(46); return Cell; FZ is the Fontsize I am taking from the viewboxes directly, but a straight conversion doesnt work Thanks in Advance! A: I've created a standalone application with a lot of "test", "test\ntest", "test test test test", etc... cells. The result looks like this: I have made several assumptions: I assume that cells are created using String values. Internally, this will result in a List that contains a single Paragraph. This Paragraph will contain a single Text object. I assume that no font was defined, that's why I introduce the default font (Helvetica). I assume that no leading was defined, hence I introduce a multiplied leading of 1. I assume that no padding was defined, hence I introduce a padding of 1 This is my code: import java.io.File; import java.io.IOException; import com.itextpdf.io.font.FontProgram; import com.itextpdf.io.font.FontProgramFactory; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Cell; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.element.Table; import com.itextpdf.layout.element.Text; import com.itextpdf.layout.renderer.CellRenderer; import com.itextpdf.layout.renderer.IRenderer; public class FitCell { public static final String[] TEST = { "test", "test test test test test test test", "test test", "test", "test test test test\ntest test test test test test test test test test test", "test", "test", "test", "test\ntest\ntest\ntest", "test", "test", "test", "test", "test", "test", "test", "test", "test\ntest", "test", "test", "test", "test", "test", "test", "test test test test test test test test test test test test test test" }; private class FitContentCellRenderer extends CellRenderer { public FitContentCellRenderer(Cell modelElement) { super(modelElement); try { // We assume that the Cell is created by passing a String // This means that the Cell consists of one Paragraph Paragraph p = (Paragraph)modelElement.getChildren().get(0); // And that the Paragraph has one Text object Text t = (Text)p.getChildren().get(0); // Using the default font FontProgram f = FontProgramFactory.createFont(); // We get the content from the Text object String content = t.getText(); // Define a default font size (to make sure that you don't have text that is excessively big). float fs = 100; // Define a font size depending on the number of lines and the height int[] fontBbox = f.getFontMetrics().getBbox(); int fh = (fontBbox[2] - fontBbox[1]); float padding = 1; modelElement.setPadding(padding); float ch = modelElement.getHeight() - 2 * padding; String text[] = content.split("\\r\\n|\\n|\\r"); fs = Math.min(fs, ch / (fh * text.length) * FontProgram.UNITS_NORMALIZATION); // Loop over all the lines PdfFont font = PdfFontFactory.createFont(f); float cw = modelElement.getWidth().getValue() - 2 * padding; for (String l : text) { float w = font.getWidth(l, 1); fs = Math.min(fs, cw / w); } p.setFontSize(fs); p.setMultipliedLeading(1); } catch(IOException ioe) { // occurs when font program can't be created; this never happens } } @Override public IRenderer getNextRenderer(){ return new FitContentCellRenderer(getModelElement()); } } private class FitContentCell extends Cell { public FitContentCell() { super(); this.setWidth(50); } @Override protected IRenderer makeNewRenderer() { return new FitContentCellRenderer(this); } } public static final String DEST = "results/tables/cell_fit_content.pdf"; public static void main(String args[]) throws IOException { File file = new File(DEST); file.getParentFile().mkdirs(); new FitCell().createPdf(DEST); } public void createPdf(String dest) throws IOException { PdfDocument pdf = new PdfDocument(new PdfWriter(dest)); Document document = new Document(pdf); Table table = new Table(new float[]{1, 1, 1, 1, 1, 1, 1}); int testcount = 0; for (int i = 0; i < 70; i++) { if (testcount >= TEST.length) { testcount = 0; } table.addCell(new FitContentCell().add(TEST[testcount++]).setHeight(20 + 10 * (i / 10))); } document.add(table); document.close(); } } In this code, I change the behavior of the Cell object in a subclass called FitCell. The behavior of FitCell is changed by overriding the CellRenderer. Actually, I'm not really changing the behavior of the renderer, but I'm changing some things the moment the renderer instance is created (before anything else happens). I define a padding for the cell, I define a font and a leading for the Paragraph and I calculate the font size of the Paragraph so that the text fits the cell. I first define a font size of 100 (which is huge), but none of the content will eventually have a font size of 100, because I first make sure that all the text fits the height of the cell; then I make sure that all the text fits the width of the cell. The result is that all the text fits the cell.
{ "pile_set_name": "StackExchange" }
Q: Absence of if / loop body allowed: example? I found a few weird constructs in Java that the compiler allows, but for which I'm not sure what could be the practical use. 1) if statement: if((score=score+10) > 110); //No if body while eg: switch(++i); is not 2) for loop: for(;;); //No loop body Are there practical, valid circumstances to use the preceding code? A: This: if((score=score+10) > 110); is equivalent to: score += 10; but has no practical use otherwise. This: for(;;); loops forever doing nothing - not particularly useful, unless you wanted to create a permanently busy thread perhaps for testing purposes.
{ "pile_set_name": "StackExchange" }
Q: How do I replace string containing square brackets Help me, please. There is a file with such strings: <b>[source:1:2:3]</b> <b>[source:2:3:1]</b> <b>[source:3:1:2]</b> <b>[source:1:3:2]</b> I only need to convert one line from this file. The result should be such a file: <b>[source:1:2:3]</b> <b>[source:2:3:1]</b> <b>[result:3:1:2]</b> <b>[source:1:3:2]</b> Broke my head trying to escape [ with sed :( Probably should be something like this: cat test.txt |sed "s,<b>\[source:3:1:2\]</b>,<b>\[result:3:1:2\]</b>,g" A: EDIT: To look for specific string and then change line use following. awk -v old_string="source" -v new_string="result" '/<b>\[source:3:1:2\]<\/b>/{sub(old_string,new_string)} 1' Input_file OR to save results into same Input_file then try following. awk -v old_string="source" -v new_string="result" '/<b>\[source:3:1:2\]<\/b>/{sub(old_string,new_string)} 1' Input_file > temp && mv temp Input_file If you are ok with awk then try following. awk 'FNR==3{sub(/source/,"result")} 1' Input_file OR if you want to have variables of current and new values in awk code then try following. awk -v old_string="source" -v new_string="result" 'FNR==3{sub(old_string,new_string)} 1' Input_file
{ "pile_set_name": "StackExchange" }
Q: Popover controllers vs. the menu popover for SplitViewController I use a floating popover to present suggestions in my UI. When the user wants to select an item from the menu bar in the splitview controller, the first tap just dismisses the popover. Therefore, the user has to tap twice, to activate a menu item. If the user wants to activate the trash can, he has to tap it twice. Once to dismiss the other popover, and once to activate the trash can. What's the best way to avoid this? A: Wild guess here - but perhaps passThroughViews - add the button view and then in the button action, dismiss the popover (need to determine if it is active). A bit hacky but could work.
{ "pile_set_name": "StackExchange" }
Q: Extending Types by Subclassing in Python This is extracted from Learning Python 4th edition. Its function is to subclass set using list. But I don't understand line 5 list.__init__([]), please help. The code works even when I commented out this line of code. Why? ### file: setsubclass.py class Set(list): def __init__(self, value = []): # Constructor list.__init__([]) # Customizes list self.concat(value) # Copies mutable defaults def intersect(self, other): # other is any sequence res = [] # self is the subject for x in self: if x in other: # Pick common items res.append(x) return Set(res) # Return a new Set def union(self, other): # other is any sequence res = Set(self) # Copy me and my list res.concat(other) return res def concat(self, value): # value: list, Set . . . for x in value: # Removes duplicates if not x in self: self.append(x) def __and__(self, other): return self.intersect(other) def __or__(self, other): return self.union(other) def __repr__(self): return 'Set:' + list.__repr__(self) if __name__ == '__main__': x = Set([1,3,5,7]) y = Set([2,1,4,5,6]) print(x, y, len(x)) print(x.intersect(y), y.union(x)) print(x & y, x | y) x.reverse(); print(x) x A: The code in the book contains an error. I've submitted an errata to O'Reilly books, which you can read along with the authors response on this page (search for 982). Here's a small snippet of his response: This code line has apparently been present in the book since the 2nd Edition (of 2003--10 years ago!), and has gone unremarked by hundreds of thousands of readers until now The line list.__init__([]) is missing an argument, and commenting it out makes no difference whatsoever, except speeding up your program slightly. Here's the corrected line: list.__init__(self, []) When calling methods that are not static methods or class methods directly on class objects, the normally implicit first argument self must be provided explicitly. If the line is corrected like this it would follow the good practice that Antonis talks about in his answer. Another way to correct the line would be by using super, which again makes the self argument implicit. super(Set, self).__init__([]) The code in the book provides a different empty list ([]) as the self argument, which causes that list to be initialized over again, whereupon it is quickly garbage collected. In other words, the whole line is dead code. To verify that the original line has no effect is easy: temporarily change [] in list.__init__([]) to a non-empty list and observe that the resulting Set instance doesn't contain those elements. Then insert self as the first argument, and observe that the items in the list are now added to the Set instance. A: You mean this line? list.__init__([]) When you override the __init__ method of any type, it's good practice to always call the inherited __init__ method; that is, the __init__ method of the base class. This way you perform initialization of the parent class, and add initialization code specific to the child class. You should follow this practice even if you are confident that the __init__ of the parent does nothing, in order to ensure compatibility with future versions. Update: As explained by Lauritz in another answer, the line list.__init__([]) is wrong. See his answer and the other answers for more. A: You mean list.__init__([])? It calls the base initializer from the subclass initializer. Your subclass has replaced the base class initializer with its own. In this case commenting that out happens to work because the unbound initializer was called with an empty list instead of self and is thus a no-op. This is an error on behalf of the authors, most likely. But it is a good idea generally to make sure the base class has run its initialization code when you subclass. That way all internal data structures the base class methods rely on have been set up correctly.
{ "pile_set_name": "StackExchange" }
Q: Prove that identity matrix is the only idempotent $n x n$ matrix that is invertible. I do get that let's say $A=(A*A)$ $A^{-1} * A = A^{-1} *(A*A)$ $(A^{-1}*A)=(A^{-1}*A)A$ Then $I=I*A$, therefore $I=A$ Are those correct? Is there another or proper way to prove this? A: Your proof is great, and completely correct. Personally, I object to the use of $*$ as denoting matrix multiplication, but that's more an opinion that anything. Another version of the proof that I like is as follows: Let's say that $A$ is invertible with $A = A^2$. Then we have $$ A^2 - A = 0 \implies\\ A(A - I) = 0 \implies\\ A^{-1}[A(A - I)] = A^{-1}[0] \implies\\ A-I = 0 $$ So, we must have $A - I = 0$, which is to say that $A = I$. Why do I like this better? I suppose the approach generalizes nicely to arbitrary polynomials and the consideration of minimal polynomials, but really I just think factoring is neat.
{ "pile_set_name": "StackExchange" }
Q: How to change color of different field in json data I am using ... GUARDIAN_REQUEST_URL = http://content.guardianapis.com/search?from-date=2015-01-01&order-by=newest&show-fields=thumbnail&q=android&api-key=test ... to parse JSON data. My app runs perfectly, but I want to change the color of different sectionName for e.g. for Technology = pink, for Society = blue. Below is the screenshot of the app. Can anyone tell me how to change color of different sections? NewsAdapter.java: public class NewsAdapter extends ArrayAdapter<News> { Context mContext; public NewsAdapter(Context context, ArrayList<News> news) { super(context, 0, news); mContext = context; } // "view holder" that holds references to each subview private class ViewHolder { private final ImageView newsImage; private final TextView sectionName; private final TextView webTitle; public ViewHolder(ImageView newsImage, TextView sectionName, TextView webTitle) { this.newsImage = newsImage; this.sectionName = sectionName; this.webTitle = webTitle; } } @NonNull @Override public View getView(int position, View convertView, ViewGroup parent) { News currentNews = getItem(position); // Check if there is an existing view (called convertView) that we can reuse, // otherwise, if convertView is null, then inflate a new list item layout. if (convertView == null) { final LayoutInflater layoutInflater = LayoutInflater.from(mContext); convertView = layoutInflater.inflate(R.layout.news_list_item, null); final ImageView newsImage = (ImageView) convertView.findViewById(R.id.image_view); final TextView sectionName = (TextView) convertView.findViewById(R.id.section_name); final TextView webTitle = (TextView) convertView.findViewById(R.id.web_title); final ViewHolder viewHolder = new ViewHolder(newsImage, sectionName, webTitle); convertView.setTag(viewHolder); } final ViewHolder viewHolder = (ViewHolder) convertView.getTag(); Picasso.with(mContext) .load(currentNews.getThumbnail()) .resize(100, 120) .into(viewHolder.newsImage); viewHolder.sectionName.setText(currentNews.getSectionName()); viewHolder.webTitle.setText(currentNews.getWebTitle()); return convertView; } } QueryUtils.java: public class QueryUtils { public QueryUtils() { } /** * Query the GUARDIAN dataset and return a list of {@link News} objects. */ public static List<News> fetchNewsData(String requestUrl) { // Create URL object URL url = createUrl(requestUrl); // Perform HTTP request to the URL and receive a JSON response back String jsonResponse = null; try { jsonResponse = makeHttpRequest(url); } catch (IOException e) { e.printStackTrace(); } // Extract relevant fields from the JSON response and create a list of {@link News}s List<News> newses = extractFeatureFromjson(jsonResponse); return newses; } /** * Returns new URL object from the given string URL. */ private static URL createUrl(String stringUrl) { URL url = null; try { url = new URL(stringUrl); } catch (MalformedURLException e) { e.printStackTrace(); } return url; } /** * Make an HTTP request to the given URL and return a String as the response. */ private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(1000); urlConnection.setConnectTimeout(1500); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // If the request was successful (response code 200), // then read the input stream and parse the response. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } } catch (IOException e){ } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { // Closing the input stream could throw an IOException, which is why // the makeHttpRequest(URL url) method signature specifies than an IOException // could be thrown. inputStream.close(); } } return jsonResponse; } /** * Convert the {@link InputStream} into a String which contains the * whole JSON response from the server. */ private static String readFromStream(InputStream inputStream) throws IOException { StringBuilder output = new StringBuilder(); if (inputStream != null) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8")); BufferedReader reader = new BufferedReader(inputStreamReader); String line = reader.readLine(); while (line != null) { output.append(line); line = reader.readLine(); } } return output.toString(); } /** * Return a list of {@link News} objects that has been built up from * parsing the given JSON response. */ private static List<News> extractFeatureFromjson(String newsJson) { // If the JSON string is empty or null, then return early. if (TextUtils.isEmpty(newsJson)) { return null; } // Create an empty ArrayList that we can start adding news to List<News> newses = new ArrayList<>(); try { JSONObject baseJsonResponse = new JSONObject(newsJson); JSONObject response = baseJsonResponse.getJSONObject("response"); JSONArray newsArray = response.getJSONArray("results"); for (int i = 0; i < newsArray.length(); i++) { JSONObject currentNews = newsArray.getJSONObject(i); String sectionName = currentNews.getString("sectionName"); Log.e("SECTION_NAME", sectionName); String webTitle = currentNews.getString("webTitle"); Log.e("WEB_TITLE", webTitle); String webUrl = currentNews.getString("webUrl"); Log.e("WEB_URL", webUrl); JSONObject fields = currentNews.getJSONObject("fields"); if (fields.has("thumbnail")) { String thumbnail = fields.getString("thumbnail"); Log.e("THUMBNAIL", thumbnail); News news = new News(thumbnail, sectionName, webTitle, webUrl); newses.add(news); } } } catch (JSONException e) { e.printStackTrace(); } return newses; } } news_list_item.xml: <?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" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical"> <android.support.v7.widget.CardView android:id="@+id/cv" android:layout_width="170dp" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp"> <ImageView android:id="@+id/image_view" android:layout_width="140dp" android:layout_height="200dp" android:layout_alignParentLeft="true" android:layout_alignParentTop="true"/> <TextView android:id="@+id/section_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAllCaps="true" android:background="@color/colorAccent" android:padding="5dp" android:textSize="9sp" android:textColor="@android:color/white" tools:text="technolgy"/> <TextView android:id="@+id/web_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/black" android:layout_marginTop="@dimen/activity_horizontal_margin" tools:text="Amazon and Google fight crucial battle over voice recognition" /> </LinearLayout> </android.support.v7.widget.CardView> A: You can change color based on your sectioned by the below changge: @NonNull @Override public View getView(int position, View convertView, ViewGroup parent) { News currentNews = getItem(position); if(currentNews.getSectionName().equals("Technology")) { viewHolder.sectionName.setBackgroundResource(R.color.yourColor); } // Check if there is an existing view (called convertView) that we can reuse, // otherwise, if convertView is null, then inflate a new list item layout. if (convertView == null) { final LayoutInflater layoutInflater = LayoutInflater.from(mContext); convertView = layoutInflater.inflate(R.layout.news_list_item, null); final ImageView newsImage = (ImageView) convertView.findViewById(R.id.image_view); final TextView sectionName = (TextView) convertView.findViewById(R.id.section_name); final TextView webTitle = (TextView) convertView.findViewById(R.id.web_title); final ViewHolder viewHolder = new ViewHolder(newsImage, sectionName, webTitle); convertView.setTag(viewHolder); } final ViewHolder viewHolder = (ViewHolder) convertView.getTag(); Picasso.with(mContext) .load(currentNews.getThumbnail()) .resize(100, 120) .into(viewHolder.newsImage); viewHolder.sectionName.setText(currentNews.getSectionName()); viewHolder.webTitle.setText(currentNews.getWebTitle()); return convertView; } Switch case for color change : switch (currentNews.getSectionName()) { case "Technology": viewHolder.sectionName.setBackgroundResource(R.color.yourColor);// change color break; default: throw new IllegalArgumentException("Invalid Color Set " + currentNews.getSectionName()); }
{ "pile_set_name": "StackExchange" }
Q: Animate element only if position is not 0 I am trying to make ul#pikame move right it its relative position IS 0, but it keeps moving right even if position is not 0. I know li_left is set to 0 at the beginning, and it remembers that and sticks to it, but I need li_left to update for each new click. My code: li_left = $('ul#pikame').css('left'); if (li_left == '0px') { $('a.prev').click(function (e) { // e.preventDefault(); $('ul#pikame').animate({ 'left': '+=127' }); e.preventDefault(); }); } to sum up, it should move right only ONCE, because after the first click the position left will not be 0. A: Your condition should be inside the click handler, not outside. $('a.prev').click(function (e) { li_left = $('ul#pikame').css('left'); if (li_left == '0px') { // e.preventDefault(); $('ul#pikame').animate({ 'left': '+=127' } e.preventDefault(); });
{ "pile_set_name": "StackExchange" }
Q: Python: Почему программа не работает? Программа запускается без ошибок, но не выполняет копирование файлов. Директории указаны существующие. В чем может быть ошибка? ОС Windows 7, если это имеет значение. UPD: Проблема решена, нужно было дописать r при помещении файла в архив. zip_command = r"zip -qr {0} {1}".format(target, ' '.join(source)) import os import time # 1. Файлы и каталоги, которые необходимо скопировать, собираются в список. source = ['C:\\Code'] # Для имен, содержащих пробелы, необходимо использовать # двойные кавычки внутри строки. # 2. Резервные копии должны храниться в основном каталоге резерва. target_dir = 'C:\\Backup' # 3. Файлы помещаются в zip-архив. # 4. Именем для zip-архива служит текущая дата и время. target = target_dir + os.sep + time.strftime('%Y%m%d %H%M%S') + '.zip' # 5. Используем команду "zip" для помещения файлов в zip-архив zip_command = "zip -qr {0} {1}".format(target, ' '.join(source)) # Запускаем создание резервной копии print(zip_command) if os.system(zip_command) == 0: print('Резервная копия успешно создана в', target) else: print('Создание резервной копии НЕ УДАЛОСЬ') A: А почему не сделать так import os import zipfile zipf = zipfile.ZipFile('Backup.zip', 'w', zipfile.ZIP_DEFLATED) path = 'test_dir' for root, dirs, files in os.walk(path): for file in files: zipf.write(os.path.join(root, file)) zipf.close()
{ "pile_set_name": "StackExchange" }
Q: Displaying set value in text box So I've got a problem. I've created a text box like that: <input type="text" id="search" name="search" class="myText" value="Search for a keyword" onclick="value=''"/> My problem basically is that after I press the text box to write a text of my own, and then press some other place on the screen, the value I set at start (Search for a keyword) will not be displayed once again. I've tried everything. How do I make it display again once I've pressed some other place on the screen? A: Get rid of the onclick="value='' You are basically saying, empty the box whenever I click on it. If you can use html5, you can use: <input type="text" id="search" name="search" class="myText" placeholder="Search for a keyword" /> And you can style it as well: <style type="text/css"> ::-moz-placeholder {color:#ddd;} ::-webkit-input-placeholder {color:#ddd;} :-ms-input-placeholder {color:#ddd;} </style>
{ "pile_set_name": "StackExchange" }
Q: Underscore JS template If loop issue I am trying to add an attribute (rel="tooltip") based on if condition <div class="symbol"><span title="<%= data%>" <% if ( data.length > 9 ) { rel="tooltip" }%>></span></div> If I am adding an alert inside if loop it works, where as the attribute change does not work. A: This has nothing to do with JavaScript (or Underscore.js) at all. <% %> are ASP tags, and rel="tooltip" is just setting a variable. You need to have ASP echo out "tooltip" (like you did with the title). <div class="symbol"><span title="<%= data %>" rel="<%= data.length > 9 ? "tooltip" : "" %>></span></div>
{ "pile_set_name": "StackExchange" }
Q: I have two inner class in class and i can't init class in swift I can't init inner class. IDE me returning error, namely "'self' used before all stored properties are initialized". I attach picture where look error is ok A: The compiler is correct, you are attempting to pass self to the constructor of Customer before all stored properties are initialised, as SESSION won't be initialised until after the Session object is initialised, but that needs self - your two requirements are mutually exclusive. You may need to rethink your architecture; If nothing else, the reference from Customer to Session combined with the reference from Session to Customer will give you a retain cycle and a memory leak. If you want to use the current architecture, it is probably best to make the Customer property of Session a weak optional to avoid both your initialisation problem and the retain cycle; class Customer { let session: Session let auth: Auth init() { self.auth = Auth() self.session = Session() session.customer = self } class Session { weak var customer: Customer? } } You could make customer an implicitly unwrapped optional to avoid the need to unwrap it explicitly each time you refer to it, but you risk a crash if customer is released or not set: class Session { weak var customer: Customer! } On a point of style, Swift properties and variables should start with a lower case letter and use camel case, so auth, session and userID, not AUTH, SESSION and USER_ID.
{ "pile_set_name": "StackExchange" }
Q: C Grid using pointers and Malloc I am Trying to work through some class examples and have gotten stuck on the following: The array grid should have length width with each entry representing a column of cells. Columns that have some occupied cells should be a malloc'ed character array of length height. with the given header: void grid(char **grid, int width, int height) grid is defined in another file as: char **grid; As I have said I have gotten stuck on using malloc, I currently have: int x; *grid = malloc(width * sizeof(char)); for(x = 0; x < width; x++){ grid[x] = malloc(height * sizeof(char)); } Can any one take a look at give me some pointers on the correct way to accomplish "Columns that have some occupied cells should be a malloc'ed character array of length height.", As I dont understand how the line: grid[x] = malloc(height * sizeof(char)); is equivalent to an array of char's Thanks A: char** grid; is a pointer to pointer. grid = malloc( width* sizeof( char* ) ) ; // Statement 1 for( int i=0; i<height; ++i ) { grid[i] = malloc( height ) ; // Statement 2 } Understand char** -> char* -> char. So first need to reserve for holding addresses amounting to width. By Statement 1, it is achieved. Now each of these index should point to a memory location holding height characters and is achieved by Statement 2. Diagramatic representation sounds more clear than description. Hope that helps ! A: In C, an array is a pointer to the first element of the array. So an array is just a memory block, with the array variable pointing onto the first element in this memory block. malloc() reserves a new memory block of the specified size. To know the size of a type (i.e. number of bytes needed to store one variable of that type), one uses the sizeof operator. Hence a character needs sizeof(char) bytes, and hence height characters need height * sizeof(char). So with the malloc() call you allocate a memory block to store all the elements of the array, and malloc() returns a pointer onto the first of them. With C's definition for an array variable (a pointer onto the first element), you can assign the results of malloc(...) to your array variable.
{ "pile_set_name": "StackExchange" }
Q: Convert datetime to unix timestamp in python When I try to convert from UTC timestamp to normal date and add the right timezone I can't find the way to convert the time back to Unix timestamp. What am I doing worng? utc_dt = datetime.utcfromtimestamp(self.__modified_time) from_zone = tz.tzutc() to_zone = tz.tzlocal() utc = utc_dt.replace(tzinfo=from_zone) central = utc.astimezone(to_zone) Central is equal to 2015-10-07 12:45:04+02:00 This is what I have when running the code, and I need to convert the time back to timestamp. A: from datetime import datetime from datetime import timedelta from calendar import timegm utc_dt = datetime.utcfromtimestamp(self.__modified_time) from_zone = tz.tzutc() to_zone = tz.tzlocal() utc = utc_dt.replace(tzinfo=from_zone) central = utc.astimezone(to_zone) unix_time_central = timegm(central.timetuple())
{ "pile_set_name": "StackExchange" }
Q: Traducción del inglés "token" (compiladores) En el ámbito de los compiladores e intérpretes de lenguajes, existe el concepto de "token", que es cada una de las partes en que se divide una cadena en un lenguaje formal durante el análisis léxico. Posteriormente, (por lo general) tiene lugar un análisis sintáctico que parte de estos "tokens" para construir un árbol sintáctico, que luego se interpreta o se traduce a una representación distinta. Por ejemplo, en resultado = unNúmero + otroNúmero; Los "tokens" que se obtendrían del análisis léxico del ejemplo anterior podrían ser (los pongo separados por comas): resultado, =, unNúmero, +, otroNúmero, ; ¿Cómo podría traducirse al español la palabra "token" en este contexto? He pensado "símbolo", pero ya existe el concepto de "symbol" o "símbolo" con un significado distinto (cada uno de los identificadores utilizados en un programa, como en este caso "resultado", "unNúmero" y "otroNúmero"). A: Como se dice en los comentarios, muchos artículos usan la palabra en inglés: token. Este artículo de Wikipedia lo llama componente léxico: Un analizador léxico o analizador lexicográfico (en inglés scanner) es la primera fase de un compilador, consistente en un programa que recibe como entrada el código fuente de otro programa (secuencia de caracteres) y produce una salida compuesta de tokens (componentes léxicos) o símbolos. Para mí, "componente léxico" o "unidad léxica" son buenas traducciones porque capturan el significado bastante bien.
{ "pile_set_name": "StackExchange" }
Q: OP_WITH_INVALID_USER_TYPE_EXCEPTION error I have a scheduled class which scans through all of the records which have been made for a specific custom object and creates what is a "Monthly Report" record for that record (on a different object). It populates one of the fields in the new record with a name which appears in one of the fields of the original object. However, it is getting a "OP_WITH_INVALID_USER_TYPE_EXCEPTION" error when firing off. I read this helpful post regarding the error : https://developer.salesforce.com/forums?id=906F000000090bRIAQ That seems to be a possibility for my problem. However, in my case the code is being fired off by a schedule, not a trigger. So, would I still be getting the same problem if I was creating new records by a schedule and populating a field with a Chatter Free user ? Granted, that person is indeed regarded as the "Owner" of the record and is the only name on the record, but I didn't know if Salesforce technically regarded the person as the "owner" if it was merely a name in a field. Anybody have any ideas on this ? A: Chatter-only users cannot be referenced in 'lookup' fields such as Owner. There are 2 alternatives: create a text field and put the user's names in it instead of the Id's (not so nice, obviously) create an additional User lookup field (not Owner, since that is completely blocked by SF) and fill that with the userId. Note that this will not work in the GUI, only via apex. Basically you use the workaround described here: https://success.salesforce.com/ideaView?id=08730000000gAeIAAU#
{ "pile_set_name": "StackExchange" }
Q: Multibyte character issue with .match? The following code is something I am beginning to test for use within a "Texas Hold Em" style game I am working on. My question is why, when running the following code, does the puts involving a "♥" return a "\u" in it's place. I feel certain it is this multibyte character that is causing the issue becuse on the second puts , I replaced the ♦ with a d in the array of strings and it returned what i was expecting. See Below: My Code: #! /usr/bin/env ruby # encoding: utf-8 table_cards = ["|2♥|", "|8♥|", "|6d|", "|6♣|", "|Q♠|"] # Array of cards player_1_face_1 = "8" player_1_suit_1 = "♦" # Player 1's face and suit of first card he has player_1_face_2 = "6" player_1_suit_2 = "♥" # Player 1's face and suit of second card he has test_str_1 = /(\D8\D{2})/.match(table_cards.to_s) # EX: Searching for match between face values on (player 1's |8♦|) and the |8♥| on the table test_str_2 = /(\D6\D{2})/.match(table_cards.to_s) # EX: Searching for match between face values on (player 1's |6♥|) and the |6d| on the table puts "#{test_str_1}" puts "#{test_str_2}" Puts to Screen: |8\u |6d| -- My goal would be to get the first puts to return: |8♥| I am not so much looking for a solution to this (there may not even be one) but more so a "as simple as possible" explanation of what is causing this issue and why. Thanks ahead of time for any information on what is happening here and how I can tackle the goal. A: The "\u" you're seeing is the Unicode string indicator. For example, Unicode character 'HEAVY BLACK HEART' (U+2764) can be printed as "\u2764". A friendly Unicode character listing site is http://unicode-table.com/en/sets/ Are you able to launch interactive Ruby in your shell and print a heart like this? irb irb> puts "\u2764" ❤ When I run your code in my Ruby, I get the answer you expect: test_str_1 = /(\D8\D{2})/.match(table_cards.to_s) => #<MatchData "|8♥|" 1:"|8♥|"> What happens if you try a regex that is more specific to your cards? test_str_1 = /(\|8[♥♦♣♠]\|)/.match(table_cards.to_s) In your example output, you're not seeing the Unicode heart symbol as you want. Instead, your output is printing the "\u" which is the Unicode starter, but then not printing the rest of the expected string which is "2764". See the comment by the Tin Man that describes encoding for your console. If he's correct, then I expect the more-specific regex will succeed, but still print the wrong output. See the comment by David Knipe that says it looks like it gets truncated because the regex only matches 4 characters. If he's correct, then I expect the more-specific regex will succeed and also print the right output. (The rest of this answer is typical for Unix; if you're on Windows, ignore the rest here...) To show your system language settings, try this in your shell: echo $LC_ALL echo $LC_CTYPE If they are not "UTF-8" or something like that, try this in your shell: export LC_ALL=en_US.UTF-8 export LC_CTYPE=en_US.UTF-8 Then re-run your code -- be sure to use the same shell. If this works, and you want to make this permanent, one way is to add these here: # /etc/environment LC_ALL=en_US.UTF-8 LC_CTYPE=en_US.UTF-8 Then source that file from your .bashrc or .zshrc or whatever shell startup file you use.
{ "pile_set_name": "StackExchange" }
Q: Identities for hypergeometric functions ${}_2F_1$ with z=1/2 Is there a closed form (or approximation) for a hypergeometric function of form: $_2F_1(1,b+c;c;\frac{1}{2}) \quad \text{where} \; b,c \in \mathbb{N}$ ? I researched all identities in http://functions.wolfram.com/HypergeometricFunctions/Hypergeometric2F1/03/04/ but nothing seems to work for me. A: Case $1$: $c\neq1$ Then $_2F_1\left(1,b+c;c;\dfrac{1}{2}\right)$ $=~_2F_1\left(b+c,1;c;\dfrac{1}{2}\right)$ $=\dfrac{1}{B(1,c-1)}\int_0^1\dfrac{(1-x)^{c-2}}{\left(1-\dfrac{x}{2}\right)^{b+c}}dx$ $=\dfrac{2^{b+c}(c-1)!}{0!(c-2)!}\int_0^1\dfrac{(1-x)^{c-2}}{(2-x)^{b+c}}dx$ $=2^{b+c}(c-1)\int_0^1\dfrac{(2-x-1)^{c-2}}{(2-x)^{b+c}}dx$ $=2^{b+c}(c-1)\int_0^1\sum\limits_{n=0}^{c-2}\dfrac{C_n^{c-2}(-1)^n(2-x)^{c-n-2}}{(2-x)^{b+c}}dx$ $=2^{b+c}(c-1)\int_0^1\sum\limits_{n=0}^{c-2}\dfrac{(-1)^n(c-2)!(2-x)^{-b-n-2}}{n!(c-n-2)!}dx$ $=2^{b+c}(c-1)\left[-\sum\limits_{n=0}^{c-2}\dfrac{(-1)^n(c-2)!(2-x)^{-b-n-1}}{n!(c-n-2)!(-b-n-1)}\right]_0^1$ $=\left[\sum\limits_{n=0}^{c-2}\dfrac{(-1)^n(c-1)!2^{b+c}}{n!(c-n-2)!(b+n+1)(2-x)^{b+n+1}}\right]_0^1$ $=\sum\limits_{n=0}^{c-2}\dfrac{(-1)^n(c-1)!2^{b+c}}{n!(c-n-2)!(b+n+1)}-\sum\limits_{n=0}^{c-2}\dfrac{(-1)^n(c-1)!2^{c-n-1}}{n!(c-n-2)!(b+n+1)}$ Case $2$: $c=1$ Then $_2F_1\left(1,b+1;1;\dfrac{1}{2}\right)$ $=~_2F_1\left(b+1,1;1;\dfrac{1}{2}\right)$ $=\left(1-\dfrac{1}{2}\right)^{-b-1}$ $=\dfrac{1}{2^{b+1}}$
{ "pile_set_name": "StackExchange" }
Q: Pagination inTypo3 I have written a TYPO3 extension which lists records from database on pages. Now I have to add pagination at bottom of page with 10 records on each page like tt_news does. Can anybody please give me a hint A: Try the extension "Universal page browser" (http://typo3.org/extensions/repository/view/pagebrowse). This extension provides page browsing services to other extensions.
{ "pile_set_name": "StackExchange" }
Q: Unity3D: Detect if mouse has clicked on a UI element? This is a pretty simple question, but it seems something has changed on Unity in the last versions answers I've found on the internet are no longer valid, so here goes nothing: I got some UI elements, and a "InputController" class which is intended to handle the user input during the game (Input on the controllers are handled through the onclick events). What I'm looking is for a way to being able to know if the mouse is clicking a UI element to block the execution of my input handling (and avoid the user clicking on "pause" while also the game executes "left button clicked." Now, most solutions I've fond were a bit messy or used EventSystem.current.IsPointerOverGameObject() (like this one, which was shown when writing this question), which in 2019.4 does not longer appear. So, there's any new way to do this, do I have to make some hacky solution to receive the event from the UI, then block the execution of my code or am I missing something here? A: You should look into interfaces like IPointerEnterHandler and IPointerExitHandler. If you implement these interfaces for your UI elements, you can add the necessary code to the OnPointerEnter and OnPointerExit methods that those interfaces require. It should be as simple as adding a bool to your InputController such as isInputEnabled and only handling input when that is true. Set it to false OnPointerEnter and true OnPointerExit.
{ "pile_set_name": "StackExchange" }
Q: What is the difference between transfer_split and transfer? Using the monero-wallet-rpc program, from the documentation, I can't understand the difference between transfer and transfer_split. When should I use transfer and when should I use transfer_split? Please help me. transfer Send monero to a number of recipients. transfer_split Same as transfer, but can split into more than one tx if necessary. A: transfer, the older of the two commands, creates a single transaction. This can fail if you try to create a transaction with too many destinations / the transaction becomes too large. transfer_split may create more than one transaction. This is useful if you are wanting to create transactions with a higher number of destinations as it can efficiently split the the transfer, as necessary, into multiple transactions. If you are only ever doing single destination transfers, you can safely use either. If you need to create transfers to multiple destinations, it's safer to just use transfer_split. IIRC, the only reason transfer still exists is for backwards compatibility, i.e. to not break existing applications that were built before transfer_split was added.
{ "pile_set_name": "StackExchange" }
Q: Compact union of images of equicontinuous family Suppose $\{f_n, n = 1, 2, \dots\}$ is an equicontinuous family of real-valued functions on a compact metric space $(X, d)$. What are some appropriate conditions ensuring that $\cup_{n = 1}^\infty f_n(X)$ is compact? In particular, is it enough that $\sup_n \sup_x \vert f_n(x)\vert \leq M$ for some constant $M< \infty$? A: No (as zhw.'s hint should allude), to have that the set $\underset{n \in \mathbb{N}}{\cup}\, f_n(X) \subseteq \mathbb{R}$ is compact it is insufficient to merely assume that $\mathscr{F}=\{\, f_n:X \to \mathbb{R} : n \in \mathbb{N}\}$ is a uniformly bounded equicontinuous family of functions on a compact metric space $(X,d)$. If $(X,d)$ is a compact metric space and $\mathscr{F}=\{\, f_n : n \in \mathbb{N}\}$ is an equicontinuous family of real-valued functions on $X$, then $\underset{n \in \mathbb{N}}{\bigcup} f_n(X)$ is a compact subset of $\mathbb{R}$ if and only if $\mathscr{F}$ is closed and bounded in $C(X)$ (the set of continuous real-valued functions on $X$) with the supremum metric $\rho(\, f, g)= \underset{x \in X}{\sup} |\, f(x)-g(x)|$. Sticking with $X=[0,1]$, another example to consider is the sequence of real-valued functions on $X$ $\{g_n\}_{n=1}^\infty$ such that $g_n(x)=x+\frac{1}{n}$ ($n=1,2,\ldots$).
{ "pile_set_name": "StackExchange" }
Q: Why do we need high energy to explore small dimensions? I am taking a quantum physics class, and for the life of me, I can not remember why we would need a vast amount of energy to understand the microscopic universe. A: Frequently one probes matter by bombarding it with radiation or with other pieces of matter, and then looking at the products. This is called a scattering experiment. Since the probe system is quantum, whether or not it is made of light or matter, it is associated with a wavelength. The de Broglie relation tells you that this wavelength is $\lambda = h/p$, where $h$ is Planck's constant and $p$ is the momentum of the probe. This de Broglie wavelength gives a lower limit to the resolution of the probe. Any feature smaller than this will simply be smeared/averaged over the probe's wavelength, and so will not be visible. For the same reason, normal microscopes only work down to a few hundred nm (the wavelength of visible light). Electron microscopes allow you to see smaller features because the electrons have a smaller wavelength. Therefore, the smaller the feature you would like to see, the higher must be the momentum, and thus the energy, of your probe system. This is one (oversimplified) reason why the LHC has to be so large and achieve such high energies (relative to usual microscopic scales). A: Apart from the fact that high energies correspond to short wavelengths, as has been explained in the other answers, another reason for studying high energy collisions is noteworthy as well: Many unstable elementary particles have large masses and, due to conservation of energy, can only be produced by decay from highly energetic systems. Examples include heavy quarks, W- and Z-bosons and basically all hadrons except for protons and neutrons. So if you include knowledge of all elementary particles and their interactions in the category "understanding of the microscopic universe", then this is definitely an answer to your question. Below you can find a table of the elementary particles and their masses. As you can see, many of them exceed 1 GeV, which is very heavy compared to electrons, which we experience in daily life. A: You have probably seen the relation between energy and frequency for photons $ E = hf$. Since the speed of a photon is $c$, the wavelength is $\lambda = c/f$ so $$E = hc/\lambda. $$ Therefore short wavelengths correspond to high energies.
{ "pile_set_name": "StackExchange" }
Q: How to get all Fields names in golang proto generated complex structs I am trying to get all the fields names in the go file generated from proto. Below is the generated struct. type Action struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Types that are valid to be assigned to ActionType: // *Action_TaskAction ActionType isAction_ActionType `protobuf_oneof:"action_type"` } As it is seen that ActionType is oneof Field in proto which is implemented as below. type isAction_ActionType interface { isAction_ActionType() } type Action_TaskAction struct { TaskAction *TaskAction `protobuf:"bytes,16,opt,name=task_action,json=taskAction,proto3,oneof"` } type TaskAction struct { Progress float32 `protobuf:"fixed32,1,opt,name=progress,proto3" json:"progress,omitempty"` } As I want to get the field name in TaskAction struct which is Progress. I am using below code to get the field names but facing issue if the field type is interface(for oneof field) func printFieldNames(t reflect.Type) error { for i := 0; i < t.NumField(); i++ { field := t.Field(i) if field.Type.Kind() == reflect.Struct { printFieldNames(field.Type) continue } if field.Type.Kind() == reflect.Interface { // what to do here. } column := field.Tag.Get("json") fmt.Println("column: ", column) } return nil } A: If the type is interface, you can't do much about that. In an actual value it may be a struct or any other type that implements that interface, but the interface type itself cannot tell you this, it does not restrict the concrete type. You may do what you want if you start with reflect.Value instead of reflect.Type, because if you have a value, you can examine the value (or its type) that is stored in the interface. To get the reflect.Value descriptor wrapped in an interface value, you may use reflect.Elem(). Also, to handle pointer to structs, you again may use reflect.Elem() to get the pointed value. You may check if a value is a pointer by comparing its kind to reflect.Ptr. Here's an example of your printFieldNames(), rewritten to work with reflect.Value, and it recurses into structs stored in interface values. This is not a solution that handles all cases, but demonstrates how to do it: func printFieldNames(v reflect.Value) { for i := 0; i < v.NumField(); i++ { field := v.Field(i) if field.Kind() == reflect.Ptr { field = field.Elem() } if field.Kind() == reflect.Struct { printFieldNames(field) continue } if field.Kind() == reflect.Interface { wrapped := field.Elem() if wrapped.Kind() == reflect.Ptr { wrapped = wrapped.Elem() } printFieldNames(wrapped) } structfield := v.Type().Field(i) column := structfield.Tag.Get("json") fmt.Printf("column: %s, json tag: %s\n", structfield.Name, column) } } Testing it: a := Action{ ActionType: Action_TaskAction{ TaskAction: &TaskAction{}, }, } printFieldNames(reflect.ValueOf(a)) Output will be (try it on the Go Playground): column: Name, json tag: name,omitempty column: Progress, json tag: progress,omitempty column: ActionType, json tag:
{ "pile_set_name": "StackExchange" }
Q: ASP.Net MVC 5 Render PDF in Browser from Byte[] C# I am working with Kendo MVC and I want to render an uploaded PDF into a Tabstrip. When getting the PDF file to show in the tab, I am calling my controller and subsequent service, getting the file data as a byte array and returning data into its respective div using the following code. public FileStreamResult GetRxPdf(int prescriptionId) { var retVal = _service.GetRxPdf(prescriptionId); byte[] byteArray = retVal.FileData; MemoryStream pdfStream = new MemoryStream(); pdfStream.Write(byteArray, 0, byteArray.Length); pdfStream.Position = 0; return new FileStreamResult(pdfStream, retVal.ContentType); } The rendered output is not the PDF, but is as follows %PDF-1.7 %���� 1 0 obj <>/OutputIntents[<>] /Metadata 148 0 R/ViewerPreferences 149 0 R>> endobj 2 0 obj <> endobj 3 0 obj <>/XObject<>/ProcSet[/PDF/Text/ImageB/ImageC/ImageI] >>/Annots[ 7 0 R 10 0 R 11 0 R 21 0 R] /MediaBox[ 0 0 595.32 841.92] /Contents 4 0 R/StructParents 0>> endobj 4 0 obj <> stream x��]Ys�F~W��ɔ5�\�I�֒��[9[�yH�@S�̲�����7���=Ip��P�TE��3������1�>[,��&�e��7�ϖ��������������?�N/&���r~w����%~��lr5[|�mq�������$%�W׊e!I8+jAIÊ����ׯ��㣳��ӗ������|w|��eA�H�D����uqy3�����F������G/`�/�G��m�����4r�g����m�*��/s^%�HQ�R�]䛋����]��h1S>�W������R^�0>���՘�Q1(�'l�zL���z>棇��pm0����=�±7�;�� ?��]��ů�>�� ��U�~�O?��a�^���>�A+�xD %�Ԍ�H� /�������$MD�~�A2V6�Ѣ��Q....more file data here... 0000166807 00000 n trailer <] >> startxref 166853 %%EOF When the data comes back via an ajax call it this is how it is passed to the div $("#divRxPdf").html(data); I would be grateful if anyone could help me with this and show the PDF in the Div accordingly. A: Update: PDF needs to be embeded in the HTML with <embed> or <iframe> . You could also use library such as pdf.js to render pdf files with some controls. The pdf.js readme has samples and how to: https://github.com/mozilla/pdf.js You can return the pdf as file by passing the binary using retun File() method public ActionResult GetRxPdf(int prescriptionId) { var retVal = _service.GetRxPdf(prescriptionId); byte[] byteArray = retVal.FileData; return File(byteArray , "application/pdf" , "Filename.pdf"); }
{ "pile_set_name": "StackExchange" }
Q: Is in general true that $[a,b] + [c,d] = [a+c,b+d]$? Let $a,b,c,d\in \mathbb{R}$ with $a\leq b $ and $c\leq d$. If we consider the Minkowski sum $A+ B = \{x+y : x\in A,y\in B \},$ is true in general that $[a,b] + [c,d] = [a+c, b+d] $? A: The set $X = [a, b] + [c, d]$ clearly lies within the closed interval $[a + c, b + d]$ and contains its endpoints. Since $X$ is the image of the connected set $[a, b]\times [c, d]$ under the continuous map $(x, y) \to x + y$, it is itself connected, and thus must be exactly $[a+c, b + d]$.
{ "pile_set_name": "StackExchange" }
Q: Fill in the translucent color insider the circular slider I would like to implement the custom circular slider for IOS. I refer to the EFCircularSlider to create my own one. When it comes to the customization such as filling in the translucent color insider the circular slider , i have found that this line is not working. Would you please tell me are there any other alternatives? CGContextSetFillColorWithColor(ctx, [UIColor greenColor].CGColor ); The below is my code (EFCircularSlider.m) #import "EFCircularSlider.h" #import <QuartzCore/QuartzCore.h> #import <CoreImage/CoreImage.h> #define kDefaultFontSize 14.0f; #define ToRad(deg) ( (M_PI * (deg)) / 180.0 ) #define ToDeg(rad) ( (180.0 * (rad)) / M_PI ) #define SQR(x) ( (x) * (x) ) @interface EFCircularSlider (private) @property (readonly, nonatomic) CGFloat radius; @end @implementation EFCircularSlider { int angle; int fixedAngle; NSMutableDictionary* labelsWithPercents; NSArray* labelsEvenSpacing; } - (void)defaults { // Defaults _maximumValue = 100.0f; _minimumValue = 0.0f; _currentValue = 0.0f; _lineWidth = 5; _lineRadiusDisplacement = 0; _unfilledColor = [UIColor lightGrayColor]; _filledColor = [UIColor blueColor]; _handleColor = _filledColor; _labelFont = [UIFont systemFontOfSize:10.0f]; _snapToLabels = NO; _handleType = EFSemiTransparentWhiteCircle; _labelColor = [UIColor redColor]; _labelDisplacement = 2; self.backgroundColor = [UIColor clearColor]; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self defaults]; [self setFrame:frame]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { if ((self=[super initWithCoder:aDecoder])){ [self defaults]; } return self; } #pragma mark - Setter/Getter - (void)setFrame:(CGRect)frame { [super setFrame:frame]; angle = [self angleFromValue]; } - (CGFloat)radius { //radius = self.frame.size.height/2 - [self circleDiameter]/2; return self.frame.size.height/2 - _lineWidth/2 - ([self circleDiameter]-_lineWidth) - _lineRadiusDisplacement; } - (void)setCurrentValue:(float)currentValue { _currentValue=currentValue; if(_currentValue>_maximumValue) _currentValue=_maximumValue; else if(_currentValue<_minimumValue) _currentValue=_minimumValue; angle = [self angleFromValue]; [self setNeedsLayout]; [self setNeedsDisplay]; [self sendActionsForControlEvents:UIControlEventValueChanged]; } #pragma mark - drawing methods - (void)drawRect:(CGRect)rect { [super drawRect:rect]; CGContextRef ctx = UIGraphicsGetCurrentContext(); //Draw the unfilled circle //CGContextAddArc(ctx, self.frame.size.width/2, self.frame.size.height/2, self.radius, 0, M_PI *2, 0); CGContextAddArc(ctx, self.frame.size.width/2, self.frame.size.height/2, self.radius, 0, M_PI *2, 0); [_unfilledColor setStroke]; CGContextSetLineWidth(ctx, _lineWidth); CGContextSetLineCap(ctx, kCGLineCapButt); CGContextDrawPath(ctx, kCGPathStroke); //Draw the filled circle if((_handleType == EFDoubleCircleWithClosedCenter || _handleType == EFDoubleCircleWithOpenCenter) && fixedAngle > 5) { CGContextAddArc(ctx, self.frame.size.width/2 , self.frame.size.height/2, self.radius, 3*M_PI/2, 3*M_PI/2-ToRad(angle+3), 0); } else { CGContextAddArc(ctx, self.frame.size.width/2 , self.frame.size.height/2, self.radius, 3*M_PI/2, 3*M_PI/2-ToRad(angle), 0); } [_filledColor setStroke]; CGContextSetLineWidth(ctx, _lineWidth); CGContextSetLineCap(ctx, kCGLineCapButt); CGContextDrawPath(ctx, kCGPathStroke); UIView *colourView = [[UIView alloc] initWithFrame:rect]; colourView.opaque = NO; colourView.alpha = .7f; //colourView.backgroundColor = [UIColor colorWithRed:0.13f green:0.14f blue:0.15f alpha:1.00f]; //CGContextSetStrokeColorWithColor(ctx, [UIColor greenColor].CGColor); CGContextSetFillColorWithColor(ctx, [UIColor greenColor].CGColor ); // CGContextFillRect(ctx, (CGRect){ {0,0}, colourView.size} ); //Add the labels (if necessary) if(labelsEvenSpacing != nil) { [self drawLabels:ctx]; } //The draggable part [self drawHandle:ctx]; } -(void) drawHandle:(CGContextRef)ctx{ CGContextSaveGState(ctx); CGPoint handleCenter = [self pointFromAngle: angle]; if(_handleType == EFSemiTransparentWhiteCircle) { [[UIColor colorWithWhite:0.3 alpha:0.7] set]; CGContextFillEllipseInRect(ctx, CGRectMake(handleCenter.x, handleCenter.y, _lineWidth, _lineWidth)); } else if(_handleType == EFSemiTransparentBlackCircle) { [[UIColor colorWithWhite:0.0 alpha:0.7] set]; CGContextFillEllipseInRect(ctx, CGRectMake(handleCenter.x, handleCenter.y, _lineWidth, _lineWidth)); } else if(_handleType == EFDoubleCircleWithClosedCenter) { [_handleColor set]; CGContextAddArc(ctx, handleCenter.x + (_lineWidth)/2, handleCenter.y + (_lineWidth)/2, _lineWidth, 0, M_PI *2, 0); CGContextSetLineWidth(ctx, 7); CGContextSetLineCap(ctx, kCGLineCapButt); CGContextDrawPath(ctx, kCGPathStroke); CGContextFillEllipseInRect(ctx, CGRectMake(handleCenter.x, handleCenter.y, _lineWidth-1, _lineWidth-1)); } else if(_handleType == EFDoubleCircleWithOpenCenter) { [_handleColor set]; CGContextAddArc(ctx, handleCenter.x + (_lineWidth)/2, handleCenter.y + (_lineWidth)/2, _lineWidth/2 + 5, 0, M_PI *2, 0); CGContextSetLineWidth(ctx, 4); CGContextSetLineCap(ctx, kCGLineCapButt); CGContextDrawPath(ctx, kCGPathStroke); CGContextAddArc(ctx, handleCenter.x + _lineWidth/2, handleCenter.y + _lineWidth/2, _lineWidth/2, 0, M_PI *2, 0); CGContextSetLineWidth(ctx, 2); CGContextSetLineCap(ctx, kCGLineCapButt); CGContextDrawPath(ctx, kCGPathStroke); } else if(_handleType == EFBigCircle) { [_handleColor set]; CGContextFillEllipseInRect(ctx, CGRectMake(handleCenter.x-2.5, handleCenter.y-2.5, _lineWidth+5, _lineWidth+5)); } CGContextRestoreGState(ctx); } - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { CGPoint p1 = [self centerPoint]; CGPoint p2 = point; CGFloat xDist = (p2.x - p1.x); CGFloat yDist = (p2.y - p1.y); double distance = sqrt((xDist * xDist) + (yDist * yDist)); return distance < self.radius + 11; } -(void) drawLabels:(CGContextRef)ctx { if(labelsEvenSpacing == nil || [labelsEvenSpacing count] == 0) { return; } else { #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0 NSDictionary *attributes = @{ NSFontAttributeName: _labelFont, NSForegroundColorAttributeName: _labelColor }; #endif CGFloat fontSize = ceilf(_labelFont.pointSize); NSInteger distanceToMove = -[self circleDiameter]/2 - fontSize/2 - _labelDisplacement; for (int i=0; i<[labelsEvenSpacing count]; i++) { NSString *label = [labelsEvenSpacing objectAtIndex:[labelsEvenSpacing count] - i - 1]; CGFloat percentageAlongCircle = i/(float)[labelsEvenSpacing count]; CGFloat degreesForLabel = percentageAlongCircle * 360; CGSize labelSize=CGSizeMake([self widthOfString:label withFont:_labelFont], [self heightOfString:label withFont:_labelFont]); CGPoint closestPointOnCircleToLabel = [self pointFromAngle:degreesForLabel withObjectSize:labelSize]; CGRect labelLocation = CGRectMake(closestPointOnCircleToLabel.x, closestPointOnCircleToLabel.y, labelSize.width, labelSize.height); CGPoint centerPoint = CGPointMake(self.frame.size.width/2, self.frame.size.height/2); float radiansTowardsCenter = ToRad(AngleFromNorth(centerPoint, closestPointOnCircleToLabel, NO)); labelLocation.origin.x = (labelLocation.origin.x + distanceToMove * cos(radiansTowardsCenter)); labelLocation.origin.y = (labelLocation.origin.y + distanceToMove * sin(radiansTowardsCenter)); #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0 [label drawInRect:labelLocation withAttributes:attributes]; #else [_labelColor setFill]; [label drawInRect:labelLocation withFont:_labelFont]; #endif } } } #pragma mark - UIControl functions -(BOOL) beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event { [super beginTrackingWithTouch:touch withEvent:event]; return YES; } -(BOOL) continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event { [super continueTrackingWithTouch:touch withEvent:event]; CGPoint lastPoint = [touch locationInView:self]; [self moveHandle:lastPoint]; [self sendActionsForControlEvents:UIControlEventValueChanged]; return YES; } -(void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{ [super endTrackingWithTouch:touch withEvent:event]; if(_snapToLabels && labelsEvenSpacing != nil) { CGFloat newAngle=0; float minDist = 360; for (int i=0; i<[labelsEvenSpacing count]; i++) { CGFloat percentageAlongCircle = i/(float)[labelsEvenSpacing count]; CGFloat degreesForLabel = percentageAlongCircle * 360; if(abs(fixedAngle - degreesForLabel) < minDist) { newAngle=degreesForLabel ? 360 - degreesForLabel : 0; minDist = abs(fixedAngle - degreesForLabel); } } angle = newAngle; _currentValue = [self valueFromAngle]; [self setNeedsDisplay]; } } -(void)moveHandle:(CGPoint)point { CGPoint centerPoint; centerPoint = [self centerPoint]; int currentAngle = floor(AngleFromNorth(centerPoint, point, NO)); angle = 360 - 90 - currentAngle; _currentValue = [self valueFromAngle]; [self setNeedsDisplay]; } - (CGPoint)centerPoint { return CGPointMake(self.frame.size.width/2, self.frame.size.height/2); } #pragma mark - helper functions -(CGPoint)pointFromAngle:(int)angleInt{ //Define the Circle center CGPoint centerPoint = CGPointMake(self.frame.size.width/2 - _lineWidth/2, self.frame.size.height/2 - _lineWidth/2); //Define The point position on the circumference CGPoint result; result.y = round(centerPoint.y + self.radius * sin(ToRad(-angleInt-90))) ; result.x = round(centerPoint.x + self.radius * cos(ToRad(-angleInt-90))); return result; } -(CGPoint)pointFromAngle:(int)angleInt withObjectSize:(CGSize)size{ //Define the Circle center CGPoint centerPoint = CGPointMake(self.frame.size.width/2 - size.width/2, self.frame.size.height/2 - size.height/2); //Define The point position on the circumference CGPoint result; result.y = round(centerPoint.y + self.radius * sin(ToRad(-angleInt-90))) ; result.x = round(centerPoint.x + self.radius * cos(ToRad(-angleInt-90))); return result; } - (CGFloat)circleDiameter { if(_handleType == EFSemiTransparentWhiteCircle) { return _lineWidth; } else if(_handleType == EFSemiTransparentBlackCircle) { return _lineWidth; } else if(_handleType == EFDoubleCircleWithClosedCenter) { return _lineWidth * 2 + 3.5; } else if(_handleType == EFDoubleCircleWithOpenCenter) { return _lineWidth + 2.5 + 2; } else if(_handleType == EFBigCircle) { return _lineWidth + 2.5; } return 0; } static inline float AngleFromNorth(CGPoint p1, CGPoint p2, BOOL flipped) { CGPoint v = CGPointMake(p2.x-p1.x,p2.y-p1.y); float vmag = sqrt(SQR(v.x) + SQR(v.y)), result = 0; v.x /= vmag; v.y /= vmag; double radians = atan2(v.y,v.x); result = ToDeg(radians); return (result >=0 ? result : result + 360.0); } -(float) valueFromAngle { if(angle < 0) { _currentValue = -angle; } else { _currentValue = 270 - angle + 90; } fixedAngle = _currentValue; return (_currentValue*(_maximumValue - _minimumValue))/360.0f; } - (float)angleFromValue { angle = 360 - (360.0f*_currentValue/_maximumValue); if(angle==360) angle=0; return angle; } - (CGFloat) widthOfString:(NSString *)string withFont:(UIFont*)font { NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil]; return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width; } - (CGFloat) heightOfString:(NSString *)string withFont:(UIFont*)font { NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil]; return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].height; } #pragma mark - public methods -(void)setInnerMarkingLabels:(NSArray*)labels{ labelsEvenSpacing = labels; [self setNeedsDisplay]; } @end EFCircularSlider.h #import <UIKit/UIKit.h> @interface EFCircularSlider : UIControl typedef NS_ENUM(NSInteger, EFHandleType) { EFSemiTransparentWhiteCircle, EFSemiTransparentBlackCircle, EFDoubleCircleWithOpenCenter, EFDoubleCircleWithClosedCenter, EFBigCircle }; @property (nonatomic) float minimumValue; @property (nonatomic) float maximumValue; @property (nonatomic) float currentValue; @property (nonatomic) int lineWidth; @property (nonatomic) int lineRadiusDisplacement; @property (nonatomic, strong) UIColor* filledColor; @property (nonatomic, strong) UIColor* unfilledColor; @property (nonatomic, strong) UIColor* handleColor; @property (nonatomic) EFHandleType handleType; @property (nonatomic, strong) UIFont* labelFont; @property (nonatomic, strong) UIColor* labelColor; @property (nonatomic, assign) NSInteger labelDisplacement; @property (nonatomic) BOOL snapToLabels; -(void)setInnerMarkingLabels:(NSArray*)labels; @end A: You can only do 1 CGContextDrawPath with the implicit path, and use kCGPathFill to fill it. Also, if you want the translucent background color to not interfere with the overlaying arc: draw the background first use an actual transparent color (alpha < 1.0) Do this: CGContextAddArc(ctx, self.frame.size.width/2, self.frame.size.height/2, self.radius, 0, M_PI *2, 0); CGContextClosePath(ctx); CGContextSetFillColorWithColor(ctx, [UIColor colorWithRed:0 green:.5 // dark green blue:0 alpha:.25] // translucent .CGColor ); CGContextDrawPath(ctx, kCGPathFill); ...before you do that (redefine CGContextAddArc) CGContextAddArc(ctx, self.frame.size.width/2, self.frame.size.height/2, self.radius, 0, M_PI *2, 0); CGContextClosePath(ctx); [_unfilledColor setStroke]; CGContextSetLineWidth(ctx, _lineWidth); CGContextSetLineCap(ctx, kCGLineCapButt); CGContextDrawPath(ctx, kCGPathStroke); PS. Nice control. Make sources public when anti-aliased and ready!
{ "pile_set_name": "StackExchange" }
Q: What is the word for a love of ignorance, or a distaste of knowledge? I'm looking for a word or short phrase that encapsulates the desire to eschew new knowledge, whether it be due to a fear of change or possibly a fear of science or research as a whole. An example might be a group of people looking to have their congressional representative allocate money elsewhere as opposed to scientific endeavors. They may claim that the "elsewhere" is of a higher priority or for the greater good, but they may really be acting out of ________ or because the group is a group of _________(s). This example is not all-inclusive. edit: There's a word or phrase I'm trying to think of that almost implies a sort of smugness.. A "my ignorance is better than your knowledge" kind of attitude. A: Anti-intellectualism is a handy (and self-explanatory) term, particularly in American politics today. It has great currency in the news media of late, largely with regard to situations such as the one described in your example. A: There is a rare word misosophy defined as the hatred of wisdom or knowledge. An example from OED: Much of modern philosophy is in fact not at all a ‘love of wisdom’ but a hatred of it so that it should appropriately be called ‘misosophy’. S. H. Nasr, Ideals & Realities of Islam, 1966 It is from the ancient Greek μισόσοϕος hating wisdom ( < μισο- miso- comb. form + -σοϕος , combining form of σοϕός wise) + -y suffix. [OED] Additionally, you can call the person a misosophist. Another similar rare word is misogrammatist, a person who hates letters or learning. [miso- comb. form + ancient Greek γράμματα ‘letters’, plural of γράμμα letter + -ist suffix].[OED] A: Not precisely opposed to knowledge or intellectualism, but a close relative nonetheless is philistinism. A philistine is one who is hostile or indifferent to culture and the arts. Adjective is philistine as in a philistine government. This sense of philistine (no capital letter) arose as a result of a confrontation between town and gown in Jena (now in Germany), in the late 17th century; a sermon on the conflict quoted: 'the Philistines are upon you' (Judges 16). which led to an association between the townspeople and those hostile to culture. (Oxford Dictionary Online)
{ "pile_set_name": "StackExchange" }
Q: Parse elements from HTML I'm looking to just create a csv file of animal hospitals by state. I think my selecting of html is incorrect. I want to iterate through the elements selecting the right tags to parse the state, name, address, phone #. from lxml import html import requests link = "https://vcahospitals.com/find-a-hospital/location-directory" response = requests.get(link, allow_redirects = False) #get page data from server, block redirects sourceCode = response.content #get string of source code from response htmlElem = html.document_fromstring(sourceCode) #make HTML element object print(sourceCode) [Example page html. I've tried selecting all div elements as classes][1] I would think this grabs all the state hospitals, but it only prints out one state's worth A: You have indented the print statement in your code wrong. for el in state_hospitals: text = el.text_content() # indented in the for block. print (text)
{ "pile_set_name": "StackExchange" }
Q: Why is the single-rear derailleur that enables <= 12 speeds so popular? All the high-end MTB, and road racers seem to have somewhere between ... 6 and 12 gears. NO derailleur up-front, only a few to scroll through in back. I get the KISS principle behind it; I like having first gear made extra-extra large to make up for missing lower gear elsewhere. Seriously why is this so popular? All the $5000+ bikes have ONE deralleur and limited gears. Is it really better to design gearsets this way? Why? Is it faster? More durable? A: Any less than 21 speeds for that kind of jack seems wasteful to me. You must understand that what matters is not how much "speeds" drivetrain offers, but the available range and other factors (see below). Let's compare 3x7 13-30 24-32-42 and 1x12 10-50 36: 3x7 has 404% range versus 500% range of 1x12. That's a 96% difference! 1x12 will also be lighter by at least several hundred grams. The quality of parts will also be generally higher, given that there are no modern high end 3x7 complete groups. Even compared to a 2x10 11-36 28-38 444% 1x12 has a wider range. Seriously why is this so popular? Why people choose one-by: Similar or wider range with reduced simplicity. Weight reduction. Frees up bar space for remote control levers (suspension lockout, adjustable seatpost). Availability. SRAM does not offer 2x12 or 3x12. And why not: Cost (in some cases). Maybe a reduced service life. A lot of factors contribute to this, I think it's a complex matter. Limited availability. Good luck finding a replacement 12 speed chain in third-world nowhere. Is this a fad? Is it really better to design gearsets this way? Why? Cuz Shimano said? Is it faster? More durable? It's a legitimate trend that offers benefits for some people at cost that other people might not find acceptable. A general advice would be to use what you find suitable for your application scenarios. Manufacturers might have their own reasons to reduce front gears amount, hype/trends and manufacturing costs being among them. Only companies are able to answer about particular reasons, but I doubt you'd hear anything beyond approved PR talk. Not like it has any different for a bike industry since always.
{ "pile_set_name": "StackExchange" }
Q: Can we use "next of kin" for things as a metaphor? Wheat has been man's next of kin. Does this sentence make sense to native English speakers?? It's supposed to be a simile, meaning wheat is like family to humans. It's a translated sentence from a Persian text. A: This sounds very strange to me. "Next of kin" describes a close blood relationship, which typically carries legal obligations like inheritance, medical decision making, etc. To say that wheat is man's next of kin seems like a massive overstatement of that relationship - there is no genetic link whatsoever, and it would be unusual to have a very close personal "kinship" bond with a plant that can't really do anything except sit in place and grow. You might be able to jokingly say "my dog is my next of kin", since that at least carries some form of personal bond that would be reminiscent of kinship. But to say that a species of plant is the next of kin of a species of animal implies a personal, genetic, or societal link between the two, none of which are really the case. Mankind is not rearing wheat to one day take its place, which is what one generally does with a next of kin. In sum, "next of kin" can be used in a non-literal sense, but it carries the connotation of a close personal bond, as well as the sense of the succession of a lineage. Wheat seems far too dissimilar to a person or a normal "kin" relationhip to aptly describe it as man's "next of kin" (unless you happen to be writing a book about a post-apocalytic world that is dominated by wheat).
{ "pile_set_name": "StackExchange" }
Q: Cant put sound button into fragment So I have two apps created. One is making sound when I click the button and the second one has a navigation drawer activity. All I want to do is put this button with sound to the one of the fragments I have created but it doesnt work for me. Im total beginner who just watching tutorials on youtube I want to put this public class MainActivity extends AppCompatActivity { SoundPool mySound; int anotheroneId; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mySound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); anotheroneId = mySound.load(this, R.raw.anotherone, 1); Into this public class FragmentThree extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_three,container,false); } A: You have to override the method onActivityCreated like this @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mySound = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); anotheroneId = mySound.load(getActivity().getApplicationContext(), R.raw.anotherone, 1); }
{ "pile_set_name": "StackExchange" }
Q: Use a relative path with NSTask Arguments in Objective-C I have virtually no programing experience beyond shell scripting, but I'm in a situation where I need to call a binary with launchd and because of security changes in Catilina, it looks as though it cannot be a AppleScript .app, Automator .app, or a Platypus .app. All three of those call some sort of GUI element and none will work as at startup. I've cobbled together a snippet of code that compiles and works to call the script I need. I've bundled it a .app, signed it, and it works. But I'd very much like to call the script relative to the binary. How can I call the equivalent of [task setArguments:@[ @"../Resources/script" ]]; instead of [task setArguments:@[ @"/Full/Path/To/script" ]]; Below is the entirety of the main.m #import <Foundation/Foundation.h> enter code here int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here... NSTask *task = [[NSTask alloc] init]; [task setLaunchPath:@"/bin/zsh"]; [task setArguments:@[ @"/Full/Path/To/script" ]]; [task launch]; } return 0; } As an aside, I know there are much better ways to do this, but my goal os not to have an award winning app, but to simply bridge a specific problem. Many thanks. A: You get the current directory with NSFileManager NSString* path = [[NSFileManager defaultManager] currentDirectoryPath]; The first argument in argv is the path to the binary Either NSString *path = [NSString stringWithUTF8String:argv[0]]; or NSString *path = [[NSProcessInfo processInfo] arguments][0];
{ "pile_set_name": "StackExchange" }
Q: ¿Qué diferencia hay entre ISOc++11 y GNUc++11? ¿Existe alguna diferencia entre el estándar ISOc++11 y GNUc++11 a la hora de compilar el código? A: La compilación ISO se trata del estándar C++11 sin más, mientras que GNU incluye las extensiones propias de GNU. En ambos casos vas a poder hacer uso del estándar C++11. La opción más portable es la ISO ya que hacer uso de las extensiones GNU impide que el código compile en sistemas no compatibles con GNU. Si tu programa compila con ISO entonces también lo hará con GNU, pero lo contrario no está garantizado. Para revisar las extensiones de la compilación con GNU puedes visitar el siguiente enlace
{ "pile_set_name": "StackExchange" }
Q: Is there a short way to do Django objects.create() Newbie here. I happen to have a create object with more than 50 fields, Is there a short way to write a create object? Any suggestion is really appreciated. Thanks SOA_detail.objects.create( soa =instance, sitename =rec_fields['sitename'], site_addr =rec_fields['site_addr'], call_sign =rec_fields['call_sign'], no_years =rec_fields['no_years'], channel =rec_fields['channel'], ppp_units =rec_fields['ppp_units'], rsl_units =rec_fields['rsl_units'], freq =rec_fields['freq'], ... duplicate_fee =rec_fields['duplicate_fee']) Ans. After a guide from jproffitt. Here's what I did. With the assumption of: header_name =[] is a dynamic listing of field names. SOA_detail is my model. soa_detail = [] is the values. for i in range(len(header_name)): for model_field in SOA_detail._meta._fields(): # check every header_name if it is in model field name if header_name[i] == model_field.name: # update dict if found rec_fields[header_name[i]] = soa_detail[i] SOA_detail.objects.create(soa=instance, **rec_fields) This is much better than my original script consist of almost 100 lines. A: If rec_fields is a dictionary with all the model fields as keys, you can just do SOA_detail.objects.create(soa=instance, **rec_fields)
{ "pile_set_name": "StackExchange" }